diff --git a/.gitattributes b/.gitattributes index 171ec7c271da52c722c0f32770104da2de6dca3a..daba532231649930039d0a50f7487d670603016f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -4443,3 +4443,5 @@ tool_server/.venv/lib/python3.12/site-packages/ray/core/src/ray/raylet/raylet fi tool_server/.venv/lib/python3.12/site-packages/ray/dag/__pycache__/compiled_dag_node.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text tool_server/.venv/lib/python3.12/site-packages/ray/data/__pycache__/dataset.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text tool_server/.venv/lib/python3.12/site-packages/ray/data/__pycache__/read_api.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/algorithm.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/algorithm_config.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..071ff6c660e995994b07cea491d847db53355203 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/__pycache__/issue_detector.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/__pycache__/issue_detector.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cdb0d66fa4288a5e706597354eb20420e7bd0da7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/__pycache__/issue_detector.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/__pycache__/issue_detector_configuration.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/__pycache__/issue_detector_configuration.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd2a2c11fc0e3f67421a2b3fb9f8b64a4f30f2b2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/__pycache__/issue_detector_configuration.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/__pycache__/issue_detector_manager.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/__pycache__/issue_detector_manager.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87054b0fe0ba1276768b6ad67cb3c17e543e4d1a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/__pycache__/issue_detector_manager.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/detectors/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/detectors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0fd93c5ce9d9716db22bebc8bc5ee89c21291b25 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/detectors/__init__.py @@ -0,0 +1,19 @@ +from ray.data._internal.issue_detection.detectors.hanging_detector import ( + HangingExecutionIssueDetector, + HangingExecutionIssueDetectorConfig, +) +from ray.data._internal.issue_detection.detectors.hash_shuffle_detector import ( + HashShuffleAggregatorIssueDetector, +) +from ray.data._internal.issue_detection.detectors.high_memory_detector import ( + HighMemoryIssueDetector, + HighMemoryIssueDetectorConfig, +) + +__all__ = [ + "HangingExecutionIssueDetector", + "HangingExecutionIssueDetectorConfig", + "HighMemoryIssueDetector", + "HighMemoryIssueDetectorConfig", + "HashShuffleAggregatorIssueDetector", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/detectors/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/detectors/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4956eb65882dc3e627beb960b3d6823eb534799 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/detectors/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/detectors/__pycache__/hanging_detector.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/detectors/__pycache__/hanging_detector.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..efe3f7cbae3579857622972c78032532717222ec Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/detectors/__pycache__/hanging_detector.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/detectors/__pycache__/hash_shuffle_detector.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/detectors/__pycache__/hash_shuffle_detector.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0cb69df59a1918da97f63260f235703cbb5dc68 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/detectors/__pycache__/hash_shuffle_detector.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/detectors/__pycache__/high_memory_detector.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/detectors/__pycache__/high_memory_detector.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4dfc484916ff9a4147bd909c233e6123452b5dec Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/detectors/__pycache__/high_memory_detector.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/detectors/hanging_detector.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/detectors/hanging_detector.py new file mode 100644 index 0000000000000000000000000000000000000000..381ba05f7bc165f2b683ef7fbea339c98ace6a3c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/detectors/hanging_detector.py @@ -0,0 +1,163 @@ +import time +from collections import defaultdict +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Dict, List, Set + +from ray.data._internal.issue_detection.issue_detector import ( + Issue, + IssueDetector, + IssueType, +) + +if TYPE_CHECKING: + from ray.data._internal.execution.interfaces.op_runtime_metrics import ( + TaskDurationStats, + ) + from ray.data._internal.execution.streaming_executor import StreamingExecutor + from ray.data.context import DataContext + +# Default minimum count of tasks before using adaptive thresholds +DEFAULT_OP_TASK_STATS_MIN_COUNT = 10 +# Default multiple of standard deviations to use as hanging threshold +DEFAULT_OP_TASK_STATS_STD_FACTOR = 10 +# Default detection time interval. +DEFAULT_DETECTION_TIME_INTERVAL_S = 30.0 + + +@dataclass +class HangingExecutionState: + operator_id: str + task_idx: int + bytes_output: int + start_time_hanging: float + + +@dataclass +class HangingExecutionIssueDetectorConfig: + op_task_stats_min_count: int = field(default=DEFAULT_OP_TASK_STATS_MIN_COUNT) + op_task_stats_std_factor: float = field(default=DEFAULT_OP_TASK_STATS_STD_FACTOR) + detection_time_interval_s: float = DEFAULT_DETECTION_TIME_INTERVAL_S + + +class HangingExecutionIssueDetector(IssueDetector): + def __init__(self, executor: "StreamingExecutor", ctx: "DataContext"): + super().__init__(executor, ctx) + self._detector_cfg: HangingExecutionIssueDetectorConfig = ( + ctx.issue_detectors_config.hanging_detector_config + ) + self._op_task_stats_min_count = self._detector_cfg.op_task_stats_min_count + self._op_task_stats_std_factor_threshold = ( + self._detector_cfg.op_task_stats_std_factor + ) + + # Map of operator id to dict of task_idx to hanging execution info (bytes read and + # start time for hanging time calculation) + self._state_map: Dict[str, Dict[int, HangingExecutionState]] = defaultdict(dict) + # Map of operator id to set of task_idx that are hanging + self._hanging_op_tasks: Dict[str, Set[int]] = defaultdict(set) + # Map of operator id to operator name + self._op_id_to_name: Dict[str, str] = {} + + def _create_issues( + self, + hanging_op_tasks: List[HangingExecutionState], + op_task_stats_map: Dict[str, "TaskDurationStats"], + ) -> List[Issue]: + issues = [] + for state in hanging_op_tasks: + if state.task_idx not in self._hanging_op_tasks[state.operator_id]: + op_name = self._op_id_to_name.get(state.operator_id, state.operator_id) + duration = time.perf_counter() - state.start_time_hanging + avg_duration = op_task_stats_map[state.operator_id].mean() + message = ( + f"A task of operator {op_name} with task index " + f"{state.task_idx} has been running for {duration:.2f}s, which is longer" + f" than the average task duration of this operator ({avg_duration:.2f}s)." + f" If this message persists, please check the stack trace of the " + "task for potential hanging issues." + ) + issues.append( + Issue( + dataset_name=self._executor._dataset_id, + operator_id=state.operator_id, + issue_type=IssueType.HANGING, + message=message, + ) + ) + self._hanging_op_tasks[state.operator_id].add(state.task_idx) + + return issues + + def detect(self) -> List[Issue]: + op_task_stats_map: Dict[str, "TaskDurationStats"] = {} + for operator, op_state in self._executor._topology.items(): + op_metrics = operator.metrics + op_task_stats_map[operator.id] = op_metrics._op_task_duration_stats + self._op_id_to_name[operator.id] = operator.name + if op_state._finished: + # Remove finished operators / tasks from the state map + if operator.id in self._state_map: + del self._state_map[operator.id] + if operator.id in self._hanging_op_tasks: + del self._hanging_op_tasks[operator.id] + else: + active_tasks_idx = set() + for task in operator.get_active_tasks(): + task_info = op_metrics._running_tasks.get(task.task_index(), None) + if task_info is None: + # if the task is not in the running tasks map, it has finished + # remove it from the state map and hanging op tasks, if present + self._state_map[operator.id].pop(task.task_index(), None) + self._hanging_op_tasks[operator.id].discard(task.task_index()) + continue + + active_tasks_idx.add(task.task_index()) + bytes_output = task_info.bytes_outputs + + prev_state_value = self._state_map[operator.id].get( + task.task_index(), None + ) + + if ( + prev_state_value is None + or bytes_output != prev_state_value.bytes_output + ): + self._state_map[operator.id][ + task.task_index() + ] = HangingExecutionState( + operator_id=operator.id, + task_idx=task.task_index(), + bytes_output=bytes_output, + start_time_hanging=time.perf_counter(), + ) + + # Remove any tasks that are no longer active + task_idxs_to_remove = ( + set(self._state_map[operator.id].keys()) - active_tasks_idx + ) + for task_idx in task_idxs_to_remove: + del self._state_map[operator.id][task_idx] + + hanging_op_tasks = [] + for op_id, op_state_values in self._state_map.items(): + op_task_stats = op_task_stats_map[op_id] + for task_idx, state_value in op_state_values.items(): + curr_time = time.perf_counter() - state_value.start_time_hanging + if op_task_stats.count() > self._op_task_stats_min_count: + mean = op_task_stats.mean() + stddev = op_task_stats.stddev() + threshold = mean + self._op_task_stats_std_factor_threshold * stddev + + if curr_time > threshold: + hanging_op_tasks.append(state_value) + + # create issues for newly detected hanging tasks, then update the hanging task set + issues = self._create_issues( + hanging_op_tasks=hanging_op_tasks, + op_task_stats_map=op_task_stats_map, + ) + + return issues + + def detection_time_interval_s(self) -> float: + return self._detector_cfg.detection_time_interval_s diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/detectors/hash_shuffle_detector.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/detectors/hash_shuffle_detector.py new file mode 100644 index 0000000000000000000000000000000000000000..345b5983aa38b67218c9be2cd0b287f68c9e2182 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/detectors/hash_shuffle_detector.py @@ -0,0 +1,110 @@ +import time +from typing import TYPE_CHECKING, List + +import ray +from ray.data._internal.execution.operators.hash_shuffle import ( + AggregatorHealthInfo, + HashShuffleOperator, +) +from ray.data._internal.issue_detection.issue_detector import ( + Issue, + IssueDetector, + IssueType, +) +from ray.data._internal.util import GiB + +if TYPE_CHECKING: + from ray.data._internal.execution.streaming_executor import StreamingExecutor + from ray.data.context import DataContext + + +class HashShuffleAggregatorIssueDetector(IssueDetector): + """Detector for hash shuffle aggregator health issues.""" + + def __init__(self, executor: "StreamingExecutor", ctx: "DataContext"): + super().__init__(executor, ctx) + self._last_warning_times = {} # Track per-operator warning times + + def detect(self) -> List[Issue]: + issues = [] + current_time = time.time() + + # Find all hash shuffle operators in the topology + for op in self._executor._topology.keys(): + if not isinstance(op, HashShuffleOperator): + continue + + # Skip if operator doesn't have aggregator pool yet + if op._aggregator_pool is None: + continue + + pool = op._aggregator_pool + aggregator_info = pool.check_aggregator_health() + + if aggregator_info is None: + continue + + # Check if we should emit a warning for this operator + should_warn = self._should_emit_warning( + op.id, current_time, aggregator_info + ) + + if should_warn: + message = self._format_health_warning(aggregator_info) + issues.append( + Issue( + dataset_name=self._executor._dataset_id, + operator_id=op.id, + issue_type=IssueType.HANGING, + message=message, + ) + ) + self._last_warning_times[op.id] = current_time + + return issues + + def detection_time_interval_s(self) -> float: + return self._ctx.hash_shuffle_aggregator_health_warning_interval_s + + def _should_emit_warning( + self, op_id: str, current_time: float, info: AggregatorHealthInfo + ) -> bool: + """Check if we should emit a warning for this operator.""" + if not info.has_unready_aggregators: + # Clear warning time if all aggregators are healthy + self._last_warning_times.pop(op_id, None) + return False + + # Check if enough time has passed since start + if ( + current_time - info.started_at + < self._ctx.min_hash_shuffle_aggregator_wait_time_in_s + ): + return False + + # Check if enough time has passed since last warning + last_warning = self._last_warning_times.get(op_id) + if last_warning is None: + return True + + return current_time - last_warning >= self.detection_time_interval_s() + + def _format_health_warning(self, info: AggregatorHealthInfo) -> str: + """Format the health warning message.""" + available_resources = ray.available_resources() + available_cpus = available_resources.get("CPU", 0) + cluster_resources = ray.cluster_resources() + total_memory = cluster_resources.get("memory", 0) + available_memory = available_resources.get("memory", 0) + + return ( + f"Only {info.ready_aggregators} out of {info.total_aggregators} " + f"hash-shuffle aggregators are ready after {info.wait_time:.1f} secs. " + f"This might indicate resource contention for cluster resources " + f"(available CPUs: {available_cpus}, required CPUs: {info.required_resources.cpu}). " + f"Cluster only has {available_memory / GiB:.2f} GiB available memory, required memory: {info.required_resources.memory / GiB:.2f} GiB. " + f"{total_memory / GiB:.2f} GiB total memory. " + f"Consider increasing cluster size or reducing the number of aggregators " + f"via `DataContext.max_hash_shuffle_aggregators`. " + f"Will continue checking every {self.detection_time_interval_s()}s." + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/detectors/high_memory_detector.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/detectors/high_memory_detector.py new file mode 100644 index 0000000000000000000000000000000000000000..1dbc3e20fd59ac98d73891e919c6e70712f6f846 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/issue_detection/detectors/high_memory_detector.py @@ -0,0 +1,101 @@ +import textwrap +from dataclasses import dataclass +from typing import TYPE_CHECKING, Dict, List + +from ray.data._internal.execution.operators.map_operator import MapOperator +from ray.data._internal.execution.util import memory_string +from ray.data._internal.issue_detection.issue_detector import ( + Issue, + IssueDetector, + IssueType, +) + +if TYPE_CHECKING: + from ray.data._internal.execution.streaming_executor import StreamingExecutor + from ray.data.context import DataContext + +HIGH_MEMORY_PERIODIC_WARNING = """ +Operator '{op_name}' uses {memory_per_task} of memory per task on average, but Ray +only requests {initial_memory_request} per task at the start of the pipeline. + +To avoid out-of-memory errors, consider setting `memory={memory_per_task}` in the +appropriate function or method call. (This might be unnecessary if the number of +concurrent tasks is low.) + +To change the frequency of this warning, set +`DataContext.get_current().issue_detectors_config.high_memory_detector_config.detection_time_interval_s`, +or disable the warning by setting value to -1. (current value: +{detection_time_interval_s}) +""" # noqa: E501 + + +@dataclass +class HighMemoryIssueDetectorConfig: + detection_time_interval_s: float = 30 + + +class HighMemoryIssueDetector(IssueDetector): + + # Many nodes have a 4 GiB : 1 core ratio, but this isn't always the case (e.g., for + # high memory nodes). + _MEMORY_PER_CORE_ESTIMATE = 4 * 1024**3 + + def __init__(self, executor: "StreamingExecutor", ctx: "DataContext"): + super().__init__(executor, ctx) + self._detector_cfg = ctx.issue_detectors_config.high_memory_detector_config + + self._initial_memory_requests: Dict[MapOperator, int] = {} + for op in self._executor._topology.keys(): + if isinstance(op, MapOperator): + self._initial_memory_requests[op] = ( + op._get_runtime_ray_remote_args().get("memory") or 0 + ) + + def detect(self) -> List[Issue]: + issues = [] + for op in self._executor._topology.keys(): + if not isinstance(op, MapOperator): + continue + + if op.metrics.average_max_uss_per_task is None: + continue + + remote_args = op._get_runtime_ray_remote_args() + num_cpus_per_task = remote_args.get("num_cpus", 1) + max_memory_per_task = self._MEMORY_PER_CORE_ESTIMATE * num_cpus_per_task + + if ( + op.metrics.average_max_uss_per_task > self._initial_memory_requests[op] + and op.metrics.average_max_uss_per_task >= max_memory_per_task + ): + message = HIGH_MEMORY_PERIODIC_WARNING.format( + op_name=op.name, + memory_per_task=memory_string(op.metrics.average_max_uss_per_task), + initial_memory_request=memory_string( + self._initial_memory_requests[op] + ), + detection_time_interval_s=self.detection_time_interval_s(), + ) + issues.append( + Issue( + dataset_name=self._executor._dataset_id, + operator_id=op.id, + issue_type=IssueType.HIGH_MEMORY, + message=_format_message(message), + ) + ) + + return issues + + def detection_time_interval_s(self) -> float: + return self._detector_cfg.detection_time_interval_s + + +def _format_message(message: str) -> str: + # Apply some formatting to make the message look nicer when printed. + formatted_paragraphs = [] + for paragraph in message.split("\n\n"): + formatted_paragraph = textwrap.fill(paragraph, break_long_words=False).strip() + formatted_paragraphs.append(formatted_paragraph) + formatted_message = "\n\n".join(formatted_paragraphs) + return "\n\n" + formatted_message + "\n" diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/iterator/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/iterator/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..270c9af0ac1ee73c707a08ce18019fa3d47f6c08 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/iterator/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/iterator/__pycache__/iterator_impl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/iterator/__pycache__/iterator_impl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b27e92c4128f539b844d3395a9238462ca422db Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/iterator/__pycache__/iterator_impl.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/iterator/__pycache__/stream_split_iterator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/iterator/__pycache__/stream_split_iterator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc6a9b13de3ea5016130a07fb2635bf502cd612e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/iterator/__pycache__/stream_split_iterator.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99fdb4f4c07dc908b4351911799b5fc7ed782004 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/__pycache__/optimizers.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/__pycache__/optimizers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3542e46f2522e478db0cd1c17ca159f7bed57ae Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/__pycache__/optimizers.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/__pycache__/ruleset.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/__pycache__/ruleset.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6a1abe35b09a0129ef0e25a9c84a2351882d3a6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/__pycache__/ruleset.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/__pycache__/util.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/__pycache__/util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..594868e07d69f1e018b2b31b55411090ff17d701 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/__pycache__/util.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1e6e84d908bd5a2f89fcb0f94375a7f50bf473a9 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/__init__.py @@ -0,0 +1,18 @@ +from .logical_operator import LogicalOperator +from .logical_plan import LogicalPlan +from .operator import Operator +from .optimizer import Optimizer, Rule +from .physical_plan import PhysicalPlan +from .plan import Plan +from .source_operator import SourceOperator + +__all__ = [ + "LogicalOperator", + "LogicalPlan", + "Operator", + "Optimizer", + "PhysicalPlan", + "Plan", + "Rule", + "SourceOperator", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd1e7000bb8f9a52cb0f1a95783a00801837567c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/__pycache__/logical_operator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/__pycache__/logical_operator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f24a18ef7b29621b69b63c65c5688a48cf8badd2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/__pycache__/logical_operator.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/__pycache__/logical_plan.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/__pycache__/logical_plan.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..573972f44657de3da079b620d38d788490e40004 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/__pycache__/logical_plan.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/__pycache__/operator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/__pycache__/operator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c32f41d0bbd07b13be3d2b0580c20b7fb637f46d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/__pycache__/operator.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/__pycache__/optimizer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/__pycache__/optimizer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6de5c4c19c19d22005b22ef894fdfd88c75823dd Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/__pycache__/optimizer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/__pycache__/physical_plan.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/__pycache__/physical_plan.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b8e33dbf6b734d63bace0013252cd40a69ff6ac Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/__pycache__/physical_plan.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/__pycache__/plan.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/__pycache__/plan.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64515a65603168bf82f5fe3716515c07363b458d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/__pycache__/plan.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/__pycache__/source_operator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/__pycache__/source_operator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2539dff1de9f020bc3794925473e9e596dd44113 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/__pycache__/source_operator.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/logical_operator.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/logical_operator.py new file mode 100644 index 0000000000000000000000000000000000000000..27c39840af1dfdfce5461c66847dc6cb0765094f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/logical_operator.py @@ -0,0 +1,88 @@ +from typing import TYPE_CHECKING, Any, Callable, Dict, Iterator, List, Optional + +from .operator import Operator +from ray.data.block import BlockMetadata + +if TYPE_CHECKING: + from ray.data.block import Schema + + +class LogicalOperator(Operator): + """Abstract class for logical operators. + + A logical operator describes transformation, and later is converted into + physical operator. + """ + + def __init__( + self, + name: str, + input_dependencies: List["LogicalOperator"], + num_outputs: Optional[int] = None, + ): + super().__init__( + name, + input_dependencies, + ) + for x in input_dependencies: + assert isinstance(x, LogicalOperator), x + self._num_outputs = num_outputs + + def estimated_num_outputs(self) -> Optional[int]: + """Returns the estimated number of blocks that + would be outputted by this logical operator. + + This method does not execute the plan, so it does not take into consideration + block splitting. This method only considers high-level block constraints like + `Dataset.repartition(num_blocks=X)`. A more accurate estimation can be given by + `PhysicalOperator.num_outputs_total()` during execution. + """ + if self._num_outputs is not None: + return self._num_outputs + elif len(self._input_dependencies) == 1: + return self._input_dependencies[0].estimated_num_outputs() + return None + + # Override the following 3 methods to correct type hints. + + @property + def input_dependencies(self) -> List["LogicalOperator"]: + return super().input_dependencies # type: ignore + + @property + def output_dependencies(self) -> List["LogicalOperator"]: + return super().output_dependencies # type: ignore + + def post_order_iter(self) -> Iterator["LogicalOperator"]: + return super().post_order_iter() # type: ignore + + def _apply_transform( + self, transform: Callable[["LogicalOperator"], "LogicalOperator"] + ) -> "LogicalOperator": + return super()._apply_transform(transform) # type: ignore + + def _get_args(self) -> Dict[str, Any]: + """This Dict must be serializable""" + return vars(self) + + def infer_schema(self) -> Optional["Schema"]: + """Returns the inferred schema of the output blocks.""" + return None + + def infer_metadata(self) -> "BlockMetadata": + """A ``BlockMetadata`` that represents the aggregate metadata of the outputs. + + This method is used by methods like :meth:`~ray.data.Dataset.schema` to + efficiently return metadata. + """ + return BlockMetadata(None, None, None, None) + + def is_lineage_serializable(self) -> bool: + """Returns whether the lineage of this operator can be serialized. + + An operator is lineage serializable if you can serialize it on one machine and + deserialize it on another without losing information. Operators that store + object references (e.g., ``InputData``) aren't lineage serializable because the + objects aren't available on the deserialized machine. + """ + return True diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/logical_plan.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/logical_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..3e0196bb440bbdb02ff2b112e2b68d8d2be58088 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/logical_plan.py @@ -0,0 +1,31 @@ +from typing import TYPE_CHECKING, List + +from .logical_operator import LogicalOperator +from .plan import Plan + +if TYPE_CHECKING: + from ray.data import DataContext + + +class LogicalPlan(Plan): + """The plan with a DAG of logical operators.""" + + def __init__(self, dag: LogicalOperator, context: "DataContext"): + super().__init__(context) + self._dag = dag + + @property + def dag(self) -> LogicalOperator: + """Get the DAG of logical operators.""" + return self._dag + + def sources(self) -> List[LogicalOperator]: + """List of operators that are sources for this plan's DAG.""" + # If an operator has no input dependencies, it's a source. + if not any(self._dag.input_dependencies): + return [self._dag] + + sources = [] + for op in self._dag.input_dependencies: + sources.extend(LogicalPlan(op, self._context).sources()) + return sources diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/operator.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/operator.py new file mode 100644 index 0000000000000000000000000000000000000000..09bf09acab87297a152d1bc246c49f520e67f342 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/operator.py @@ -0,0 +1,95 @@ +from typing import Callable, Iterator, List + + +class Operator: + """Abstract class for operators. + + Operators live on the driver side of the Dataset only. + """ + + def __init__( + self, + name: str, + input_dependencies: List["Operator"], + ): + self._name = name + self._input_dependencies = input_dependencies + self._output_dependencies = [] + + self._wire_output_deps(input_dependencies) + + @property + def name(self) -> str: + return self._name + + @property + def dag_str(self) -> str: + """String representation of the whole DAG.""" + if self.input_dependencies: + out_str = ", ".join([x.dag_str for x in self.input_dependencies]) + out_str += " -> " + else: + out_str = "" + out_str += f"{self.__class__.__name__}[{self._name}]" + return out_str + + @property + def input_dependencies(self) -> List["Operator"]: + """List of operators that provide inputs for this operator.""" + assert hasattr( + self, "_input_dependencies" + ), "Operator.__init__() was not called." + return self._input_dependencies + + @property + def output_dependencies(self) -> List["Operator"]: + """List of operators that consume outputs from this operator.""" + assert hasattr( + self, "_output_dependencies" + ), "Operator.__init__() was not called." + return self._output_dependencies + + def post_order_iter(self) -> Iterator["Operator"]: + """Depth-first traversal of this operator and its input dependencies.""" + for op in self.input_dependencies: + yield from op.post_order_iter() + yield self + + def _apply_transform( + self, transform: Callable[["Operator"], "Operator"] + ) -> "Operator": + """Recursively applies transformation (in post-order) to the operators DAG + + NOTE: This operation should be opting in to avoid in-place modifications, + instead creating new operations whenever any operator needs to be + updated. + """ + + transformed_input_ops = [] + new_ops = [] + + for input_op in self.input_dependencies: + transformed_input_op = input_op._apply_transform(transform) + transformed_input_ops.append(transformed_input_op) + # Keep track of new input ops + if transformed_input_op is not input_op: + new_ops.append(transformed_input_op) + + if new_ops: + # NOTE: Only newly created ops need to have output deps + # wired in + self._wire_output_deps(new_ops) + self._input_dependencies = transformed_input_ops + + return transform(self) + + def _wire_output_deps(self, input_dependencies: List["Operator"]): + for x in input_dependencies: + assert isinstance(x, Operator), x + x._output_dependencies.append(self) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}[{self._name}]" + + def __str__(self) -> str: + return repr(self) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/optimizer.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..8e5a9d1b874243ad15ab25a539f367f841d781fc --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/optimizer.py @@ -0,0 +1,47 @@ +from typing import List, Type + +from .plan import Plan + + +class Rule: + """Abstract class for optimization rule.""" + + def apply(self, plan: Plan) -> Plan: + """Apply the optimization rule to the execution plan.""" + raise NotImplementedError + + @classmethod + def dependencies(cls) -> List[Type["Rule"]]: + """List of rules that must be applied before this rule.""" + return [] + + @classmethod + def dependents(cls) -> List[Type["Rule"]]: + """List of rules that must be applied after this rule.""" + return [] + + +class Optimizer: + """Abstract class for optimizers. + + An optimizers transforms a DAG of operators with a list of predefined rules. + """ + + @property + def rules(self) -> List[Rule]: + """List of predefined rules for this optimizer.""" + raise NotImplementedError + + def optimize(self, plan: Plan) -> Plan: + """Optimize operators with a list of rules.""" + # Apply rules until the plan is not changed + previous_plan = plan + while True: + for rule in self.rules: + plan = rule.apply(plan) + # TODO: Eventually we should implement proper equality. + # Using str to check equality seems brittle + if plan.dag.dag_str == previous_plan.dag.dag_str: + break + previous_plan = plan + return plan diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/physical_plan.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/physical_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..29503831db85e7d87f1f044d7c910826fa970515 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/physical_plan.py @@ -0,0 +1,34 @@ +from typing import TYPE_CHECKING, Dict + +from .logical_operator import LogicalOperator +from .plan import Plan + +if TYPE_CHECKING: + from ray.data import DataContext + from ray.data._internal.execution.interfaces import PhysicalOperator + + +class PhysicalPlan(Plan): + """The plan with a DAG of physical operators.""" + + def __init__( + self, + dag: "PhysicalOperator", + op_map: Dict["PhysicalOperator", LogicalOperator], + context: "DataContext", + ): + super().__init__(context) + self._dag = dag + self._op_map = op_map + + @property + def dag(self) -> "PhysicalOperator": + """Get the DAG of physical operators.""" + return self._dag + + @property + def op_map(self) -> Dict["PhysicalOperator", LogicalOperator]: + """ + Get a mapping from physical operators to their corresponding logical operator. + """ + return self._op_map diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/plan.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/plan.py new file mode 100644 index 0000000000000000000000000000000000000000..8dba60277071a690d55b9a9a166cce74dca01bbc --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/plan.py @@ -0,0 +1,25 @@ +from typing import TYPE_CHECKING + +from .operator import Operator + +if TYPE_CHECKING: + from ray.data import DataContext + + +class Plan: + """Abstract class for logical/physical execution plans. + + This plan should hold an operator representing the plan DAG and any auxiliary data + that's useful for plan optimization or execution. + """ + + def __init__(self, context: "DataContext"): + self._context = context + + @property + def dag(self) -> Operator: + raise NotImplementedError + + @property + def context(self) -> "DataContext": + return self._context diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/source_operator.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/source_operator.py new file mode 100644 index 0000000000000000000000000000000000000000..1d4ef4f5aa26312c6f1797631dc144d7be8f6646 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/interfaces/source_operator.py @@ -0,0 +1,17 @@ +from abc import ABC, abstractmethod +from typing import TYPE_CHECKING, List, Optional + +if TYPE_CHECKING: + + from ray.data.dataset import RefBundle + + +class SourceOperator(ABC): + """Mixin for Logical operators that can be logical source nodes. + Subclasses: Read, InputData, FromAbstract. + """ + + @abstractmethod + def output_data(self) -> Optional[List["RefBundle"]]: + """The output data of this operator if already known, or ``None``.""" + pass diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a125c51e0bdc4886df751bfb234151dc8a15f09 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/all_to_all_operator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/all_to_all_operator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba2579150916cc4ebebdab6a6ddfac0313477f86 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/all_to_all_operator.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/count_operator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/count_operator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0ea6f87ceda0afd1498891f19a994e1cbcc552f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/count_operator.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/from_operators.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/from_operators.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbdbf1c5a3c61090ccceeaa30aa44b8f95cf9024 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/from_operators.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/input_data_operator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/input_data_operator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57b77abe500d3fe118f03b7adc5469c2958a8570 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/input_data_operator.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/join_operator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/join_operator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5eef360f85218d512b32775c70a978f1e4b6e60 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/join_operator.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/map_operator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/map_operator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4fb0386ad326806d9fe1ad9c8c6ac8440c01e39f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/map_operator.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/n_ary_operator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/n_ary_operator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b729363aac695c6fcd15b50f41aa2f971b07953 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/n_ary_operator.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/one_to_one_operator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/one_to_one_operator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fafdd5e5dc7212a0ffb6771d3f970f4ab93a81cc Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/one_to_one_operator.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/read_operator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/read_operator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..784d0fd0758ff8fbd959971bae82744d5e2137a7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/read_operator.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/streaming_split_operator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/streaming_split_operator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84a0b98a57ee8783f9f40a532cab52c0925f3c46 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/streaming_split_operator.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/write_operator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/write_operator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df5fd53fb68a5f5246e7eec1689e784da83d2f14 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/__pycache__/write_operator.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/all_to_all_operator.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/all_to_all_operator.py new file mode 100644 index 0000000000000000000000000000000000000000..224105a4700b7d4ac43d02246b424c77302cafe0 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/all_to_all_operator.py @@ -0,0 +1,205 @@ +from typing import TYPE_CHECKING, Any, Dict, List, Optional + +from ray.data._internal.logical.interfaces import LogicalOperator +from ray.data._internal.planner.exchange.interfaces import ExchangeTaskSpec +from ray.data._internal.planner.exchange.shuffle_task_spec import ShuffleTaskSpec +from ray.data._internal.planner.exchange.sort_task_spec import SortKey, SortTaskSpec +from ray.data.aggregate import AggregateFn +from ray.data.block import BlockMetadata + +if TYPE_CHECKING: + + from ray.data.block import Schema + + +class AbstractAllToAll(LogicalOperator): + """Abstract class for logical operators should be converted to physical + AllToAllOperator. + """ + + def __init__( + self, + name: str, + input_op: LogicalOperator, + num_outputs: Optional[int] = None, + sub_progress_bar_names: Optional[List[str]] = None, + ray_remote_args: Optional[Dict[str, Any]] = None, + ): + """ + Args: + name: Name for this operator. This is the name that will appear when + inspecting the logical plan of a Dataset. + input_op: The operator preceding this operator in the plan DAG. The outputs + of `input_op` will be the inputs to this operator. + num_outputs: The number of expected output bundles outputted by this + operator. + ray_remote_args: Args to provide to :func:`ray.remote`. + """ + super().__init__(name, [input_op], num_outputs) + self._num_outputs = num_outputs + self._ray_remote_args = ray_remote_args or {} + self._sub_progress_bar_names = sub_progress_bar_names + + +class RandomizeBlocks(AbstractAllToAll): + """Logical operator for randomize_block_order.""" + + def __init__( + self, + input_op: LogicalOperator, + seed: Optional[int] = None, + ): + super().__init__( + "RandomizeBlockOrder", + input_op, + ) + self._seed = seed + + def infer_metadata(self) -> "BlockMetadata": + assert len(self._input_dependencies) == 1, len(self._input_dependencies) + assert isinstance(self._input_dependencies[0], LogicalOperator) + return self._input_dependencies[0].infer_metadata() + + def infer_schema( + self, + ) -> Optional["Schema"]: + assert len(self._input_dependencies) == 1, len(self._input_dependencies) + assert isinstance(self._input_dependencies[0], LogicalOperator) + return self._input_dependencies[0].infer_schema() + + +class RandomShuffle(AbstractAllToAll): + """Logical operator for random_shuffle.""" + + def __init__( + self, + input_op: LogicalOperator, + name: str = "RandomShuffle", + seed: Optional[int] = None, + ray_remote_args: Optional[Dict[str, Any]] = None, + ): + super().__init__( + name, + input_op, + sub_progress_bar_names=[ + ExchangeTaskSpec.MAP_SUB_PROGRESS_BAR_NAME, + ExchangeTaskSpec.REDUCE_SUB_PROGRESS_BAR_NAME, + ], + ray_remote_args=ray_remote_args, + ) + self._seed = seed + + def infer_metadata(self) -> "BlockMetadata": + assert len(self._input_dependencies) == 1, len(self._input_dependencies) + assert isinstance(self._input_dependencies[0], LogicalOperator) + return self._input_dependencies[0].infer_metadata() + + def infer_schema( + self, + ) -> Optional["Schema"]: + assert len(self._input_dependencies) == 1, len(self._input_dependencies) + assert isinstance(self._input_dependencies[0], LogicalOperator) + return self._input_dependencies[0].infer_schema() + + +class Repartition(AbstractAllToAll): + """Logical operator for repartition.""" + + def __init__( + self, + input_op: LogicalOperator, + num_outputs: int, + shuffle: bool, + keys: Optional[List[str]] = None, + sort: bool = False, + ): + if shuffle: + sub_progress_bar_names = [ + ExchangeTaskSpec.MAP_SUB_PROGRESS_BAR_NAME, + ExchangeTaskSpec.REDUCE_SUB_PROGRESS_BAR_NAME, + ] + else: + sub_progress_bar_names = [ + ShuffleTaskSpec.SPLIT_REPARTITION_SUB_PROGRESS_BAR_NAME, + ] + super().__init__( + "Repartition", + input_op, + num_outputs=num_outputs, + sub_progress_bar_names=sub_progress_bar_names, + ) + self._shuffle = shuffle + self._keys = keys + self._sort = sort + + def infer_metadata(self) -> "BlockMetadata": + assert len(self._input_dependencies) == 1, len(self._input_dependencies) + assert isinstance(self._input_dependencies[0], LogicalOperator) + return self._input_dependencies[0].infer_metadata() + + def infer_schema( + self, + ) -> Optional["Schema"]: + assert len(self._input_dependencies) == 1, len(self._input_dependencies) + assert isinstance(self._input_dependencies[0], LogicalOperator) + return self._input_dependencies[0].infer_schema() + + +class Sort(AbstractAllToAll): + """Logical operator for sort.""" + + def __init__( + self, + input_op: LogicalOperator, + sort_key: SortKey, + batch_format: Optional[str] = "default", + ): + super().__init__( + "Sort", + input_op, + sub_progress_bar_names=[ + SortTaskSpec.SORT_SAMPLE_SUB_PROGRESS_BAR_NAME, + ExchangeTaskSpec.MAP_SUB_PROGRESS_BAR_NAME, + ExchangeTaskSpec.REDUCE_SUB_PROGRESS_BAR_NAME, + ], + ) + self._sort_key = sort_key + self._batch_format = batch_format + + def infer_metadata(self) -> "BlockMetadata": + assert len(self._input_dependencies) == 1, len(self._input_dependencies) + assert isinstance(self._input_dependencies[0], LogicalOperator) + return self._input_dependencies[0].infer_metadata() + + def infer_schema( + self, + ) -> Optional["Schema"]: + assert len(self._input_dependencies) == 1, len(self._input_dependencies) + assert isinstance(self._input_dependencies[0], LogicalOperator) + return self._input_dependencies[0].infer_schema() + + +class Aggregate(AbstractAllToAll): + """Logical operator for aggregate.""" + + def __init__( + self, + input_op: LogicalOperator, + key: Optional[str], + aggs: List[AggregateFn], + num_partitions: Optional[int] = None, + batch_format: Optional[str] = "default", + ): + super().__init__( + "Aggregate", + input_op, + sub_progress_bar_names=[ + SortTaskSpec.SORT_SAMPLE_SUB_PROGRESS_BAR_NAME, + ExchangeTaskSpec.MAP_SUB_PROGRESS_BAR_NAME, + ExchangeTaskSpec.REDUCE_SUB_PROGRESS_BAR_NAME, + ], + ) + self._key = key + self._aggs = aggs + self._num_partitions = num_partitions + self._batch_format = batch_format diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/count_operator.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/count_operator.py new file mode 100644 index 0000000000000000000000000000000000000000..409c99e3c000698622be3f6294d419d1c59ff2d8 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/count_operator.py @@ -0,0 +1,20 @@ +from typing import List + +from ray.data._internal.logical.interfaces import LogicalOperator + + +class Count(LogicalOperator): + """Logical operator that represents counting the number of rows in inputs. + + Physical operators that implement this logical operator should produce one or more + rows with a single column named `Count.COLUMN_NAME`. When you sum the values in + this column, you should get the total number of rows in the dataset. + """ + + COLUMN_NAME = "__num_rows" + + def __init__( + self, + input_dependencies: List["LogicalOperator"], + ): + super().__init__("Count", input_dependencies) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/from_operators.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/from_operators.py new file mode 100644 index 0000000000000000000000000000000000000000..0f6ec1a7a2d2bec2e5942c0396f12a44ea152c4d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/from_operators.py @@ -0,0 +1,111 @@ +import abc +import functools +from typing import TYPE_CHECKING, List, Optional, Union + +from ray.data._internal.execution.interfaces import RefBundle +from ray.data._internal.logical.interfaces import LogicalOperator, SourceOperator +from ray.data._internal.util import unify_ref_bundles_schema +from ray.data.block import ( + Block, + BlockMetadata, + BlockMetadataWithSchema, +) +from ray.types import ObjectRef + +if TYPE_CHECKING: + import pyarrow as pa + + ArrowTable = Union["pa.Table", bytes] + + +class AbstractFrom(LogicalOperator, SourceOperator, metaclass=abc.ABCMeta): + """Abstract logical operator for `from_*`.""" + + def __init__( + self, + input_blocks: List[ObjectRef[Block]], + input_metadata: List[BlockMetadataWithSchema], + ): + super().__init__(self.__class__.__name__, [], len(input_blocks)) + assert len(input_blocks) == len(input_metadata), ( + len(input_blocks), + len(input_metadata), + ) + # `owns_blocks` is False because this op may be shared by multiple Datasets. + self._input_data = [ + RefBundle( + [(input_blocks[i], input_metadata[i])], + owns_blocks=False, + schema=input_metadata[i].schema, + ) + for i in range(len(input_blocks)) + ] + + @property + def input_data(self) -> List[RefBundle]: + return self._input_data + + def output_data(self) -> Optional[List[RefBundle]]: + return self._input_data + + @functools.cached_property + def _cached_output_metadata(self) -> BlockMetadata: + return BlockMetadata( + num_rows=self._num_rows(), + size_bytes=self._size_bytes(), + input_files=None, + exec_stats=None, + ) + + def _num_rows(self): + if all(bundle.num_rows() is not None for bundle in self._input_data): + return sum(bundle.num_rows() for bundle in self._input_data) + else: + return None + + def _size_bytes(self): + metadata = [m for bundle in self._input_data for m in bundle.metadata] + if all(m.size_bytes is not None for m in metadata): + return sum(m.size_bytes for m in metadata) + else: + return None + + def infer_metadata(self) -> BlockMetadata: + return self._cached_output_metadata + + def infer_schema(self): + return unify_ref_bundles_schema(self._input_data) + + def is_lineage_serializable(self) -> bool: + # This operator isn't serializable because it contains ObjectRefs. + return False + + +class FromItems(AbstractFrom): + """Logical operator for `from_items`.""" + + pass + + +class FromBlocks(AbstractFrom): + """Logical operator for `from_blocks`.""" + + pass + + +class FromNumpy(AbstractFrom): + """Logical operator for `from_numpy`.""" + + pass + + +class FromArrow(AbstractFrom): + """Logical operator for `from_arrow`.""" + + pass + + +class FromPandas(AbstractFrom): + """Logical operator for `from_pandas`.""" + + pass diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/input_data_operator.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/input_data_operator.py new file mode 100644 index 0000000000000000000000000000000000000000..373a12e8496106194cddee614b954095aecc2a1c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/input_data_operator.py @@ -0,0 +1,56 @@ +import functools +from typing import List, Optional + +from ray.data._internal.execution.interfaces import RefBundle +from ray.data._internal.logical.interfaces import LogicalOperator, SourceOperator +from ray.data._internal.util import unify_schemas_with_validation +from ray.data.block import BlockMetadata + + +class InputData(LogicalOperator, SourceOperator): + """Logical operator for input data. + + This may hold cached blocks from a previous Dataset execution. + """ + + def __init__( + self, + input_data: List[RefBundle], + ): + super().__init__("InputData", [], len(input_data)) + self.input_data = input_data + + def output_data(self) -> Optional[List[RefBundle]]: + return self.input_data + + def infer_metadata(self) -> BlockMetadata: + return self._cached_output_metadata + + @functools.cached_property + def _cached_output_metadata(self) -> BlockMetadata: + return BlockMetadata( + num_rows=self._num_rows(), + size_bytes=self._size_bytes(), + input_files=None, + exec_stats=None, + ) + + def _num_rows(self): + if all(bundle.num_rows() is not None for bundle in self.input_data): + return sum(bundle.num_rows() for bundle in self.input_data) + else: + return None + + def _size_bytes(self): + metadata = [m for bundle in self.input_data for m in bundle.metadata] + if all(m.size_bytes is not None for m in metadata): + return sum(m.size_bytes for m in metadata) + else: + return None + + def infer_schema(self): + return unify_schemas_with_validation([data.schema for data in self.input_data]) + + def is_lineage_serializable(self) -> bool: + # This operator isn't serializable because it contains ObjectRefs. + return False diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/join_operator.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/join_operator.py new file mode 100644 index 0000000000000000000000000000000000000000..eeca27044f521579e4b690284ecd033393810ddf --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/join_operator.py @@ -0,0 +1,121 @@ +from enum import Enum +from typing import TYPE_CHECKING, Any, Dict, Optional, Sequence, Tuple + +from ray.data._internal.logical.interfaces import LogicalOperator +from ray.data._internal.logical.operators.n_ary_operator import NAry + +if TYPE_CHECKING: + from ray.data import Schema + + +class JoinType(Enum): + INNER = "inner" + LEFT_OUTER = "left_outer" + RIGHT_OUTER = "right_outer" + FULL_OUTER = "full_outer" + LEFT_SEMI = "left_semi" + RIGHT_SEMI = "right_semi" + LEFT_ANTI = "left_anti" + RIGHT_ANTI = "right_anti" + + +class Join(NAry): + """Logical operator for join.""" + + def __init__( + self, + left_input_op: LogicalOperator, + right_input_op: LogicalOperator, + join_type: str, + left_key_columns: Tuple[str], + right_key_columns: Tuple[str], + *, + num_partitions: int, + left_columns_suffix: Optional[str] = None, + right_columns_suffix: Optional[str] = None, + partition_size_hint: Optional[int] = None, + aggregator_ray_remote_args: Optional[Dict[str, Any]] = None, + ): + """ + Args: + left_input_op: The input operator at left hand side. + right_input_op: The input operator at right hand side. + join_type: The kind of join that should be performed, one of ("inner", + "left_outer", "right_outer", "full_outer", "left_semi", "right_semi", + "left_anti", "right_anti"). + left_key_columns: The columns from the left Dataset that should be used as + keys of the join operation. + right_key_columns: The columns from the right Dataset that should be used as + keys of the join operation. + partition_size_hint: Hint to joining operator about the estimated + avg expected size of the resulting partition (in bytes) + num_partitions: Total number of expected blocks outputted by this + operator. + """ + + try: + join_type_enum = JoinType(join_type) + except ValueError: + raise ValueError( + f"Invalid join type: '{join_type}'. " + f"Supported join types are: {', '.join(jt.value for jt in JoinType)}." + ) + + super().__init__(left_input_op, right_input_op, num_outputs=num_partitions) + + self._left_key_columns = left_key_columns + self._right_key_columns = right_key_columns + self._join_type = join_type_enum + + self._left_columns_suffix = left_columns_suffix + self._right_columns_suffix = right_columns_suffix + + self._partition_size_hint = partition_size_hint + self._aggregator_ray_remote_args = aggregator_ray_remote_args + + @staticmethod + def _validate_schemas( + left_op_schema: "Schema", + right_op_schema: "Schema", + left_key_column_names: Tuple[str], + right_key_column_names: Tuple[str], + ): + def _col_names_as_str(keys: Sequence[str]): + keys_joined = ", ".join(map(lambda k: f"'{k}'", keys)) + return f"[{keys_joined}]" + + if len(left_key_column_names) < 1: + raise ValueError( + f"At least 1 column name to join on has to be provided (got " + f"{_col_names_as_str(left_key_column_names)})" + ) + + if len(left_key_column_names) != len(right_key_column_names): + raise ValueError( + f"Number of columns provided for left and right datasets has to match " + f"(got {_col_names_as_str(left_key_column_names)} and " + f"{_col_names_as_str(right_key_column_names)})" + ) + + def _get_key_column_types(schema: "Schema", keys: Tuple[str]): + return ( + [ + _type + for name, _type in zip(schema.names, schema.types) + if name in keys + ] + if schema + else None + ) + + right_op_key_cols = _get_key_column_types( + right_op_schema, left_key_column_names + ) + left_op_key_cols = _get_key_column_types(left_op_schema, right_key_column_names) + + if left_op_key_cols != right_op_key_cols: + raise ValueError( + f"Key columns are expected to be present and have the same types " + "in both left and right operands of the join operation: " + f"left has {left_op_schema}, but right has {right_op_schema}" + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/map_operator.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/map_operator.py new file mode 100644 index 0000000000000000000000000000000000000000..6b1bcefba5ad9e2191b9261bf9652976062b0464 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/map_operator.py @@ -0,0 +1,362 @@ +import functools +import inspect +import logging +from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional + +from ray.data._internal.compute import ComputeStrategy, TaskPoolStrategy +from ray.data._internal.logical.interfaces import LogicalOperator +from ray.data._internal.logical.operators.one_to_one_operator import AbstractOneToOne +from ray.data.block import UserDefinedFunction +from ray.data.expressions import Expr +from ray.data.preprocessor import Preprocessor + +if TYPE_CHECKING: + import pyarrow as pa + + +logger = logging.getLogger(__name__) + + +class AbstractMap(AbstractOneToOne): + """Abstract class for logical operators that should be converted to physical + MapOperator. + """ + + def __init__( + self, + name: str, + input_op: Optional[LogicalOperator] = None, + num_outputs: Optional[int] = None, + *, + min_rows_per_bundled_input: Optional[int] = None, + ray_remote_args: Optional[Dict[str, Any]] = None, + ray_remote_args_fn: Optional[Callable[[], Dict[str, Any]]] = None, + compute: Optional[ComputeStrategy] = None, + ): + """ + Args: + name: Name for this operator. This is the name that will appear when + inspecting the logical plan of a Dataset. + input_op: The operator preceding this operator in the plan DAG. The outputs + of `input_op` will be the inputs to this operator. + min_rows_per_bundled_input: Min number of rows a single bundle of blocks + passed on to the task must possess. + ray_remote_args: Args to provide to :func:`ray.remote`. + ray_remote_args_fn: A function that returns a dictionary of remote args + passed to each map worker. The purpose of this argument is to generate + dynamic arguments for each actor/task, and will be called each time + prior to initializing the worker. Args returned from this dict + always override the args in ``ray_remote_args``. Note: this is an + advanced, experimental feature. + """ + super().__init__(name, input_op, num_outputs) + self._min_rows_per_bundled_input = min_rows_per_bundled_input + self._ray_remote_args = ray_remote_args or {} + self._ray_remote_args_fn = ray_remote_args_fn + self._compute = compute or TaskPoolStrategy() + + +class AbstractUDFMap(AbstractMap): + """Abstract class for logical operators performing a UDF that should be converted + to physical MapOperator. + """ + + def __init__( + self, + name: str, + input_op: LogicalOperator, + fn: UserDefinedFunction, + *, + fn_args: Optional[Iterable[Any]] = None, + fn_kwargs: Optional[Dict[str, Any]] = None, + fn_constructor_args: Optional[Iterable[Any]] = None, + fn_constructor_kwargs: Optional[Dict[str, Any]] = None, + min_rows_per_bundled_input: Optional[int] = None, + compute: Optional[ComputeStrategy] = None, + ray_remote_args_fn: Optional[Callable[[], Dict[str, Any]]] = None, + ray_remote_args: Optional[Dict[str, Any]] = None, + ): + """ + Args: + name: Name for this operator. This is the name that will appear when + inspecting the logical plan of a Dataset. + input_op: The operator preceding this operator in the plan DAG. The outputs + of `input_op` will be the inputs to this operator. + fn: User-defined function to be called. + fn_args: Arguments to `fn`. + fn_kwargs: Keyword arguments to `fn`. + fn_constructor_args: Arguments to provide to the initializor of `fn` if + `fn` is a callable class. + fn_constructor_kwargs: Keyword Arguments to provide to the initializor of + `fn` if `fn` is a callable class. + min_rows_per_bundled_input: The target number of rows to pass to + ``MapOperator._add_bundled_input()``. + compute: The compute strategy, either ``TaskPoolStrategy`` (default) to use + Ray tasks, or ``ActorPoolStrategy`` to use an autoscaling actor pool. + ray_remote_args_fn: A function that returns a dictionary of remote args + passed to each map worker. The purpose of this argument is to generate + dynamic arguments for each actor/task, and will be called each time + prior to initializing the worker. Args returned from this dict will + always override the args in ``ray_remote_args``. Note: this is an + advanced, experimental feature. + ray_remote_args: Args to provide to :func:`ray.remote`. + """ + name = self._get_operator_name(name, fn) + super().__init__( + name, + input_op, + min_rows_per_bundled_input=min_rows_per_bundled_input, + ray_remote_args=ray_remote_args, + compute=compute, + ) + self._fn = fn + self._fn_args = fn_args + self._fn_kwargs = fn_kwargs + self._fn_constructor_args = fn_constructor_args + self._fn_constructor_kwargs = fn_constructor_kwargs + self._ray_remote_args_fn = ray_remote_args_fn + + def _get_operator_name(self, op_name: str, fn: UserDefinedFunction): + """Gets the Operator name including the map `fn` UDF name.""" + # If the input `fn` is a Preprocessor, the + # name is simply the name of the Preprocessor class. + if inspect.ismethod(fn) and isinstance(fn.__self__, Preprocessor): + return fn.__self__.__class__.__name__ + + # Otherwise, it takes the form of `()`, + # e.g. `MapBatches(my_udf)`. + try: + if inspect.isclass(fn): + # callable class + return f"{op_name}({fn.__name__})" + elif inspect.ismethod(fn): + # class method + return f"{op_name}({fn.__self__.__class__.__name__}.{fn.__name__})" + elif inspect.isfunction(fn): + # normal function or lambda function. + return f"{op_name}({fn.__name__})" + elif isinstance(fn, functools.partial): + # functools.partial + return f"{op_name}({fn.func.__name__})" + else: + # callable object. + return f"{op_name}({fn.__class__.__name__})" + except AttributeError as e: + logger.error("Failed to get name of UDF %s: %s", fn, e) + return "" + + +class MapBatches(AbstractUDFMap): + """Logical operator for map_batches.""" + + def __init__( + self, + input_op: LogicalOperator, + fn: UserDefinedFunction, + batch_size: Optional[int] = None, + batch_format: str = "default", + zero_copy_batch: bool = False, + fn_args: Optional[Iterable[Any]] = None, + fn_kwargs: Optional[Dict[str, Any]] = None, + fn_constructor_args: Optional[Iterable[Any]] = None, + fn_constructor_kwargs: Optional[Dict[str, Any]] = None, + min_rows_per_bundled_input: Optional[int] = None, + compute: Optional[ComputeStrategy] = None, + ray_remote_args_fn: Optional[Callable[[], Dict[str, Any]]] = None, + ray_remote_args: Optional[Dict[str, Any]] = None, + ): + super().__init__( + "MapBatches", + input_op, + fn, + fn_args=fn_args, + fn_kwargs=fn_kwargs, + fn_constructor_args=fn_constructor_args, + fn_constructor_kwargs=fn_constructor_kwargs, + min_rows_per_bundled_input=min_rows_per_bundled_input, + compute=compute, + ray_remote_args_fn=ray_remote_args_fn, + ray_remote_args=ray_remote_args, + ) + self._batch_size = batch_size + self._batch_format = batch_format + self._zero_copy_batch = zero_copy_batch + + def can_modify_num_rows(self) -> bool: + return False + + +class MapRows(AbstractUDFMap): + """Logical operator for map.""" + + def __init__( + self, + input_op: LogicalOperator, + fn: UserDefinedFunction, + fn_args: Optional[Iterable[Any]] = None, + fn_kwargs: Optional[Dict[str, Any]] = None, + fn_constructor_args: Optional[Iterable[Any]] = None, + fn_constructor_kwargs: Optional[Dict[str, Any]] = None, + compute: Optional[ComputeStrategy] = None, + ray_remote_args_fn: Optional[Callable[[], Dict[str, Any]]] = None, + ray_remote_args: Optional[Dict[str, Any]] = None, + ): + super().__init__( + "Map", + input_op, + fn, + fn_args=fn_args, + fn_kwargs=fn_kwargs, + fn_constructor_args=fn_constructor_args, + fn_constructor_kwargs=fn_constructor_kwargs, + compute=compute, + ray_remote_args_fn=ray_remote_args_fn, + ray_remote_args=ray_remote_args, + ) + + def can_modify_num_rows(self) -> bool: + return False + + +class Filter(AbstractUDFMap): + """Logical operator for filter.""" + + def __init__( + self, + input_op: LogicalOperator, + fn: Optional[UserDefinedFunction] = None, + fn_args: Optional[Iterable[Any]] = None, + fn_kwargs: Optional[Dict[str, Any]] = None, + fn_constructor_args: Optional[Iterable[Any]] = None, + fn_constructor_kwargs: Optional[Dict[str, Any]] = None, + filter_expr: Optional["pa.dataset.Expression"] = None, + compute: Optional[ComputeStrategy] = None, + ray_remote_args_fn: Optional[Callable[[], Dict[str, Any]]] = None, + ray_remote_args: Optional[Dict[str, Any]] = None, + ): + # Ensure exactly one of fn or filter_expr is provided + if not ((fn is None) ^ (filter_expr is None)): + raise ValueError("Exactly one of 'fn' or 'filter_expr' must be provided") + self._filter_expr = filter_expr + + super().__init__( + "Filter", + input_op, + fn=fn, + fn_args=fn_args, + fn_kwargs=fn_kwargs, + fn_constructor_args=fn_constructor_args, + fn_constructor_kwargs=fn_constructor_kwargs, + compute=compute, + ray_remote_args_fn=ray_remote_args_fn, + ray_remote_args=ray_remote_args, + ) + + def can_modify_num_rows(self) -> bool: + return True + + +class Project(AbstractMap): + """Logical operator for select_columns.""" + + def __init__( + self, + input_op: LogicalOperator, + cols: Optional[List[str]] = None, + cols_rename: Optional[Dict[str, str]] = None, + exprs: Optional[ + Dict[str, "Expr"] + ] = None, # TODO Remove cols and cols_rename and replace them with corresponding exprs + compute: Optional[ComputeStrategy] = None, + ray_remote_args: Optional[Dict[str, Any]] = None, + ): + super().__init__( + "Project", + input_op=input_op, + ray_remote_args=ray_remote_args, + compute=compute, + ) + self._batch_size = None + self._cols = cols + self._cols_rename = cols_rename + self._exprs = exprs + self._batch_format = "pyarrow" + self._zero_copy_batch = True + + if exprs is not None: + # Validate that all values are expressions + for name, expr in exprs.items(): + if not isinstance(expr, Expr): + raise TypeError( + f"Expected Expr for column '{name}', got {type(expr)}" + ) + + @property + def cols(self) -> Optional[List[str]]: + return self._cols + + @property + def cols_rename(self) -> Optional[Dict[str, str]]: + return self._cols_rename + + @property + def exprs(self) -> Optional[Dict[str, "Expr"]]: + return self._exprs + + def can_modify_num_rows(self) -> bool: + return False + + +class FlatMap(AbstractUDFMap): + """Logical operator for flat_map.""" + + def __init__( + self, + input_op: LogicalOperator, + fn: UserDefinedFunction, + fn_args: Optional[Iterable[Any]] = None, + fn_kwargs: Optional[Dict[str, Any]] = None, + fn_constructor_args: Optional[Iterable[Any]] = None, + fn_constructor_kwargs: Optional[Dict[str, Any]] = None, + compute: Optional[ComputeStrategy] = None, + ray_remote_args_fn: Optional[Callable[[], Dict[str, Any]]] = None, + ray_remote_args: Optional[Dict[str, Any]] = None, + ): + super().__init__( + "FlatMap", + input_op, + fn, + fn_args=fn_args, + fn_kwargs=fn_kwargs, + fn_constructor_args=fn_constructor_args, + fn_constructor_kwargs=fn_constructor_kwargs, + compute=compute, + ray_remote_args_fn=ray_remote_args_fn, + ray_remote_args=ray_remote_args, + ) + + def can_modify_num_rows(self) -> bool: + return True + + +class StreamingRepartition(AbstractMap): + """Logical operator for streaming repartition operation. + Args: + target_num_rows_per_block: The target number of rows per block granularity for + streaming repartition. + """ + + def __init__( + self, + input_op: LogicalOperator, + target_num_rows_per_block: int, + ): + super().__init__("StreamingRepartition", input_op) + self._target_num_rows_per_block = target_num_rows_per_block + + @property + def target_num_rows_per_block(self) -> int: + return self._target_num_rows_per_block + + def can_modify_num_rows(self) -> bool: + return False diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/n_ary_operator.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/n_ary_operator.py new file mode 100644 index 0000000000000000000000000000000000000000..7977fafdf74e53798085b67d30683e7be40098f4 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/n_ary_operator.py @@ -0,0 +1,60 @@ +from typing import Optional + +from ray.data._internal.logical.interfaces import LogicalOperator + + +class NAry(LogicalOperator): + """Base class for n-ary operators, which take multiple input operators.""" + + def __init__( + self, + *input_ops: LogicalOperator, + num_outputs: Optional[int] = None, + ): + """ + Args: + input_ops: The input operators. + """ + super().__init__(self.__class__.__name__, list(input_ops), num_outputs) + + +class Zip(NAry): + """Logical operator for zip.""" + + def __init__( + self, + left_input_op: LogicalOperator, + right_input_op: LogicalOperator, + ): + """ + Args: + left_input_op: The input operator at left hand side. + right_input_op: The input operator at right hand side. + """ + super().__init__(left_input_op, right_input_op) + + def estimated_num_outputs(self): + left_num_outputs = self._input_dependencies[0].estimated_num_outputs() + right_num_outputs = self._input_dependencies[1].estimated_num_outputs() + if left_num_outputs is None or right_num_outputs is None: + return None + return max(left_num_outputs, right_num_outputs) + + +class Union(NAry): + """Logical operator for union.""" + + def __init__( + self, + *input_ops: LogicalOperator, + ): + super().__init__(*input_ops) + + def estimated_num_outputs(self): + total_num_outputs = 0 + for input in self._input_dependencies: + num_outputs = input.estimated_num_outputs() + if num_outputs is None: + return None + total_num_outputs += num_outputs + return total_num_outputs diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/one_to_one_operator.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/one_to_one_operator.py new file mode 100644 index 0000000000000000000000000000000000000000..d9195aebcbdbcde0b3e159b36fad1f010a78b847 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/one_to_one_operator.py @@ -0,0 +1,85 @@ +from typing import TYPE_CHECKING, Optional + +from ray.data._internal.logical.interfaces import LogicalOperator +from ray.data.block import BlockMetadata + +if TYPE_CHECKING: + + from ray.data.block import Schema + + +class AbstractOneToOne(LogicalOperator): + """Abstract class for one-to-one logical operators, which + have one input and one output dependency. + """ + + def __init__( + self, + name: str, + input_op: Optional[LogicalOperator], + num_outputs: Optional[int] = None, + ): + """ + Args: + name: Name for this operator. This is the name that will appear when + inspecting the logical plan of a Dataset. + input_op: The operator preceding this operator in the plan DAG. The outputs + of `input_op` will be the inputs to this operator. + """ + super().__init__(name, [input_op] if input_op else [], num_outputs) + + @property + def input_dependency(self) -> LogicalOperator: + return self._input_dependencies[0] + + def can_modify_num_rows(self) -> bool: + """Whether this operator can modify the number of rows, + i.e. number of input rows != number of output rows.""" + ... + + +class Limit(AbstractOneToOne): + """Logical operator for limit.""" + + def __init__( + self, + input_op: LogicalOperator, + limit: int, + ): + super().__init__( + f"limit={limit}", + input_op, + ) + self._limit = limit + + def can_modify_num_rows(self) -> bool: + return True + + def infer_metadata(self) -> BlockMetadata: + return BlockMetadata( + num_rows=self._num_rows(), + size_bytes=None, + input_files=self._input_files(), + exec_stats=None, + ) + + def infer_schema( + self, + ) -> Optional["Schema"]: + assert len(self._input_dependencies) == 1, len(self._input_dependencies) + assert isinstance(self._input_dependencies[0], LogicalOperator) + return self._input_dependencies[0].infer_schema() + + def _num_rows(self): + assert len(self._input_dependencies) == 1, len(self._input_dependencies) + assert isinstance(self._input_dependencies[0], LogicalOperator) + input_rows = self._input_dependencies[0].infer_metadata().num_rows + if input_rows is not None: + return min(input_rows, self._limit) + else: + return None + + def _input_files(self): + assert len(self._input_dependencies) == 1, len(self._input_dependencies) + assert isinstance(self._input_dependencies[0], LogicalOperator) + return self._input_dependencies[0].infer_metadata().input_files diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/read_operator.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/read_operator.py new file mode 100644 index 0000000000000000000000000000000000000000..aef39c554d23c51a2618f6747fb8f7c58d41c334 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/read_operator.py @@ -0,0 +1,117 @@ +import functools +from typing import Any, Dict, Optional, Union + +from ray.data._internal.logical.interfaces import SourceOperator +from ray.data._internal.logical.operators.map_operator import AbstractMap +from ray.data.block import ( + BlockMetadata, + BlockMetadataWithSchema, +) +from ray.data.datasource.datasource import Datasource, Reader + + +class Read(AbstractMap, SourceOperator): + """Logical operator for read.""" + + def __init__( + self, + datasource: Datasource, + datasource_or_legacy_reader: Union[Datasource, Reader], + parallelism: int, + mem_size: Optional[int], + num_outputs: Optional[int] = None, + ray_remote_args: Optional[Dict[str, Any]] = None, + concurrency: Optional[int] = None, + ): + super().__init__( + f"Read{datasource.get_name()}", + None, + num_outputs, + ray_remote_args=ray_remote_args, + ) + self._datasource = datasource + self._datasource_or_legacy_reader = datasource_or_legacy_reader + self._parallelism = parallelism + self._mem_size = mem_size + self._concurrency = concurrency + self._detected_parallelism = None + + def output_data(self): + return None + + def set_detected_parallelism(self, parallelism: int): + """ + Set the true parallelism that should be used during execution. This + should be specified by the user or detected by the optimizer. + """ + self._detected_parallelism = parallelism + + def get_detected_parallelism(self) -> int: + """ + Get the true parallelism that should be used during execution. + """ + return self._detected_parallelism + + def infer_metadata(self) -> BlockMetadata: + """A ``BlockMetadata`` that represents the aggregate metadata of the outputs. + + This method gets metadata from the read tasks. It doesn't trigger any actual + execution. + """ + return self._cached_output_metadata.metadata + + def infer_schema(self): + return self._cached_output_metadata.schema + + @functools.cached_property + def _cached_output_metadata(self) -> "BlockMetadataWithSchema": + # Legacy datasources might not implement `get_read_tasks`. + if self._datasource.should_create_reader: + empty_meta = BlockMetadata(None, None, None, None) + return BlockMetadataWithSchema(metadata=empty_meta, schema=None) + + # HACK: Try to get a single read task to get the metadata. + read_tasks = self._datasource.get_read_tasks(1) + if len(read_tasks) == 0: + # If there are no read tasks, the dataset is probably empty. + empty_meta = BlockMetadata(None, None, None, None) + return BlockMetadataWithSchema(metadata=empty_meta, schema=None) + + # `get_read_tasks` isn't guaranteed to return exactly one read task. + metadata = [read_task.metadata for read_task in read_tasks] + + if all(meta.num_rows is not None for meta in metadata): + num_rows = sum(meta.num_rows for meta in metadata) + else: + num_rows = None + + if all(meta.size_bytes is not None for meta in metadata): + size_bytes = sum(meta.size_bytes for meta in metadata) + else: + size_bytes = None + + input_files = [] + for meta in metadata: + if meta.input_files is not None: + input_files.extend(meta.input_files) + + meta = BlockMetadata( + num_rows=num_rows, + size_bytes=size_bytes, + input_files=input_files, + exec_stats=None, + ) + schemas = [ + read_task.schema for read_task in read_tasks if read_task.schema is not None + ] + from ray.data._internal.util import unify_schemas_with_validation + + schema = None + if schemas: + schema = unify_schemas_with_validation(schemas) + return BlockMetadataWithSchema(metadata=meta, schema=schema) + + def can_modify_num_rows(self) -> bool: + # NOTE: Returns true, since most of the readers expands its input + # and produce many rows for every single row of the input + return True diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/streaming_split_operator.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/streaming_split_operator.py new file mode 100644 index 0000000000000000000000000000000000000000..aca15639504395d224f0a95ee88a53e20012937b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/streaming_split_operator.py @@ -0,0 +1,20 @@ +from typing import List, Optional + +from ray.data import NodeIdStr +from ray.data._internal.logical.interfaces import LogicalOperator + + +class StreamingSplit(LogicalOperator): + """Logical operator that represents splitting the input data to `n` splits.""" + + def __init__( + self, + input_op: LogicalOperator, + num_splits: int, + equal: bool, + locality_hints: Optional[List[NodeIdStr]] = None, + ): + super().__init__("StreamingSplit", [input_op]) + self._num_splits = num_splits + self._equal = equal + self._locality_hints = locality_hints diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/write_operator.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/write_operator.py new file mode 100644 index 0000000000000000000000000000000000000000..bbf0159fa4f36aacc1c4ed82892226d20b7ca8f9 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/operators/write_operator.py @@ -0,0 +1,35 @@ +from typing import Any, Dict, Optional, Union + +from ray.data._internal.logical.interfaces import LogicalOperator +from ray.data._internal.logical.operators.map_operator import AbstractMap +from ray.data.datasource.datasink import Datasink +from ray.data.datasource.datasource import Datasource + + +class Write(AbstractMap): + """Logical operator for write.""" + + def __init__( + self, + input_op: LogicalOperator, + datasink_or_legacy_datasource: Union[Datasink, Datasource], + ray_remote_args: Optional[Dict[str, Any]] = None, + concurrency: Optional[int] = None, + **write_args, + ): + if isinstance(datasink_or_legacy_datasource, Datasink): + min_rows_per_bundled_input = ( + datasink_or_legacy_datasource.min_rows_per_write + ) + else: + min_rows_per_bundled_input = None + + super().__init__( + "Write", + input_op, + min_rows_per_bundled_input=min_rows_per_bundled_input, + ray_remote_args=ray_remote_args, + ) + self._datasink_or_legacy_datasource = datasink_or_legacy_datasource + self._write_args = write_args + self._concurrency = concurrency diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4994268c0736ecdfe21f7a7360f89f13934edfed --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/__init__.py @@ -0,0 +1,3 @@ +from ray.data._internal.logical.rules.operator_fusion import FuseOperators + +__all__ = ["FuseOperators"] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9be21574ee73819f6c5a6f09aec1e8a1d31810ef Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/__pycache__/configure_map_task_memory.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/__pycache__/configure_map_task_memory.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be98992a0bc580be584c9a820606f7c9da98c2ad Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/__pycache__/configure_map_task_memory.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/__pycache__/inherit_batch_format.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/__pycache__/inherit_batch_format.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..897cf660a296718743a64dbc92650999be7c35ad Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/__pycache__/inherit_batch_format.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/__pycache__/inherit_target_max_block_size.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/__pycache__/inherit_target_max_block_size.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cadfb8e832eeee33967074c1f296564e3b9368be Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/__pycache__/inherit_target_max_block_size.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/__pycache__/limit_pushdown.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/__pycache__/limit_pushdown.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b15b1cffed053ed3c0794ccf561abae03c9411f2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/__pycache__/limit_pushdown.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/__pycache__/operator_fusion.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/__pycache__/operator_fusion.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f497b5642e7f7674c200d8fd17a9ebbc8b7c585 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/__pycache__/operator_fusion.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/__pycache__/set_read_parallelism.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/__pycache__/set_read_parallelism.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3479e8761f94de5ad4fcea1b3aa2689f03748ed7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/__pycache__/set_read_parallelism.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/__pycache__/zero_copy_map_fusion.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/__pycache__/zero_copy_map_fusion.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56bce25a10a92005822497463015f653dbca66a7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/__pycache__/zero_copy_map_fusion.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/configure_map_task_memory.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/configure_map_task_memory.py new file mode 100644 index 0000000000000000000000000000000000000000..c805159274682d0aa109d66a18f078ae99b63f85 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/configure_map_task_memory.py @@ -0,0 +1,81 @@ +import abc +import copy +from typing import Any, Dict, Optional + +from ray.data._internal.execution.operators.map_operator import MapOperator +from ray.data._internal.logical.interfaces import Rule +from ray.data._internal.logical.interfaces.physical_plan import PhysicalPlan +from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy + + +class ConfigureMapTaskMemoryRule(Rule, abc.ABC): + def apply(self, plan: PhysicalPlan) -> PhysicalPlan: + for op in plan.dag.post_order_iter(): + if not isinstance(op, MapOperator): + continue + + def ray_remote_args_fn( + op: MapOperator = op, original_ray_remote_args_fn=op._ray_remote_args_fn + ) -> Dict[str, Any]: + assert isinstance(op, MapOperator), op + + static_ray_remote_args = copy.deepcopy(op._ray_remote_args) + + dynamic_ray_remote_args = {} + if original_ray_remote_args_fn is not None: + dynamic_ray_remote_args = original_ray_remote_args_fn() + + if ( + "memory" not in static_ray_remote_args + and "memory" not in dynamic_ray_remote_args + # If this rule configures memory but the user hasn't specified + # memory in the placement group, then Ray won't be able to + # schedule tasks. + and not any( + isinstance( + scheduling_strategy, PlacementGroupSchedulingStrategy + ) + for scheduling_strategy in ( + static_ray_remote_args.get("scheduling_strategy"), + dynamic_ray_remote_args.get("scheduling_strategy"), + op.data_context.scheduling_strategy, + op.data_context.scheduling_strategy_large_args, + ) + ) + ): + memory = self.estimate_per_task_memory_requirement(op) + if memory is not None: + dynamic_ray_remote_args["memory"] = memory + + return dynamic_ray_remote_args + + op._ray_remote_args_fn = ray_remote_args_fn + + return plan + + @abc.abstractmethod + def estimate_per_task_memory_requirement(self, op: MapOperator) -> Optional[int]: + """Estimate the per-task memory requirement for the given map operator. + + This is used to configure the `memory` argument in `ray.remote`. + """ + ... + + +class ConfigureMapTaskMemoryUsingOutputSize(ConfigureMapTaskMemoryRule): + def estimate_per_task_memory_requirement(self, op: MapOperator) -> Optional[int]: + # Typically, this configuration won't make a difference because + # `average_bytes_per_output` is usually ~128 MiB and each core usually has + # 4 GiB of memory. However, if `num_cpus` is small (e.g., 0.01) or + # `target_max_block_size` is large (e.g., 1GB), then tasks can OOM even + # if it just uses enough memory to produce an output block. By setting + # `memory` to the average output size, we can mitigate this case. + # + # We set it to 1 target block size out of assumption that *at least* 1 copy + # of data (to process heap) will be made during processing. + # + # Note that, unless object store memory is manually specified, by default Ray's + # "memory" resource is exclusive of the Object Store memory allocated on the + # node (i.e., its total allocatable value is Total memory - Object Store + # memory). + return op.metrics.average_bytes_per_output diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/inherit_batch_format.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/inherit_batch_format.py new file mode 100644 index 0000000000000000000000000000000000000000..2dd265cd08b119250d08dcf71691e1b3701fb08a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/inherit_batch_format.py @@ -0,0 +1,42 @@ +from collections import deque +from typing import Iterable + +from ray.data._internal.logical.interfaces import LogicalOperator, LogicalPlan, Rule +from ray.data._internal.logical.operators.all_to_all_operator import AbstractAllToAll +from ray.data._internal.logical.operators.map_operator import MapBatches + + +class InheritBatchFormatRule(Rule): + """For AbstractAllToAll based operator, apply this rule + to inherit batch_format from upstream operator by traversing + the entire DAG.""" + + def apply(self, plan: LogicalPlan) -> LogicalPlan: + optimized_dag: LogicalOperator = self._apply(plan.dag) + new_plan = LogicalPlan(dag=optimized_dag, context=plan.context) + return new_plan + + def _apply(self, op: LogicalOperator): + # Post-order traversal. + nodes: Iterable[LogicalOperator] = deque() + for node in op.post_order_iter(): + nodes.appendleft(node) + + while len(nodes) > 0: + current_op = nodes.pop() + + if isinstance(current_op, AbstractAllToAll): + # traversal up the DAG until we find MapBatches with batch_format + # or we reach to source op and do nothing + upstream_op = current_op.input_dependencies[0] + while upstream_op.input_dependencies: + if ( + isinstance(upstream_op, MapBatches) + and upstream_op._batch_format + ): + current_op._batch_format = upstream_op._batch_format + break + upstream_op = upstream_op.input_dependencies[0] + + # just return the default op + return op diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/inherit_target_max_block_size.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/inherit_target_max_block_size.py new file mode 100644 index 0000000000000000000000000000000000000000..298ff6c4edbff9cfab6ea14418dc61b81c93e1e8 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/inherit_target_max_block_size.py @@ -0,0 +1,30 @@ +from typing import Optional + +from ray.data._internal.execution.interfaces import PhysicalOperator +from ray.data._internal.logical.interfaces import PhysicalPlan, Rule + + +class InheritTargetMaxBlockSizeRule(Rule): + """For each op that has overridden the default target max block size, + propagate to upstream ops until we reach an op that has also overridden the + target max block size.""" + + def apply(self, plan: PhysicalPlan) -> PhysicalPlan: + self._propagate_target_max_block_size_to_upstream_ops(plan.dag) + return plan + + def _propagate_target_max_block_size_to_upstream_ops( + self, dag: PhysicalOperator, target_max_block_size: Optional[int] = None + ): + if dag.target_max_block_size is not None: + # Set the target block size to inherit for + # upstream ops. + target_max_block_size = dag.target_max_block_size + elif target_max_block_size is not None: + # Inherit from downstream op. + dag.set_target_max_block_size(target_max_block_size) + + for upstream_op in dag.input_dependencies: + self._propagate_target_max_block_size_to_upstream_ops( + upstream_op, target_max_block_size + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/limit_pushdown.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/limit_pushdown.py new file mode 100644 index 0000000000000000000000000000000000000000..c3c8e5f786e3fcd51e9223a6d55b3dd1fef25e79 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/limit_pushdown.py @@ -0,0 +1,182 @@ +import copy +from collections import deque +from typing import Iterable, List + +from ray.data._internal.logical.interfaces import LogicalOperator, LogicalPlan, Rule +from ray.data._internal.logical.operators.map_operator import MapBatches +from ray.data._internal.logical.operators.n_ary_operator import Union +from ray.data._internal.logical.operators.one_to_one_operator import ( + AbstractOneToOne, + Limit, +) + + +class LimitPushdownRule(Rule): + """Rule for pushing down the limit operator. + + When a limit operator is present, we apply the limit on the + most upstream operator that supports it. We are conservative and only + push through operators that we know for certain do not modify row counts: + - Project operations (column selection) + - MapRows operations (row-wise transformations that preserve row count) + - Union operations (limits are prepended to each branch) + + We stop at: + - Any operator that can modify the number of output rows (Sort, Shuffle, Aggregate, Read etc.) + + In addition, we also fuse consecutive Limit operators into a single + Limit operator, i.e. `Limit[n] -> Limit[m]` becomes `Limit[min(n, m)]`. + """ + + def apply(self, plan: LogicalPlan) -> LogicalPlan: + # The DAG's root is the most downstream operator. + optimized_dag = self._apply_limit_pushdown(plan.dag) + optimized_dag = self._apply_limit_fusion(optimized_dag) + return LogicalPlan(dag=optimized_dag, context=plan.context) + + def _apply_limit_pushdown(self, op: LogicalOperator) -> LogicalOperator: + """Push down Limit operators in the given operator DAG. + + This implementation uses ``LogicalOperator._apply_transform`` to + post-order-traverse the DAG and rewrite each ``Limit`` node via + :py:meth:`_push_limit_down`. + """ + + def transform(node: LogicalOperator) -> LogicalOperator: + if isinstance(node, Limit): + if isinstance(node.input_dependency, Union): + return self._push_limit_into_union(node) + return self._push_limit_down(node) + return node + + # ``_apply_transform`` returns the (potentially new) root of the DAG. + return op._apply_transform(transform) + + def _push_limit_into_union(self, limit_op: Limit) -> Limit: + """Push `limit_op` INTO every branch of its upstream Union + and preserve the global limit. + + Existing topology: + child₁ , child₂ , … -> Union -> Limit + + New topology: + child₁ -> Limit ->│ + │ + child₂ -> Limit ->┤ Union ──► Limit (original) + │ + … -> Limit ->│ + """ + union_op = limit_op.input_dependency + assert isinstance(union_op, Union) + + # 1. Detach the original Union from its children. + original_children = list(union_op.input_dependencies) + for child in original_children: + if union_op in child._output_dependencies: + child._output_dependencies.remove(union_op) + + # 2. Insert a branch-local Limit and push it further upstream. + branch_tails: List[LogicalOperator] = [] + for child in original_children: + raw_limit = Limit(child, limit_op._limit) # child → limit + if isinstance(child, Union): + # This represents the limit operator appended after the union. + pushed_tail = self._push_limit_into_union(raw_limit) + else: + # This represents the operator that takes place of the original limit position. + pushed_tail = self._push_limit_down(raw_limit) + branch_tails.append(pushed_tail) + + # 3. Re-attach the Union so that it consumes the *tails*. + new_union = Union(*branch_tails) + for tail in branch_tails: + tail._output_dependencies.append(new_union) + + # 4. Re-wire the original (global) Limit to consume the *new* Union. + limit_op._input_dependencies = [new_union] + new_union._output_dependencies = [limit_op] + + return limit_op + + def _push_limit_down(self, limit_op: Limit) -> LogicalOperator: + """Push a single limit down through compatible operators conservatively. + + Similar to the original algorithm but more conservative in what we push through. + """ + limit_op_copy = copy.copy(limit_op) + + # Traverse up the DAG until we reach the first operator that meets + # one of the stopping conditions + new_input_into_limit = limit_op.input_dependency + ops_between_new_input_and_limit: List[LogicalOperator] = [] + + while ( + isinstance(new_input_into_limit, AbstractOneToOne) + and not new_input_into_limit.can_modify_num_rows() + and not isinstance(new_input_into_limit, MapBatches) + # We should push past MapBatches, but MapBatches can modify the row count TODO: add a flag in map_batches that allows the user to opt in ensure row preservation + ): + new_input_into_limit_copy = copy.copy(new_input_into_limit) + ops_between_new_input_and_limit.append(new_input_into_limit_copy) + new_input_into_limit = new_input_into_limit.input_dependency + + # If we couldn't push through any operators, return original + if not ops_between_new_input_and_limit: + return limit_op + + # Link the Limit operator and its newly designated input op from above. + limit_op_copy._input_dependencies = [new_input_into_limit] + new_input_into_limit._output_dependencies = [limit_op_copy] + + # Wire limit_op_copy to the first operator that should come after it + # (which is the last one we added to the list). Going from up upstream to downstream. + current_op = limit_op_copy + for next_op in reversed(ops_between_new_input_and_limit): + current_op._output_dependencies = [next_op] + next_op._input_dependencies = [current_op] + current_op = next_op + + # Link up all operations from last downstream op to post old limit location (further downstream) + last_op = current_op + for downstream_op in limit_op.output_dependencies: + downstream_op._input_dependencies = [last_op] + last_op._output_dependencies = limit_op.output_dependencies + return last_op + + def _apply_limit_fusion(self, op: LogicalOperator) -> LogicalOperator: + """Given a DAG of LogicalOperators, traverse the DAG and fuse all + back-to-back Limit operators, i.e. + Limit[n] -> Limit[m] becomes Limit[min(n, m)]. + + Returns a new LogicalOperator with the Limit operators fusion applied.""" + + # Post-order traversal. + nodes: Iterable[LogicalOperator] = deque() + for node in op.post_order_iter(): + nodes.appendleft(node) + + while len(nodes) > 0: + current_op = nodes.pop() + + # If we encounter two back-to-back Limit operators, fuse them. + if isinstance(current_op, Limit): + upstream_op = current_op.input_dependency + if isinstance(upstream_op, Limit): + new_limit = min(current_op._limit, upstream_op._limit) + fused_limit_op = Limit(upstream_op.input_dependency, new_limit) + + # Link the fused Limit operator to its input and output ops, i.e.: + # `upstream_input -> limit_upstream -> limit_downstream -> downstream_output` # noqa: E501 + # becomes `upstream_input -> fused_limit -> downstream_output` + fused_limit_op._input_dependencies = upstream_op.input_dependencies + fused_limit_op._output_dependencies = current_op.output_dependencies + + # Replace occurrences of the upstream Limit operator in + # output_dependencies with the newly fused Limit operator. + upstream_input = upstream_op.input_dependency + upstream_input._output_dependencies = [fused_limit_op] + + for current_output in current_op.output_dependencies: + current_output._input_dependencies = [fused_limit_op] + nodes.append(fused_limit_op) + return current_op diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/operator_fusion.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/operator_fusion.py new file mode 100644 index 0000000000000000000000000000000000000000..13104de04be890ba26ed12c4de0ae25e960ecd4d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/operator_fusion.py @@ -0,0 +1,546 @@ +import itertools +import logging +from typing import List, Optional + +from ray.data._internal.compute import ( + ActorPoolStrategy, + ComputeStrategy, + TaskPoolStrategy, +) +from ray.data._internal.execution.interfaces import ( + PhysicalOperator, + RefBundle, + TaskContext, +) +from ray.data._internal.execution.interfaces.transform_fn import ( + AllToAllTransformFnResult, +) +from ray.data._internal.execution.operators.actor_pool_map_operator import ( + ActorPoolMapOperator, +) +from ray.data._internal.execution.operators.base_physical_operator import ( + AllToAllOperator, +) +from ray.data._internal.execution.operators.map_operator import MapOperator +from ray.data._internal.execution.operators.task_pool_map_operator import ( + TaskPoolMapOperator, +) +from ray.data._internal.logical.interfaces import PhysicalPlan, Rule +from ray.data._internal.logical.operators.all_to_all_operator import ( + AbstractAllToAll, + RandomShuffle, + Repartition, +) +from ray.data._internal.logical.operators.map_operator import ( + AbstractMap, + AbstractUDFMap, +) +from ray.data.context import DataContext + +# Scheduling strategy can be inherited from upstream operator if not specified. +INHERITABLE_REMOTE_ARGS = ["scheduling_strategy"] + + +logger = logging.getLogger(__name__) + + +class FuseOperators(Rule): + """Fuses linear chains of compatible physical operators.""" + + def apply(self, plan: PhysicalPlan) -> PhysicalPlan: + self._op_map = plan.op_map.copy() + # Do DFS fusion on compatible pairwise operators in two passes. + # In the first pass, only fuse back-to-back map operators together. + fused_dag = self._fuse_map_operators_in_dag(plan.dag) + + # Now that we have fused together all back-to-back map operators, + # we fuse together MapOperator -> AllToAllOperator pairs. + fused_dag = self._fuse_all_to_all_operators_in_dag(fused_dag) + + # Update output dependencies after fusion. + # TODO(hchen): Instead of updating the depdencies manually, + # we need a better abstraction for manipulating the DAG. + self._remove_output_deps(fused_dag) + self._update_output_deps(fused_dag) + + new_plan = PhysicalPlan(fused_dag, self._op_map, plan.context) + return new_plan + + def _remove_output_deps(self, op: PhysicalOperator) -> None: + for input in op._input_dependencies: + input._output_dependencies = [] + self._remove_output_deps(input) + + def _update_output_deps(self, op: PhysicalOperator) -> None: + for input in op._input_dependencies: + input._output_dependencies.append(op) + self._update_output_deps(input) + + def _fuse_map_operators_in_dag(self, dag: PhysicalOperator) -> MapOperator: + """Starting at the given operator, traverses up the DAG of operators + and recursively fuses compatible MapOperator -> MapOperator pairs. + Returns the current (root) operator after completing upstream operator fusions. + """ + upstream_ops = dag.input_dependencies + while ( + len(upstream_ops) == 1 + and isinstance(dag, MapOperator) + and isinstance(upstream_ops[0], MapOperator) + and self._can_fuse(dag, upstream_ops[0]) + ): + # Fuse operator with its upstream op. + dag = self._get_fused_map_operator(dag, upstream_ops[0]) + upstream_ops = dag.input_dependencies + + # Done fusing back-to-back map operators together here, + # move up the DAG to find the next map operators to fuse. + dag._input_dependencies = [ + self._fuse_map_operators_in_dag(upstream_op) for upstream_op in upstream_ops + ] + return dag + + def _fuse_all_to_all_operators_in_dag( + self, dag: AllToAllOperator + ) -> AllToAllOperator: + """Starting at the given operator, traverses up the DAG of operators + and recursively fuses compatible MapOperator -> AllToAllOperator pairs. + + Also, sets the target block size of the immediately upstream map op to + match the shuffle block size. We use a larger block size for shuffles + because tiny blocks are bad for I/O performance. + + Returns the current (root) operator after completing upstream operator fusions. + """ + upstream_ops = dag.input_dependencies + while ( + len(upstream_ops) == 1 + and isinstance(dag, AllToAllOperator) + and isinstance(upstream_ops[0], MapOperator) + and self._can_fuse(dag, upstream_ops[0]) + ): + # Fuse operator with its upstream op. + dag = self._get_fused_all_to_all_operator(dag, upstream_ops[0]) + upstream_ops = dag.input_dependencies + + # Done fusing MapOperator -> AllToAllOperator together here, + # move up the DAG to find the next pair of operators to fuse. + dag._input_dependencies = [ + self._fuse_all_to_all_operators_in_dag(upstream_op) + for upstream_op in upstream_ops + ] + return dag + + def _can_fuse(self, down_op: PhysicalOperator, up_op: PhysicalOperator) -> bool: + """Returns whether the provided downstream operator can be fused with the given + upstream operator. + + We currently support fusing two operators if the following are all true: + * We are fusing either MapOperator -> MapOperator or + MapOperator -> AllToAllOperator. + * They either use the same compute configuration, or the upstream operator + uses a task pool while the downstream operator uses an actor pool. + * If both operators involve callable classes, the callable classes are + the same class AND constructor args are the same for both. + * They have compatible remote arguments. + """ + if not up_op.supports_fusion() or not down_op.supports_fusion(): + return False + + # We currently only support fusing for the following cases: + # - TaskPoolMapOperator -> TaskPoolMapOperator/ActorPoolMapOperator + # - TaskPoolMapOperator -> AllToAllOperator + # (only RandomShuffle and Repartition LogicalOperators are currently supported) + if not ( + ( + isinstance(up_op, TaskPoolMapOperator) + and isinstance(down_op, (TaskPoolMapOperator, ActorPoolMapOperator)) + ) + or ( + isinstance(up_op, TaskPoolMapOperator) + and isinstance(down_op, AllToAllOperator) + ) + ): + return False + + down_logical_op = self._op_map[down_op] + up_logical_op = self._op_map[up_op] + + if up_op.get_additional_split_factor() > 1: + return False + + # If the downstream operator takes no input, it cannot be fused with + # the upstream operator. + if not down_logical_op._input_dependencies: + return False + + # We currently only support fusing for the following cases: + # - AbstractMap -> AbstractMap + # - AbstractMap -> RandomShuffle + # - AbstractMap -> Repartition (shuffle=True) + if not ( + ( + isinstance(up_logical_op, AbstractMap) + and isinstance(down_logical_op, AbstractMap) + and self._can_fuse_map_ops(up_logical_op, down_logical_op) + ) + or ( + isinstance(up_logical_op, AbstractMap) + and isinstance(down_logical_op, RandomShuffle) + ) + # Do not fuse Repartition operator if shuffle is disabled + # (i.e. using split shuffle). + or ( + isinstance(up_logical_op, AbstractMap) + and isinstance(down_logical_op, Repartition) + and down_logical_op._shuffle + ) + ): + return False + + # Only fuse if the ops' remote arguments are compatible. + if not _are_remote_args_compatible( + getattr(up_logical_op, "_ray_remote_args", {}), + getattr(down_logical_op, "_ray_remote_args", {}), + ): + return False + + # Do not fuse if either op specifies a `_ray_remote_args_fn`, + # since it is not known whether the generated args will be compatible. + if getattr(up_logical_op, "_ray_remote_args_fn", None) or getattr( + down_logical_op, "_ray_remote_args_fn", None + ): + return False + + if not self._can_merge_target_max_block_size( + up_op.target_max_block_size, + down_op.target_max_block_size, + up_op.data_context, + ): + return False + + # Otherwise, ops are compatible for fusion. + return True + + @classmethod + def _fuse_compute_strategy( + cls, up_compute: ComputeStrategy, down_compute: ComputeStrategy + ) -> Optional[ComputeStrategy]: + """Fuse the compute strategies of the upstream and downstream operators. + Returns None if they are not compatible. + + Task->Task and Task->Actor are allowed. + Actor->Actor and Actor->Task are not allowed. + """ + if isinstance(up_compute, ActorPoolStrategy): + return None + assert isinstance(up_compute, TaskPoolStrategy) + if isinstance(down_compute, TaskPoolStrategy): + # For Task->Task, the sizes must match. + if up_compute.size != down_compute.size: + return None + return down_compute + else: + assert isinstance(down_compute, ActorPoolStrategy) + # For Task->Actor, if Task's size is set, it must match Actor's max_size. + if up_compute.size is not None and up_compute.size != down_compute.max_size: + return None + return down_compute + + def _can_merge_target_max_block_size( + self, + up_target_max_block_size: Optional[int], + down_target_max_block_size: Optional[int], + data_context: DataContext, + ): + # If the upstream op overrode the target max block size, only fuse if + # they are equal. + if up_target_max_block_size is not None: + if down_target_max_block_size is None: + down_target_max_block_size = data_context.target_max_block_size + if up_target_max_block_size != down_target_max_block_size: + return False + return True + + def _get_merged_target_max_block_size( + self, + up_target_max_block_size: Optional[int], + down_target_max_block_size: Optional[int], + ): + if up_target_max_block_size is not None: + # If the upstream op overrode the target max block size, we can + # only merge if the downstream op matches or uses the default. + assert ( + down_target_max_block_size is None + or down_target_max_block_size == up_target_max_block_size + ) + return up_target_max_block_size + else: + # Upstream op inherits the downstream op's target max block size, + # because the downstream op is the one that outputs the final + # blocks. + return down_target_max_block_size + + def _get_fused_map_operator( + self, down_op: MapOperator, up_op: MapOperator + ) -> MapOperator: + assert self._can_fuse(down_op, up_op), ( + "Current rule supports fusing MapOperator->MapOperator, but received: " + f"{type(up_op).__name__} -> {type(down_op).__name__}" + ) + + # Fuse operator names. + name = up_op.name + "->" + down_op.name + + down_logical_op = self._op_map.pop(down_op) + up_logical_op = self._op_map.pop(up_op) + assert isinstance(down_logical_op, AbstractMap) + assert isinstance(up_logical_op, AbstractMap) + + # Derive min num rows per input bundle + min_rows_per_bundled_input = self._derive_bundle_min_num_rows( + down_logical_op, up_logical_op + ) + + target_max_block_size = self._get_merged_target_max_block_size( + up_op.target_max_block_size, down_op.target_max_block_size + ) + + compute = self._fuse_compute_strategy( + up_logical_op._compute, down_logical_op._compute + ) + assert compute is not None + + # Merge map task kwargs + map_task_kwargs = {**up_op._map_task_kwargs, **down_op._map_task_kwargs} + + ray_remote_args = up_logical_op._ray_remote_args + ray_remote_args_fn = ( + up_logical_op._ray_remote_args_fn or down_logical_op._ray_remote_args_fn + ) + # Make the upstream operator's inputs the new, fused operator's inputs. + input_deps = up_op.input_dependencies + assert len(input_deps) == 1 + input_op = input_deps[0] + + # Fused physical map operator. + assert up_op.data_context is down_op.data_context + op = MapOperator.create( + up_op.get_map_transformer().fuse(down_op.get_map_transformer()), + input_op, + up_op.data_context, + target_max_block_size=target_max_block_size, + name=name, + compute_strategy=compute, + min_rows_per_bundle=min_rows_per_bundled_input, + map_task_kwargs=map_task_kwargs, + ray_remote_args=ray_remote_args, + ray_remote_args_fn=ray_remote_args_fn, + ) + op.set_logical_operators(*up_op._logical_operators, *down_op._logical_operators) + for map_task_kwargs_fn in itertools.chain( + up_op._map_task_kwargs_fns, down_op._map_task_kwargs_fns + ): + op.add_map_task_kwargs_fn(map_task_kwargs_fn) + + # Build a map logical operator to be used as a reference for further fusion. + # TODO(Scott): This is hacky, remove this once we push fusion to be purely based + # on a lower-level operator spec. + if isinstance(up_logical_op, AbstractUDFMap): + input_op = up_logical_op.input_dependency + else: + # Bottom out at the source logical op (e.g. Read()). + input_op = up_logical_op + if isinstance(down_logical_op, AbstractUDFMap): + logical_op = AbstractUDFMap( + name, + input_op, + down_logical_op._fn, + fn_args=down_logical_op._fn_args, + fn_kwargs=down_logical_op._fn_kwargs, + fn_constructor_args=down_logical_op._fn_constructor_args, + fn_constructor_kwargs=down_logical_op._fn_constructor_kwargs, + min_rows_per_bundled_input=min_rows_per_bundled_input, + compute=compute, + ray_remote_args_fn=ray_remote_args_fn, + ray_remote_args=ray_remote_args, + ) + else: + # The downstream op is AbstractMap instead of AbstractUDFMap. + logical_op = AbstractMap( + name, + input_op, + min_rows_per_bundled_input=min_rows_per_bundled_input, + ray_remote_args_fn=ray_remote_args_fn, + ray_remote_args=ray_remote_args, + ) + self._op_map[op] = logical_op + # Return the fused physical operator. + return op + + @classmethod + def _derive_bundle_min_num_rows( + cls, + down_logical_op: AbstractMap, + up_logical_op: AbstractMap, + ) -> Optional[int]: + us_bundle_min_rows_req = up_logical_op._min_rows_per_bundled_input + ds_bundle_min_rows_req = down_logical_op._min_rows_per_bundled_input + + # In case neither of the ops specify `min_rows_per_bundled_input`, + # return None + if us_bundle_min_rows_req is None and ds_bundle_min_rows_req is None: + return None + + # Target min bundle size is selected as max of upstream and downstream ones + # such that it could satisfy both of their requirements + return max( + ds_bundle_min_rows_req or 0, + us_bundle_min_rows_req or 0, + ) + + def _get_fused_all_to_all_operator( + self, down_op: AllToAllOperator, up_op: MapOperator + ) -> AllToAllOperator: + assert self._can_fuse(down_op, up_op), ( + "Current rule supports fusing MapOperator -> AllToAllOperator" + f", but received: {type(up_op).__name__} -> {type(down_op).__name__}" + ) + + # Fuse operator names. + name = up_op.name + "->" + down_op.name + + down_logical_op = self._op_map.pop(down_op) + up_logical_op = self._op_map.pop(up_op) + assert isinstance(down_logical_op, AbstractAllToAll) + assert isinstance(up_logical_op, AbstractMap) + + # Fuse transformation functions. + ray_remote_args = up_logical_op._ray_remote_args + down_transform_fn = down_op.get_transformation_fn() + up_map_transformer = up_op.get_map_transformer() + + def fused_all_to_all_transform_fn( + blocks: List[RefBundle], + ctx: TaskContext, + ) -> AllToAllTransformFnResult: + """To fuse MapOperator->AllToAllOperator, we store the map function + in the TaskContext so that it may be used by the downstream + AllToAllOperator's transform function.""" + ctx.upstream_map_transformer = up_map_transformer + ctx.upstream_map_ray_remote_args = ray_remote_args + return down_transform_fn(blocks, ctx) + + # Make the upstream operator's inputs the new, fused operator's inputs. + input_deps = up_op.input_dependencies + assert len(input_deps) == 1 + input_op = input_deps[0] + + target_max_block_size = self._get_merged_target_max_block_size( + up_op.target_max_block_size, down_op.target_max_block_size + ) + + assert up_op.data_context is down_op.data_context + op = AllToAllOperator( + fused_all_to_all_transform_fn, + input_op, + up_op.data_context, + target_max_block_size=target_max_block_size, + num_outputs=down_op._num_outputs, + # Transfer over the existing sub-progress bars from + # the AllToAllOperator (if any) into the fused operator. + sub_progress_bar_names=down_op._sub_progress_bar_names, + name=name, + ) + # Bottom out at the source logical op (e.g. Read()). + input_op = up_logical_op + + if isinstance(down_logical_op, RandomShuffle): + logical_op = RandomShuffle( + input_op, + name=name, + ray_remote_args=ray_remote_args, + ) + elif isinstance(down_logical_op, Repartition): + logical_op = Repartition( + input_op, + num_outputs=down_logical_op._num_outputs, + shuffle=down_logical_op._shuffle, + ) + self._op_map[op] = logical_op + # Return the fused physical operator. + return op + + @classmethod + def _can_fuse_map_ops( + cls, + upstream_op: AbstractMap, + downstream_op: AbstractMap, + ) -> bool: + if ( + cls._fuse_compute_strategy( + upstream_op._compute, + downstream_op._compute, + ) + is None + ): + return False + + # Do not fuse Map operators in case: + # + # - Upstream could (potentially) drastically modify number of rows, while + # - Downstream has `min_rows_per_input_bundle` specified + # + # Fusing such transformations is not desirable as it could + # + # - Drastically reduce parallelism for the upstream up (for ex, if + # fusing ``Read->MapBatches(batch_size=...)`` with large enough batch-size + # could drastically reduce parallelism level of the Read op) + # + # - Potentially violate batching semantic by fusing + # ``Filter->MapBatches(batch_size=...)`` + # + if ( + upstream_op.can_modify_num_rows() + and downstream_op._min_rows_per_bundled_input is not None + ): + logger.debug( + f"Upstream operator '{upstream_op}' could be modifying # of input " + f"rows, while downstream operator '{downstream_op}' expects at least " + f"{downstream_op._min_rows_per_bundled_input} rows in a batch. " + f"Skipping fusion" + ) + + return False + + return True + + +def _are_remote_args_compatible(prev_args, next_args): + """Check if Ray remote arguments are compatible for merging.""" + prev_args = _canonicalize(prev_args) + next_args = _canonicalize(next_args) + remote_args = next_args.copy() + for key in INHERITABLE_REMOTE_ARGS: + # NOTE: We only carry over inheritable value in case + # of it not being provided in the remote args + if key in prev_args and key not in remote_args: + remote_args[key] = prev_args[key] + + if prev_args != remote_args: + return False + return True + + +def _canonicalize(remote_args: dict) -> dict: + """Returns canonical form of given remote args.""" + remote_args = remote_args.copy() + if "num_cpus" not in remote_args or remote_args["num_cpus"] is None: + remote_args["num_cpus"] = 1 + if "num_gpus" not in remote_args or remote_args["num_gpus"] is None: + remote_args["num_gpus"] = 0 + resources = remote_args.get("resources", {}) + for k, v in list(resources.items()): + if v is None or v == 0.0: + del resources[k] + remote_args["resources"] = resources + return remote_args diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/set_read_parallelism.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/set_read_parallelism.py new file mode 100644 index 0000000000000000000000000000000000000000..faf88a682f8e21bc6f67972397d7bb04f272ef4f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/set_read_parallelism.py @@ -0,0 +1,140 @@ +import logging +import math +from typing import Optional, Tuple, Union + +from ray import available_resources as ray_available_resources +from ray.data._internal.execution.interfaces import PhysicalOperator +from ray.data._internal.execution.operators.input_data_buffer import InputDataBuffer +from ray.data._internal.logical.interfaces import PhysicalPlan, Rule +from ray.data._internal.logical.operators.read_operator import Read +from ray.data._internal.util import _autodetect_parallelism +from ray.data.context import WARN_PREFIX, DataContext +from ray.data.datasource.datasource import Datasource, Reader + +logger = logging.getLogger(__name__) + + +def compute_additional_split_factor( + datasource_or_legacy_reader: Union[Datasource, Reader], + parallelism: int, + mem_size: int, + target_max_block_size: Optional[int], + cur_additional_split_factor: Optional[int] = None, +) -> Tuple[int, str, int, Optional[int]]: + """Returns parallelism to use and the min safe parallelism to avoid OOMs.""" + + ctx = DataContext.get_current() + detected_parallelism, reason, _ = _autodetect_parallelism( + parallelism, target_max_block_size, ctx, datasource_or_legacy_reader, mem_size + ) + num_read_tasks = len( + datasource_or_legacy_reader.get_read_tasks(detected_parallelism) + ) + expected_block_size = None + if mem_size: + expected_block_size = mem_size / num_read_tasks + logger.debug( + f"Expected in-memory size {mem_size}," f" block size {expected_block_size}" + ) + if target_max_block_size is None: + # Unlimited block size -> no extra splits + size_based_splits = 1 + else: + size_based_splits = round( + max(1, expected_block_size / target_max_block_size) + ) + else: + size_based_splits = 1 + if cur_additional_split_factor: + size_based_splits *= cur_additional_split_factor + logger.debug(f"Size based split factor {size_based_splits}") + estimated_num_blocks = num_read_tasks * size_based_splits + logger.debug(f"Blocks after size splits {estimated_num_blocks}") + + available_cpu_slots = ray_available_resources().get("CPU", 1) + if ( + parallelism != -1 + and num_read_tasks >= available_cpu_slots * 4 + and num_read_tasks >= 5000 + ): + logger.warning( + f"{WARN_PREFIX} The requested number of read blocks of {parallelism} " + "is more than 4x the number of available CPU slots in the cluster of " + f"{available_cpu_slots}. This can " + "lead to slowdowns during the data reading phase due to excessive " + "task creation. Reduce the value to match with the available " + "CPU slots in the cluster, or set override_num_blocks to -1 for Ray Data " + "to automatically determine the number of read tasks blocks." + "You can ignore this message if the cluster is expected to autoscale." + ) + + # Add more output splitting for each read task if needed. + # TODO(swang): For parallelism=-1 (user did not explicitly set + # parallelism), and if the following operator produces much larger blocks, + # we should scale down the target max block size here instead of using + # splitting, which can have higher memory usage. + if estimated_num_blocks < detected_parallelism and estimated_num_blocks > 0: + k = math.ceil(detected_parallelism / estimated_num_blocks) + estimated_num_blocks = estimated_num_blocks * k + return detected_parallelism, reason, estimated_num_blocks, k + + return detected_parallelism, reason, estimated_num_blocks, None + + +class SetReadParallelismRule(Rule): + """ + This rule sets the read op's task parallelism based on the target block + size, the requested parallelism, the number of read files, and the + available resources in the cluster. + + If the parallelism is lower than requested, this rule also sets a split + factor to split the output blocks of the read task, so that the following + operator will have the desired parallelism. + """ + + def apply(self, plan: PhysicalPlan) -> PhysicalPlan: + ops = [plan.dag] + + while len(ops) > 0: + op = ops.pop(0) + if isinstance(op, InputDataBuffer): + continue + logical_op = plan.op_map[op] + if isinstance(logical_op, Read): + self._apply(op, logical_op) + ops += op.input_dependencies + + return plan + + def _apply(self, op: PhysicalOperator, logical_op: Read): + ( + detected_parallelism, + reason, + estimated_num_blocks, + k, + ) = compute_additional_split_factor( + logical_op._datasource_or_legacy_reader, + logical_op._parallelism, + logical_op._mem_size, + op.actual_target_max_block_size, + op._additional_split_factor, + ) + + if logical_op._parallelism == -1: + assert reason != "" + logger.debug( + f"Using autodetected parallelism={detected_parallelism} " + f"for operator {logical_op.name} to satisfy {reason}." + ) + logical_op.set_detected_parallelism(detected_parallelism) + + if k is not None: + logger.debug( + f"To satisfy the requested parallelism of {detected_parallelism}, " + f"each read task output is split into {k} smaller blocks." + ) + + if k is not None: + op.set_additional_split_factor(k) + + logger.debug(f"Estimated num output blocks {estimated_num_blocks}") diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/zero_copy_map_fusion.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/zero_copy_map_fusion.py new file mode 100644 index 0000000000000000000000000000000000000000..d8f3ec9761123e36655033ee2329b32788bc85ad --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/logical/rules/zero_copy_map_fusion.py @@ -0,0 +1,97 @@ +from abc import abstractmethod +from typing import List, Type + +from ray.data._internal.execution.operators.map_operator import MapOperator +from ray.data._internal.execution.operators.map_transformer import ( + BuildOutputBlocksMapTransformFn, + MapTransformFn, + MapTransformFnCategory, + MapTransformFnDataType, +) +from ray.data._internal.logical.interfaces.optimizer import Rule +from ray.data._internal.logical.interfaces.physical_plan import PhysicalPlan +from ray.data._internal.logical.rules.operator_fusion import FuseOperators + + +class ZeroCopyMapFusionRule(Rule): + """Base abstract class for all zero-copy map fusion rules. + + A zero-copy map fusion rule is a rule that optimizes the transform_fn chain of + a fused MapOperator. The optimization is usually done by removing unnecessary + data conversions. + + This base abstract class defines the common util functions. And subclasses + should implement the `_optimize` method for the concrete optimization + strategy. + """ + + @classmethod + def dependencies(cls) -> List[Type[Rule]]: + return [FuseOperators] + + def apply(self, plan: PhysicalPlan) -> PhysicalPlan: + self._traverse(plan.dag) + return plan + + def _traverse(self, op): + """Traverse the DAG and apply the optimization to each MapOperator.""" + if isinstance(op, MapOperator): + map_transformer = op.get_map_transformer() + transform_fns = map_transformer.get_transform_fns() + new_transform_fns = self._optimize(transform_fns) + # Physical operators won't be shared, + # so it's safe to modify the transform_fns in place. + map_transformer.set_transform_fns(new_transform_fns) + + for input_op in op.input_dependencies: + self._traverse(input_op) + + @abstractmethod + def _optimize(self, transform_fns: List[MapTransformFn]) -> List[MapTransformFn]: + """Optimize the transform_fns chain of a MapOperator. + + Args: + transform_fns: The old transform_fns chain. + Returns: + The optimized transform_fns chain. + """ + ... + + +class EliminateBuildOutputBlocks(ZeroCopyMapFusionRule): + """This rule eliminates unnecessary BuildOutputBlocksMapTransformFn + (which is of category MapTransformFnCategory.PostProcess), if the previous fn + already outputs blocks. + + This happens for the "Read -> Map/Write" fusion. + """ + + def _optimize(self, transform_fns: List[MapTransformFn]) -> List[MapTransformFn]: + # For the following subsquence, + # 1. Any MapTransformFn with block output. + # 2. BuildOutputBlocksMapTransformFn + # 3. Any MapTransformFn with block input. + # We drop the BuildOutputBlocksMapTransformFn in the middle. + new_transform_fns = [] + + for i in range(len(transform_fns)): + cur_fn = transform_fns[i] + drop = False + if ( + i > 0 + and i < len(transform_fns) - 1 + and isinstance(cur_fn, BuildOutputBlocksMapTransformFn) + ): + assert cur_fn.category == MapTransformFnCategory.PostProcess + prev_fn = transform_fns[i - 1] + next_fn = transform_fns[i + 1] + if ( + prev_fn.output_type == MapTransformFnDataType.Block + and next_fn.input_type == MapTransformFnDataType.Block + ): + assert prev_fn.category == MapTransformFnCategory.DataProcess + drop = True + if not drop: + new_transform_fns.append(cur_fn) + + return new_transform_fns diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f244fd8ed9b668aabb57e1c14b8a3183874ee09 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/aggregate.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/aggregate.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c16771d27865eb993b82441e6b29e179a1b12201 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/aggregate.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/plan_all_to_all_op.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/plan_all_to_all_op.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8bea0e2552bbc4e246445efc5ca271c8f0ea30e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/plan_all_to_all_op.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/plan_read_op.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/plan_read_op.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5836f6025fdd5dc84a99cf29d13cc362959947b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/plan_read_op.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/plan_udf_map_op.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/plan_udf_map_op.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7bf3cf8562fffa5120a9291d15c6756cbe75704e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/plan_udf_map_op.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/plan_write_op.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/plan_write_op.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..846ab30dad66ea7939685a0915e3c1f80f51fda3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/plan_write_op.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/planner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/planner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0586ed324c979e8100b47d9e2170d54725d3604c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/planner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/random_shuffle.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/random_shuffle.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c67d62766c5bba4978daaface201c1588228bed3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/random_shuffle.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/randomize_blocks.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/randomize_blocks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9dff75e9364792c7052e55f6527351154dada474 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/randomize_blocks.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/repartition.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/repartition.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..419c63edee6d59c9f6c1198b4e708ce874be4595 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/repartition.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/sort.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/sort.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04ba23c90b20654d3c9e4839ecfd6fbcbc3e8905 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/__pycache__/sort.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef68f60a9442c266fe4fb4c6dbd4c2e9a51071da Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/__pycache__/aggregate_task_spec.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/__pycache__/aggregate_task_spec.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b94c6f29ba27157614099c1e7b22a0c377a7d5f1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/__pycache__/aggregate_task_spec.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/__pycache__/interfaces.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/__pycache__/interfaces.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63a06dffc1316f80606934ccdab8c9235f5e45fa Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/__pycache__/interfaces.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/__pycache__/pull_based_shuffle_task_scheduler.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/__pycache__/pull_based_shuffle_task_scheduler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d81068c3619b59bef381bd0c4d81f32550ab26bf Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/__pycache__/pull_based_shuffle_task_scheduler.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/__pycache__/push_based_shuffle_task_scheduler.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/__pycache__/push_based_shuffle_task_scheduler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..216b63bcf7753c9af4bf21fed19ba0f768f50f98 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/__pycache__/push_based_shuffle_task_scheduler.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/__pycache__/shuffle_task_spec.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/__pycache__/shuffle_task_spec.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d0bb06a40728bcb9e084143bbca59bdf796fd48 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/__pycache__/shuffle_task_spec.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/__pycache__/sort_task_spec.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/__pycache__/sort_task_spec.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eeb2d58081fc3506efd42d984322fc5ec34f1446 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/__pycache__/sort_task_spec.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/__pycache__/split_repartition_task_scheduler.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/__pycache__/split_repartition_task_scheduler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab8cfa61934b129afc59c3bc1874a19401dbeda2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/__pycache__/split_repartition_task_scheduler.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/aggregate_task_spec.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/aggregate_task_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..b6d8f80dca8083c17eaee2cd80a4a74f035b555f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/aggregate_task_spec.py @@ -0,0 +1,125 @@ +from typing import List, Tuple, Union + +from ray.data._internal.planner.exchange.interfaces import ExchangeTaskSpec +from ray.data._internal.planner.exchange.sort_task_spec import SortKey +from ray.data._internal.table_block import TableBlockAccessor +from ray.data.aggregate import AggregateFn, AggregateFnV2, Count +from ray.data.block import ( + Block, + BlockAccessor, + BlockExecStats, + BlockMetadataWithSchema, + KeyType, +) + + +class SortAggregateTaskSpec(ExchangeTaskSpec): + """ + The implementation for sort-based aggregate tasks. + + Aggregate is done in 2 steps: partial aggregate of individual blocks, and + final aggregate of sorted blocks. + + Partial aggregate (`map`): each block is sorted locally, then partitioned into + smaller blocks according to the boundaries. Each partitioned block is aggregated + separately, then passed to a final aggregate task. + + Final aggregate (`reduce`): each task would receive a block from every worker that + consists of items in a certain range. It then merges the sorted blocks and + aggregates on-the-fly. + """ + + def __init__( + self, + boundaries: List[KeyType], + key: SortKey, + aggs: List[AggregateFn], + batch_format: str, + ): + super().__init__( + map_args=[boundaries, key, aggs], + reduce_args=[key, aggs, batch_format], + ) + + @staticmethod + def map( + idx: int, + block: Block, + output_num_blocks: int, + boundaries: List[KeyType], + sort_key: SortKey, + aggs: List[AggregateFn], + ) -> List[Union[Block, "BlockMetadataWithSchema"]]: + stats = BlockExecStats.builder() + + block = SortAggregateTaskSpec._prune_unused_columns(block, sort_key, aggs) + if sort_key.get_columns(): + partitions = BlockAccessor.for_block(block).sort_and_partition( + boundaries, + sort_key, + ) + else: + partitions = [block] + parts = [ + BlockAccessor.for_block(p)._aggregate(sort_key, aggs) for p in partitions + ] + from ray.data.block import BlockMetadataWithSchema + + meta_with_schema = BlockMetadataWithSchema.from_block( + block, stats=stats.build() + ) + return parts + [meta_with_schema] + + @staticmethod + def reduce( + key: SortKey, + aggs: List[AggregateFn], + batch_format: str, + *mapper_outputs: List[Block], + partial_reduce: bool = False, + ) -> Tuple[Block, "BlockMetadataWithSchema"]: + normalized_blocks = TableBlockAccessor.normalize_block_types( + mapper_outputs, + target_block_type=ExchangeTaskSpec._derive_target_block_type(batch_format), + ) + blocks, meta_with_schema = BlockAccessor.for_block( + normalized_blocks[0] + )._combine_aggregated_blocks( + list(normalized_blocks), key, aggs, finalize=not partial_reduce + ) + return blocks, meta_with_schema + + @staticmethod + def _prune_unused_columns( + block: Block, + sort_key: SortKey, + aggs: Tuple[AggregateFn], + ) -> Block: + """Prune unused columns from block before aggregate.""" + prune_columns = True + columns = set() + key = sort_key.get_columns() + + if isinstance(key, str): + columns.add(key) + elif isinstance(key, list): + columns.update(key) + elif callable(key): + prune_columns = False + + for agg in aggs: + if isinstance(agg, AggregateFnV2) and agg.get_target_column(): + columns.add(agg.get_target_column()) + elif not isinstance(agg, Count): + # Don't prune columns if any aggregate key is not string. + prune_columns = False + + block_accessor = BlockAccessor.for_block(block) + if ( + prune_columns + and isinstance(block_accessor, TableBlockAccessor) + and block_accessor.num_rows() > 0 + ): + return block_accessor.select(list(columns)) + else: + return block diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/interfaces.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/interfaces.py new file mode 100644 index 0000000000000000000000000000000000000000..84388543509fc1b5236992114933dfb7ebf1d9ba --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/interfaces.py @@ -0,0 +1,146 @@ +import logging +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union + +import ray._private.worker +from ray.air.util.data_batch_conversion import BatchFormat +from ray.data._internal.execution.interfaces import RefBundle +from ray.data._internal.stats import StatsDict +from ray.data._internal.util import convert_bytes_to_human_readable_str +from ray.data.block import Block, BlockType +from ray.data.context import DataContext + +if TYPE_CHECKING: + + from ray.data.block import BlockMetadataWithSchema + +logger = logging.getLogger(__name__) + + +class ExchangeTaskSpec: + """ + An interface to specify the exchange map and reduce tasks. + + Subclasses should implement the `map` and `reduce` static methods. + `map` method is to transform one input block into multiple output blocks. + `reduce` is to combine multiple map output blocks. Both methods are + single-task operations. See `ExchangeScheduler` for how to distribute + the operations across multiple tasks. + + Any custom arguments for `map` and `reduce` methods should be specified by + setting `map_args` and `reduce_args`. + + The concept here is similar to the exchange operator described in + "Volcano - An Extensible and Parallel Query Evaluation System" + (https://dl.acm.org/doi/10.1109/69.273032). + """ + + MAP_SUB_PROGRESS_BAR_NAME = "Shuffle Map" + REDUCE_SUB_PROGRESS_BAR_NAME = "Shuffle Reduce" + + def __init__(self, map_args: List[Any] = None, reduce_args: List[Any] = None): + self._map_args = map_args or [] + self._reduce_args = reduce_args or [] + assert isinstance(self._map_args, list) + assert isinstance(self._reduce_args, list) + + @staticmethod + def map( + idx: int, + block: Block, + output_num_blocks: int, + ) -> List[Union[Block, "BlockMetadataWithSchema"]]: + """ + Map function to be run on each input block. + + Returns list of [BlockMetadata, Block1, Block2, ..., BlockN]. + """ + raise NotImplementedError + + @staticmethod + def reduce( + *mapper_outputs: List[Block], + partial_reduce: bool = False, + ) -> Tuple[Block, "BlockMetadataWithSchema"]: + """ + Reduce function to be run for each output block. + + Args: + mapper_outputs: List of map output blocks to reduce. + partial_reduce: Whether should partially or fully reduce. + + Returns: + The reduced block and its metadata. + """ + raise NotImplementedError + + @staticmethod + def _derive_target_block_type(batch_format: str) -> Optional[BlockType]: + if batch_format == BatchFormat.ARROW: + return BlockType.ARROW + elif batch_format == BatchFormat.PANDAS: + return BlockType.PANDAS + else: + # NOTE: Unless desired batch-format is specified, avoid + # overriding existing one + return None + + +class ExchangeTaskScheduler: + """ + An interface to schedule exchange tasks (`exchange_spec`) for multi-nodes + execution. + """ + + def __init__(self, exchange_spec: ExchangeTaskSpec): + """ + Args: + exchange_spec: The implementation of exchange tasks to execute. + """ + self._exchange_spec = exchange_spec + # If driver memory exceeds this threshold, warn the user. For now, this + # only applies to shuffle ops because most other ops are unlikely to use as + # much driver memory. + self.warn_on_driver_memory_usage_bytes: Optional[ + int + ] = DataContext.get_current().warn_on_driver_memory_usage_bytes + + def execute( + self, + refs: List[RefBundle], + output_num_blocks: int, + map_ray_remote_args: Optional[Dict[str, Any]] = None, + reduce_ray_remote_args: Optional[Dict[str, Any]] = None, + warn_on_driver_memory_usage: Optional[int] = None, + ) -> Tuple[List[RefBundle], StatsDict]: + """ + Execute the exchange tasks on input `refs`. + """ + raise NotImplementedError + + def warn_on_high_local_memory_store_usage(self) -> None: + ray_core_worker = ray._private.worker.global_worker.core_worker + local_memory_store_bytes_used = ( + ray_core_worker.get_local_memory_store_bytes_used() + ) + self.warn_on_driver_memory_usage( + local_memory_store_bytes_used, + "More than " + f"{convert_bytes_to_human_readable_str(local_memory_store_bytes_used)} " + "of driver memory used to store Ray Data block data and metadata. " + "This job may exit if driver memory is insufficient.\n\n" + "This can happen when many tiny blocks are created. " + "Check the block size using Dataset.stats() and see " + "https://docs.ray.io/en/latest/data/performance-tips.html" + " for mitigation.", + ) + + def warn_on_driver_memory_usage( + self, memory_usage_bytes: int, log_str: str + ) -> None: + if self.warn_on_driver_memory_usage_bytes is None: + return + + if memory_usage_bytes > self.warn_on_driver_memory_usage_bytes: + logger.warning(log_str) + # Double the threshold to avoid verbose warnings. + self.warn_on_driver_memory_usage_bytes = memory_usage_bytes * 2 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/pull_based_shuffle_task_scheduler.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/pull_based_shuffle_task_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..262382b2a08ed728bb639b8416e016f21753a0bc --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/pull_based_shuffle_task_scheduler.py @@ -0,0 +1,160 @@ +import logging +from typing import Any, Dict, List, Optional, Tuple + +from ray._private.ray_constants import CALLER_MEMORY_USAGE_PER_OBJECT_REF +from ray.data._internal.execution.interfaces import RefBundle, TaskContext +from ray.data._internal.planner.exchange.interfaces import ( + ExchangeTaskScheduler, + ExchangeTaskSpec, +) +from ray.data._internal.remote_fn import cached_remote_fn +from ray.data._internal.stats import StatsDict +from ray.data._internal.util import ( + convert_bytes_to_human_readable_str, + unzip, +) +from ray.data.block import BlockMetadataWithSchema, to_stats + +logger = logging.getLogger(__name__) + + +class PullBasedShuffleTaskScheduler(ExchangeTaskScheduler): + """ + The pull-based map-reduce shuffle scheduler. + + Map tasks are first scheduled to generate map output blocks. After all map output + are generated, then reduce tasks are scheduled to combine map output blocks + together. + + The concept here is similar to + "MapReduce: Simplified Data Processing on Large Clusters" + (https://dl.acm.org/doi/10.1145/1327452.1327492). + """ + + def execute( + self, + refs: List[RefBundle], + output_num_blocks: int, + task_ctx: TaskContext, + map_ray_remote_args: Optional[Dict[str, Any]] = None, + reduce_ray_remote_args: Optional[Dict[str, Any]] = None, + _debug_limit_execution_to_num_blocks: Optional[int] = None, + ) -> Tuple[List[RefBundle], StatsDict]: + + # TODO: eagerly delete the input and map output block references in order to + # eagerly release the blocks' memory. + input_blocks_list = [] + for ref_bundle in refs: + input_blocks_list.extend(ref_bundle.block_refs) + input_num_blocks = len(input_blocks_list) + input_owned = all(b.owns_blocks for b in refs) + + caller_memory_usage = ( + input_num_blocks * output_num_blocks * CALLER_MEMORY_USAGE_PER_OBJECT_REF + ) + self.warn_on_driver_memory_usage( + caller_memory_usage, + "Execution is estimated to use at least " + f"{convert_bytes_to_human_readable_str(caller_memory_usage)} " + "of driver memory. Ensure that the driver machine has at least " + "this much memory to ensure job completion.\n\n" + "To reduce the " + "amount of driver memory needed, enable push-based shuffle using " + "RAY_DATA_PUSH_BASED_SHUFFLE=1 " + "(https://docs.ray.io/en/latest/data/performance-tips.html" + ").", + ) + + if map_ray_remote_args is None: + map_ray_remote_args = {} + if reduce_ray_remote_args is None: + reduce_ray_remote_args = {} + if "scheduling_strategy" not in reduce_ray_remote_args: + reduce_ray_remote_args = reduce_ray_remote_args.copy() + reduce_ray_remote_args["scheduling_strategy"] = "SPREAD" + + shuffle_map = cached_remote_fn(self._exchange_spec.map) + shuffle_reduce = cached_remote_fn(self._exchange_spec.reduce) + + sub_progress_bar_dict = task_ctx.sub_progress_bar_dict + bar_name = ExchangeTaskSpec.MAP_SUB_PROGRESS_BAR_NAME + assert bar_name in sub_progress_bar_dict, sub_progress_bar_dict + map_bar = sub_progress_bar_dict[bar_name] + + if _debug_limit_execution_to_num_blocks is not None: + input_blocks_list = input_blocks_list[:_debug_limit_execution_to_num_blocks] + logger.debug(f"Limiting execution to {len(input_blocks_list)} map tasks") + + shuffle_map_out = [ + shuffle_map.options( + **map_ray_remote_args, + num_returns=1 + output_num_blocks, + ).remote(i, block, output_num_blocks, *self._exchange_spec._map_args) + for i, block in enumerate(input_blocks_list) + ] + + # The first item returned is the BlockMetadata. + shuffle_map_metadata_schema = [] + for i, refs in enumerate(shuffle_map_out): + shuffle_map_metadata_schema.append(refs[-1]) + shuffle_map_out[i] = refs[:-1] + + if _debug_limit_execution_to_num_blocks is not None: + while len(shuffle_map_out) < output_num_blocks: + # Repeat the first map task's results. + shuffle_map_out.append(shuffle_map_out[0][:]) + + shuffle_map_metadata_schema = map_bar.fetch_until_complete( + shuffle_map_metadata_schema + ) + + self.warn_on_high_local_memory_store_usage() + + bar_name = ExchangeTaskSpec.REDUCE_SUB_PROGRESS_BAR_NAME + assert bar_name in sub_progress_bar_dict, sub_progress_bar_dict + reduce_bar = sub_progress_bar_dict[bar_name] + + if _debug_limit_execution_to_num_blocks is not None: + output_num_blocks = _debug_limit_execution_to_num_blocks + logger.debug(f"Limiting execution to {output_num_blocks} reduce tasks") + shuffle_reduce_out = [ + shuffle_reduce.options(**reduce_ray_remote_args, num_returns=2).remote( + *self._exchange_spec._reduce_args, + *[shuffle_map_out[i][j] for i in range(input_num_blocks)], + ) + for j in range(output_num_blocks) + ] + + # Release map task outputs from the Ray object store. + del shuffle_map_out + + new_blocks, new_metadata_schema = [], [] + if shuffle_reduce_out: + new_blocks, new_metadata_schema = unzip(shuffle_reduce_out) + new_metadata_schema: List[ + "BlockMetadataWithSchema" + ] = reduce_bar.fetch_until_complete(list(new_metadata_schema)) + + self.warn_on_high_local_memory_store_usage() + + output = [] + for block, meta_with_schema in zip(new_blocks, new_metadata_schema): + output.append( + RefBundle( + [ + ( + block, + meta_with_schema.metadata, + ) + ], + owns_blocks=input_owned, + schema=meta_with_schema.schema, + ) + ) + + stats = { + "map": to_stats(shuffle_map_metadata_schema), + "reduce": to_stats(new_metadata_schema), + } + + return (output, stats) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/push_based_shuffle_task_scheduler.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/push_based_shuffle_task_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..901eb69bd969f9317a8dd8323b14d1d6cd171d65 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/push_based_shuffle_task_scheduler.py @@ -0,0 +1,853 @@ +import logging +import math +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, TypeVar, Union + +import ray +from ray._private.ray_constants import CALLER_MEMORY_USAGE_PER_OBJECT_REF +from ray.data._internal.execution.interfaces import RefBundle, TaskContext +from ray.data._internal.planner.exchange.interfaces import ( + ExchangeTaskScheduler, + ExchangeTaskSpec, +) +from ray.data._internal.progress_bar import ProgressBar +from ray.data._internal.remote_fn import cached_remote_fn +from ray.data._internal.stats import StatsDict +from ray.data._internal.util import ( + convert_bytes_to_human_readable_str, + unzip, +) +from ray.data.block import ( + Block, + BlockAccessor, + BlockExecStats, + BlockMetadata, + BlockMetadataWithSchema, + _take_first_non_empty_schema, + to_stats, +) +from ray.data.context import DataContext +from ray.types import ObjectRef +from ray.util.scheduling_strategies import NodeAffinitySchedulingStrategy + +if TYPE_CHECKING: + + from ray.data.block import BlockMetadataWithSchema + +logger = logging.getLogger(__name__) + + +T = TypeVar("T") +U = TypeVar("U") + + +class _MergeTaskSchedule: + def __init__(self, output_num_blocks: int, num_merge_tasks_per_round: int): + self.output_num_blocks = output_num_blocks + self.num_merge_tasks_per_round = num_merge_tasks_per_round + self.num_reducers_per_merger = output_num_blocks // num_merge_tasks_per_round + self._num_mergers_with_extra_reducer = ( + output_num_blocks % num_merge_tasks_per_round + ) + + if self.num_reducers_per_merger == 0: + self.num_merge_tasks_per_round = self._num_mergers_with_extra_reducer + self.num_reducers_per_merger = 1 + self._num_mergers_with_extra_reducer = 0 + + def __repr__(self): + return ( + f" num merge tasks per round: {self.num_merge_tasks_per_round}\n" + f" num reduce tasks per merge task: {self.num_reducers_per_merger}\n" + " num merge tasks with extra reduce task: " + f"{self._num_mergers_with_extra_reducer}" + ) + + def get_num_reducers_per_merge_idx(self, merge_idx: int) -> int: + """ + Each intermediate merge task will produce outputs for a partition of P + final reduce tasks. This helper function returns P based on the merge + task index. + """ + assert merge_idx < self.num_merge_tasks_per_round + num_reducers_for_cur_merger = self.num_reducers_per_merger + if merge_idx < self._num_mergers_with_extra_reducer: + num_reducers_for_cur_merger += 1 + return num_reducers_for_cur_merger + + def get_merge_idx_for_reducer_idx(self, reducer_idx: int) -> int: + if ( + reducer_idx + < (self.num_reducers_per_merger + 1) * self._num_mergers_with_extra_reducer + ): + merge_idx = reducer_idx // (self.num_reducers_per_merger + 1) + else: + reducer_idx -= ( + self.num_reducers_per_merger + 1 + ) * self._num_mergers_with_extra_reducer + merge_idx = ( + self._num_mergers_with_extra_reducer + + reducer_idx // self.num_reducers_per_merger + ) + assert merge_idx < self.num_merge_tasks_per_round + return merge_idx + + def round_robin_reduce_idx_iterator(self): + """ + When there are multiple nodes, merge tasks are spread throughout the + cluster to improve load-balancing. Each merge task produces outputs for + a contiguous partition of reduce tasks. This method creates an iterator + that returns reduce task indices round-robin across the merge tasks. + This can be used to submit reduce tasks in a way that spreads the load + evenly across the cluster. + """ + idx = 0 + round_idx = 0 + while idx < self.output_num_blocks: + for merge_idx in range(self.num_merge_tasks_per_round): + if merge_idx < self._num_mergers_with_extra_reducer: + reduce_idx = merge_idx * (self.num_reducers_per_merger + 1) + num_reducers_for_cur_merger = self.num_reducers_per_merger + 1 + else: + reduce_idx = self._num_mergers_with_extra_reducer * ( + self.num_reducers_per_merger + 1 + ) + merge_idx -= self._num_mergers_with_extra_reducer + reduce_idx += merge_idx * self.num_reducers_per_merger + num_reducers_for_cur_merger = self.num_reducers_per_merger + + if round_idx >= num_reducers_for_cur_merger: + continue + + reduce_idx += round_idx + yield reduce_idx + idx += 1 + round_idx += 1 + + +class _PushBasedShuffleStage: + def __init__( + self, + output_num_blocks: int, + num_rounds: int, + num_map_tasks_per_round: int, + merge_task_placement: List[str], + ): + # The number of rounds of map-merge tasks. Reducer tasks are given the + # outputs of the merge tasks as inputs. Reducer tasks receive one input + # per round. + self.num_rounds = num_rounds + # The number of map tasks per round of map-merge tasks. The map task + # produces one output per merge task in the same round. + self.num_map_tasks_per_round = num_map_tasks_per_round + + node_strategies = { + node_id: { + "scheduling_strategy": NodeAffinitySchedulingStrategy( + node_id, soft=True + ) + } + for node_id in set(merge_task_placement) + } + self._merge_task_options = [ + node_strategies[node_id] for node_id in merge_task_placement + ] + + self.merge_schedule = _MergeTaskSchedule( + output_num_blocks, len(merge_task_placement) + ) + + def get_estimated_num_refs(self) -> int: + # Number of intermediate blocks = Number of rounds x (map tasks per + # round * merge tasks per round). + num_intermediate_refs = self.num_rounds * ( + self.num_map_tasks_per_round * self.merge_schedule.num_merge_tasks_per_round + ) + # Number of input blocks + intermediate blocks + output blocks. + num_refs_total = ( + (self.num_rounds * self.num_map_tasks_per_round) + + num_intermediate_refs + + self.merge_schedule.output_num_blocks + ) + return num_refs_total + + def get_merge_task_options(self, merge_idx): + return self._merge_task_options[merge_idx] + + def __repr__(self): + return ( + "num map tasks per round (num args per merge task): " + f"{self.num_map_tasks_per_round}\n" + f"num rounds (num args per reduce task): {self.num_rounds}\n" + "merge task placement: \n" + f"{self.merge_schedule}" + ) + + +class _PipelinedStageExecutor: + def __init__( + self, + stage_iter, + num_tasks_per_round: int, + max_concurrent_rounds: int = 1, + progress_bar: Optional[ProgressBar] = None, + ): + self._stage_iter = stage_iter + self._num_tasks_per_round = num_tasks_per_round + self._max_concurrent_rounds = max_concurrent_rounds + self._progress_bar = progress_bar + + self._rounds: List[List[ObjectRef]] = [] + self._task_idx = 0 + + self._submit_round() + + self._num_block_bytes_stored_at_driver = 0 + + def __iter__(self): + return self + + def __next__(self) -> List["BlockMetadataWithSchema"]: + """ + Submit one round of tasks. If we already have the max concurrent rounds + in flight, first wait for the oldest round of tasks to finish. + """ + prev_metadata_and_schema = [] + if all(len(r) == 0 for r in self._rounds): + raise StopIteration + + if len(self._rounds) >= self._max_concurrent_rounds: + prev_metadata_schema_refs = self._rounds.pop(0) + if prev_metadata_schema_refs: + if self._progress_bar is not None: + prev_metadata_and_schema = self._progress_bar.fetch_until_complete( + prev_metadata_schema_refs + ) + # TODO(swang): Eagerly free the previous round's args. + # See https://github.com/ray-project/ray/issues/42145. + else: + prev_metadata_and_schema = ray.get(prev_metadata_schema_refs) + + self._submit_round() + + return prev_metadata_and_schema + + def _submit_round(self): + assert len(self._rounds) < self._max_concurrent_rounds + task_round = [] + for _ in range(self._num_tasks_per_round): + try: + task_round.append(next(self._stage_iter)) + except StopIteration: + break + self._rounds.append(task_round) + + +class _MapStageIterator: + def __init__(self, input_blocks_list, shuffle_map, map_args): + self._input_blocks_list = input_blocks_list + self._shuffle_map = shuffle_map + self._map_args = map_args + + self._mapper_idx = 0 + self._map_results = [] + + def __iter__(self): + return self + + def __next__(self): + if not self._input_blocks_list: + raise StopIteration + + block = self._input_blocks_list.pop(0) + # NOTE(swang): Results are shuffled between map and merge tasks, so + # there is no advantage to colocating specific map and merge tasks. + # Therefore, we do not specify a node affinity policy for map tasks + # in case the caller or Ray has a better scheduling strategy, e.g., + # based on data locality. + map_result = self._shuffle_map.remote( + self._mapper_idx, + block, + *self._map_args, + ) + metadata_schema_ref = map_result.pop(-1) + self._map_results.append(map_result) + self._mapper_idx += 1 + return metadata_schema_ref + + def pop_map_results(self) -> List[List[ObjectRef]]: + map_results = self._map_results + self._map_results = [] + return map_results + + +class _MergeStageIterator: + def __init__( + self, + map_stage_iter: _MapStageIterator, + shuffle_merge, + stage: _PushBasedShuffleStage, + reduce_args, + ): + self._map_stage_iter = map_stage_iter + self._shuffle_merge = shuffle_merge + self._stage = stage + self._reduce_args = reduce_args + + self._merge_idx = 0 + self._map_result_buffer = None + # Final outputs from the map-merge stage. + # This is a map from merge task index to a nested list of merge results + # (ObjectRefs). Each merge task index corresponds to a partition of P + # final reduce tasks. + self._all_merge_results = [ + [] for _ in range(self._stage.merge_schedule.num_merge_tasks_per_round) + ] + + def __next__(self): + if not self._map_result_buffer or not self._map_result_buffer[0]: + assert self._merge_idx == 0 + self._map_result_buffer = self._map_stage_iter.pop_map_results() + + if not self._map_result_buffer: + raise StopIteration + + # Shuffle the map results for the merge tasks. + merge_args = [map_result.pop(0) for map_result in self._map_result_buffer] + num_merge_returns = self._stage.merge_schedule.get_num_reducers_per_merge_idx( + self._merge_idx + ) + merge_result = self._shuffle_merge.options( + num_returns=1 + num_merge_returns, + **self._stage.get_merge_task_options(self._merge_idx), + ).remote( + *merge_args, + reduce_args=self._reduce_args, + ) + metadata_schema_ref = merge_result.pop(-1) + self._all_merge_results[self._merge_idx].append(merge_result) + del merge_result + + self._merge_idx += 1 + self._merge_idx %= self._stage.merge_schedule.num_merge_tasks_per_round + return metadata_schema_ref + + def pop_merge_results(self) -> List[List[ObjectRef]]: + """Return a nested list of merge task results. The list at index i + stores the outputs of the i-th merge task submitted during each + map-merge round. Each merge task returns a list of outputs because it + may produce outputs for multiple downstream reduce tasks. + """ + all_merge_results = self._all_merge_results + self._all_merge_results = [] + return all_merge_results + + +class _ReduceStageIterator: + def __init__( + self, + stage: _PushBasedShuffleStage, + shuffle_reduce, + all_merge_results: List[List[List[ObjectRef]]], + ray_remote_args, + reduce_args: List[Any], + _debug_limit_execution_to_num_blocks: Optional[int], + ): + self._shuffle_reduce = shuffle_reduce + self._stage = stage + self._reduce_arg_blocks: List[Tuple[int, List[ObjectRef]]] = [] + self._ray_remote_args = ray_remote_args + self._reduce_args = reduce_args + + for reduce_idx in self._stage.merge_schedule.round_robin_reduce_idx_iterator(): + merge_idx = self._stage.merge_schedule.get_merge_idx_for_reducer_idx( + reduce_idx + ) + reduce_arg_blocks = [ + merge_results.pop(0) for merge_results in all_merge_results[merge_idx] + ] + self._reduce_arg_blocks.append((reduce_idx, reduce_arg_blocks)) + + assert len(self._reduce_arg_blocks) == stage.merge_schedule.output_num_blocks + + if _debug_limit_execution_to_num_blocks is not None: + self._reduce_arg_blocks = self._reduce_arg_blocks[ + :_debug_limit_execution_to_num_blocks + ] + logger.debug( + f"Limiting execution to {len(self._reduce_arg_blocks)} reduce tasks" + ) + + for merge_idx, merge_results in enumerate(all_merge_results): + assert all(len(merge_result) == 0 for merge_result in merge_results), ( + "Reduce stage did not process outputs from merge tasks at index: " + f"{merge_idx}" + ) + + self._reduce_results: List[Tuple[int, ObjectRef]] = [] + + def __iter__(self): + return self + + def __next__(self): + if not self._reduce_arg_blocks: + raise StopIteration + + reduce_idx, reduce_arg_blocks = self._reduce_arg_blocks.pop(0) + merge_idx = self._stage.merge_schedule.get_merge_idx_for_reducer_idx(reduce_idx) + # Submit one partition of reduce tasks, one for each of the P + # outputs produced by the corresponding merge task. + # We also add the merge task arguments so that the reduce task + # is colocated with its inputs. + block, meta_with_schema = self._shuffle_reduce.options( + **self._ray_remote_args, + **self._stage.get_merge_task_options(merge_idx), + num_returns=2, + ).remote(*self._reduce_args, *reduce_arg_blocks, partial_reduce=False) + self._reduce_results.append((reduce_idx, block)) + return meta_with_schema + + def pop_reduce_results(self): + reduce_results = self._reduce_results + self._reduce_results = [] + return reduce_results + + +class PushBasedShuffleTaskScheduler(ExchangeTaskScheduler): + """ + Push-based shuffle merges intermediate map outputs on the reducer nodes + while other map tasks are executing. The merged outputs are merged again + during a final reduce stage. This works as follows: + + 1. Submit rounds of concurrent map and merge tasks until all map inputs + have been processed. In each round, we execute: + + M map tasks + Each produces N outputs. Each output contains P blocks. + N merge tasks + Takes 1 output from each of M map tasks. + Each produces P outputs. + Where M and N are chosen to maximize parallelism across CPUs. Note that + this assumes that all CPUs in the cluster will be dedicated to the + shuffle job. + + Map and merge tasks are pipelined so that we always merge the previous + round of map outputs while executing the next round of map tasks. + + 2. In the final reduce stage: + R reduce tasks + Takes 1 output from one of the merge tasks from every round. + + Notes: + N * P = R = total number of output blocks + M / N = merge factor - the ratio of map : merge tasks is to improve + pipelined parallelism. For example, if map takes twice as long to + execute as merge, then we should set this to 2. If pipeline bubbles + appear and the merge tasks are much longer than the map tasks, then + the merge factor should be decreased, and vice versa. + See paper at https://arxiv.org/abs/2203.05072 for more details. + """ + + def execute( + self, + refs: List[RefBundle], + output_num_blocks: int, + task_ctx: TaskContext, + map_ray_remote_args: Optional[Dict[str, Any]] = None, + reduce_ray_remote_args: Optional[Dict[str, Any]] = None, + merge_factor: float = 2, + _debug_limit_execution_to_num_blocks: int = None, + ) -> Tuple[List[RefBundle], StatsDict]: + logger.debug("Using experimental push-based shuffle.") + # TODO: Preemptively clear the blocks list since we will incrementally delete + # the last remaining references as we submit the dependent map tasks during the + # map-merge stage. + + # TODO(swang): For jobs whose reduce work is heavier than the map work, + # we should support fractional merge factors. + # TODO(swang): For large jobs, we should try to choose the merge factor + # automatically, e.g., by running one test round of map and merge tasks + # and comparing their run times. + # TODO(swang): Add option to automatically reduce write amplification + # during map-merge stage, by limiting how many partitions can be + # processed concurrently. + input_blocks_list = [] + for ref_bundle in refs: + input_blocks_list.extend(ref_bundle.block_refs) + input_owned = all(b.owns_blocks for b in refs) + + if map_ray_remote_args is None: + map_ray_remote_args = {} + if reduce_ray_remote_args is None: + reduce_ray_remote_args = {} + # The placement strategy for reduce tasks is overwritten to colocate + # them with their inputs from the merge stage, so remove any + # pre-specified scheduling strategy here. + reduce_ray_remote_args = reduce_ray_remote_args.copy() + reduce_ray_remote_args.pop("scheduling_strategy", None) + + # Compute all constants used for task scheduling. + num_cpus_per_node_map = _get_num_cpus_per_node_map() + stage = self._compute_shuffle_schedule( + num_cpus_per_node_map, + len(input_blocks_list), + merge_factor, + output_num_blocks, + ) + + caller_memory_usage = ( + stage.get_estimated_num_refs() * CALLER_MEMORY_USAGE_PER_OBJECT_REF + ) + self.warn_on_driver_memory_usage( + caller_memory_usage, + "Execution is estimated to use at least " + f"{convert_bytes_to_human_readable_str(caller_memory_usage)}" + " of driver memory. Ensure that the driver machine has at least " + "this much memory to ensure job completion.", + ) + + # TODO(swang): Use INFO level. Currently there is no easy way to set + # the logging level to DEBUG from a driver script, so just print + # verbosely for now. + # See https://github.com/ray-project/ray/issues/42002. + logger.debug(f"Push-based shuffle schedule:\n{stage}") + + map_fn = self._map_partition + merge_fn = self._merge + + def map_partition(*args, **kwargs): + return map_fn(self._exchange_spec.map, *args, **kwargs) + + def merge(*args, **kwargs): + return merge_fn(self._exchange_spec.reduce, *args, **kwargs) + + shuffle_map = cached_remote_fn(map_partition) + shuffle_map = shuffle_map.options( + **map_ray_remote_args, + num_returns=1 + stage.merge_schedule.num_merge_tasks_per_round, + ) + + if _debug_limit_execution_to_num_blocks is not None: + input_blocks_list = input_blocks_list[:_debug_limit_execution_to_num_blocks] + logger.debug(f"Limiting execution to {len(input_blocks_list)} map tasks") + map_stage_iter = _MapStageIterator( + input_blocks_list, + shuffle_map, + [output_num_blocks, stage.merge_schedule, *self._exchange_spec._map_args], + ) + + sub_progress_bar_dict = task_ctx.sub_progress_bar_dict + bar_name = ExchangeTaskSpec.MAP_SUB_PROGRESS_BAR_NAME + assert bar_name in sub_progress_bar_dict, sub_progress_bar_dict + map_bar = sub_progress_bar_dict[bar_name] + map_stage_executor = _PipelinedStageExecutor( + map_stage_iter, stage.num_map_tasks_per_round, progress_bar=map_bar + ) + + shuffle_merge = cached_remote_fn(merge) + merge_stage_iter = _MergeStageIterator( + map_stage_iter, shuffle_merge, stage, self._exchange_spec._reduce_args + ) + merge_stage_executor = _PipelinedStageExecutor( + merge_stage_iter, + stage.merge_schedule.num_merge_tasks_per_round, + max_concurrent_rounds=2, + ) + # Execute the map-merge stage. This submits tasks in rounds of M map + # tasks and N merge tasks each. Task execution between map and merge is + # pipelined, so that while executing merge for one round of inputs, we + # also execute the map tasks for the following round. + map_done = False + merge_done = False + map_stage_metadata_schema = [] + merge_stage_metadata_schema = [] + while not (map_done and merge_done): + try: + map_stage_metadata_schema += next(map_stage_executor) + except StopIteration: + map_done = True + break + + try: + merge_stage_metadata_schema += next(merge_stage_executor) + except StopIteration: + merge_done = True + break + + self.warn_on_high_local_memory_store_usage() + + all_merge_results = merge_stage_iter.pop_merge_results() + + if _debug_limit_execution_to_num_blocks is not None: + for merge_idx in range(len(all_merge_results)): + while len(all_merge_results[merge_idx]) < stage.num_rounds: + # Repeat the first merge task's results. + all_merge_results[merge_idx].append( + all_merge_results[merge_idx][0][:] + ) + + # Execute and wait for the reduce stage. + bar_name = ExchangeTaskSpec.REDUCE_SUB_PROGRESS_BAR_NAME + assert bar_name in sub_progress_bar_dict, sub_progress_bar_dict + reduce_bar = sub_progress_bar_dict[bar_name] + + shuffle_reduce = cached_remote_fn(self._exchange_spec.reduce) + reduce_stage_iter = _ReduceStageIterator( + stage, + shuffle_reduce, + all_merge_results, + reduce_ray_remote_args, + self._exchange_spec._reduce_args, + _debug_limit_execution_to_num_blocks, + ) + + max_reduce_tasks_in_flight = output_num_blocks + ctx = DataContext.get_current() + if ctx.pipeline_push_based_shuffle_reduce_tasks: + # If pipelining is enabled, we should still try to utilize all + # cores. + max_reduce_tasks_in_flight = min( + max_reduce_tasks_in_flight, sum(num_cpus_per_node_map.values()) + ) + + reduce_stage_executor = _PipelinedStageExecutor( + reduce_stage_iter, + max_reduce_tasks_in_flight, + max_concurrent_rounds=2, + progress_bar=reduce_bar, + ) + reduce_stage_metadata_schema = [] + while True: + try: + reduce_stage_metadata_schema += next(reduce_stage_executor) + except StopIteration: + break + + self.warn_on_high_local_memory_store_usage() + + new_blocks = reduce_stage_iter.pop_reduce_results() + sorted_blocks = [ + (block[0], block[1], reduce_stage_metadata_schema[i]) + for i, block in enumerate(new_blocks) + ] + sorted_blocks.sort(key=lambda x: x[0]) + + new_blocks, reduce_stage_metadata_schema = [], [] + if sorted_blocks: + res: Tuple[ + List[Any], List[ObjectRef[Block]], List[BlockMetadataWithSchema] + ] = unzip(sorted_blocks) + _, new_blocks, reduce_stage_metadata_schema = res + del sorted_blocks + + if _debug_limit_execution_to_num_blocks is not None: + output_num_blocks = min( + _debug_limit_execution_to_num_blocks, output_num_blocks + ) + + assert ( + len(new_blocks) == output_num_blocks + ), f"Expected {output_num_blocks} outputs, produced {len(new_blocks)}" + + output = [] + for block, meta_with_schema in zip(new_blocks, reduce_stage_metadata_schema): + output.append( + RefBundle( + [ + ( + block, + meta_with_schema.metadata, + ) + ], + owns_blocks=input_owned, + schema=meta_with_schema.schema, + ) + ) + + stats = { + "map": to_stats(map_stage_metadata_schema), + "merge": to_stats(merge_stage_metadata_schema), + "reduce": to_stats(reduce_stage_metadata_schema), + } + + return (output, stats) + + @staticmethod + def _map_partition( + map_fn, + idx: int, + block: Block, + output_num_blocks: int, + schedule: _MergeTaskSchedule, + *map_args: List[Any], + ) -> List[Union[Block, "BlockMetadataWithSchema"]]: + mapper_outputs = map_fn(idx, block, output_num_blocks, *map_args) + + # A merge task may produce results for multiple downstream reducer + # tasks. Therefore, each map task should give each merge task a + # partition of its outputs, where the length of the partition is equal + # to the number of reducers downstream to the merge task. + partition = [] + merge_idx = 0 + while merge_idx < schedule.num_merge_tasks_per_round and mapper_outputs: + output = mapper_outputs.pop(0) + partition.append(output) + + if len(partition) == schedule.get_num_reducers_per_merge_idx(merge_idx): + yield partition + + partition = [] + merge_idx += 1 + + assert not partition + assert len(mapper_outputs) == 1, ( + mapper_outputs, + "The last output should be a BlockMetadataWithSchema", + ) + assert isinstance(mapper_outputs[0], BlockMetadataWithSchema) + yield mapper_outputs[0] + + assert merge_idx == schedule.num_merge_tasks_per_round, ( + merge_idx, + schedule.num_merge_tasks_per_round, + ) + + @staticmethod + def _merge( + reduce_fn, + *all_mapper_outputs: List[List[Block]], + reduce_args: Optional[List[Any]] = None, + ) -> List[Union["BlockMetadataWithSchema", Block]]: + """ + Returns list of [BlockMetadata, O1, O2, O3, ...output_num_blocks]. + """ + assert ( + len({len(mapper_outputs) for mapper_outputs in all_mapper_outputs}) == 1 + ), "Received different number of map inputs" + stats = BlockExecStats.builder() + if not reduce_args: + reduce_args = [] + + num_rows = 0 + size_bytes = 0 + schemas = [] + for i, mapper_outputs in enumerate(zip(*all_mapper_outputs)): + block_meta_with_schema: Tuple[Block, "BlockMetadataWithSchema"] = reduce_fn( + *reduce_args, *mapper_outputs, partial_reduce=True + ) + block, meta_with_schema = block_meta_with_schema + yield block + + block = BlockAccessor.for_block(block) + num_rows += block.num_rows() + size_bytes += block.size_bytes() + del block + schemas.append(meta_with_schema.schema) + + schema = _take_first_non_empty_schema(iter(schemas)) + + meta = BlockMetadata( + num_rows=num_rows, + size_bytes=size_bytes, + input_files=None, + exec_stats=stats.build(), + ) + meta_with_schema = BlockMetadataWithSchema(metadata=meta, schema=schema) + yield meta_with_schema + + @staticmethod + def _compute_shuffle_schedule( + num_cpus_per_node_map: Dict[str, int], + num_input_blocks: int, + merge_factor: float, + num_output_blocks: int, + ) -> _PushBasedShuffleStage: + num_cpus_total = sum(v for v in num_cpus_per_node_map.values()) + logger.debug( + f"Found {num_cpus_total} CPUs available CPUs for push-based shuffle." + ) + num_tasks_per_map_merge_group = merge_factor + 1 + num_total_merge_tasks = math.ceil(num_input_blocks / merge_factor) + + num_merge_tasks_per_round = 0 + merge_task_placement = [] + leftover_cpus = 0 + # Compute the total number of merge tasks and their node placement. + # Each merge task should be grouped with `merge_factor` map tasks for + # pipelining. These groups should then be spread across nodes according + # to CPU availability for load-balancing. + num_input_blocks_remaining = num_input_blocks + for node, num_cpus in num_cpus_per_node_map.items(): + # First find how many merge tasks we should run on this node. + # We take the min of the number of CPUs on this node and the number + # of input blocks that we haven't scheduled yet, in case there are + # fewer input blocks than CPU slots on this node. + num_cpu_slots = min(num_cpus, num_input_blocks_remaining) + num_merge_tasks_on_cur_node = round( + num_cpu_slots / num_tasks_per_map_merge_group + ) + # For small datasets, the number of tasks to run may be less than + # the total CPU slots available. + num_merge_tasks_on_cur_node = min( + num_merge_tasks_on_cur_node, num_total_merge_tasks + ) + for i in range(num_merge_tasks_on_cur_node): + merge_task_placement.append(node) + # We schedule `merge_factor` many map tasks for every merge + # task. Subtract from the number of input blocks remaining to + # account for cases where the number of map tasks is smaller + # than the available CPU slots. + num_input_blocks_remaining -= merge_factor + num_cpus -= num_tasks_per_map_merge_group + num_merge_tasks_per_round += num_merge_tasks_on_cur_node + + # Handle the case where a single node cannot fit a group of map and + # merge tasks, but we can spread the group across multiple distinct + # nodes. + leftover_cpus += num_cpus + if ( + leftover_cpus >= num_tasks_per_map_merge_group + and num_merge_tasks_per_round < num_total_merge_tasks + ): + merge_task_placement.append(node) + num_merge_tasks_per_round += 1 + leftover_cpus -= num_tasks_per_map_merge_group + num_input_blocks_remaining -= merge_factor + + num_input_blocks_remaining = max(0, num_input_blocks_remaining) + + if num_merge_tasks_per_round == 0: + # For small datasets, make sure we have at least one merge task. + for node, num_cpus in num_cpus_per_node_map.items(): + if num_cpus >= 1: + merge_task_placement.append(node) + num_merge_tasks_per_round = 1 + break + + assert num_merge_tasks_per_round == len(merge_task_placement) + assert num_merge_tasks_per_round > 0, num_merge_tasks_per_round + # Use the remaining CPUs to execute map tasks. + num_map_tasks_per_round = num_cpus_total - num_merge_tasks_per_round + num_map_tasks_per_round = min(num_map_tasks_per_round, num_input_blocks) + # Make sure there is at least one map task in each round. + num_map_tasks_per_round = max(num_map_tasks_per_round, 1) + + num_rounds = math.ceil(num_input_blocks / num_map_tasks_per_round) + return _PushBasedShuffleStage( + num_output_blocks, + num_rounds, + num_map_tasks_per_round, + merge_task_placement, + ) + + +def _get_num_cpus_per_node_map() -> Dict[str, int]: + total_resources_by_node = ray.state.total_resources_per_node() + # Map from per-node resource name to number of CPUs available on that + # node. + num_cpus_per_node_map = {} + for node_id, resources in total_resources_by_node.items(): + num_cpus = int(resources.get("CPU", 0)) + if num_cpus == 0: + continue + num_cpus_per_node_map[node_id] = num_cpus + return num_cpus_per_node_map diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/shuffle_task_spec.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/shuffle_task_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..48c4c9f84a54b5b70964c6695dee21f6e8e51d0f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/shuffle_task_spec.py @@ -0,0 +1,146 @@ +import logging +import math +from typing import Callable, Iterable, List, Optional, Tuple, Union + +import numpy as np + +from ray.data._internal.delegating_block_builder import DelegatingBlockBuilder +from ray.data._internal.planner.exchange.interfaces import ExchangeTaskSpec +from ray.data.block import ( + Block, + BlockAccessor, + BlockExecStats, + BlockMetadata, + BlockMetadataWithSchema, +) +from ray.data.context import MAX_SAFE_BLOCK_SIZE_FACTOR + +logger = logging.getLogger(__name__) + + +class ShuffleTaskSpec(ExchangeTaskSpec): + """ + The implementation for shuffle tasks. + + This is used by random_shuffle() and repartition(). + """ + + SPLIT_REPARTITION_SUB_PROGRESS_BAR_NAME = "Split Repartition" + + def __init__( + self, + target_shuffle_max_block_size: int, + random_shuffle: bool = False, + random_seed: Optional[int] = None, + upstream_map_fn: Optional[Callable[[Iterable[Block]], Iterable[Block]]] = None, + ): + super().__init__( + map_args=[ + target_shuffle_max_block_size, + upstream_map_fn, + random_shuffle, + random_seed, + ], + reduce_args=[random_shuffle, random_seed], + ) + + @staticmethod + def map( + idx: int, + block: Block, + output_num_blocks: int, + target_shuffle_max_block_size: int, + upstream_map_fn: Optional[Callable[[Iterable[Block]], Iterable[Block]]], + random_shuffle: bool, + random_seed: Optional[int], + ) -> List[Union[Block, "BlockMetadataWithSchema"]]: + stats = BlockExecStats.builder() + if upstream_map_fn: + # TODO: Support dynamic block splitting in + # all-to-all ops, to avoid having to re-fuse + # upstream blocks together. + upstream_map_iter = upstream_map_fn([block]) + mapped_block = next(upstream_map_iter) + builder = BlockAccessor.for_block(mapped_block).builder() + builder.add_block(mapped_block) + for mapped_block in upstream_map_iter: + builder.add_block(mapped_block) + # Drop the upstream inputs to reduce memory usage. + del mapped_block + block = builder.build() + block = BlockAccessor.for_block(block) + if ( + block.size_bytes() + > MAX_SAFE_BLOCK_SIZE_FACTOR * target_shuffle_max_block_size + ): + logger.warning( + "Input block to map task has size " + f"{block.size_bytes() // (1024 * 1024)}MiB, which exceeds " + "DataContext.get_current().target_shuffle_max_block_size=" + f"{target_shuffle_max_block_size // (1024 * 1024)}MiB. " + "This can lead to out-of-memory errors and can happen " + "when map tasks are fused to the shuffle operation. " + "To prevent fusion, call Dataset.materialize() on the " + "dataset before shuffling." + ) + + # Randomize the distribution of records to blocks. + if random_shuffle: + seed_i = random_seed + idx if random_seed is not None else None + block = block.random_shuffle(seed_i) + block = BlockAccessor.for_block(block) + + # Build a list of slices to return. It's okay to put the results in a + # list instead of yielding them as a generator because slicing the + # ArrowBlock is zero-copy. + slice_sz = max(1, math.ceil(block.num_rows() / output_num_blocks)) + slices = [] + for i in range(output_num_blocks): + slices.append(block.slice(i * slice_sz, (i + 1) * slice_sz)) + + # Randomize the distribution order of the blocks (this prevents empty + # outputs when input blocks are very small). + if random_shuffle: + random = np.random.RandomState(seed_i) + random.shuffle(slices) + + num_rows = sum(BlockAccessor.for_block(s).num_rows() for s in slices) + assert num_rows == block.num_rows(), (num_rows, block.num_rows()) + from ray.data.block import BlockMetadataWithSchema + + meta = block.get_metadata(exec_stats=stats.build()) + schema = block.schema() + meta_with_schema = BlockMetadataWithSchema(metadata=meta, schema=schema) + return slices + [meta_with_schema] + + @staticmethod + def reduce( + random_shuffle: bool, + random_seed: Optional[int], + *mapper_outputs: List[Block], + partial_reduce: bool = False, + ) -> Tuple[Block, "BlockMetadataWithSchema"]: + # TODO: Support fusion with other downstream operators. + stats = BlockExecStats.builder() + builder = DelegatingBlockBuilder() + for block in mapper_outputs: + builder.add_block(block) + new_block = builder.build() + accessor = BlockAccessor.for_block(new_block) + if random_shuffle: + new_block = accessor.random_shuffle( + random_seed if random_seed is not None else None + ) + accessor = BlockAccessor.for_block(new_block) + new_metadata = BlockMetadata( + num_rows=accessor.num_rows(), + size_bytes=accessor.size_bytes(), + input_files=None, + exec_stats=stats.build(), + ) + from ray.data.block import BlockMetadataWithSchema + + meta_with_schema = BlockMetadataWithSchema( + metadata=new_metadata, schema=accessor.schema() + ) + return new_block, meta_with_schema diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/sort_task_spec.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/sort_task_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..9e843f77eadb2b505e0f7f233cb9e0037bc0789b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/sort_task_spec.py @@ -0,0 +1,239 @@ +from typing import TYPE_CHECKING, List, Optional, Tuple, TypeVar, Union + +import numpy as np + +from ray.data._internal.delegating_block_builder import DelegatingBlockBuilder +from ray.data._internal.planner.exchange.interfaces import ExchangeTaskSpec +from ray.data._internal.progress_bar import ProgressBar +from ray.data._internal.remote_fn import cached_remote_fn +from ray.data._internal.table_block import TableBlockAccessor +from ray.data._internal.util import NULL_SENTINEL +from ray.data.block import Block, BlockAccessor, BlockExecStats +from ray.types import ObjectRef + +T = TypeVar("T") + +if TYPE_CHECKING: + import pyarrow + + from ray.data.block import BlockMetadataWithSchema + + +class SortKey: + """SortKey class to convert between different sort args formats.""" + + def __init__( + self, + key: Optional[Union[str, List[str]]] = None, + descending: Union[bool, List[bool]] = False, + boundaries: Optional[List[T]] = None, + ): + if key is None: + key = [] + if isinstance(key, str): + key = [key] + if not (isinstance(key, list) and all(isinstance(k, str) for k in key)): + raise ValueError( + f"Key must be a string or a list of strings, but got {key}." + ) + if isinstance(descending, bool): + descending = [descending for _ in key] + elif isinstance(descending, list): + if len(descending) != len(key): + raise ValueError( + "Length of `descending` does not match the length of the key." + ) + self._columns = key + self._descending = descending + if boundaries: + for item in boundaries: + if not isinstance(item, (int, float)): + raise ValueError( + "The type of items in boundaries must be int or float." + ) + boundaries = list(set(boundaries)) + boundaries.sort() + self._boundaries = boundaries + + def get_columns(self) -> List[str]: + return self._columns + + def get_descending(self) -> List[bool]: + return self._descending + + def to_arrow_sort_args(self) -> List[Tuple[str, str]]: + return [ + (key, "descending" if desc else "ascending") + for key, desc in zip(self._columns, self._descending) + ] + + def to_pandas_sort_args(self) -> Tuple[List[str], List[bool]]: + return self._columns, [not desc for desc in self._descending] + + def validate_schema(self, schema: Optional[Union[type, "pyarrow.lib.Schema"]]): + """Check the key function is valid on the given schema.""" + if schema is None: + # Dataset is empty/cleared, validation not possible. + return + + if self._columns and len(schema.names) > 0: + schema_names_set = set(schema.names) + for column in self._columns: + if column not in schema_names_set: + raise ValueError( + f"You specified the column '{column}', but there's no such " + "column in the dataset. The dataset has columns: " + f"{schema.names}" + ) + + @property + def boundaries(self): + return self._boundaries + + +class SortTaskSpec(ExchangeTaskSpec): + """ + The implementation for distributed sort tasks. + + The algorithm is similar to [External Merge Sort] + (https://en.wikipedia.org/wiki/External_sorting). + Sorting is done in 3 steps: sampling, sorting individual blocks, and + merging sorted blocks. + + Sampling (`sample_boundaries`): we get a number of sample items from each block, + sort them, and use them to compute boundaries that would partition all items into + approximately equal ranges. + + Sorting (`map`): each block is sorted locally, then partitioned into smaller + blocks according to the boundaries. Each partitioned block is passed to a merge + task. + + Merging (`reduce`): a merge task would receive a block from every worker that + consists of items in a certain range. It then merges the sorted blocks into one + sorted block and becomes part of the new, sorted block. + """ + + SORT_SAMPLE_SUB_PROGRESS_BAR_NAME = "Sort Sample" + + def __init__( + self, + boundaries: List[T], + sort_key: SortKey, + batch_format: str, + ): + super().__init__( + map_args=[boundaries, sort_key], + reduce_args=[sort_key, batch_format], + ) + + @staticmethod + def map( + idx: int, + block: Block, + output_num_blocks: int, + boundaries: List[T], + sort_key: SortKey, + ) -> List[Union[Block, "BlockMetadataWithSchema"]]: + stats = BlockExecStats.builder() + accessor = BlockAccessor.for_block(block) + out = accessor.sort_and_partition(boundaries, sort_key) + from ray.data.block import BlockMetadataWithSchema + + meta_with_schema = BlockMetadataWithSchema.from_block( + block, stats=stats.build() + ) + return out + [meta_with_schema] + + @staticmethod + def reduce( + sort_key: SortKey, + batch_format: str, + *mapper_outputs: List[Block], + partial_reduce: bool = False, + ) -> Tuple[Block, "BlockMetadataWithSchema"]: + normalized_blocks = TableBlockAccessor.normalize_block_types( + mapper_outputs, + target_block_type=ExchangeTaskSpec._derive_target_block_type(batch_format), + ) + blocks, meta_with_schema = BlockAccessor.for_block( + normalized_blocks[0] + ).merge_sorted_blocks(normalized_blocks, sort_key) + return blocks, meta_with_schema + + @staticmethod + def sample_boundaries( + blocks: List[ObjectRef[Block]], + sort_key: SortKey, + num_reducers: int, + sample_bar: Optional[ProgressBar] = None, + ) -> List[T]: + """ + Return (num_reducers - 1) items in ascending order from the blocks that + partition the domain into ranges with approximately equally many elements. + Each boundary item is a tuple of a form (col1_value, col2_value, ...). + """ + columns = sort_key.get_columns() + n_samples = int(num_reducers * 10 / len(blocks)) + + sample_block = cached_remote_fn(_sample_block) + + sample_results = [ + sample_block.remote(block, n_samples, sort_key) for block in blocks + ] + if sample_bar is None: + sample_bar = ProgressBar( + SortTaskSpec.SORT_SAMPLE_SUB_PROGRESS_BAR_NAME, + len(blocks) * n_samples, + unit="rows", + ) + # TODO(zhilong): Update sort sample bar before finished. + samples = sample_bar.fetch_until_complete(sample_results) + del sample_results + samples: List[Block] = [s for s in samples if len(s) > 0] + # The dataset is empty + if len(samples) == 0: + return [None] * (num_reducers - 1) + + # Convert samples to a sorted list[tuple[...]] where each tuple represents a + # sample. + # TODO: Once we deprecate pandas blocks, we can avoid this conversion and + # directly sort the samples. + builder = DelegatingBlockBuilder() + for sample in samples: + builder.add_block(sample) + samples_table = builder.build() + samples_dict = BlockAccessor.for_block(samples_table).to_numpy(columns=columns) + # This zip does the transposition from list of column values to list of tuples. + samples_list = list(zip(*samples_dict.values())) + + def is_na(x): + # Check if x is None or NaN. Type casting to np.array first to avoid + # isnan failing on strings and other types. + if x is None: + return True + x = np.asarray(x) + if np.issubdtype(x.dtype, np.number): + return np.isnan(x) + return False + + # To allow multi-directional sort, we utilize Python's stable sort: we + # sort several times with different directions. We do this in reverse, so + # that the last key we sort by is the primary sort key passed by the user. + for i, desc in list(enumerate(sort_key.get_descending()))[::-1]: + # Sort the list, but Nones should be NULL_SENTINEL to ensure safe sorting. + samples_list.sort( + key=lambda sample: NULL_SENTINEL if is_na(sample[i]) else sample[i], + reverse=desc, + ) + + # Each boundary corresponds to a quantile of the data. + quantile_indices = [ + int(q * (len(samples_list) - 1)) + for q in np.linspace(0, 1, num_reducers + 1) + ] + # Exclude the first and last quantiles because they're 0 and 1. + return [samples_list[i] for i in quantile_indices[1:-1]] + + +def _sample_block(block: Block, n_samples: int, sort_key: SortKey) -> Block: + return BlockAccessor.for_block(block).sample(n_samples, sort_key) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/split_repartition_task_scheduler.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/split_repartition_task_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..1c3a563ef6948b52033d60ba415ea37adf26b507 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/exchange/split_repartition_task_scheduler.py @@ -0,0 +1,166 @@ +from typing import Any, Dict, List, Optional, Tuple + +import ray +from ray.data._internal.execution.interfaces import RefBundle, TaskContext +from ray.data._internal.execution.interfaces.transform_fn import ( + AllToAllTransformFnResult, +) +from ray.data._internal.planner.exchange.interfaces import ( + ExchangeTaskScheduler, +) +from ray.data._internal.planner.exchange.shuffle_task_spec import ShuffleTaskSpec +from ray.data._internal.remote_fn import cached_remote_fn +from ray.data._internal.split import _split_at_indices +from ray.data._internal.util import unzip +from ray.data.block import ( + Block, + BlockMetadata, + BlockMetadataWithSchema, +) +from ray.types import ObjectRef + + +class SplitRepartitionTaskScheduler(ExchangeTaskScheduler): + """ + The split (non-shuffle) repartition scheduler. + + First, we calculate global splits needed to produce `output_num_blocks` blocks. + After the split blocks are generated accordingly, reduce tasks are scheduled + to combine split blocks together. + """ + + def execute( + self, + refs: List[RefBundle], + output_num_blocks: int, + ctx: TaskContext, + map_ray_remote_args: Optional[Dict[str, Any]] = None, + reduce_ray_remote_args: Optional[Dict[str, Any]] = None, + ) -> AllToAllTransformFnResult: + input_num_rows = 0 + input_owned_by_consumer = True + for ref_bundle in refs: + block_num_rows = ref_bundle.num_rows() + if block_num_rows is None: + raise ValueError( + "Cannot split partition on blocks with unknown number of rows." + ) + input_num_rows += block_num_rows + if not ref_bundle.owns_blocks: + input_owned_by_consumer = False + + # Compute the (output_num_blocks) indices needed for an equal split of the + # input blocks. When output_num_blocks=1, the total number of + # input rows is used as the end index during the split calculation, + # so that we can combine all input blocks into a single output block. + indices = [] + if output_num_blocks == 1: + indices = [input_num_rows] + else: + cur_idx = 0 + for _ in range(output_num_blocks - 1): + cur_idx += input_num_rows / output_num_blocks + indices.append(int(cur_idx)) + assert len(indices) <= output_num_blocks, (indices, output_num_blocks) + + if map_ray_remote_args is None: + map_ray_remote_args = {} + if reduce_ray_remote_args is None: + reduce_ray_remote_args = {} + if "scheduling_strategy" not in reduce_ray_remote_args: + reduce_ray_remote_args = reduce_ray_remote_args.copy() + reduce_ray_remote_args["scheduling_strategy"] = "SPREAD" + + blocks_with_metadata: List[Tuple[ObjectRef[Block], BlockMetadata]] = [] + for ref_bundle in refs: + blocks_with_metadata.extend(ref_bundle.blocks) + split_return = _split_at_indices( + blocks_with_metadata, indices, input_owned_by_consumer + ) + split_block_refs, split_metadata = [], [] + for b, m in zip(*split_return): + split_block_refs.append(b) + split_metadata.extend(m) + + sub_progress_bar_dict = ctx.sub_progress_bar_dict + bar_name = ShuffleTaskSpec.SPLIT_REPARTITION_SUB_PROGRESS_BAR_NAME + assert bar_name in sub_progress_bar_dict, sub_progress_bar_dict + reduce_bar = sub_progress_bar_dict[bar_name] + + reduce_task = cached_remote_fn(self._exchange_spec.reduce) + reduce_return = [ + reduce_task.options(**reduce_ray_remote_args, num_returns=2).remote( + *self._exchange_spec._reduce_args, + *split_block_refs[j], + ) + for j in range(output_num_blocks) + # Only process splits which contain blocks. + if len(split_block_refs[j]) > 0 + ] + + reduce_block_refs, reduce_metadata_schema = [], [] + if reduce_return: + reduce_block_refs, reduce_metadata_schema = unzip(reduce_return) + reduce_metadata_schema: List[ + "BlockMetadataWithSchema" + ] = reduce_bar.fetch_until_complete(list(reduce_metadata_schema)) + reduce_block_refs = list(reduce_block_refs) + + # Handle empty blocks. + if len(reduce_block_refs) < output_num_blocks: + import pyarrow as pa + + from ray.data._internal.arrow_block import ArrowBlockBuilder + from ray.data._internal.pandas_block import ( + PandasBlockBuilder, + PandasBlockSchema, + ) + + num_empty_blocks = output_num_blocks - len(reduce_block_refs) + if len(reduce_metadata_schema) > 0: + first_block_schema = reduce_metadata_schema[0].schema + if isinstance(first_block_schema, pa.Schema): + builder = ArrowBlockBuilder() + elif isinstance(first_block_schema, PandasBlockSchema): + builder = PandasBlockBuilder() + else: + raise ValueError( + "Cannot split partition on blocks with unknown block schema:" + f" {first_block_schema}." + ) + else: + # If the result is empty, default to Arrow format for the empty blocks. + builder = ArrowBlockBuilder() + + empty_block = builder.build() + empty_meta_with_schema = BlockMetadataWithSchema.from_block( + empty_block + ) # No stats for empty block. + empty_block_refs, empty_metadata = zip( + *[ + (ray.put(empty_block), empty_meta_with_schema) + for _ in range(num_empty_blocks) + ] + ) + reduce_block_refs.extend(empty_block_refs) + reduce_metadata_schema.extend(empty_metadata) + + output = [] + assert len(reduce_block_refs) == len(reduce_metadata_schema), ( + len(reduce_block_refs), + len(reduce_metadata_schema), + ) + for block, meta_with_schema in zip(reduce_block_refs, reduce_metadata_schema): + output.append( + RefBundle( + [(block, meta_with_schema.metadata)], + owns_blocks=input_owned_by_consumer, + schema=meta_with_schema.schema, + ) + ) + stats = { + "split": split_metadata, + "reduce": reduce_metadata_schema, + } + + return (output, stats) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/plan_expression/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/plan_expression/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/plan_expression/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/plan_expression/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6271161518ca6973c9d6b9fd8abe9bfd7654487 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/plan_expression/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/plan_expression/__pycache__/expression_evaluator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/plan_expression/__pycache__/expression_evaluator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..109eb30aed55c5ad44b0b124c254c4f29d49eae1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/plan_expression/__pycache__/expression_evaluator.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/plan_expression/expression_evaluator.py b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/plan_expression/expression_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..2a1adffca7181b0bad31271fac702f59889cfe26 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/data/_internal/planner/plan_expression/expression_evaluator.py @@ -0,0 +1,236 @@ +import ast +import logging + +import pyarrow as pa +import pyarrow.compute as pc +import pyarrow.dataset as ds + +logger = logging.getLogger(__name__) + + +# NOTE: (srinathk) There are 3 distinct stages of handling passed in exprs: +# 1. Parsing it (as text) +# 2. Resolving unbound names (to schema) +# 3. Converting resolved expressions to PA ones +# Need to break up the abstraction provided by ExpressionEvaluator. + + +class ExpressionEvaluator: + @staticmethod + def get_filters(expression: str) -> ds.Expression: + """Parse and evaluate the expression to generate a filter condition. + + Args: + expression: A string representing the filter expression to parse. + + Returns: + A PyArrow compute expression for filtering data. + + """ + try: + tree = ast.parse(expression, mode="eval") + return _ConvertToArrowExpressionVisitor().visit(tree.body) + except SyntaxError as e: + raise ValueError(f"Invalid syntax in the expression: {expression}") from e + except Exception as e: + logger.exception(f"Error processing expression: {e}") + raise + + +class _ConvertToArrowExpressionVisitor(ast.NodeVisitor): + def visit_Compare(self, node: ast.Compare) -> ds.Expression: + """Handle comparison operations (e.g., a == b, a < b, a in b). + + Args: + node: The AST node representing a comparison operation. + + Returns: + An expression representing the comparison. + """ + # Handle left operand + # TODO Validate columns + if isinstance(node.left, ast.Attribute): + # Visit and handle attributes + left_expr = self.visit(node.left) + elif isinstance(node.left, ast.Name): + # Treat as a simple field + left_expr = self.visit(node.left) + elif isinstance(node.left, ast.Constant): + # Constant values are used directly + left_expr = node.left.value + else: + raise ValueError(f"Unsupported left operand type: {type(node.left)}") + + comparators = [self.visit(comp) for comp in node.comparators] + + op = node.ops[0] + if isinstance(op, ast.In): + return left_expr.isin(comparators[0]) + elif isinstance(op, ast.NotIn): + return ~left_expr.isin(comparators[0]) + elif isinstance(op, ast.Eq): + return left_expr == comparators[0] + elif isinstance(op, ast.NotEq): + return left_expr != comparators[0] + elif isinstance(op, ast.Lt): + return left_expr < comparators[0] + elif isinstance(op, ast.LtE): + return left_expr <= comparators[0] + elif isinstance(op, ast.Gt): + return left_expr > comparators[0] + elif isinstance(op, ast.GtE): + return left_expr >= comparators[0] + else: + raise ValueError(f"Unsupported operator type: {op}") + + def visit_BoolOp(self, node: ast.BoolOp) -> ds.Expression: + """Handle logical operations (e.g., a and b, a or b). + + Args: + node: The AST node representing a boolean operation. + + Returns: + An expression representing the logical operation. + """ + conditions = [self.visit(value) for value in node.values] + combined_expr = conditions[0] + + for condition in conditions[1:]: + if isinstance(node.op, ast.And): + # Combine conditions with logical AND + combined_expr &= condition + elif isinstance(node.op, ast.Or): + # Combine conditions with logical OR + combined_expr |= condition + else: + raise ValueError( + f"Unsupported logical operator: {type(node.op).__name__}" + ) + + return combined_expr + + def visit_Name(self, node: ast.Name) -> ds.Expression: + """Handle variable (name) nodes and return them as pa.dataset.Expression. + + Even if the name contains periods, it's treated as a single string. + + Args: + node: The AST node representing a variable. + + Returns: + The variable wrapped as a pa.dataset.Expression. + """ + # Directly use the field name as a string (even if it contains periods) + field_name = node.id + return pc.field(field_name) + + def visit_Attribute(self, node: ast.Attribute) -> object: + """Handle attribute access (e.g., np.nan). + + Args: + node: The AST node representing an attribute access. + + Returns: + object: The attribute value. + + Raises: + ValueError: If the attribute is unsupported. + """ + # Recursively visit the left side (base object or previous attribute) + if isinstance(node.value, ast.Attribute): + # If the value is an attribute, recursively resolve it + left_expr = self.visit(node.value) + return pc.field(f"{left_expr}.{node.attr}") + + elif isinstance(node.value, ast.Name): + # If the value is a name (e.g., "foo"), we can directly return the field + left_name = node.value.id # The base name, e.g., "foo" + return pc.field(f"{left_name}.{node.attr}") + + raise ValueError(f"Unsupported attribute: {node.attr}") + + def visit_List(self, node: ast.List) -> ds.Expression: + """Handle list literals. + + Args: + node: The AST node representing a list. + + Returns: + The list of elements wrapped as a pa.dataset.Expression. + """ + elements = [self.visit(elt) for elt in node.elts] + return pa.array(elements) + + def visit_UnaryOp(self, node: ast.UnaryOp) -> ds.Expression: + """Handle case where comparator is UnaryOP (e.g., a == -1). + AST for this expression will be Compare(left=Name(id='a'), ops=[Eq()], + comparators=[UnaryOp(op=USub(), operand=Constant(value=1))]) + + Args: + node: The constant value.""" + + op = node.op + if isinstance(op, ast.USub): + return pc.scalar(-node.operand.value) + else: + raise ValueError(f"Unsupported unary operator: {op}") + + # TODO (srinathk) Note that visit_Constant does not return pa.dataset.Expression + # because to support function in() which takes in a List, the elements in the List + # needs to values instead of pa.dataset.Expression per pyarrow.dataset.Expression + # specification. May be down the road, we can update it as Arrow relaxes this + # constraint. + def visit_Constant(self, node: ast.Constant) -> object: + """Handle constant values (e.g., numbers, strings). + + Args: + node: The AST node representing a constant value. + + Returns: + object: The constant value itself (e.g., number, string, or boolean). + """ + return node.value # Return the constant value directly. + + def visit_Call(self, node: ast.Call) -> ds.Expression: + """Handle function calls (e.g., is_nan(a), is_valid(b)). + + Args: + node: The AST node representing a function call. + + Returns: + The corresponding expression based on the function called. + + Raises: + ValueError: If the function is unsupported or has incorrect arguments. + """ + func_name = node.func.id + function_map = { + "is_nan": lambda arg: arg.is_nan(), + "is_null": lambda arg, nan_is_null=False: arg.is_null( + nan_is_null=nan_is_null + ), + "is_valid": lambda arg: arg.is_valid(), + "isin": lambda arg1, arg2: arg1.isin(arg2), + } + + if func_name in function_map: + # Visit all arguments of the function call + args = [self.visit(arg) for arg in node.args] + # Handle the "is_null" function with one or two arguments + if func_name == "is_null": + if len(args) == 1: + return function_map[func_name](args[0]) + elif len(args) == 2: + return function_map[func_name](args[0], args[1]) + else: + raise ValueError("is_null function requires one or two arguments.") + # Handle the "isin" function with exactly two arguments + elif func_name == "isin" and len(args) != 2: + raise ValueError("isin function requires two arguments.") + # Ensure the function has one argument (for functions like is_valid) + elif func_name != "isin" and len(args) != 1: + raise ValueError(f"{func_name} function requires exactly one argument.") + # Call the corresponding function with the arguments + return function_map[func_name](*args) + else: + raise ValueError(f"Unsupported function: {func_name}") diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7623baf7b1b419c166c925fbc379d7fdec2f3878 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/datasink.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/datasink.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8e172e988c947757773ddef58a77ebb02137ba3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/datasink.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/datasource.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/datasource.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ec7cd1bc34708926ce0af8cffc4b9fffd74569d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/datasource.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/file_based_datasource.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/file_based_datasource.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..215d21e5496cf8ba71a2f3fe9417bc756accf97d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/file_based_datasource.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/file_datasink.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/file_datasink.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f412851e8d5e21e57c0385d6ac5f2c6686d83fff Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/file_datasink.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/file_meta_provider.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/file_meta_provider.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..467cf74a581751e8a1113badab274c796c7c847e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/file_meta_provider.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/filename_provider.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/filename_provider.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ed891a5acf67347722470b38acdde99e6152975 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/filename_provider.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/parquet_meta_provider.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/parquet_meta_provider.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bed131ece32b3023cf20e921142ae46c5ac36224 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/parquet_meta_provider.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/partitioning.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/partitioning.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4780c8141763e21c376a8f9752f82d0f53e6cbd8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/partitioning.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/path_util.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/path_util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6cdbeeb11311d603808349af71604b7d58432a9e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/datasource/__pycache__/path_util.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/extensions/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/extensions/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c927645e6bda5c9eedb0d6cf62836364462709d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/extensions/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/extensions/__pycache__/object_extension.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/extensions/__pycache__/object_extension.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d29c6b3ea401aa6106298a3db8e72b41a2daf9f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/extensions/__pycache__/object_extension.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/extensions/__pycache__/tensor_extension.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/extensions/__pycache__/tensor_extension.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c23949b2227b7b630e74807038a6df99b3db2c0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/extensions/__pycache__/tensor_extension.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b4ad0278fcea253edc1a9a330c807bf140e0020 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/chain.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/chain.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05ae80d6dd18d8151fc0cfca21f385af7569cfa6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/chain.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/concatenator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/concatenator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3cb9ee62500699337564373dd0a12297cb54cf4d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/concatenator.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/discretizer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/discretizer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c30affbd742bdecd6a4fd64e431b01681e3371bb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/discretizer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/encoder.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/encoder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1a33e4384e3f8ff0c9b459a3290b5a265e9e85a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/encoder.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/hasher.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/hasher.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..511a65cefc386a27b9b926ef76461bba7dba9287 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/hasher.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/imputer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/imputer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58625ec5007ac4b38ccc9b928dc9ece160a899e2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/imputer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/normalizer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/normalizer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff896e1c4076940689ed0516ac840763b85af622 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/normalizer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/scaler.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/scaler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0706feeb590a2586583453c35592fbaafb12f747 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/scaler.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/tokenizer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/tokenizer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c144248dd23869a355ab0660e0bbfdcc8a2a6cc Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/tokenizer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/torch.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/torch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d1acaf3edf967b65055edf88db30fca61ab8e56 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/torch.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/transformer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/transformer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..553185229f9dfb02da70a613c0f6077d9ee1de90 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/transformer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..070c8b89e286c259f4d1f1cfab09e5428513ddcf Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/vectorizer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/vectorizer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13a64fb968fe84ae904c4b26914ed2fe3cdb09e5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/data/preprocessors/__pycache__/vectorizer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4fa653c5166f702c3e2bcf9c20b6ea6d31d11351 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/compiled_dag_ref.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/compiled_dag_ref.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15e75f721c8576a095be1fa920215b67a7b76047 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/compiled_dag_ref.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/dynamic_resources.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/dynamic_resources.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe7cceb9c725b28d8209e5a64f1c90891511aee8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/dynamic_resources.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/gradio_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/gradio_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..184b23a9af0862fa06fd9371fb64133e64d398fa Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/gradio_utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/internal_kv.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/internal_kv.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1be433483263d2bee1900480e0cd363abfcd1c06 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/internal_kv.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/locations.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/locations.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d392a01f35c882f5065b3b1641ff647084abf66 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/locations.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/queue.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/queue.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04c9897750e4ca759af791dfda2782db33db2f0b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/queue.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/shuffle.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/shuffle.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..572cbae9fd86ecb0e0cca4a91e04bb7c8aaf18a0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/shuffle.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/tf_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/tf_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1cbe5e5505ae3ecbbd25188ff87b1e88e2579ef1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/tf_utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/tqdm_ray.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/tqdm_ray.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72904e24d73ddf05ab9057ee2eb1a7dbba835c50 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/__pycache__/tqdm_ray.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..caf2351fae6fb2281a46fd187b3e00fe0149d6c5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__init__.py @@ -0,0 +1,43 @@ +from ray.experimental.channel.cached_channel import CachedChannel +from ray.experimental.channel.common import ( # noqa: F401 + AwaitableBackgroundReader, + AwaitableBackgroundWriter, + ChannelContext, + ChannelInterface, + ChannelOutputType, + CompiledDAGArgs, + ReaderInterface, + SynchronousReader, + SynchronousWriter, + WriterInterface, +) +from ray.experimental.channel.communicator import Communicator +from ray.experimental.channel.cpu_communicator import CPUCommunicator +from ray.experimental.channel.intra_process_channel import IntraProcessChannel +from ray.experimental.channel.shared_memory_channel import ( + BufferedSharedMemoryChannel, + Channel, + CompositeChannel, +) +from ray.experimental.channel.torch_tensor_accelerator_channel import ( + TorchTensorAcceleratorChannel, +) + +__all__ = [ + "AwaitableBackgroundReader", + "AwaitableBackgroundWriter", + "CachedChannel", + "Channel", + "Communicator", + "CPUCommunicator", + "ReaderInterface", + "SynchronousReader", + "SynchronousWriter", + "WriterInterface", + "ChannelContext", + "TorchTensorAcceleratorChannel", + "IntraProcessChannel", + "CompositeChannel", + "BufferedSharedMemoryChannel", + "CompiledDAGArgs", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1bc39a9b48397af67ada8e473f5439e0c2442c7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/accelerator_context.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/accelerator_context.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7f606c96f0217d353694df0d7eb067750ac03cc Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/accelerator_context.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/auto_transport_type.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/auto_transport_type.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7e54691b9931874997c7d9e50f57bffef3da7eb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/auto_transport_type.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/cached_channel.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/cached_channel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69734f18b5ebc8f385ceda0d9a6024edee54a51d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/cached_channel.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/common.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c4b04de8ca5fadb878df3e971dcf1728095704c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/common.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/communicator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/communicator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d817a22cf53897aa37ad895b52ce46ec4e12cab Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/communicator.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/communicator_handle.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/communicator_handle.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9578806bf39003c9af4cb89116beceea1ef5d224 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/communicator_handle.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/conftest.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/conftest.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b4298a1e09da462f6e13f1fdf6cf4c53f7b6909 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/conftest.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/cpu_communicator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/cpu_communicator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a343cd1be6919a57955585d1b1883d8a1999cb0c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/cpu_communicator.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/intra_process_channel.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/intra_process_channel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bafeda8d877f977d68c7224a1b7013d8e12eea3a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/intra_process_channel.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/nccl_group.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/nccl_group.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f218053b095e230d02a9c9f2c062bc247736eb2b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/nccl_group.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/serialization_context.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/serialization_context.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2093e5524a6e4ceb8c597235deb5f3b1f201a3f0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/serialization_context.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/shared_memory_channel.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/shared_memory_channel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04b1b580c35a622e845f5fe068f0004bb90127f0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/shared_memory_channel.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/torch_tensor_accelerator_channel.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/torch_tensor_accelerator_channel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4154833c138256e85b08ee8bb5346064591d29e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/torch_tensor_accelerator_channel.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/torch_tensor_type.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/torch_tensor_type.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8ebe831032c99385c04022f96cd958458157c7a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/torch_tensor_type.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b7504ad4f180584409d0443ee1a80e10e209dcf Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/__pycache__/utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/accelerator_context.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/accelerator_context.py new file mode 100644 index 0000000000000000000000000000000000000000..9acc1ad67d33c0013b7d17de759ab7c90de5c8b4 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/accelerator_context.py @@ -0,0 +1,245 @@ +import threading +import importlib +import ray +from typing import TYPE_CHECKING, Optional, Type, ContextManager, List +from contextlib import nullcontext +from ray.experimental.channel.communicator import Communicator +from ray._private.accelerators import get_accelerator_manager_for_resource + +if TYPE_CHECKING: + import torch + +# The accelerator context singleton on this process. +_accelerator_context_lock = threading.Lock() +_default_accelerator_context: Optional["AcceleratorContext"] = None +_global_custom_context: Optional["AcceleratorContext"] = None + + +class AcceleratorContext: + """ + Provides a unified interface for managing different accelerator backends + This includes stream management, event creation, device context control, + and communicator support for distributed communication. + """ + + def __init__(self, torch_module_name: str, communicator_cls: Type[Communicator]): + """ + Initializes an accelerator context with the specified torch device module + and communicator class. + + Args: + torch_module_name: Name of the torch device module (e.g., "cuda", "cpu"). + communicator_cls: Class used to handle communication. + """ + + # The name of the torch module (e.g., 'cuda', 'npu') + self._torch_module_name: str = torch_module_name + # The Communicator class used to manage communication + self._communicator_cls: Type[Communicator] = communicator_cls + + # Import the torch backend module (e.g., torch.cuda) if the device is not 'cpu'. + if torch_module_name != "cpu": + self._torch_mod = importlib.import_module(f"torch.{torch_module_name}") + + @staticmethod + def get() -> "AcceleratorContext": + """ + Returns the singleton instance of the accelerator context. + + If a custom accelerator has been registered, initializes the context + based on the registration. Otherwise, selects an appropriate runtime + based on the available device (CUDA or CPU) and registers the + corresponding default communicator. + + Returns: + AcceleratorContext: A singleton instance of the appropriate + runtime context. + """ + + global _default_accelerator_context, _global_custom_context + + with _accelerator_context_lock: + if _global_custom_context is not None: + return _global_custom_context + + if _default_accelerator_context is None: + if len(ray.get_gpu_ids()) > 0: + from ray.experimental.channel.nccl_group import _NcclGroup + + _default_accelerator_context = AcceleratorContext( + "cuda", _NcclGroup + ) + else: + from ray.experimental.channel.cpu_communicator import ( + CPUCommunicator, + ) + + _default_accelerator_context = AcceleratorContext( + "cpu", CPUCommunicator + ) + + return _default_accelerator_context + + @staticmethod + def set(accelerator_context: "AcceleratorContext") -> None: + """ + Overwrites the default accelerator context. + + Args: + accelerator_context: The context to register. + """ + global _global_custom_context + + # Accelerator context is registered. + _global_custom_context = accelerator_context + + def get_accelerator_devices(self) -> List["torch.device"]: + """ + Gets the torch device list configured for this process. + + Returns: + List[torch.device]: The torch device list. + """ + import torch + + if self._torch_module_name == "cpu": + return [torch.device("cpu")] + + if self._torch_module_name == "cuda": + accelerator_ids = [str(id) for id in ray.get_gpu_ids()] + accelerator_manager = get_accelerator_manager_for_resource("GPU") + else: + accelerator_ids = [ + str(id) + for id in ray.get_runtime_context().get_accelerator_ids()[ + self._torch_module_name.upper() + ] + ] + accelerator_manager = get_accelerator_manager_for_resource( + self._torch_module_name.upper() + ) + + device_ids = [] + + if len(accelerator_ids) > 0: + accelerator_visible_list = ( + accelerator_manager.get_current_process_visible_accelerator_ids() + ) + if accelerator_visible_list is None: + accelerator_visible_list = [] + + # If there are multiple Accelerators, return a list of devices. + # If using fractional Accelerators, these IDs are not guaranteed + # to be unique across different processes. + for accelerator_id in accelerator_ids: + try: + device_ids.append(accelerator_visible_list.index(accelerator_id)) + except IndexError: + raise RuntimeError( + f"{accelerator_manager.get_visible_accelerator_ids_env_var()} set incorrectly. " + f"expected to include {accelerator_id}. " + "Did you override this environment" + " variable? If not, please help file an issue on Github." + ) + + else: + # If called on the driver or outside of Ray Train, return the + # 0th device. + device_ids.append(0) + + return [ + torch.device(f"{self._torch_module_name}:{device_id}") + for device_id in device_ids + ] + + def get_device_context(self, device: "torch.device") -> ContextManager: + """ + Retrieves the context manager for the specified accelerator device. + There is no device context for CPU, returning a nullcontext. + + Args: + device: The target device for which the context manager is required. + + Returns: + ContextManager: A context manager specific to the device type. + """ + if device.type == "cpu": + return nullcontext() + + return self._torch_mod.device(device) + + def current_stream(self): + """ + Retrieves the current execution stream for the accelerator device. + """ + return self._torch_mod.current_stream() + + def create_event(self): + """ + Creates an event object for the accelerator device. + """ + return self._torch_mod.Event() + + def generate_communicator_id(self) -> str: + """ + Generates a communication identifier for communication group. + """ + return self._communicator_cls.generate_communicator_id() + + def create_communicator(self, *args, **kwargs) -> Communicator: + """ + Creates a communication group for collective operations. + """ + return self._communicator_cls(*args, **kwargs) + + @property + def module_name(self) -> str: + """ + Gets the name of the torch module backing the accelerator. + """ + return self._torch_module_name + + @property + def communicator_cls(self) -> Optional[Type[Communicator]]: + """ + Returns the communicator class. + """ + return self._communicator_cls + + @property + def accelerator_count(self) -> int: + """ + Returns the number of accelerators assigned by ray. + """ + if self._torch_module_name == "cuda": + return len(ray.get_gpu_ids()) + else: + accelerator_ids = ray.get_runtime_context().get_accelerator_ids() + return len(accelerator_ids.get(self._torch_module_name.upper(), [])) + + +def register_accelerator_context( + torch_module_name: str, communicator_cls: Type[Communicator] +): + """ + Registers the accelerator context with the specified device type and communicator. + + Args: + torch_module_name: The name of the device module under torch. + communicator_cls: The communicator class associated with the device. + """ + accelerator_context = AcceleratorContext(torch_module_name, communicator_cls) + AcceleratorContext.set(accelerator_context) + + +def is_accelerator_context_registered(): + """ + Checks whether a custom accelerator context has been registered. + + Returns: + bool: True if a custom accelerator context is registered + (_global_custom_context is not None), False otherwise. + """ + if _global_custom_context is not None: + return True + return False diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/auto_transport_type.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/auto_transport_type.py new file mode 100644 index 0000000000000000000000000000000000000000..4017ac1fe921e83d6917dbff258bf85fb06066dd --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/auto_transport_type.py @@ -0,0 +1,182 @@ +from typing import Dict, List, Optional, Tuple, Union + +import ray +from ray.experimental.channel import ChannelOutputType +from ray.experimental.channel.torch_tensor_type import TorchTensorType +from ray.experimental.util.types import Device + + +class AutoTransportType(ChannelOutputType): + """ + Type hint for automatic transport selection for tensors. + + With this type hint Compiled Graphs automatically decide the best transport + to use (e.g., accellerator or shared memory) based on the node locations and + GPU IDs of the readers and writers. + """ + + def __init__( + self, + device: Device = Device.DEFAULT, + _static_shape: bool = False, + _direct_return: bool = False, + ): + self._device = device + self._static_shape = _static_shape + self._direct_return = _direct_return + + @property + def device(self) -> Device: + return self._device + + def create_channel( + self, + writer: Optional["ray.actor.ActorHandle"], + reader_and_node_list: List[Tuple["ray.actor.ActorHandle", str]], + driver_actor_id: Optional[str] = None, + ) -> "ChannelOutputType": + """ + Directly calling create_channel() on AutoTransportType should not happen, + just raise an exception with informative message. + """ + raise ValueError( + "This should not happen: AutoTransportType should " + "have been resolved before creating a channel. " + "Please file a Ray GitHub issue for bug report." + ) + + +class TypeHintResolver: + """ + This class is used to resolve `AutoChannelType` into an actual channel type + (e.g., `TorchTensorType` with proper transport) based on node locations and + GPU IDs of the readers and writers. + """ + + def __init__(self, actor_to_gpu_ids: Dict["ray.actor.ActorHandle", List[str]]): + """ + Args: + actor_to_gpu_ids: Mapping from actor handle to its GPU IDs. + """ + self._actor_to_gpu_ids = actor_to_gpu_ids + + def _get_gpu_ids(self, actor: "ray.actor.ActorHandle") -> List[str]: + """ + Get the GPU IDs of the actor. + + Returns: + The GPU IDs of the actor. If the actor is not found, + return an empty list. + """ + gpu_ids = self._actor_to_gpu_ids.get(actor, []) + assert len(gpu_ids) <= 1, ( + "Compiled Graphs currently don't support allocating multiple GPUs " + "to a single actor" + ) + return gpu_ids + + def _use_same_gpu( + self, + writer_and_node: Tuple["ray.actor.ActorHandle", str], + reader_and_node: Union[ + Tuple["ray.actor.ActorHandle", str], + List[Tuple["ray.actor.ActorHandle", str]], + ], + ) -> bool: + """ + Check if the writer and readers use the same GPU. + + Args: + writer_and_node: A tuple of writer actor handle and its node ID. + reader_and_node: A tuple of reader actor handle and its node ID, or + a list of such tuples. + + Returns: + True if the writer and all the readers use the same GPU, False otherwise. + """ + if isinstance(reader_and_node, list): + return all( + self._use_same_gpu(writer_and_node, entry) for entry in reader_and_node + ) + if writer_and_node[1] != reader_and_node[1]: + return False + writer_gpu_ids = self._get_gpu_ids(writer_and_node[0]) + reader_gpu_ids = self._get_gpu_ids(reader_and_node[0]) + return writer_gpu_ids == reader_gpu_ids + + def _use_gpu( + self, actors: Union["ray.actor.ActorHandle", List["ray.actor.ActorHandle"]] + ) -> bool: + """ + Check if the actors use GPUs. + + Args: + actors: An actor handle or a list of actor handles. + + Returns: + True if the actors use GPUs, False otherwise. + """ + if isinstance(actors, list): + return all(self._use_gpu(actor) for actor in actors) + gpu_ids = self._get_gpu_ids(actors) + return len(gpu_ids) > 0 + + def resolve( + self, + auto_transport_type: AutoTransportType, + writer_and_node: Tuple[Optional["ray.actor.ActorHandle"], str], + reader_and_node_list: List[Tuple[Optional["ray.actor.ActorHandle"], str]], + ) -> "ChannelOutputType": + """ + Resolve auto_transport_type to the actual channel output type + based on the node locations and GPU IDs. + + Args: + auto_transport_type: The type to resolve + writer_and_node: A tuple of writer actor handle and its node ID. + A None writer actor handle means the writer is the driver. + reader_and_node_list: A list of tuples of reader actor handle and its + node ID. A None reader actor handle means the reader is the driver. + + Returns: + The actual channel type. + """ + writer = writer_and_node[0] + readers = [reader for reader, _ in reader_and_node_list] + + if writer is None or any(reader is None for reader in readers): + # None means actor is the driver, currently driver on GPU + # is not supported, so we always use shared memory to transfer + # tensors. + return TorchTensorType( + device=auto_transport_type.device, + _static_shape=auto_transport_type._static_shape, + _direct_return=auto_transport_type._direct_return, + ) + + # Case 1: writer and readers don't both use GPU, use shared memory + # to transport the tensors + if not (self._use_gpu(writer) and self._use_gpu(readers)): + return TorchTensorType( + device=auto_transport_type.device, + _static_shape=auto_transport_type._static_shape, + _direct_return=auto_transport_type._direct_return, + ) + + # Case 2: writer and readers use the same GPU are are on the same node, + # use shared memory to transport the tensors + if self._use_same_gpu(writer_and_node, reader_and_node_list): + return TorchTensorType( + device=auto_transport_type.device, + _static_shape=auto_transport_type._static_shape, + _direct_return=auto_transport_type._direct_return, + ) + + # Case 3: writer and readers use different GPUs, use accelerator to transport + # the tensors + return TorchTensorType( + transport="accelerator", + device=auto_transport_type.device, + _static_shape=auto_transport_type._static_shape, + _direct_return=auto_transport_type._direct_return, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/cached_channel.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/cached_channel.py new file mode 100644 index 0000000000000000000000000000000000000000..3417ddba9d834ded3284bd877fb13c5fe3f326d9 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/cached_channel.py @@ -0,0 +1,111 @@ +import uuid +from typing import Any, Optional + +from ray.experimental.channel.common import ChannelInterface + + +class CachedChannel(ChannelInterface): + """ + CachedChannel wraps an inner channel and caches the data read from it until + `num_reads` reads have completed. If inner channel is None, the data + is written to serialization context and retrieved from there. This is useful + when passing data within the same actor and a shared memory channel can be + avoided. + + Args: + num_reads: The number of reads from this channel that must happen before + writing again. Readers must be methods of the same actor. + inner_channel: The inner channel to cache data from. If None, the data is + read from the serialization context. + _channel_id: The unique ID for the channel. If None, a new ID is generated. + """ + + def __init__( + self, + num_reads: int, + inner_channel: Optional[ChannelInterface] = None, + _channel_id: Optional[str] = None, + ): + assert num_reads > 0, "num_reads must be greater than 0." + self._num_reads = num_reads + self._inner_channel = inner_channel + # Generate a unique ID for the channel. The writer and reader will use + # this ID to store and retrieve data from the _SerializationContext. + self._channel_id = _channel_id + if self._channel_id is None: + self._channel_id = str(uuid.uuid4()) + + def ensure_registered_as_writer(self) -> None: + if self._inner_channel is not None: + self._inner_channel.ensure_registered_as_writer() + + def ensure_registered_as_reader(self) -> None: + if self._inner_channel is not None: + self._inner_channel.ensure_registered_as_reader() + + def __reduce__(self): + return CachedChannel, ( + self._num_reads, + self._inner_channel, + self._channel_id, + ) + + def __str__(self) -> str: + return ( + f"CachedChannel(channel_id={self._channel_id}, " + f"num_reads={self._num_reads}), " + f"inner_channel={self._inner_channel})" + ) + + def write(self, value: Any, timeout: Optional[float] = None): + self.ensure_registered_as_writer() + # TODO: better organize the imports + from ray.experimental.channel import ChannelContext + + if self._inner_channel is not None: + self._inner_channel.write(value, timeout) + return + + # Otherwise no need to check timeout as the operation is non-blocking. + + # Because both the reader and writer are in the same worker process, + # we can directly store the data in the context instead of storing + # it in the channel object. This removes the serialization overhead of `value`. + ctx = ChannelContext.get_current().serialization_context + ctx.set_data(self._channel_id, value, self._num_reads) + + def read(self, timeout: Optional[float] = None) -> Any: + self.ensure_registered_as_reader() + # TODO: better organize the imports + from ray.experimental.channel import ChannelContext + + ctx = ChannelContext.get_current().serialization_context + if ctx.has_data(self._channel_id): + # No need to check timeout as the operation is non-blocking. + return ctx.get_data(self._channel_id) + + assert ( + self._inner_channel is not None + ), "Cannot read from the serialization context while inner channel is None." + value = self._inner_channel.read(timeout) + ctx.set_data(self._channel_id, value, self._num_reads) + # NOTE: Currently we make a contract with Compiled Graph users that the + # channel results should not be mutated by the actor methods. + # When the user needs to modify the channel results, they should + # make a copy of the channel results and modify the copy. + # This is the same contract as used in IntraProcessChannel. + # This contract is NOT enforced right now in either case. + # TODO(rui): introduce a flag to control the behavior: + # for example, by default we make a deep copy of the channel + # result, but the user can turn off the deep copy for performance + # improvements. + # https://github.com/ray-project/ray/issues/47409 + return ctx.get_data(self._channel_id) + + def close(self) -> None: + from ray.experimental.channel import ChannelContext + + if self._inner_channel is not None: + self._inner_channel.close() + ctx = ChannelContext.get_current().serialization_context + ctx.reset_data(self._channel_id) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/common.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/common.py new file mode 100644 index 0000000000000000000000000000000000000000..8de5f5642312102ed8a1a075077e9802e4df8da5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/common.py @@ -0,0 +1,681 @@ +import asyncio +import concurrent +import sys +import threading +import time +from dataclasses import dataclass +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + List, + NamedTuple, + Optional, + Tuple, + Union, +) + +import ray +import ray.exceptions +from ray.experimental.channel.communicator import Communicator +from ray.experimental.channel.communicator_handle import CommunicatorHandle +from ray.experimental.channel.accelerator_context import AcceleratorContext +from ray.experimental.channel.serialization_context import _SerializationContext +from ray.util.annotations import DeveloperAPI, PublicAPI + +# The context singleton on this process. +_default_context: "Optional[ChannelContext]" = None +_context_lock = threading.Lock() + +if TYPE_CHECKING: + import torch + + +def retry_and_check_interpreter_exit(f: Callable[[], None]) -> bool: + """This function is only useful when f contains channel read/write. + + Keep retrying channel read/write inside `f` and check if interpreter exits. + It is important in case the read/write happens in a separate thread pool. + See https://github.com/ray-project/ray/pull/47702 + + f should a function that doesn't receive any input and return nothing. + """ + exiting = False + while True: + try: + f() + break + except ray.exceptions.RayChannelTimeoutError: + if sys.is_finalizing(): + # Interpreter exits. We should ignore the error and + # stop reading so that the thread can join. + exiting = True + break + + return exiting + + +# Holds the input arguments for Compiled Graph +@PublicAPI(stability="alpha") +class CompiledDAGArgs(NamedTuple): + args: Tuple[Any, ...] + kwargs: Dict[str, Any] + + +@PublicAPI(stability="alpha") +class ChannelOutputType: + def register_custom_serializer(self) -> None: + """ + Register any custom serializers needed to pass data of this type. This + method should be run on the reader(s) and writer of a channel, which + are the driver and/or Ray actors. + + NOTE: When custom serializers are registered with Ray, the registered + deserializer is shipped with the serialized value and used on the + receiving end. Therefore, the deserializer function should *not* + capture state that is meant to be worker-local, such as the worker's + default device. Instead, these should be extracted from the + worker-local _SerializationContext. + """ + pass + + def create_channel( + self, + writer: Optional["ray.actor.ActorHandle"], + reader_and_node_list: List[Tuple["ray.actor.ActorHandle", str]], + driver_actor_id: Optional[str] = None, + ) -> "ChannelInterface": + """ + Instantiate a ChannelInterface class that can be used + to pass data of this type. + + Args: + writer: The actor that may write to the channel. None signifies the driver. + reader_and_node_list: A list of tuples, where each tuple contains a reader + actor handle and the node ID where the actor is located. + driver_actor_id: If this is a CompositeChannel that is read by a driver and + that driver is an actual actor, this will be the actor ID of that + driver actor. + Returns: + A ChannelInterface that can be used to pass data + of this type. + """ + raise NotImplementedError + + def requires_accelerator(self) -> bool: + # By default, channels do not require accelerator. + return False + + def get_custom_communicator(self) -> Optional[Communicator]: + """ + Return the custom communicator group if one is specified. + """ + return None + + def set_communicator_id(self, group_id: str) -> None: + raise NotImplementedError + + +@DeveloperAPI +@dataclass +class ChannelContext: + serialization_context = _SerializationContext() + _torch_available: Optional[bool] = None + _torch_device: Optional["torch.device"] = None + _current_stream: Optional["torch.cuda.Stream"] = None + + def __init__(self): + # Used for the torch.Tensor accelerator transport. + self.communicators: Dict[str, "Communicator"] = {} + # Used for driver process to store actors in the communicator. + self.communicator_handles: Dict[str, "CommunicatorHandle"] = {} + + @staticmethod + def get_current() -> "ChannelContext": + """Get or create a singleton context. + + If the context has not yet been created in this process, it will be + initialized with default settings. + """ + + global _default_context + + with _context_lock: + if _default_context is None: + _default_context = ChannelContext() + + return _default_context + + @property + def torch_available(self) -> bool: + """ + Check if torch package is available. + """ + if self._torch_available is not None: + return self._torch_available + + try: + import torch # noqa: F401 + except ImportError: + self._torch_available = False + return False + self._torch_available = True + return True + + @property + def torch_device(self) -> "torch.device": + if self._torch_device is None: + self._torch_device = AcceleratorContext.get().get_accelerator_devices()[0] + + return self._torch_device + + def set_torch_device(self, device: "torch.device"): + self._torch_device = device + + +@PublicAPI(stability="alpha") +class ChannelInterface: + """ + Abstraction for a transport between a writer actor and some number of + reader actors. + """ + + def __init__( + self, + writer: Optional[ray.actor.ActorHandle], + readers: List[Optional[ray.actor.ActorHandle]], + typ: Optional["ChannelOutputType"], + ): + """ + Create a channel that can be read and written by a Ray driver or actor. + + Args: + writer: The actor that may write to the channel. None signifies the driver. + readers: The actors that may read from the channel. None signifies + the driver. + typ: Type information about the values passed through the channel. + """ + pass + + def ensure_registered_as_writer(self): + """ + Check whether the process is a valid writer. This method must be idempotent. + """ + raise NotImplementedError + + def ensure_registered_as_reader(self): + """ + Check whether the process is a valid reader. This method must be idempotent. + """ + raise NotImplementedError + + def write(self, value: Any, timeout: Optional[float] = None) -> None: + """ + Write a value to the channel. + + Blocks if there are still pending readers for the previous value. The + writer may not write again until the specified number of readers have + read the value. + + Args: + value: The value to write. + timeout: The maximum time in seconds to wait to write the value. + None means using default timeout, 0 means immediate timeout + (immediate success or timeout without blocking), -1 means + infinite timeout (block indefinitely). + """ + raise NotImplementedError + + def read(self, timeout: Optional[float] = None) -> Any: + """ + Read the latest value from the channel. This call will block until a + value is available to read. + + Subsequent calls to read() may *block* if the deserialized object is + zero-copy (e.g., bytes or a numpy array) *and* the object is still in scope. + + Args: + timeout: The maximum time in seconds to wait to read the value. + None means using default timeout, 0 means immediate timeout + (immediate success or timeout without blocking), -1 means + infinite timeout (block indefinitely). + + Returns: + Any: The deserialized value. If the deserialized value is an + Exception, it will be returned directly instead of being raised. + """ + raise NotImplementedError + + def close(self) -> None: + """ + Close this channel. This method must not block and it must be made + idempotent. Any existing values in the channel may be lost after the + channel is closed. + """ + raise NotImplementedError + + +# Interfaces for channel I/O. +@DeveloperAPI +class ReaderInterface: + def __init__( + self, + input_channels: List[ChannelInterface], + ): + assert isinstance(input_channels, list) + for chan in input_channels: + assert isinstance(chan, ChannelInterface) + + self._input_channels = input_channels + self._closed = False + self._num_reads = 0 + + # A list of channels that were not read in the last `read` call + # because the reader returned immediately when a RayTaskError was found. + # These channels must be consumed before the next read to avoid reading + # stale data remaining from the last read. + self._leftover_channels: List[ChannelInterface] = [] + + def get_num_reads(self) -> int: + return self._num_reads + + def start(self): + raise NotImplementedError + + def _read_list(self, timeout: Optional[float] = None) -> List[Any]: + """ + Read a list of values from this reader. + + Args: + timeout: The maximum time in seconds to wait for reading. + None means using default timeout which is infinite, 0 means immediate + timeout (immediate success or timeout without blocking), -1 means + infinite timeout (block indefinitely). + + """ + raise NotImplementedError + + def read(self, timeout: Optional[float] = None) -> List[Any]: + """ + Read from this reader. + + Args: + timeout: The maximum time in seconds to wait for reading. + None means using default timeout, 0 means immediate timeout + (immediate success or timeout without blocking), -1 means + infinite timeout (block indefinitely). + """ + assert ( + timeout is None or timeout >= 0 or timeout == -1 + ), "Timeout must be non-negative or -1." + outputs = self._read_list(timeout) + self._num_reads += 1 + return outputs + + def close(self) -> None: + self._closed = True + for channel in self._input_channels: + channel.close() + + def _consume_leftover_channels_if_needed( + self, timeout: Optional[float] = None + ) -> None: + # Consume the channels that were not read in the last `read` call because a + # RayTaskError was returned from another channel. If we don't do this, the + # read operation will read stale versions of the object refs. + # + # If a RayTaskError is returned from a leftover channel, it will be ignored. + # If a read operation times out, a RayChannelTimeoutError exception will be + # raised. + # + # TODO(kevin85421): Currently, a DAG with NCCL channels and fast fail enabled + # may not be reusable. Revisit this in the future. + for c in self._leftover_channels: + start_time = time.monotonic() + c.read(timeout) + if timeout is not None: + timeout -= time.monotonic() - start_time + timeout = max(timeout, 0) + self._leftover_channels = [] + + +@DeveloperAPI +class SynchronousReader(ReaderInterface): + def __init__( + self, + input_channels: List[ChannelInterface], + ): + super().__init__(input_channels) + + def start(self): + pass + + def _read_list(self, timeout: Optional[float] = None) -> List[Any]: + self._consume_leftover_channels_if_needed(timeout) + # We don't update `remaining_timeout` here because in the worst case, + # consuming leftover channels requires reading all `_input_channels`, + # which users expect to complete within the original `timeout`. Updating + # `remaining_timeout` could cause unexpected timeouts in subsequent read + # operations. + + # It is a special case that `timeout` is set to 0, which means + # read once for each channel. + is_zero_timeout = timeout == 0 + + results = [None for _ in range(len(self._input_channels))] + if timeout is None or timeout == -1: + timeout = float("inf") + timeout_point = time.monotonic() + timeout + remaining_timeout = timeout + + from ray.dag import DAGContext + + ctx = DAGContext.get_current() + iteration_timeout = ctx.read_iteration_timeout + + # Iterate over the input channels with a shorter timeout for each iteration + # to detect RayTaskError early and fail fast. + done_channels = set() + while len(done_channels) < len(self._input_channels): + for i, c in enumerate(self._input_channels): + if c in done_channels: + continue + try: + result = c.read(min(remaining_timeout, iteration_timeout)) + results[i] = result + done_channels.add(c) + if isinstance(result, ray.exceptions.RayTaskError): + # If we raise an exception immediately, it will be considered + # as a system error which will cause the execution loop to + # exit. Hence, return immediately and let `_process_return_vals` + # handle the exception. + # + # Return a list of RayTaskError so that the caller will not + # get an undefined partial result. + self._leftover_channels = [ + c for c in self._input_channels if c not in done_channels + ] + return [result for _ in range(len(self._input_channels))] + except ray.exceptions.RayChannelTimeoutError as e: + remaining_timeout = max(timeout_point - time.monotonic(), 0) + if remaining_timeout == 0: + raise e + continue + + remaining_timeout = max(timeout_point - time.monotonic(), 0) + if remaining_timeout == 0 and not is_zero_timeout: + raise ray.exceptions.RayChannelTimeoutError( + f"Cannot read all channels within {timeout} seconds" + ) + return results + + def release_channel_buffers(self, timeout: Optional[float] = None) -> None: + for c in self._input_channels: + start_time = time.monotonic() + assert hasattr( + c, "release_buffer" + ), "release_buffer() is only supported for shared memory channel " + "(e.g., Channel, BufferedSharedMemoryChannel, CompositeChannel) " + "and used between the last actor and the driver, but got a channel" + f" of type {type(c)}." + c.release_buffer(timeout) + if timeout is not None: + timeout -= time.monotonic() - start_time + timeout = max(timeout, 0) + + +@DeveloperAPI +class AwaitableBackgroundReader(ReaderInterface): + """ + Asyncio-compatible channel reader. + + The reader is constructed with an async queue of futures whose values it + will fulfill. It uses a threadpool to execute the blocking calls to read + from the input channel(s). + """ + + def __init__( + self, + input_channels: List[ChannelInterface], + fut_queue: asyncio.Queue, + ): + super().__init__(input_channels) + self._fut_queue = fut_queue + self._background_task = None + self._background_task_executor = concurrent.futures.ThreadPoolExecutor( + max_workers=1, thread_name_prefix="channel.AwaitableBackgroundReader" + ) + + def start(self): + self._background_task = asyncio.ensure_future(self.run()) + + def _run(self): + # Give it a default timeout 60 seconds to release the buffers + # of the channels that were not read in the last `read` call. + self._consume_leftover_channels_if_needed(60) + + results = [None for _ in range(len(self._input_channels))] + + from ray.dag import DAGContext + + ctx = DAGContext.get_current() + iteration_timeout = ctx.read_iteration_timeout + + done_channels = set() + while len(done_channels) < len(self._input_channels): + for i, c in enumerate(self._input_channels): + if c in done_channels: + continue + try: + result = c.read(iteration_timeout) + results[i] = result + done_channels.add(c) + if isinstance(result, ray.exceptions.RayTaskError): + self._leftover_channels = [ + c for c in self._input_channels if c not in done_channels + ] + return [result for _ in range(len(self._input_channels))] + except ray.exceptions.RayChannelTimeoutError: + pass + if sys.is_finalizing(): + return results + return results + + async def run(self): + loop = asyncio.get_running_loop() + while not self._closed: + res, fut = await asyncio.gather( + loop.run_in_executor(self._background_task_executor, self._run), + self._fut_queue.get(), + return_exceptions=True, + ) + + # Set the result on the main thread. + fut.set_result(res) + # NOTE(swang): If the object is zero-copy deserialized, then it + # will stay in scope as long as ret and the future are in scope. + # Therefore, we must delete both here after fulfilling the future. + del res + del fut + + def close(self): + super().close() + self._background_task_executor.shutdown(cancel_futures=True) + self._background_task.cancel() + + +@DeveloperAPI +class WriterInterface: + def __init__( + self, + output_channels: List[ChannelInterface], + output_idxs: List[Optional[Union[int, str]]], + is_input=False, + ): + """ + Initialize the writer. + + Args: + output_channels: The output channels to write to. + output_idxs: The indices of the values to write to each channel. + This has the same length as `output_channels`. If `is_input` is True, + the index can be an integer or a string to retrieve the corresponding + value from `args` or `kwargs` in the DAG's input. If `is_input` + is False, the entire value is written if the index is None. Otherwise, + the value at the specified index in the tuple is written. + is_input: Whether the writer is DAG input writer or not. + """ + + assert len(output_channels) == len(output_idxs) + self._output_channels = output_channels + self._output_idxs = output_idxs + self._closed = False + self._num_writes = 0 + self._is_input = is_input + + def get_num_writes(self) -> int: + return self._num_writes + + def start(self): + raise NotImplementedError() + + def write(self, val: Any, timeout: Optional[float] = None) -> None: + """ + Write the value. + + Args: + timeout: The maximum time in seconds to wait for writing. 0 means + immediate timeout (immediate success or timeout without blocking). + -1 and None mean infinite timeout (blocks indefinitely). + """ + raise NotImplementedError() + + def close(self) -> None: + self._closed = True + for channel in self._output_channels: + channel.close() + + +def _adapt(raw_args: Any, key: Optional[Union[int, str]], is_input: bool): + """ + Adapt the raw arguments to the key. If `is_input` is True, this method will + retrieve the value from the input data for an InputAttributeNode. Otherwise, it + will retrieve either a partial value or the entire value from the output of + a ClassMethodNode. + + Args: + raw_args: The raw arguments to adapt. + key: The key to adapt. + is_input: Whether the writer is DAG input writer or not. + """ + if is_input: + if not isinstance(raw_args, CompiledDAGArgs): + # Fast path for a single input. + return raw_args + else: + args = raw_args.args + kwargs = raw_args.kwargs + + if isinstance(key, int): + return args[key] + else: + return kwargs[key] + else: + if key is not None: + return raw_args[key] + else: + return raw_args + + +@DeveloperAPI +class SynchronousWriter(WriterInterface): + def start(self): + for channel in self._output_channels: + channel.ensure_registered_as_writer() + + def write(self, val: Any, timeout: Optional[float] = None) -> None: + # If it is an exception, there's only 1 return value. + # We have to send the same data to all channels. + if isinstance(val, Exception): + if len(self._output_channels) > 1: + val = tuple(val for _ in range(len(self._output_channels))) + + if not self._is_input: + if len(self._output_channels) > 1: + if not isinstance(val, tuple): + raise ValueError( + f"Expected a tuple of {len(self._output_channels)} outputs, " + f"but got {type(val)}" + ) + if len(val) != len(self._output_channels): + raise ValueError( + f"Expected {len(self._output_channels)} outputs, but got " + f"{len(val)} outputs" + ) + + for i, channel in enumerate(self._output_channels): + idx = self._output_idxs[i] + val_i = _adapt(val, idx, self._is_input) + channel.write(val_i, timeout) + self._num_writes += 1 + + +@DeveloperAPI +class AwaitableBackgroundWriter(WriterInterface): + def __init__( + self, + output_channels: List[ChannelInterface], + output_idxs: List[Optional[Union[int, str]]], + is_input=False, + ): + super().__init__(output_channels, output_idxs, is_input=is_input) + self._queue = asyncio.Queue() + self._background_task = None + self._background_task_executor = concurrent.futures.ThreadPoolExecutor( + max_workers=1, thread_name_prefix="channel.AwaitableBackgroundWriter" + ) + + def start(self): + for channel in self._output_channels: + channel.ensure_registered_as_writer() + self._background_task = asyncio.ensure_future(self.run()) + + def _run(self, res): + if not self._is_input: + if len(self._output_channels) > 1: + if not isinstance(res, tuple): + raise ValueError( + f"Expected a tuple of {len(self._output_channels)} outputs, " + f"but got {type(res)}" + ) + if len(res) != len(self._output_channels): + raise ValueError( + f"Expected {len(self._output_channels)} outputs, but got " + f"{len(res)} outputs" + ) + + for i, channel in enumerate(self._output_channels): + idx = self._output_idxs[i] + res_i = _adapt(res, idx, self._is_input) + exiting = retry_and_check_interpreter_exit( + lambda: channel.write(res_i, timeout=1) + ) + if exiting: + break + + async def run(self): + loop = asyncio.get_event_loop() + while True: + res = await self._queue.get() + await loop.run_in_executor(self._background_task_executor, self._run, res) + + async def write(self, val: Any) -> None: + if self._closed: + raise RuntimeError("DAG execution cancelled") + await self._queue.put(val) + self._num_writes += 1 + + def close(self): + self._background_task.cancel() + super().close() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/communicator.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/communicator.py new file mode 100644 index 0000000000000000000000000000000000000000..69113055f6f708fe895b384cfbf6a9fc8597b29f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/communicator.py @@ -0,0 +1,199 @@ +from abc import ABC, abstractmethod +from typing import TYPE_CHECKING, Callable, List, Optional, Tuple + +import ray +from ray.experimental.util.types import ReduceOp +from ray.util.annotations import DeveloperAPI + +if TYPE_CHECKING: + import torch + + +# Signature for a torch.Tensor allocator is: +# (shape: Tuple[int], dtype: torch.dtype) -> torch.Tensor. +TorchTensorAllocator = Callable[[Tuple[int], "torch.dtype"], "torch.Tensor"] + + +@DeveloperAPI +class Communicator(ABC): + """ + Communicator for a group of Compiled Graph actors on NVIDIA GPU. + + The Compiled Graph execution leverages this internally to support communication + between actors in the group. + """ + + @abstractmethod + def initialize(self, rank: int) -> None: + """ + Initialize the communicator from the actor. + + This is called once by Compiled Graph on each actor to initialize the + communicator,before any other methods. + + Args: + rank: The rank of this actor in the group. + """ + raise NotImplementedError + + @abstractmethod + def get_actor_handles(self) -> List["ray.actor.ActorHandle"]: + """ + Get handles of all actors for this communicator group. + """ + raise NotImplementedError + + @abstractmethod + def get_rank(self, actor: ray.actor.ActorHandle) -> int: + """ + Return the given actor's rank in the group. + + Args: + actor: The actor handle to look up. + """ + raise NotImplementedError + + @abstractmethod + def get_self_rank(self) -> Optional[int]: + """ + Return this actor's rank. + """ + raise NotImplementedError + + def get_world_size(self) -> int: + """ + Return the number of ranks in the group. + """ + raise NotImplementedError + + @abstractmethod + def send(self, value: "torch.Tensor", peer_rank: int) -> None: + """ + Send a torch.Tensor to a peer. + + This returns when the send kernel has been queued, but the kernel may + not have completed. Therefore, the caller should ensure that there are + no concurrent writes to the sent `value` until the send has finished. + + Args: + value: The torch.Tensor to send. It should already be on this + actor's default device. + peer_rank: The rank of the actor to send to. + """ + raise NotImplementedError + + @abstractmethod + def recv( + self, + shape: Tuple[int], + dtype: "torch.dtype", + peer_rank: int, + allocator: Optional[TorchTensorAllocator] = None, + ) -> "torch.Tensor": + """ + Receive a torch.Tensor from a peer and synchronize. + + After this call returns, the receive buffer is safe to read from from + any stream. An RayChannelError will be raised if an error occurred (e.g., + remote actor died), and the buffer is not safe to read. + + Args: + shape: The shape of the tensor to receive. + dtype: The dtype of the tensor to receive. + peer_rank: The rank of the actor to receive from. + allocator: A function to allocate the tensor to receive into. + """ + raise NotImplementedError + + @property + @abstractmethod + def recv_stream(self): + """ + Return the torch stream context used for receiving tensors. + """ + raise NotImplementedError + + @property + @abstractmethod + def send_stream(self): + """ + Return the torch stream context used for sending tensors. + """ + raise NotImplementedError + + @abstractmethod + def allgather( + self, + send_buf: "torch.Tensor", + recv_buf: "torch.Tensor", + ) -> None: + """ + Collectively allgather the tensor across the group. + + Args: + send_buf: The input torch.tensor to allgather. It should already be + on this actor's default device. + recv_buf: The output torch.tensor to store the allgather result. + """ + raise NotImplementedError + + @abstractmethod + def allreduce( + self, + send_buf: "torch.Tensor", + recv_buf: "torch.Tensor", + op: ReduceOp, + ) -> None: + """ + Collectively allreduce the tensor across the group. + + Args: + send_buf: The input torch.tensor to allreduce. It should already be + on this actor's default device. + recv_buf: The output torch.tensor to store the allreduce result. + op: The reduce operation. + """ + raise NotImplementedError + + @abstractmethod + def reducescatter( + self, + send_buf: "torch.Tensor", + recv_buf: "torch.Tensor", + op: ReduceOp, + ) -> None: + """ + Collectively reducescatter the tensor across the group. + + Args: + send_buf: The input torch.tensor to reducescatter. It should already be + on this actor's default device. + recv_buf: The output torch.tensor to store the reducescatter result. + op: The reduce operation. + """ + raise NotImplementedError + + @abstractmethod + def destroy(self) -> None: + """ + Destroy the GPU communicator. + + Any destruction and cleanup for the GPU communicator should be + done here. Implement as a noop is nothing is needed. + """ + raise NotImplementedError + + @abstractmethod + def get_transport_name(self) -> str: + """ + Return the type of the communicator (gpu or cpu). + """ + raise NotImplementedError + + @classmethod + @abstractmethod + def generate_communicator_id(cls) -> str: + """ + Return the unique id of the communicator. + """ + raise NotImplementedError diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/communicator_handle.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/communicator_handle.py new file mode 100644 index 0000000000000000000000000000000000000000..26dd000ad98ca28f20f8df8d1436b56972486594 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/communicator_handle.py @@ -0,0 +1,27 @@ +from typing import List +import ray + + +class CommunicatorHandle: + """ + A lightweight communicator handle used by the driver to store handles to + the actors in the communicator. + """ + + def __init__( + self, + actor_handles: List["ray.actor.ActorHandle"], + ): + """ + Initializes the CommunicatorHandle with the given actor handles. + + Args: + actor_handles: A list of actor handles to be stored. + """ + self._actor_handles = actor_handles + + def get_actor_handles(self) -> List["ray.actor.ActorHandle"]: + """ + Retuan all actor handles in this communicator. + """ + return self._actor_handles diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/conftest.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..0e6cb1c04a8fc7ca4b2e4b9c46d1b2ce1a6fc19d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/conftest.py @@ -0,0 +1,185 @@ +import asyncio +from collections import defaultdict +from typing import Optional, Tuple +from unittest import mock + +import torch + +import ray +import ray.dag +import ray.experimental.channel as ray_channel +from ray.experimental.channel import nccl_group +from ray.experimental.channel.communicator import TorchTensorAllocator +from ray.experimental.util.types import Device + + +@ray.remote(num_cpus=0) +class Barrier: + """ + Barrier that blocks the given number of actors until all actors have + reached the barrier. This is used to mock out blocking NCCL ops. + """ + + def __init__(self, num_actors=2): + self.num_actors = num_actors + self.condition = asyncio.Condition() + # Buffer for the data that is "sent" between the actors, each entry is + # one p2p op. + self.data = {} + # Buffer for the number of actors seen, each entry is one p2p op. + self.num_actors_seen = defaultdict(int) + + # Add a new mock for the TorchTensorType.device property + device_property_patcher = mock.patch( + "ray.experimental.channel.torch_tensor_type.TorchTensorType.device", + new_callable=mock.PropertyMock, + return_value=Device.CPU, + ) + device_property_patcher.start() + + async def wait(self, idx: int, data=None): + """ + Wait at barrier until all actors have sent `idx`. One actor should + provide `data`, and this value will be returned by this method for all + other actors. + """ + async with self.condition: + if data is not None: + assert idx not in self.data, (self.data, self.num_actors_seen) + self.data[idx] = data + self.num_actors_seen[idx] += 1 + + if self.num_actors_seen[idx] == self.num_actors: + # Wake up all tasks waiting on this condition. + self.condition.notify_all() + else: + await self.condition.wait_for( + lambda: self.num_actors_seen[idx] == self.num_actors + ) + + if data is None: + data = self.data[idx] + + return data + + +class MockCudaStream: + def __init__(self): + self.cuda_stream = 0 + + def synchronize(self): + pass + + +class MockNcclGroup(nccl_group._NcclGroup): + """ + Mock the internal _NcclGroup to use a barrier actor instead of a NCCL group + for communication. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + # We use the op index to synchronize the sender and receiver at the + # barrier. + self.num_ops = defaultdict(int) + self.barriers = set() + + def send(self, tensor: torch.Tensor, peer_rank: int): + # "Send" the tensor to the barrier actor. + barrier_key = sorted([self.get_self_rank(), peer_rank]) + barrier_key = f"barrier-{barrier_key[0]}-{barrier_key[1]}" + barrier = ray.get_actor(name=barrier_key) + self.barriers.add(barrier) + ray.get(barrier.wait.remote(self.num_ops[barrier_key], tensor)) + self.num_ops[barrier_key] += 1 + + def recv( + self, + shape: Tuple[int], + dtype: torch.dtype, + peer_rank: int, + allocator: Optional[TorchTensorAllocator] = None, + ): + # "Receive" the tensor from the barrier actor. + barrier_key = sorted([self.get_self_rank(), peer_rank]) + barrier_key = f"barrier-{barrier_key[0]}-{barrier_key[1]}" + barrier = ray.get_actor(name=barrier_key) + self.barriers.add(barrier) + received_tensor = ray.get(barrier.wait.remote(self.num_ops[barrier_key])) + assert ( + allocator is not None + ), "torch tensor allocator is required for MockNcclGroup" + buf = allocator(shape, dtype) + buf[:] = received_tensor[:] + self.num_ops[barrier_key] += 1 + return buf + + def destroy(self) -> None: + for barrier in self.barriers: + ray.kill(barrier) + + +def start_nccl_mock(): + """ + Patch methods that require CUDA. + """ + # Mock cupy dependencies. + nccl_mock = mock.MagicMock() + nccl_mock.nccl.get_unique_id.return_value = 0 + cp_patcher = mock.patch.dict( + "sys.modules", + { + "cupy.cuda": nccl_mock, + "cupy": mock.MagicMock(), + "ray.util.collective.collective_group": mock.MagicMock(), + }, + ) + cp_patcher.start() + + # Mock send/recv ops to use an actor instead of NCCL. + ray.experimental.channel.nccl_group._NcclGroup = MockNcclGroup + + # PyTorch mocks. + stream_patcher = mock.patch( + "torch.cuda.current_stream", new_callable=lambda: MockCudaStream + ) + stream_patcher.start() + new_stream_patcher = mock.patch( + "torch.cuda.Stream", new_callable=lambda: MockCudaStream + ) + new_stream_patcher.start() + tensor_patcher = mock.patch("torch.Tensor.device", torch.device("cuda")) + tensor_patcher.start() + tensor_patcher = mock.patch("torch.Tensor.is_cuda", True) + tensor_patcher.start() + tensor_allocator_patcher = mock.patch( + "ray.experimental.channel.torch_tensor_accelerator_channel._torch_zeros_allocator", + lambda shape, dtype: torch.zeros(shape, dtype=dtype), + ) + tensor_allocator_patcher.start() + + # Add a new mock for the TorchTensorType.device property + device_property_patcher = mock.patch( + "ray.experimental.channel.torch_tensor_type.TorchTensorType.device", + new_callable=mock.PropertyMock, + return_value=Device.CPU, + ) + device_property_patcher.start() + + ctx = ray_channel.ChannelContext.get_current() + ctx.set_torch_device(torch.device("cuda")) + + +class TracedChannel(ray_channel.shared_memory_channel.Channel): + """ + Patched Channel that records all write ops for testing. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + self.ops = [] + + def write(self, *args, **kwargs): + self.ops.append((args, kwargs)) + return super().write(*args, **kwargs) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/cpu_communicator.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/cpu_communicator.py new file mode 100644 index 0000000000000000000000000000000000000000..e0d7f199d7c723c7077e012eed7b9b1fc66ea51a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/cpu_communicator.py @@ -0,0 +1,207 @@ +import asyncio +from collections import defaultdict +from typing import TYPE_CHECKING, Dict, List, Optional, Tuple + +import ray +from ray.experimental.channel.communicator import ( + Communicator, + ReduceOp, + TorchTensorAllocator, +) + +if TYPE_CHECKING: + import torch + + +@ray.remote(num_cpus=0) +class CPUCommBarrier: + """ + Barrier actor that blocks the given number of actors until all actors have + reached the Barrier. + + p2p operations are not done here (completed via shared memory channel). + """ + + def __init__(self, num_actors: int): + self.num_actors = num_actors + self.condition = asyncio.Condition() + # Stores the data for each collective operation + self.collective_data: Dict[int, List["torch.Tensor"]] = defaultdict(list) + # Stores the shape of data for each collective operation + self.collective_data_shape: Dict[int, "torch.Tensor.type"] = {} + # Buffer for the number of actors seen + self.num_actors_seen = defaultdict(int) + # Number of actors who have read the result, and are about to exit the function. + # State is kept so we only garbage collect after the last actor has read the + # relevant data. + self.num_actors_read = defaultdict(int) + + async def wait_collective(self, op_id: int, data: "torch.Tensor", op: ReduceOp): + """ + Wait at the communicator until all actors have sent `op_id` and `data`. + Once data from all actors is received, execute the collective `op` + on the communicator actor and return the result. + """ + async with self.condition: + self.collective_data[op_id].append(data) + self.num_actors_seen[op_id] += 1 + + if self.num_actors_seen[op_id] == self.num_actors: + # Apply the collective operation across all gathered tensors + data = self._apply_op(op, self.collective_data[op_id]) + self.collective_data[op_id] = data + self.condition.notify_all() + else: + await self.condition.wait_for( + lambda: self.num_actors_seen[op_id] == self.num_actors + ) + + data = self.collective_data[op_id] + self.num_actors_read[op_id] += 1 + + if self.num_actors_read[op_id] == self.num_actors: + del self.collective_data[op_id] + del self.num_actors_seen[op_id] + del self.num_actors_read[op_id] + + return data + + def _apply_op(self, op: ReduceOp, tensors: List["torch.Tensor"]) -> "torch.Tensor": + """Apply the specified reduction operation across a list of tensors.""" + + result = tensors[0].clone() + if op == ReduceOp.SUM: + for tensor in tensors[1:]: + result += tensor + elif op == ReduceOp.PRODUCT: + for tensor in tensors[1:]: + result *= tensor + elif op == ReduceOp.MAX: + for tensor in tensors[1:]: + result = torch.max(result, tensor) + elif op == ReduceOp.MIN: + for tensor in tensors[1:]: + result = torch.min(result, tensor) + elif op == ReduceOp.AVG: + result = sum(tensors) / len(tensors) + else: + raise ValueError(f"Operation {op} not supported") + return result + + +class CPUCommunicator(Communicator): + """ + Uses a CPU-based communicator actor instead of an accelerator group like NCCL. + """ + + def __init__(self, world_size: int, actor_handles: List["ray.actor.ActorHandle"]): + """We use the op index to synchronize the sender and receiver at the + communicator actor.""" + self._world_size = world_size + self._actor_handles = actor_handles + self.num_ops = defaultdict(int) + + # For collective communication, one barrier will be created for + # each unique group of participants. + self.barriers = set() + self._rank = None + + def send(self, tensor: "torch.Tensor", peer_rank: int): + # p2p operations are done via a shared memory channel, initialized in + # `create_channel` of `TorchTensorType` + pass + + def recv( + self, + shape: Tuple[int], + dtype: "torch.dtype", + peer_rank: int, + allocator: Optional[TorchTensorAllocator] = None, + ): + # See the comment on `send` + pass + + def allgather( + self, + send_buf: "torch.Tensor", + recv_buf: "torch.Tensor", + ): + raise NotImplementedError + + def allreduce( + self, + send_buf: "torch.Tensor", + recv_buf: "torch.Tensor", + op: ReduceOp = ReduceOp.SUM, + ): + all_ranks = [ + self.get_rank(actor_handle) for actor_handle in self.get_actor_handles() + ] + barrier_key = "barrier-collective-" + "-".join(map(str, sorted(all_ranks))) + barrier = CPUCommBarrier.options(name=barrier_key, get_if_exists=True).remote( + self._world_size + ) + self.barriers.add(barrier) + + result = ray.get( + barrier.wait_collective.remote(self.num_ops[barrier_key], send_buf, op) + ) + assert recv_buf is not None, "Receiving buffer required for CPUCommunicator" + recv_buf[:] = result[:] + self.num_ops[barrier_key] += 1 + + def reducescatter( + self, + send_buf: "torch.Tensor", + recv_buf: "torch.Tensor", + op: ReduceOp = ReduceOp.SUM, + ): + raise NotImplementedError + + def destroy(self) -> None: + for barrier in self.barriers: + ray.kill(barrier) + + def initialize(self, rank: int) -> None: + self._rank = rank + + def get_actor_handles(self) -> List["ray.actor.ActorHandle"]: + return self._actor_handles + + def get_rank(self, actor: ray.actor.ActorHandle) -> int: + """ + Return the given actor's rank in the CPU communicator. + + Args: + actor: The actor handle to look up. + """ + actor_ids = [a._ray_actor_id for a in self._actor_handles] + try: + rank = actor_ids.index(actor._ray_actor_id) + except ValueError: + raise ValueError("Actor is not in the CPUCommunicator group.") + return rank + + def get_self_rank(self) -> Optional[int]: + return self._rank + + def get_world_size(self) -> int: + """ + Return the number of ranks in the CPU communicator. + """ + return self._world_size + + def get_transport_name(self) -> str: + return "cpu" + + def recv_stream(self): + raise NotImplementedError + + def send_stream(self): + raise NotImplementedError + + @classmethod + def generate_communicator_id(cls) -> str: + import uuid + + return str(uuid.uuid4()) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/intra_process_channel.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/intra_process_channel.py new file mode 100644 index 0000000000000000000000000000000000000000..11133e0ebe6081d0fd235951c3c299a2ea0b4966 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/intra_process_channel.py @@ -0,0 +1,70 @@ +import uuid +from typing import Any, Optional + +from ray.experimental.channel import ChannelContext +from ray.experimental.channel.common import ChannelInterface +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class IntraProcessChannel(ChannelInterface): + """ + IntraProcessChannel is a channel for communication between two tasks in the same + worker process. It writes data directly to the worker's _SerializationContext + and reads data from the _SerializationContext to avoid the serialization + overhead and the need for reading/writing from shared memory. Note that if the + readers may mutate the data, users should deep copy the data themselves to avoid + side effects. + + Args: + num_readers: The number of readers that will read from this channel. Readers + can be the same method of the same actor. + """ + + def __init__( + self, + num_readers, + _channel_id: Optional[str] = None, + ): + # Generate a unique ID for the channel. The writer and reader will use + # this ID to store and retrieve data from the _SerializationContext. + self._channel_id = _channel_id + self._num_readers = num_readers + if self._channel_id is None: + self._channel_id = str(uuid.uuid4()) + + def ensure_registered_as_writer(self) -> None: + pass + + def ensure_registered_as_reader(self) -> None: + pass + + def __reduce__(self): + return IntraProcessChannel, ( + self._num_readers, + self._channel_id, + ) + + def __str__(self) -> str: + return f"IntraProcessChannel(channel_id={self._channel_id})" + + def write(self, value: Any, timeout: Optional[float] = None): + self.ensure_registered_as_writer() + # No need to check timeout as the operation is non-blocking. + + # Because both the reader and writer are in the same worker process, + # we can directly store the data in the context instead of storing + # it in the channel object. This removes the serialization overhead of `value`. + ctx = ChannelContext.get_current().serialization_context + ctx.set_data(self._channel_id, value, self._num_readers) + + def read(self, timeout: Optional[float] = None, deserialize: bool = True) -> Any: + self.ensure_registered_as_reader() + assert deserialize, "Data passed from the actor to itself is never serialized" + # No need to check timeout as the operation is non-blocking. + ctx = ChannelContext.get_current().serialization_context + return ctx.get_data(self._channel_id) + + def close(self) -> None: + ctx = ChannelContext.get_current().serialization_context + ctx.reset_data(self._channel_id) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/nccl_group.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/nccl_group.py new file mode 100644 index 0000000000000000000000000000000000000000..f81c8c4bcadbc4558cf9342c5b5aa734a401191c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/nccl_group.py @@ -0,0 +1,374 @@ +import logging +from types import ModuleType +from typing import TYPE_CHECKING, Callable, List, Optional, Tuple + +import ray +from ray.exceptions import RayChannelError +from ray.experimental.channel.communicator import Communicator, TorchTensorAllocator +from ray.experimental.util.types import ReduceOp +from ray.experimental.channel.accelerator_context import AcceleratorContext + +if TYPE_CHECKING: + import torch + + +# 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 _NcclGroup(Communicator): + """ + Represents an actor's NCCL communicator. This is the default NCCL communicator + to be used in Compiled Graph if a custom communicator is not provided. + + This class is not thread-safe. + """ + + def __init__( + self, + world_size: int, + comm_id: tuple, + rank: Optional[int], + actor_handles: List["ray.actor.ActorHandle"], + cuda_stream: Optional["torch.cuda.Stream"], + use_communication_streams: bool = False, + ): + """ + Initialize a NCCL communicator that can be used to communicate p2p with + other GPU actors. + + This method blocks until the same call has been made on all other + actors in the group, with the same arguments for world_size and + comm_id. + + NOTE: A concurrent NCCL group can coexist with this one but using the + two groups concurrently on different CUDA streams may cause deadlock. + See + https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/usage/communicators.html + #using-multiple-nccl-communicators-concurrently. + + If the user can guarantee that all involved actors execute the same ops + in the same order, then the other NCCL group should use the given + `cuda_stream`, and there will not be a concurrency issue. Otherwise, + the other stream needs to synchronize with the given `cuda_stream` + before and after it launches NCCL ops, e.g., at the beginning and end + of a DAG task. + + Args: + world_size: The number of participating actors/devices. + comm_id: A unique communicator ID returned by + cupy.cuda.nccl.get_unique_id(). + rank: The rank of this actor. If None, then the caller is not a + participant of the NCCL group. + actor_handles: A list of actor handles, in rank order. + cuda_stream: A raw CUDA stream to dispatch NCCL ops to. If rank is + specified, then this must be specified too. + use_communication_streams: Whether to use dedicated send and recv + streams for communication. If True, communication and computation + can be overlapped to improve performance. + """ + self._world_size = world_size + self._rank: Optional[int] = rank + self.nccl_util: Optional[ModuleType] = None + self._actor_handles = actor_handles + self._use_communication_streams = use_communication_streams + + if rank is not None: + assert ray.get_gpu_ids(), "NCCL actor has no GPUs assigned" + assert cuda_stream is not None, "NCCL actor must specify cuda_stream" + + expected_rank = self.get_rank(ray.get_runtime_context().current_actor) + assert ( + rank == expected_rank + ), f"NCCL actor's rank {rank} does not match expected rank {expected_rank}" + + from ray.util.collective.collective_group import nccl_util + + self.nccl_util = nccl_util + self._comm = self.nccl_util.NcclCommunicator(world_size, comm_id, rank) + else: + # Driver does not have a rank. + self._comm = None + + self._cuda_stream: Optional["torch.cuda.Stream"] = None + self._send_stream: Optional["torch.cuda.Stream"] = None + self._recv_stream: Optional["torch.cuda.Stream"] = None + if cuda_stream is not None: + assert rank is not None, "NCCL actor has no rank assigned" + self._cuda_stream = cuda_stream + + if use_communication_streams: + import torch + + # TODO(swang): Allow default device to be overridden. + device = AcceleratorContext.get().get_accelerator_devices()[0] + + self._send_stream = torch.cuda.Stream(device=device) + self._recv_stream = torch.cuda.Stream(device=device) + else: + self._send_stream = self._cuda_stream + self._recv_stream = self._cuda_stream + + self._closed = False + + def initialize(self, rank: int) -> None: + # No additional initialization is needed. + pass + + def get_actor_handles(self) -> List["ray.actor.ActorHandle"]: + return self._actor_handles + + def get_rank(self, actor: ray.actor.ActorHandle) -> int: + """ + Return the given actor's rank in the NCCL communicator. + + Args: + actor: The actor handle to look up. + """ + actor_ids = [a._ray_actor_id for a in self._actor_handles] + try: + rank = actor_ids.index(actor._ray_actor_id) + except ValueError: + raise ValueError("Actor is not in the NCCL group.") + return rank + + def get_self_rank(self) -> Optional[int]: + """ + Return this actor's rank. + """ + return self._rank + + def get_world_size(self) -> int: + """ + Return the number of ranks in the NCCL communicator. + """ + return self._world_size + + def send(self, buf: "torch.Tensor", peer_rank: int) -> None: + """ + Send a torch.Tensor to a peer. + + This returns when the send kernel has been queued, but the kernel may + not have completed. Therefore, the caller should ensure that there are + no concurrent writes to the sent `buf` until the send has finished. + That is, either all writes should be submitted on the current stream + (self._cuda_stream) or, if on a different stream, that stream should + synchronize with the current stream. + + Args: + buf: The torch.Tensor to send. It should already be on this + actor's default device. + peer_rank: The rank of the actor to send to. + """ + if self._closed: + raise RayChannelError("NCCL group has been destroyed.") + + if self._use_communication_streams: + # We observed that if all recv/compute/send operations run on GPU, + # since there is no synchronization, the CPU execution loop may be + # far ahead of the GPU operations and lead to runtime failures. + # To avoid that, we synchronize on the send stream. + # TODO(rui): find a better approach + self._send_stream.synchronize() + + # TODO(swang): Handle send/recv async NCCL errors such as network + # failures. + self._comm.send( + self.nccl_util.get_tensor_ptr(buf), + buf.numel(), + self.nccl_util.get_nccl_tensor_dtype(buf), + peer_rank, + self._send_stream.cuda_stream, + ) + + def recv( + self, + shape: Tuple[int], + dtype: "torch.dtype", + peer_rank: int, + allocator=Optional[TorchTensorAllocator], + ) -> "torch.Tensor": + """ + Receive a torch.Tensor from a peer and synchronize the current stream. + + After this call returns, the receive buffer is safe to read from from + any stream. An RayChannelError will be raised if an error occurred (e.g., + remote actor died), and the buffer is not safe to read. + + Args: + buf: The torch.Tensor to receive into. This buffer is safe to read + peer_rank: The rank of the actor to receive from. + """ + if self._closed: + raise RayChannelError("NCCL group has been destroyed.") + assert allocator is not None, "NCCL group requires a tensor allocator" + buf = allocator(shape, dtype) + + if self._use_communication_streams: + # We observed that if all recv/compute/send operations run on GPU, + # since there is no synchronization, the CPU execution loop may be + # far ahead of the GPU operations and lead to runtime failures. + # To avoid that, we synchronize on the recv stream. + # TODO(rui): find a better approach + self._recv_stream.synchronize() + + self._comm.recv( + self.nccl_util.get_tensor_ptr(buf), + buf.numel(), + self.nccl_util.get_nccl_tensor_dtype(buf), + peer_rank, + self._recv_stream.cuda_stream, + ) + else: + self._comm.recv( + self.nccl_util.get_tensor_ptr(buf), + buf.numel(), + self.nccl_util.get_nccl_tensor_dtype(buf), + peer_rank, + self._recv_stream.cuda_stream, + ) + + # Buffer values are undefined if NCCL ops are aborted. Therefore, we + # need to synchronize here and check that the channel is still open to + # ensure that the receive buffer is valid. + # TODO(swang): Avoid CUDA synchronization. + self._cuda_stream.synchronize() + + if self._closed: + raise RayChannelError("NCCL group has been destroyed.") + return buf + + def _exec_collective( + self, + send_buf: "torch.Tensor", + recv_buf: "torch.Tensor", + operation: "Callable[..., None]", + *operation_args, + ): + if self._closed: + raise RayChannelError("NCCL group has been destroyed.") + + assert send_buf.dtype == recv_buf.dtype, ( + "Ray Compiled Graph derived the dtype of recv_buf from send_buf, " + "so send_buf and recv_buf must have the same dtype. " + "If you see this error, please file an issue at Ray repository." + ) + + operation(*operation_args) + + # Buffer values are undefined if NCCL ops are aborted. Therefore, we + # need to synchronize here and check that the channel is still open to + # ensure that the receive buffer is valid. + # TODO(swang): Avoid CUDA synchronization. + # TODO(wxdeng): This synchronize will be optional after merging the unify PR. + self._cuda_stream.synchronize() + if self._closed: + raise RayChannelError( + "NCCL group has been destroyed during allreduce operation. " + "There may be a dtype mismatch between input tensors from " + "different ranks." + ) + + def allgather( + self, + send_buf: "torch.Tensor", + recv_buf: "torch.Tensor", + ): + operation_args = [ + self.nccl_util.get_tensor_ptr(send_buf), + self.nccl_util.get_tensor_ptr(recv_buf), + send_buf.numel(), + self.nccl_util.get_nccl_tensor_dtype(send_buf), + self._cuda_stream.cuda_stream, + ] + self._exec_collective( + send_buf, + recv_buf, + self._comm.allGather, + *operation_args, + ) + + def allreduce( + self, + send_buf: "torch.Tensor", + recv_buf: "torch.Tensor", + op: ReduceOp = ReduceOp.SUM, + ): + operation_args = [ + self.nccl_util.get_tensor_ptr(send_buf), + self.nccl_util.get_tensor_ptr(recv_buf), + send_buf.numel(), + self.nccl_util.get_nccl_tensor_dtype(send_buf), + op.value, + self._cuda_stream.cuda_stream, + ] + self._exec_collective( + send_buf, + recv_buf, + self._comm.allReduce, + *operation_args, + ) + + def reducescatter( + self, + send_buf: "torch.Tensor", + recv_buf: "torch.Tensor", + op: ReduceOp = ReduceOp.SUM, + ): + operation_args = [ + self.nccl_util.get_tensor_ptr(send_buf), + self.nccl_util.get_tensor_ptr(recv_buf), + recv_buf.numel(), + self.nccl_util.get_nccl_tensor_dtype(send_buf), + op.value, + self._cuda_stream.cuda_stream, + ] + self._exec_collective( + send_buf, + recv_buf, + self._comm.reduceScatter, + *operation_args, + ) + + @property + def recv_stream(self): + import torch + + return torch.cuda.StreamContext(self._recv_stream) + + @property + def send_stream(self): + import torch + + return torch.cuda.StreamContext(self._send_stream) + + def destroy(self) -> None: + """ + Destroy the NCCL group. + """ + if self._closed: + return + + self._closed = True + + if self._comm is not None: + logger.info( + "Destructing NCCL group on actor: " + f"{ray.get_runtime_context().current_actor}" + ) + # Abort *after* setting the _closed flag. This ensures that NCCL + # ops that were blocked on a remote peer will see that the _closed + # flag is True when they exit from the abort. + self._comm.abort() + self._comm.destroy() + + def get_transport_name(self) -> str: + return "accelerator" + + @classmethod + def generate_communicator_id(cls) -> str: + from cupy.cuda import nccl + + return nccl.get_unique_id() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/serialization_context.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/serialization_context.py new file mode 100644 index 0000000000000000000000000000000000000000..40784b38f4098d422d5066d8134d4328f071e069 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/serialization_context.py @@ -0,0 +1,229 @@ +import warnings +from typing import TYPE_CHECKING, Any, Dict, List, Set, Tuple, Union + +from ray.experimental.util.types import Device + +if TYPE_CHECKING: + import numpy as np + import torch + + +_TORCH_WARNING_FILTER_ACTIVATE = True + + +class _SerializationContext: + def __init__(self): + # If true, then tensors found in the data to serialize are extracted + # and the caller should send them through an external transport. + self._use_external_transport: bool = False + # If _use_external_transport is True, then these are + # the tensors that should be sent or received + # out-of-band, through the external transport. + self._out_of_band_tensors: List["torch.Tensor"] = [] + # During serialization, tensors sent out-of-band are replaced with + # integer placeholders. This tracks the set of placeholders seen. + self._deserialized_tensor_placeholders: Set[int] = set() + + # Buffer for transferring data between tasks in the same worker process. + # The key is the channel ID, and the value is the data. We don't use a + # lock when reading/writing the buffer because a DAG node actor will only + # execute one task at a time in `do_exec_tasks`. It will not execute multiple + # Ray tasks on a single actor simultaneously. + self.intra_process_channel_buffers: Dict[str, Any] = {} + # The number of readers for each channel. When the number of readers + # reaches 0, remove the data from the buffer. + self.channel_id_to_num_readers: Dict[str, int] = {} + + def set_target_device(self, device: Device) -> None: + self._target_device = device + + def set_data(self, channel_id: str, value: Any, num_readers: int) -> None: + assert num_readers > 0, "num_readers must be greater than 0." + assert ( + channel_id not in self.intra_process_channel_buffers + ), f"Channel {channel_id} already exists in the buffer." + assert ( + channel_id not in self.channel_id_to_num_readers + ), f"Channel {channel_id} already exists in the channel_id_to_num_readers." + + self.intra_process_channel_buffers[channel_id] = value + self.channel_id_to_num_readers[channel_id] = num_readers + + def has_data(self, channel_id: str) -> bool: + return channel_id in self.intra_process_channel_buffers + + def get_data(self, channel_id: str) -> Any: + assert ( + channel_id in self.intra_process_channel_buffers + ), f"Channel {channel_id} does not exist in the buffer." + assert ( + channel_id in self.channel_id_to_num_readers + ), f"Channel {channel_id} does not exist in the channel_id_to_num_readers." + + self.channel_id_to_num_readers[channel_id] -= 1 + if self.channel_id_to_num_readers[channel_id] == 0: + # All readers have read the data, so we can remove it. + self.channel_id_to_num_readers.pop(channel_id) + return self.intra_process_channel_buffers.pop(channel_id) + return self.intra_process_channel_buffers[channel_id] + + def reset_data(self, channel_id: str) -> None: + self.intra_process_channel_buffers.pop(channel_id, None) + self.channel_id_to_num_readers.pop(channel_id, None) + + def set_use_external_transport(self, use_external_transport: bool) -> None: + self._use_external_transport = use_external_transport + + @property + def use_external_transport(self) -> bool: + return self._use_external_transport + + def reset_out_of_band_tensors( + self, tensors: List["torch.Tensor"] + ) -> Tuple[List["torch.Tensor"], Set[int]]: + """ + Return and reset the out-of-band tensors and all tensor placeholders + that were deserialized since the last call to reset. + """ + prev_tensors = self._out_of_band_tensors + deserialized_tensor_placeholders = self._deserialized_tensor_placeholders + self._out_of_band_tensors = tensors + self._deserialized_tensor_placeholders = set() + return prev_tensors, deserialized_tensor_placeholders + + def serialize_tensor( + self, tensor: "torch.Tensor" + ) -> Union[int, Tuple["np.ndarray", "torch.dtype", str]]: + from ray.experimental.channel import ChannelContext + + ctx = ChannelContext.get_current() + if self._use_external_transport and tensor.device == ctx.torch_device: + # External transport is enabled and we found a tensor that matches + # our device. Add the actual tensor to a buffer. The buffer of + # tensors should later be popped by the caller and sent via + # external transport. + self._out_of_band_tensors.append(tensor) + # Return a placeholder. + return len(self._out_of_band_tensors) - 1 + + return self.serialize_to_numpy_or_scalar(tensor) + + def serialize_to_numpy_or_scalar( + self, tensor: "torch.Tensor" + ) -> Tuple[Union["np.ndarray", Any], "torch.dtype", str]: + """ + Serialize a tensor to a numpy array, + or a scalar when the tensor is 0-dim. + """ + import torch + + tensor_device_type = tensor.device.type + + # Transfer through Ray's shared memory store for now. + # TODO(swang): This requires two copies, one to transfer from GPU to + # CPU and another from CPU to shared memory. Ideally we should elide + # the first copy and memcpy directly from GPU to the shared memory + # buffer. + if tensor_device_type != "cpu": + tensor = tensor.to("cpu") + + # Numpy does not have an equivalent dtype for all torch dtypes, so + # instead of casting directly to numpy: + # 1) for non-scalar tensors, we first use a view with a common dtype (uint8) + # and then view as numpy array. + # 2) for scalar tensors, we cannot use a uint8 view when the size differs, + # so we save the original item and type information. + if tensor.dim() > 0: + return (tensor.view(torch.uint8).numpy(), tensor.dtype, tensor_device_type) + else: + return (tensor.item(), tensor.dtype, tensor_device_type) + + def deserialize_tensor( + self, + val: Union[Tuple["np.ndarray", "torch.dtype", str], int], + target_device: Device, + ): + + # Found a placeholder for a tensor that was serialized via accelerator. + # Replace it with the corresponding deserialized tensor. + if isinstance(val, int): + placeholder = val + self._deserialized_tensor_placeholders.add(placeholder) + assert placeholder < len(self._out_of_band_tensors), ( + "placeholder", + placeholder, + "out_of_band_tensors", + self._out_of_band_tensors, + ) + tensor = self._out_of_band_tensors[placeholder] + if target_device == Device.CPU: + tensor = tensor.to("cpu") + return tensor + + np_array, dtype, tensor_device_type = val + return self.deserialize_from_numpy_or_scalar( + np_array, dtype, tensor_device_type, target_device + ) + + def deserialize_from_numpy_or_scalar( + self, + np_array: Union["np.ndarray", Any], + dtype: "torch.dtype", + tensor_device_type: str, + target_device: Device, + ): + import torch + import numpy as np + + if target_device == Device.DEFAULT: + target_device_type = tensor_device_type + elif target_device in [Device.GPU, Device.CUDA]: + target_device_type = "cuda" + else: + target_device_type = target_device.value + + # TODO(swang): Support local P2P transfers if available. + if target_device_type != "cpu": + + def convert_numpy_to_tensor(np_array): + if not isinstance(np_array, np.ndarray): + # For scalar tensors, create the 0-dim tensor. + return torch.tensor( + np_array, device=target_device_type, dtype=dtype + ) + else: + # For non-scalar tensors, view as the original dtype. + # It does zero-copy convert np_array inside shared memory to + # a tensor. Since we move data to GPU immediately, it is safe. + cpu_tensor = torch.from_numpy(np_array).view(dtype) + return cpu_tensor.to(device=target_device_type) + + global _TORCH_WARNING_FILTER_ACTIVATE + # filtering warning messages would be the bottleneck for + # deserializing torch tensors. Since the warning only prompts once, + # we would only deal with it for the first time. + if _TORCH_WARNING_FILTER_ACTIVATE: + with warnings.catch_warnings(): + # Since np_array.is_writable is False (it is set by Ray), + # this raises a warning. Suppress it. + warnings.filterwarnings( + "ignore", + category=UserWarning, + message="The given NumPy array is not writable", + ) + gpu_tensor = convert_numpy_to_tensor(np_array) + _TORCH_WARNING_FILTER_ACTIVATE = False + else: + gpu_tensor = convert_numpy_to_tensor(np_array) + + return gpu_tensor + + # TODO(swang): Use zero-copy from_numpy() if np_array.flags.writeable + # is True. This is safe to set when deserializing np_array if the + # upstream task has num_readers=1. + if not isinstance(np_array, np.ndarray): + # For scalar tensors, create the 0-dim tensor. + return torch.tensor(np_array, device=target_device_type, dtype=dtype) + else: + # For non-scalar tensors, view as the original dtype. + return torch.tensor(np_array, device=target_device_type).view(dtype) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/shared_memory_channel.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/shared_memory_channel.py new file mode 100644 index 0000000000000000000000000000000000000000..11cac4bc3439c76ce75334edfb808a37ab09e52b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/shared_memory_channel.py @@ -0,0 +1,796 @@ +import io +import logging +import time +from collections import defaultdict, namedtuple +from typing import Any, Dict, List, Optional, Set, Tuple, Union + +import ray +import ray.exceptions +from ray._raylet import SerializedObject +from ray.experimental.channel import utils +from ray.experimental.channel.common import ChannelInterface, ChannelOutputType +from ray.experimental.channel.intra_process_channel import IntraProcessChannel +from ray.experimental.channel.utils import get_self_actor +from ray.util.annotations import DeveloperAPI, PublicAPI + +# 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__) + + +def _create_channel_ref( + self, + buffer_size_bytes: int, +) -> "ray.ObjectRef": + """ + Create a channel that can be read and written through Ray's shared-memory + object store. + + The channel has no buffer, so the writer will block until reader(s) have + read the previous value. + + A writer and colocated readers can communicate via a shared memory buffer. + If the readers are remote, then RPC is used to synchronize the writer and + readers' buffers. + + Args: + buffer_size_bytes: The initial buffer size in bytes for messages + that can be passed between tasks in the DAG. The buffers will + be automatically resized if larger messages are written to the + channel. + Returns: + Channel: A wrapper around ray.ObjectRef. + """ + worker = ray._private.worker.global_worker + worker.check_connected() + + value = b"0" * buffer_size_bytes + + try: + object_ref = worker.put_object( + value, owner_address=None, _is_experimental_channel=True + ) + except ray.exceptions.ObjectStoreFullError: + logger.info( + "Put failed since the value was either too large or the " + "store was full of pinned objects." + ) + raise + return object_ref + + +# Compiled Graph maintains 1 reader object reference (also called buffer) per node. +# reader_ref: The object reference. +# ref_owner_actor_id: The actor who created the object reference. +# num_readers: The number of reader actors who reads this object reference. +ReaderRefInfo = namedtuple( + "ReaderRefInfo", ["reader_ref", "ref_owner_actor_id", "num_reader_actors"] +) + + +class _ResizeChannel: + """ + When a channel must be resized, the channel backing store must be resized on both + the writer and the reader nodes. The writer first resizes its own backing store. The + writer then uses an instance of this class as a sentinel value to tell the reader to + resize its own backing store. The class instance is sent through the channel. + """ + + def __init__( + self, + _node_id_to_reader_ref_info: Dict[str, ReaderRefInfo], + ): + """ + Args: + _node_id_to_reader_ref_info: A node id to ReaderRefInfo. + """ + self._node_id_to_reader_ref_info = _node_id_to_reader_ref_info + + +class SharedMemoryType(ChannelOutputType): + def __init__( + self, + *, + buffer_size_bytes: Optional[int] = None, + num_shm_buffers: Optional[int] = None, + ): + """ + Args: + buffer_size_bytes: The initial buffer size in bytes for messages + that can be passed between tasks in the DAG. The buffers will + be automatically resized if larger messages are written to the + channel. + num_shm_buffers: The number of shared memory buffers per channel. + Note: In the case of multiple nodes, we only support 1 shared + memory buffer. + """ + super().__init__() + + from ray.dag import DAGContext + + ctx = DAGContext.get_current() + + if buffer_size_bytes is None: + buffer_size_bytes = ctx.buffer_size_bytes + self.buffer_size_bytes = buffer_size_bytes + if num_shm_buffers is None: + num_shm_buffers = 1 + self._num_shm_buffers = num_shm_buffers + + def create_channel( + self, + writer: Optional["ray.actor.ActorHandle"], + reader_and_node_list: List[Tuple["ray.actor.ActorHandle", str]], + driver_actor_id: Optional[str] = None, + ) -> "Channel": + """ + Instantiate a ChannelInterface class that can be used + to pass data of this type. + + Args: + writer: The actor that may write to the channel. None signifies the driver. + reader_and_node_list: A list of tuples, where each tuple contains a reader + actor handle and the node ID where the actor is located. + driver_actor_id: If this channel is read by a driver and that driver is an + actual actor, this will be the actor ID of that driver actor. + + Returns: + A ChannelInterface that can be used to pass data + of this type. + """ + return CompositeChannel( + writer, + reader_and_node_list, + self._num_shm_buffers, + driver_actor_id, + ) + + +@PublicAPI(stability="alpha") +class Channel(ChannelInterface): + """ + A wrapper type for ray.ObjectRef. Currently supports ray.get but not + ray.wait. + """ + + def __init__( + self, + writer: Optional[ray.actor.ActorHandle], + reader_and_node_list: List[Tuple["ray.actor.ActorHandle", str]], + typ: Optional[Union[int, SharedMemoryType]] = None, + _writer_node_id: Optional["ray.NodeID"] = None, + _writer_ref: Optional["ray.ObjectRef"] = None, + _node_id_to_reader_ref_info: Optional[Dict[str, ReaderRefInfo]] = None, + _writer_registered: bool = False, + _reader_registered: bool = False, + ): + """ + Create a channel that can be read and written by co-located Ray processes. + + Anyone may write to or read from the channel. The channel has no + buffer, so the writer will block until reader(s) have read the previous + value. + + Args: + writer: The actor that may write to the channel. None signifies the driver. + reader_and_node_list: A list of tuples, where each tuple contains a reader + actor handle and the node ID where the actor is located. + typ: Type information about the values passed through the channel. + Either an integer representing the max buffer size in bytes + allowed, or a SharedMemoryType. + Returns: + Channel: A wrapper around ray.ObjectRef. + """ + assert len(reader_and_node_list) > 0 + for reader, _ in reader_and_node_list: + assert isinstance(reader, ray.actor.ActorHandle) + + if typ is None: + typ = SharedMemoryType() + elif isinstance(typ, int): + typ = SharedMemoryType(buffer_size_bytes=typ) + + # The min buffer size must be large enough to at least fit an instance of the + # _ResizeChannel class along with any metadata. + MIN_BUFFER_SIZE = int(1000) # 1000 bytes + if typ.buffer_size_bytes < MIN_BUFFER_SIZE: + raise ValueError( + "typ.buffer_size_bytes must be at least MIN_BUFFER_SIZE " + f"({MIN_BUFFER_SIZE} bytes)" + ) + + self._writer = writer + self._reader_and_node_list = reader_and_node_list + self._typ = typ + + self._worker = ray._private.worker.global_worker + self._worker.check_connected() + + self._writer_registered = _writer_registered + self._reader_registered = _reader_registered + # NodeID -> ReaderRefInfo on that node. Note that there's only 1 + # reader ref per node. + self._node_id_to_reader_ref_info: Dict[str, ReaderRefInfo] = ( + _node_id_to_reader_ref_info or {} + ) + + # Node ID -> a list of reader actors. + self._node_id_to_readers: Dict[str, "ray.actor.ActorHandle"] = defaultdict(list) + for reader, node_id in self._reader_and_node_list: + self._node_id_to_readers[node_id].append(reader) + + # Number of readers in a local node. + self._num_local_readers = 0 + + if _writer_ref is None: + # We are the writer. Check that the passed handle matches the + # current actor (or it is the driver). + # TODO(swang): Channels must be initially constructed by the writer + # actor, so we shouldn't need to include `writer` in the + # constructor args. Either support Channels being constructed by + # someone other than the writer or remove it from the args. + self_actor = get_self_actor() + assert writer == self_actor + + self._writer_node_id = ( + ray.runtime_context.get_runtime_context().get_node_id() + ) + self._writer_ref = _create_channel_ref(self, typ.buffer_size_bytes) + + self._create_reader_refs(typ.buffer_size_bytes) + else: + assert ( + _writer_node_id is not None + ), "_writer_node_id must also be passed to the constructor when " + "_writer_ref is." + assert _node_id_to_reader_ref_info is not None, ( + "_node_id_to_reader_ref_info must also be passed to the constructor " + "when _writer_ref is." + ) + + self._writer_ref = _writer_ref + self._writer_node_id = _writer_node_id + self._node_id_to_reader_ref_info = _node_id_to_reader_ref_info + + assert self._num_local_readers == 0 + remote_node_exists = False + for node_id, readers in self._node_id_to_readers.items(): + if self.is_local_node(node_id): + self._num_local_readers += len(readers) + else: + remote_node_exists = True + # If remote node exists, we have 1 additional reader that listens + # to object changes and push them to remote nodes. + if remote_node_exists: + self._num_local_readers += 1 + # There must be at least 1 local reader + assert self._num_local_readers > 0 + + self._local_reader_ref: Optional["ray.ObjectRef"] = self._get_local_reader_ref( + self._node_id_to_reader_ref_info + ) + + def _get_local_reader_ref( + self, _node_id_to_reader_ref_info: Dict[str, ReaderRefInfo] + ) -> Optional["ray.ObjectRef"]: + for node_id, reader_ref_info in _node_id_to_reader_ref_info.items(): + if self.is_local_node(node_id): + return reader_ref_info.reader_ref + return None + + def _create_reader_refs( + self, + buffer_size_bytes: int, + ): + # TODO(jhumphri): Free the current reader ref once the reference to it is + # destroyed below. + + for node_id, readers in self._node_id_to_readers.items(): + if not self.is_local_node(node_id): + # Find 1 reader in a remote node to create a reference that's + # shared by all readers. When a new value is written to a reference, + # it is sent to this reference. + reader = readers[0] + fn = reader.__ray_call__ + self._node_id_to_reader_ref_info[node_id] = ReaderRefInfo( + reader_ref=ray.get( + fn.remote(_create_channel_ref, buffer_size_bytes) + ), + ref_owner_actor_id=reader._actor_id, + num_reader_actors=len(readers), + ) + else: + writer_id = ray.ActorID.nil() + if self._writer is not None: + writer_id = self._writer._actor_id + self._node_id_to_reader_ref_info[node_id] = ReaderRefInfo( + reader_ref=self._writer_ref, + ref_owner_actor_id=writer_id, + num_reader_actors=len(readers), + ) + # There must be only 1 node reader reference per node. + assert len(self._node_id_to_reader_ref_info) == len(self._node_id_to_readers) + + # We need to register the new writer_ref. + self._writer_registered = False + self.ensure_registered_as_writer() + + @staticmethod + def is_local_node(node_id): + return ray.runtime_context.get_runtime_context().get_node_id() == node_id + + def ensure_registered_as_writer(self) -> None: + if self._writer_registered: + return + + if not self.is_local_node(self._writer_node_id): + raise ValueError( + "`ensure_registered_as_writer()` must only be called on the node that " + "the writer is on." + ) + + remote_reader_ref_info: Dict[str, ReaderRefInfo] = {} + for node_id, reader_ref_info in self._node_id_to_reader_ref_info.items(): + if self.is_local_node(node_id): + continue + remote_reader_ref_info[node_id] = reader_ref_info + + self._worker.core_worker.experimental_channel_register_writer( + self._writer_ref, + remote_reader_ref_info, + ) + self._writer_registered = True + + def ensure_registered_as_reader(self) -> None: + if self._reader_registered: + return + + for node_id, reader_ref_info in self._node_id_to_reader_ref_info.items(): + if self.is_local_node(node_id): + self._worker.core_worker.experimental_channel_register_reader( + reader_ref_info.reader_ref, + ) + self._reader_registered = True + + @staticmethod + def _deserialize_reader_channel( + writer: ray.actor.ActorHandle, + reader_and_node_list: List[Tuple["ray.actor.ActorHandle", str]], + typ: int, + writer_node_id, + writer_ref: "ray.ObjectRef", + node_id_to_reader_ref_info: Dict[str, ReaderRefInfo], + writer_registered: bool, + reader_registered: bool, + ) -> "Channel": + chan = Channel( + writer, + reader_and_node_list, + typ, + _writer_node_id=writer_node_id, + _writer_ref=writer_ref, + _node_id_to_reader_ref_info=node_id_to_reader_ref_info, + _writer_registered=writer_registered, + _reader_registered=reader_registered, + ) + return chan + + def __reduce__(self): + assert self._node_id_to_reader_ref_info is not None + return self._deserialize_reader_channel, ( + self._writer, + self._reader_and_node_list, + self._typ, + self._writer_node_id, + self._writer_ref, + self._node_id_to_reader_ref_info, + self._writer_registered, + self._reader_registered, + ) + + def __str__(self) -> str: + return ( + f"Channel(_node_id_to_reader_ref_info={self._node_id_to_reader_ref_info}, " + f"_writer_ref={self._writer_ref})" + ) + + def _resize_channel_if_needed(self, serialized_value: str, timeout_ms: int): + # serialized_value.total_bytes *only* includes the size of the data. It does not + # include the size of the metadata, so we must account for the size of the + # metadata explicitly. + size = serialized_value.total_bytes + len(serialized_value.metadata) + if size > self._typ.buffer_size_bytes: + # Now make the channel backing store larger. + self._typ.buffer_size_bytes = size + # TODO(jhumphri): Free the current writer ref once the reference to it is + # destroyed below. + # TODO(sang): Support different policies such as 2X buffer size. + prev_writer_ref = self._writer_ref + self._writer_ref = _create_channel_ref(self, self._typ.buffer_size_bytes) + self._create_reader_refs(self._typ.buffer_size_bytes) + self._local_reader_ref = self._get_local_reader_ref( + self._node_id_to_reader_ref_info + ) + + # Write a special message to the channel so that the readers know to + # stop using the current reader_ref. + special_message = _ResizeChannel(self._node_id_to_reader_ref_info) + special_message_serialized = ( + self._worker.get_serialization_context().serialize(special_message) + ) + self._worker.core_worker.experimental_channel_put_serialized( + special_message_serialized, + prev_writer_ref, + self._num_local_readers, + timeout_ms, + ) + # TODO(sang): Clean the previous ref that won't be used. + # Right now, if we just close it here, it will not work because + # of race conditions. + # self._worker.core_worker.experimental_channel_set_error( + # prev_writer_ref + # ) + + def write(self, value: Any, timeout: Optional[float] = None) -> None: + self.ensure_registered_as_writer() + assert ( + timeout is None or timeout >= 0 or timeout == -1 + ), "Timeout must be non-negative or -1." + # -1 means no timeout (block indefinitely) + timeout_ms = int(timeout * 1000) if timeout is not None else -1 + + if not isinstance(value, SerializedObject): + try: + serialized_value = self._worker.get_serialization_context().serialize( + value + ) + except TypeError as e: + sio = io.StringIO() + ray.util.inspect_serializability(value, print_file=sio) + msg = ( + "Could not serialize the put value " + f"{repr(value)}:\n" + f"{sio.getvalue()}" + ) + raise TypeError(msg) from e + else: + serialized_value = value + + start_time = time.monotonic() + self._resize_channel_if_needed(serialized_value, timeout_ms) + if timeout is not None: + timeout_ms -= int((time.monotonic() - start_time) * 1000) + timeout_ms = max(timeout_ms, 0) + + self._worker.core_worker.experimental_channel_put_serialized( + serialized_value, + self._writer_ref, + self._num_local_readers, + timeout_ms, + ) + + def read(self, timeout: Optional[float] = None) -> Any: + assert ( + timeout is None or timeout >= 0 or timeout == -1 + ), "Timeout must be non-negative or -1." + self.ensure_registered_as_reader() + + start_time = time.monotonic() + ret = self._worker.get_objects( + [self._local_reader_ref], timeout=timeout, return_exceptions=True + )[0][0] + + if isinstance(ret, _ResizeChannel): + self._node_id_to_reader_ref_info = ret._node_id_to_reader_ref_info + self._local_reader_ref = self._get_local_reader_ref( + self._node_id_to_reader_ref_info + ) + # We need to register the new reader_ref. + self._reader_registered = False + self.ensure_registered_as_reader() + if timeout is not None: + timeout -= time.monotonic() - start_time + timeout = max(timeout, 0) + ret = self._worker.get_objects( + [self._local_reader_ref], timeout=timeout, return_exceptions=True + )[0][0] + + return ret + + def release_buffer(self, timeout: Optional[float] = None) -> None: + assert ( + timeout is None or timeout >= 0 or timeout == -1 + ), "Timeout must be non-negative or -1." + self.ensure_registered_as_reader() + self._worker.get_objects( + [self._local_reader_ref], + timeout=timeout, + return_exceptions=True, + skip_deserialization=True, + ) + + def close(self) -> None: + """ + Close this channel by setting the error bit on both the writer_ref and the + reader_ref. + """ + self._worker.core_worker.experimental_channel_set_error(self._writer_ref) + is_local_node_reader = False + + for node_id in self._node_id_to_readers.keys(): + if self.is_local_node(node_id): + is_local_node_reader = True + if is_local_node_reader: + self.ensure_registered_as_reader() + + for reader_ref_info in self._node_id_to_reader_ref_info.values(): + self._worker.core_worker.experimental_channel_set_error( + reader_ref_info.reader_ref + ) + + +@DeveloperAPI +class BufferedSharedMemoryChannel(ChannelInterface): + """A channel that can be read and written by Ray processes. + + It creates `num_shm_buffers` number of buffers and allows buffered read and + write APIs. I.e., read and write APIs are non-blocking as long as it can write to + next buffer or read from a next buffer. See `read` and `write` APIs for + more details. + + Args: + writer: The actor that may write to the channel. None signifies the driver. + reader_and_node_list: A list of tuples, where each tuple contains a reader + actor handle and the node ID where the actor is located. Note that currently + we only support this for readers on the same node as the writer. + num_shm_buffers: Number of shared memory buffers to read/write. + typ: Type information about the values passed through the channel. + Either an integer representing the max buffer size in bytes + allowed, or a SharedMemoryType. + """ + + def __init__( + self, + writer: Optional[ray.actor.ActorHandle], + reader_and_node_list: List[Tuple["ray.actor.ActorHandle", str]], + num_shm_buffers: int, + typ: Optional[Union[int, SharedMemoryType]] = None, + ): + self._num_shm_buffers = num_shm_buffers + self._buffers = [ + # We use Channel directly as a buffer implementation as + # channel only allows to have 1 shared memory buffer. + Channel(writer, reader_and_node_list, typ) + for _ in range(num_shm_buffers) + ] + # The next index to write from self._buffers. + self._next_write_index = 0 + # The next index to read from self._buffers. + self._next_read_index = 0 + + def ensure_registered_as_writer(self): + """ + Check whether the process is a valid writer. This method must be idempotent. + """ + for buffer in self._buffers: + buffer.ensure_registered_as_writer() + + def ensure_registered_as_reader(self): + """ + Check whether the process is a valid reader. This method must be idempotent. + """ + for buffer in self._buffers: + buffer.ensure_registered_as_reader() + + def write(self, value: Any, timeout: Optional[float] = None) -> None: + """Write a value to a channel. + + If the next buffer is available, it returns immediately. If the next + buffer is not read by downstream consumers, it blocks until a buffer is + available to write. If a buffer is not available within timeout, it raises + RayChannelTimeoutError. + """ + self.ensure_registered_as_writer() + # A single channel is not supposed to read and write at the same time. + assert self._next_read_index == 0 + self._buffers[self._next_write_index].write(value, timeout) + self._next_write_index += 1 + self._next_write_index %= self._num_shm_buffers + + def read(self, timeout: Optional[float] = None) -> Any: + """Read a value from a channel. + + If the next buffer is available, it returns immediately. If the next + buffer is not written by an upstream producer, it blocks until a buffer is + available to read. If a buffer is not available within timeout, it raises + RayChannelTimeoutError. + """ + self.ensure_registered_as_reader() + # A single channel is not supposed to read and write at the same time. + assert self._next_write_index == 0 + output = self._buffers[self._next_read_index].read(timeout) + self._next_read_index += 1 + self._next_read_index %= self._num_shm_buffers + return output + + def release_buffer(self, timeout: Optional[float] = None): + """Release the native buffer of the channel to allow the buffer to be reused for + future data. + + If the next buffer is available, it returns immediately. If the next + buffer is not written by an upstream producer, it blocks until a buffer is + available to be released. If a buffer is not available within timeout, it raises + RayChannelTimeoutError. + """ + # A single channel is not supposed to read and write at the same time. + assert self._next_write_index == 0 + self._buffers[self._next_read_index].release_buffer(timeout) + self._next_read_index += 1 + self._next_read_index %= self._num_shm_buffers + + def close(self) -> None: + for buffer in self._buffers: + buffer.close() + + @property + def next_write_index(self): + # Testing only + return self._next_write_index + + @property + def next_read_index(self): + # Testing only + return self._next_read_index + + +@PublicAPI(stability="alpha") +class CompositeChannel(ChannelInterface): + """ + Can be used to send data to different readers via different channels. + For example, if the reader is in the same worker process as the writer, + the data can be sent via IntraProcessChannel. If the reader is in a different + worker process, the data can be sent via shared memory channel. + + Args: + writer: The actor that may write to the channel. None signifies the driver. + reader_and_node_list: A list of tuples, where each tuple contains a reader + actor handle and the node ID where the actor is located. + num_shm_buffers: The number of shared memory buffers per channel. + Note: In the case of multiple nodes, we only support 1 shared + memory buffer. + driver_actor_id: If this channel is read by a driver and that driver is an + actual actor, this will be the actor ID of that driver actor. + """ + + def __init__( + self, + writer: Optional[ray.actor.ActorHandle], + reader_and_node_list: List[Tuple["ray.actor.ActorHandle", str]], + num_shm_buffers: int, + driver_actor_id: Optional[str] = None, + _channel_dict: Optional[Dict[ray.ActorID, ChannelInterface]] = None, + _channels: Optional[Set[ChannelInterface]] = None, + _writer_registered: bool = False, + _reader_registered: bool = False, + ): + self._writer = writer + self._reader_and_node_list = reader_and_node_list + self._num_shm_buffers = num_shm_buffers + self._driver_actor_id = driver_actor_id + self._writer_registered = _writer_registered + self._reader_registered = _reader_registered + # A dictionary that maps the actor ID to the channel object. + self._channel_dict = _channel_dict or {} + # The set of channels is a deduplicated version of the _channel_dict values. + self._channels = _channels or set() + if self._channels: + # This CompositeChannel object is created by deserialization. + # We don't need to create channels again. + return + + ( + remote_reader_and_node_list, + local_reader_and_node_list, + ) = utils.split_readers_by_locality(self._writer, self._reader_and_node_list) + # There are some local readers which are the same worker process as the writer. + # Create a local channel for the writer and the local readers. + num_local_readers = len(local_reader_and_node_list) + if num_local_readers > 0: + # Use num_readers = 1 when creating the local channel, + # because we have channel cache to support reading + # from the same channel multiple times. + local_channel = IntraProcessChannel(num_readers=1) + self._channels.add(local_channel) + actor_id = self._get_actor_id(self._writer) + self._channel_dict[actor_id] = local_channel + # There are some remote readers which are not the same Ray actor as the writer. + # We create a BufferedSharedMemoryChannel for readers on the same node, and + # a single Channel for readers on different nodes due to + # https://github.com/ray-project/ray/issues/49044 + ( + readers_same_node, + readers_different_node, + ) = utils.split_actors_by_node_locality( + utils.get_actor_node(self._writer), remote_reader_and_node_list + ) + + if len(readers_same_node) != 0: + remote_channel = BufferedSharedMemoryChannel( + self._writer, readers_same_node, num_shm_buffers + ) + self._channels.add(remote_channel) + for reader, _ in readers_same_node: + actor_id = self._get_actor_id(reader) + self._channel_dict[actor_id] = remote_channel + + if len(readers_different_node) != 0: + remote_channel = Channel(self._writer, readers_different_node) + self._channels.add(remote_channel) + for reader, _ in readers_different_node: + actor_id = self._get_actor_id(reader) + self._channel_dict[actor_id] = remote_channel + + def _get_actor_id(self, reader: ray.actor.ActorHandle) -> str: + return reader._actor_id.hex() + + def ensure_registered_as_writer(self) -> None: + if self._writer_registered: + return + for channel in self._channels: + channel.ensure_registered_as_writer() + self._writer_registered = True + + def ensure_registered_as_reader(self) -> None: + if self._reader_registered: + return + for channel in self._channels: + channel.ensure_registered_as_reader() + self._reader_registered = True + + def __reduce__(self): + return CompositeChannel, ( + self._writer, + self._reader_and_node_list, + self._num_shm_buffers, + self._driver_actor_id, + self._channel_dict, + self._channels, + self._writer_registered, + self._reader_registered, + ) + + def __str__(self) -> str: + return ( + "CompositeChannel(_channels=" + f"{[str(channel) for channel in self._channels]})" + ) + + def write(self, value: Any, timeout: Optional[float] = None) -> None: + self.ensure_registered_as_writer() + for channel in self._channels: + channel.write(value, timeout) + + def read(self, timeout: Optional[float] = None) -> Any: + self.ensure_registered_as_reader() + return self._channel_dict[self._resolve_actor_id()].read(timeout) + + def release_buffer(self, timeout: Optional[float] = None): + self.ensure_registered_as_reader() + self._channel_dict[self._resolve_actor_id()].release_buffer(timeout) + + def _resolve_actor_id(self) -> str: + actor_id = ray.get_runtime_context().get_actor_id() + # If actor_id is None, read was called by the driver + # If the driver is an actor, driver_actor_id will be set to that actor id + if actor_id is None or actor_id == self._driver_actor_id: + # Use the actor ID of the DAGDriverProxyActor. + # The proxy actor is always the first actor in the reader_and_node_list. + assert len(self._reader_and_node_list) >= 1 + driver_proxy_actor = self._reader_and_node_list[0][0] + actor_id = self._get_actor_id(driver_proxy_actor) + return actor_id + + def close(self) -> None: + for channel in self._channels: + channel.close() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/torch_tensor_accelerator_channel.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/torch_tensor_accelerator_channel.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1cb3772b6ce493f74310511b7882f13cc38d2f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/torch_tensor_accelerator_channel.py @@ -0,0 +1,872 @@ +import io +import logging +import uuid +from dataclasses import dataclass +from types import ModuleType +from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Union, Type + +import ray +import ray.util.serialization +from ray.experimental.channel import ChannelContext, utils +from ray.experimental.channel.common import ChannelInterface +from ray.experimental.channel.communicator import Communicator +from ray.experimental.channel.cpu_communicator import CPUCommunicator +from ray.experimental.channel.intra_process_channel import IntraProcessChannel +from ray.experimental.channel.communicator_handle import CommunicatorHandle +from ray.experimental.channel.shared_memory_channel import SharedMemoryType +from ray.experimental.channel.torch_tensor_type import TorchTensorType +from ray.util.annotations import DeveloperAPI +from ray.experimental.channel.accelerator_context import ( + AcceleratorContext, + register_accelerator_context, + is_accelerator_context_registered, +) + +if TYPE_CHECKING: + import torch + + from ray.experimental.channel.shared_memory_channel import Channel + + +# 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__) + + +@dataclass +class _TorchTensorMetadata: + """ + Metadata for torch.Tensors that can be sent between processes to determine + how large of a buffer to allocate on the receiver(s). + """ + + shape: Union[int, Tuple[int]] + dtype: "torch.dtype" + + +@DeveloperAPI +class TorchTensorAcceleratorChannel(ChannelInterface): + def __init__( + self, + writer: ray.actor.ActorHandle, + reader_and_node_list: List[Tuple["ray.actor.ActorHandle", str]], + typ: "TorchTensorType", + driver_actor_id: str, + tensor_metadata_channel: Optional["Channel"] = None, + _cpu_data_channel: Optional["Channel"] = None, + _gpu_data_channel: Optional["_TorchTensorAcceleratorChannel"] = None, + _local_channel: Optional["IntraProcessChannel"] = None, + ): + """ + Can be used to send accelerator tensors nested inside other data. The data is + sent via shared memory while the accelerator tensors are sent through a P2P + transport (e.g., NCCL for GPU). + + NOTE: This class is currently not thread-safe because it reads and + writes the worker-local + ray.experimental.channel.serialization_context._SerializationContext + when serializing data. + + Args: + writer: The actor that may write to the channel. None signifies the + driver. + reader_and_node_list: A list of tuples, where each tuple contains a reader + actor handle and the node ID where the actor is located. + typ: Type information about the values passed through the channel. + driver_actor_id: The actor ID of the DAGDriverProxyActor. + tensor_metadata_channel: A shared-memory channel for sending tensor + metadata. + _cpu_data_channel: A shared-memory channel for sending + non-tensor data. Its writer and readers should match the given + writer and readers. If None is provided, then we assume that + there is no CPU-specific data, i.e. the task directly returned + a CUDA torch.Tensor. + _gpu_data_channel: A channel for sending torch.Tensors via accelerator. + _local_channel: A channel for sending data between the writer and + local readers. + + NOTE: `tensor_metadata_channel` will be set only for testing purposes. + `_cpu_data_channel` is set for testing purposes and for deserialization. + `_gpu_data_channel` and `_local_channel` are set only during deserialization. + """ + self._writer = writer + self._reader_and_node_list = reader_and_node_list + self._typ = typ + + ( + remote_reader_and_node_list, + local_reader_and_node_list, + ) = utils.split_readers_by_locality(self._writer, self._reader_and_node_list) + + num_local_readers = len(local_reader_and_node_list) + self._local_channel = _local_channel + if self._local_channel is None and num_local_readers > 0: + # There are some local readers which are the same worker process as + # the writer. Create a local channel for the writer and the local readers. + # + # Use num_readers = 1 when creating the local channel, + # because we have channel cache to support reading + # from the same channel multiple times. + self._local_channel = IntraProcessChannel(num_readers=1) + + assert len(remote_reader_and_node_list) > 0, ( + "All readers are from the same actor. " + "The TorchTensorType type hint is not needed. " + "No accelerator channel will be created." + ) + self._gpu_data_channel = _gpu_data_channel + if self._gpu_data_channel is None: + self._gpu_data_channel: _TorchTensorAcceleratorChannel = ( + _TorchTensorAcceleratorChannel( + writer, + remote_reader_and_node_list, + typ, + _meta_channel=tensor_metadata_channel, + ) + ) + + self._cpu_data_channel: Optional["Channel"] = _cpu_data_channel + if self._cpu_data_channel is not None: + assert ( + not self._typ.direct_return + ), "CPU channel should be None if direct return is enabled" + + if self._cpu_data_channel is None and not self._typ.direct_return: + # Create a CPU channel to send non-tensor data. + self._cpu_data_channel = SharedMemoryType().create_channel( + writer, remote_reader_and_node_list, driver_actor_id + ) + + # Used for serialization. + self._worker = ray._private.worker.global_worker + self._worker.check_connected() + + ctx = ChannelContext.get_current() + self.serialization_ctx = ctx.serialization_context + assert self.serialization_ctx is not None + + def __reduce__(self): + return ( + TorchTensorAcceleratorChannel, + ( + self._writer, + self._reader_and_node_list, + self._typ, + # driver_actor_id and tensor_metadata_channel are used to initialize + # the _cpu_data_channel and _gpu_data_channel, so we don't need to + # pass them in here. + None, + None, + self._cpu_data_channel, + self._gpu_data_channel, + self._local_channel, + ), + ) + + def ensure_registered_as_writer(self): + if self._local_channel is not None: + self._local_channel.ensure_registered_as_writer() + self._gpu_data_channel.ensure_registered_as_writer() + if self._cpu_data_channel is not None: + self._cpu_data_channel.ensure_registered_as_writer() + + def ensure_registered_as_reader(self): + reader = utils.get_self_actor() + if reader == self._writer: + self._local_channel.ensure_registered_as_reader() + return + self._gpu_data_channel.ensure_registered_as_reader() + if self._cpu_data_channel is not None: + self._cpu_data_channel.ensure_registered_as_reader() + + def _send_cpu_and_gpu_data(self, value: Any, timeout: Optional[float]): + self.serialization_ctx.reset_out_of_band_tensors([]) + # All tensors found in `value` will be transferred via accelerator. + self.serialization_ctx.set_use_external_transport(True) + + try: + # Serialize the data. All tensors that match our current device + # will be extracted into the serialization context and replaced + # with a placeholder. + cpu_data = self._worker.get_serialization_context().serialize(value) + except TypeError as e: + sio = io.StringIO() + ray.util.inspect_serializability(value, print_file=sio) + msg = ( + "Could not serialize the put value " + f"{repr(value)}:\n" + f"{sio.getvalue()}" + ) + raise TypeError(msg) from e + finally: + # Pop the tensors that were found during serialization of `value`. + gpu_tensors, _ = self.serialization_ctx.reset_out_of_band_tensors([]) + # Reset the serialization method to now serialize torch.Tensors + # normally. + self.serialization_ctx.set_use_external_transport(False) + + # First send the extracted tensors through a GPU-specific channel. + self._gpu_data_channel.write(gpu_tensors) + # Next send the non-tensor data through a CPU-specific channel. The + # data contains placeholders for the extracted tensors. + self._cpu_data_channel.write(cpu_data) + + def write(self, value: Any, timeout: Optional[float] = None) -> None: + """ + Send a value that may contain torch.Tensors that should be sent via + external transport. + + Case 1: Use `_local_channel` to send the data to local readers. + + Case 2: Otherwise, use the following method to send the data to remote readers. + + 1) Serializes `value`. During serialization, all torch.Tensors that are + on the default device are extracted and replaced with a unique + placeholder. Thus, the serialized value will contain all non-tensor + data, and any tensors that were not on the default device (e.g., CPU + tensor returned by a GPU actor). + 2) Sends extracted torch.Tensors via the tensor data channel (e.g., + NCCL). + 3) Sends the non-tensor data via the non-tensor data channel. + + If static_non_tensor_data=True was specified, then we only perform step + (3) on the first `write` call. The reader is expected to reuse the sent + data for subsequent messages. + """ + self.ensure_registered_as_writer() + + if self._local_channel is not None: + self._local_channel.write(value) + + if isinstance(value, ray.exceptions.RayTaskError): + if self._typ.static_shape or self._typ.direct_return: + # Raise a fatal error to teardown the DAG. + # This error will also be caught from `CompiledDAGRef.get()` + # and raised to the user + # TODO(swang): Write exceptions to the tensor metadata or + # non-tensor data channel if it is available to make these + # exceptions recoverable. + raise value + + if self._cpu_data_channel is None: + # Handle the case where _direct_return=True. In this case, we check + # that the task returned a CUDA torch.Tensor and just send it + # directly without trying to serialize it first. + import torch + + # These ValueErrors will also be caught from `CompiledDAGRef.get()` + # and raised to the user + if not isinstance(value, torch.Tensor): + # TODO(swang): These errors are currently fatal for the DAG. + # This could be improved by sending the exception through the + # gpu_data_channel's CPU-based metadata channel, if one exists. + raise ValueError( + "Task annotated with _direct_return=True must " + "return a CUDA torch.Tensor, instead found value " + f"`{value}`. DAG will shut down." + ) + elif not value.is_cuda: + raise ValueError( + "Task annotated with _direct_return=True must " + "return a CUDA torch.Tensor, instead found CPU tensor. " + "DAG will shut down." + ) + self._gpu_data_channel.write([value], timeout=timeout) + else: + self._send_cpu_and_gpu_data(value, timeout) + + def _recv_cpu_and_gpu_data( + self, tensors: List["torch.Tensor"], timeout: Optional[float] = None + ) -> Any: + """ + Helper method to receive data that contains a mix of CPU and GPU data. + + Args: + tensors: The GPU data. This is a list of the torch.Tensors that + were found in the sent data. + timeout: Timeout for channel receive. + """ + self.serialization_ctx.reset_out_of_band_tensors(tensors) + + # Next, read and deserialize the non-tensor data. The registered custom + # deserializer will replace the found tensor placeholders with + # `tensors`. + data = self._cpu_data_channel.read( + timeout=timeout, + ) + # Check that all placeholders had a corresponding tensor. + ( + _, + deserialized_tensor_placeholders, + ) = self.serialization_ctx.reset_out_of_band_tensors([]) + assert deserialized_tensor_placeholders == set(range(len(tensors))) + + return data + + def read(self, timeout: Optional[float] = None) -> Any: + """ + Read a value that may contain torch.Tensors sent via external + transport. + + Case 1: If the reader is a local reader and is the same actor as the writer, + then use the `_local_channel` to read the data. + + Case 2: Otherwise, use the following method to read data from remote readers. + + 1) Receives torch.Tensors via the tensor data channel (e.g., NCCL). + 2) Reads the serialized non-tensor data. + 3) Deserializes the non-tensor data. During deserialization, replaces + all found placeholders with the received torch.Tensors. + + If _direct_return=True was specified, then we skip step (2) and (3) and + directly return the data received in (1). + """ + self.ensure_registered_as_reader() + + # If the reader is the same actor as the writer, then we can use the + # local channel to read the data. + reader = utils.get_self_actor() + if reader == self._writer: + assert self._local_channel is not None + return self._local_channel.read() + + # First, read the tensor data. + tensors = self._gpu_data_channel.read(timeout) + + if self._cpu_data_channel is None: + # Handle _direct_return=True. In this case, we expect to receive + # only one tensor, and we return it directly. + assert len(tensors) == 1 + data = tensors[0] + else: + data = self._recv_cpu_and_gpu_data(tensors, timeout) + + return data + + def close(self) -> None: + self._gpu_data_channel.close() + if self._cpu_data_channel is not None: + self._cpu_data_channel.close() + if self._local_channel is not None: + self._local_channel.close() + + +def _torch_zeros_allocator( + shape: Union[int, Tuple[int]], + dtype: "torch.dtype", +): + """ + Allocate a zeros tensor buffer matching the given metadata. + """ + import torch + + ctx = ChannelContext.get_current() + return torch.zeros(shape, dtype=dtype, device=ctx.torch_device) + + +class _TorchTensorAcceleratorChannel(ChannelInterface): + def __init__( + self, + writer: ray.actor.ActorHandle, + reader_and_node_list: List[Tuple["ray.actor.ActorHandle", str]], + typ: "TorchTensorType", + _meta_channel: Optional["Channel"] = None, + ): + """ + A helper channel for TorchTensorAcceleratorChannel that is used to transfer + lists of torch.Tensors via accelerator. This class can only transfer + torch.Tensors and cannot transfer other CPU data, such as Exception + objects or tensors nested inside of a dictionary. + + Args: + writer: The actor that may write to the channel. None signifies the driver. + reader_and_node_list: A list of tuples, where each tuple contains a reader + actor handle and the node ID where the actor is located. + typ: Type information about the values passed through the channel. + _meta_channel: A channel used to send metadata for the tensors, + i.e. shape and dtype. If not provided, and if the typ does not + specify a static shape and dtype, then a metadata channel based + on shared memory will be created. + """ + import torch + + self.torch: ModuleType = torch + + self._writer = writer + self._writer_rank: Optional[int] = None + self._reader_and_node_list = reader_and_node_list + self._reader_ranks: Optional[List[int]] = None + self._writer_registered: bool = False + self._reader_registered: bool = False + + ctx = ChannelContext.get_current() + assert isinstance( + typ.communicator_id, str + ), f"accelerator group ID ({typ.communicator_id}) must be a str." + self._typ = typ + + self._static_shape = typ.static_shape + + assert self._typ.communicator_id is not None, "No accelerator group specified." + self._accelerator_group_id: str = self._typ.communicator_id + + # If the communicators does not contain the group_id, it means the current + # process is the driver, and there’s no need to fetch the comm_group. + if self._typ.communicator_id in ctx.communicators: + self._accelerator_group: "Communicator" = ctx.communicators[ + self._typ.communicator_id + ] + assert ( + self._accelerator_group is not None + ), "ChannelContext.accelerator_group is not initialized." + + self._writer_rank = self._accelerator_group.get_rank(self._writer) + self._reader_ranks = [ + self._accelerator_group.get_rank(reader) + for reader, _ in self._reader_and_node_list + ] + + if ( + self._writer_rank is not None + and self._writer_rank == self._accelerator_group.get_self_rank() + ): + self._writer_registered = True + + if ( + self._reader_ranks + and self._accelerator_group.get_self_rank() in self._reader_ranks + ): + self._reader_registered = True + + # If the channel type specifies that the tensor shape is static, then the + # receiver can allocate buffers without needing to coordinate with the + # sender. We set the metadata on the first send-recv op. Thereafter, + # the sender must ensure that sent tensors match this metadata, and the + # receiver will allocate tensors with this shape. + self._static_tensor_metadata: Optional[List[_TorchTensorMetadata]] = None + self._meta_channel: Optional[Channel] = _meta_channel + if self._meta_channel is None and self._writer_registered: + # We are the writer. Therefore, we also need to allocate a metadata + # channel that will be used to send the shape and dtype of the + # tensor to the receiver(s). + metadata_type = SharedMemoryType() + self._meta_channel = metadata_type.create_channel( + self._writer, + self._reader_and_node_list, + None, + ) + + def ensure_registered_as_writer(self): + assert ( + self._accelerator_group is not None + ), "Actor is not part of an accelerator group" + assert self._writer_registered + ctx = ChannelContext.get_current() + assert ctx.torch_device.type != "cpu" + + def ensure_registered_as_reader(self) -> bool: + assert ( + self._accelerator_group is not None + ), "Actor is not part of an accelerator group" + assert self._reader_registered + ctx = ChannelContext.get_current() + assert ctx.torch_device.type != "cpu" + + def __reduce__(self): + return ( + self.__class__, + ( + self._writer, + self._reader_and_node_list, + self._typ, + self._meta_channel, + ), + ) + + def _get_send_tensors_metadata( + self, tensors: List["torch.Tensor"] + ) -> Optional[List[_TorchTensorMetadata]]: + """ + Helper method to get the metadata that should be sent to the reader so + that they can allocate the proper-sized buffer(s). Throws error if + static_shape=True was set and the given tensors do not match the + inferred shapes. + + Returns: The metadata to send to the reader. None means that we should + not send any metadata message to the reader. + """ + ctx = ChannelContext.get_current() + + # TODO(swang): Currently any exceptions thrown during this method are + # fatal for the DAG because there is no way for the receiver to receive + # the exception. This can be improved by sending the exception through + # the CPU-based non-tensor-data channel, if one exists. The tensor + # channel can send empty data alongside the exception to avoid hanging. + + # Get the shape and dtype of each tensor to send. + metadata_list = [] + for tensor in tensors: + # Basic type checking. + if not isinstance(tensor, self.torch.Tensor): + raise ValueError("Task must return torch.Tensors") + + if tensor.device != ctx.torch_device: + raise ValueError( + f"torch.Tensor must be on the default device: {ctx.torch_device}" + ) + + metadata = _TorchTensorMetadata(tensor.shape, tensor.dtype) + metadata_list.append(metadata) + + if self._static_tensor_metadata is not None: + if metadata_list != self._static_tensor_metadata: + metadata_str = [ + f"(shape={m.shape}, dtype={m.dtype})" for m in metadata_list + ] + expected_str = [ + f"(shape={m.shape}, dtype={m.dtype})" + for m in self._static_tensor_metadata + ] + raise ValueError( + "Expected torch.Tensors with shapes and dtypes: " + "[" + ", ".join(expected_str) + "], " + "found: [" + ", ".join(metadata_str) + "]. " + "DAG will shut down." + ) + # The receiver has already determined the shape and dtype of the + # tensors from a previous send, so no need to send the metadata + # again. + return None + + if self._static_shape: + # The shape and dtype is static. This is the first send op and + # afterwards, a ValueError will be thrown if the sent tensors do + # not match this metadata. + self._static_tensor_metadata = metadata_list + return metadata_list + + def write( + self, + tensors: List["torch.Tensor"], + timeout: Optional[float] = None, + ): + """ + Write a list of tensors via accelerator: + + 1) Send the tensor metadata, i.e. the shape and dtypes of all tensors + via the shared-memory metadata channel. + 2) Send the tensor data via accelerator. + + If static_shape=True was set, then we only perform step (1) on the + first message. The reader is expected to reuse the sent metadata for + subsequent messages. + """ + self.ensure_registered_as_writer() + + import torch + + for tensor in tensors: + assert isinstance( + tensor, torch.Tensor + ), f"{tensor} must be instance of torch.Tensor" + + # Send the tensors metadata so that the receiver knows what buffers to + # allocate. + metadata = self._get_send_tensors_metadata(tensors) + if metadata is not None: + self._meta_channel.write(metadata) + + # NOTE(swang): We must send the metadata *before* launching the accelerator + # send. We are using blocking accelerator ops, so the following calls will + # block until the kernel has been enqueued. Also, peers must launch the + # kernel together before either can proceed. Therefore, we send the + # metadata first so that the receiver can read the metadata and then + # launch the same accelerator op. + for tensor in tensors: + # TODO: If there are multiple readers, can replace with a + # broadcast. + for rank in self._reader_ranks: + self._accelerator_group.send(tensor, rank) + + def _get_recv_tensors_metadata( + self, timeout: Optional[float] = None + ) -> List[_TorchTensorMetadata]: + """ + Get the shape(s) and dtype(s) of the tensors to receive from the + metadata channel. If static_shape=True was set, then we reuse the first + metadata received. + """ + if self._static_tensor_metadata is not None: + return self._static_tensor_metadata + + meta = self._meta_channel.read(timeout) + + if self._static_shape: + self._static_tensor_metadata = meta + + return meta + + def read( + self, + timeout: Optional[float] = None, + ) -> Union["torch.Tensor", List["torch.Tensor"]]: + """ + Receive a list of tensors. + + (1) Receive the tensor metadata via the shared-memory metadata channel. + (2) Allocate buffers on our default device according to the received + tensor metadata. + (3) Receive the tensor data via accelerator. + + If static_data=True was set, then we only perform step (1) on the first + message. Subsequent messages reuse the same metadata. + + NOTE: Currently `timeout` only applies to receiving the CPU-based + tensor metadata. The GPU recv may exceed the timeout without throwing + an error. + """ + self.ensure_registered_as_reader() + + meta_list: List[_TorchTensorMetadata] = self._get_recv_tensors_metadata(timeout) + + bufs: List["torch.Tensor"] = [] + for meta in meta_list: + buf = self._accelerator_group.recv( + meta.shape, meta.dtype, self._writer_rank, _torch_zeros_allocator + ) + bufs.append(buf) + # TODO: Sync CUDA stream after receiving all tensors, instead of after + # each tensor. + return bufs + + def close(self) -> None: + self._meta_channel.close() + + self._accelerator_group.destroy() + ctx = ChannelContext.get_current() + if self._accelerator_group_id in ctx.communicators: + del ctx.communicators[self._accelerator_group_id] + + +def _do_init_communicator( + self, + group_id, + world_size, + comm_id, + rank, + actor_handles, + use_communication_streams, + custom_communicator: Optional[Communicator] = None, +): + if not custom_communicator: + assert ( + AcceleratorContext.get().accelerator_count > 0 + ), "Actors participating in Communication group must have at least one Accelerator assigned" + + ctx = ChannelContext.get_current() + if custom_communicator is not None: + custom_communicator.initialize(rank) + ctx.communicators[group_id] = custom_communicator + else: + # default to CommGroup + ctx.communicators[group_id] = AcceleratorContext.get().create_communicator( + world_size, + comm_id, + rank, + actor_handles, + AcceleratorContext.get().current_stream(), + use_communication_streams, + ) + + +def _do_destroy_communicator(self, group_id): + ctx = ChannelContext.get_current() + if group_id not in ctx.communicators: + return + ctx.communicators[group_id].destroy() + + # Keep the communicator group in the map after destruction in case there is + # still a task loop running. + + +def _do_check_has_accelerators(self) -> str: + return AcceleratorContext.get().accelerator_count > 0 + + +def do_register_accelerator_context(self, name: str, communicator: Type[Communicator]): + register_accelerator_context(name, communicator) + + +def _do_get_unique_communication_id(self) -> bool: + return AcceleratorContext.get().generate_communicator_id() + + +def _get_ranks( + actors: List[ray.actor.ActorHandle], custom_comm_group: Optional[Communicator] +) -> List[int]: + """ + Get ranks for the communicator group to use. If custom_comm_group is specified, + return the ranks of the actors in the custom communicator group, in the same + order of the actors; otherwise, return list(range(len(actors))). + + Args: + actors: A list of actors that participate in the communicator group. + custom_comm_group: The custom communicator group to use. + """ + if custom_comm_group is None: + return list(range(len(actors))) + + assert len(actors) == custom_comm_group.get_world_size(), ( + "The world size of the custom communicator group does not match the " + "number of actors." + ) + ranks = [] + for actor in actors: + rank = custom_comm_group.get_rank(actor) + assert rank not in ranks, "Duplicate rank in custom communicator group" + ranks.append(rank) + assert custom_comm_group.get_world_size() == len(actors), ( + "The world size of the custom communicator group " + f"({custom_comm_group.get_world_size()}) " + "does not match the number of actors " + f"({len(actors)})." + ) + return ranks + + +def _init_communicator( + actors: List[ray.actor.ActorHandle], + custom_communicator: Optional[Communicator] = None, + use_communication_streams: bool = False, + accelerator_module_name: Optional[str] = None, + accelerator_communicator_cls: Optional[Type[Communicator]] = None, +) -> str: + """ + Initialize a communicator group with the given actors. If a custom communicator + group is provided, then it will be used, otherwise a new communicator group + will be created. + + Args: + actors: A list of actors that participate in the communicator group. + custom_communicator: A custom communicator group to initialize. + use_communication_streams: Whether to use dedicated send and recv + streams for communication. If True, communication and computation + can be overlapped to improve performance. + accelerator_module_name: Optional name of the accelerator module to use. + accelerator_communicator_cls: Optional communicator class for the accelerator. + """ + ctx = ChannelContext.get_current() + + is_cpu_communicator = custom_communicator and isinstance( + custom_communicator, CPUCommunicator + ) + + # Register accelerator context for all actors if accelerator is not default + if accelerator_module_name and accelerator_communicator_cls: + if is_accelerator_context_registered(): + ray.get( + [ + actor.__ray_call__.remote( + do_register_accelerator_context, + accelerator_module_name, + accelerator_communicator_cls, + ) + for actor in actors + ] + ) + + has_accelerators = ray.get( + [actor.__ray_call__.remote(_do_check_has_accelerators) for actor in actors] + ) + for has_accelerator, actor in zip(has_accelerators, actors): + if not has_accelerator and not is_cpu_communicator: + raise ValueError( + f"Actor {actor} returns a tensor with type hint " + 'TorchTensor(transport="accelerator") or ' + "TorchTensor(transport=accelerator_group_handle) " + "but actor does not have an accelerator assigned by Ray." + ) + + actor_ids = {actor._ray_actor_id for actor in actors} + assert len(actor_ids) == len(actors), "Actors must be unique" + + # Allocate a communicator ID on one of the actors that will participate in + # the group. This is in case the driver is not on the same node as one of + # the communicator actors. + comm_id = ray.get(actors[0].__ray_call__.remote(_do_get_unique_communication_id)) + + # Used to uniquely identify this communicator group. + group_id = str(uuid.uuid4()) + + if custom_communicator is not None: + logger.info( + f"Initializing custom communicator group {group_id} on actors: {actors}" + ) + else: + logger.info(f"Creating communicator group {group_id} on actors: {actors}") + + world_size = len(actors) + ranks = _get_ranks(actors, custom_communicator) + init_tasks = [ + actor.__ray_call__.remote( + _do_init_communicator, + group_id, + world_size, + comm_id, + rank, + actors, + use_communication_streams, + custom_communicator, + ) + for rank, actor in zip(ranks, actors) + ] + try: + ray.get(init_tasks, timeout=30) + except ray.exceptions.GetTimeoutError: + logger.warning( + "Communicator group creation not done after 30s. communicator group" + "creation may be hung." + ) + ray.get(init_tasks) + + logger.info("Communicator group initialized.") + + if custom_communicator is not None: + ctx.communicator_handles[group_id] = CommunicatorHandle( + actor_handles=custom_communicator.get_actor_handles(), + ) + else: + ctx.communicator_handles[group_id] = CommunicatorHandle( + actor_handles=actors, + ) + + return group_id + + +def _destroy_communicator(group_id: str) -> None: + """ + Destroy the communicator group with the given ID. + """ + ctx = ChannelContext.get_current() + if group_id not in ctx.communicator_handles: + return + + group = ctx.communicator_handles[group_id] + actors = group.get_actor_handles() + destroy_tasks = [ + actor.__ray_call__.remote( + _do_destroy_communicator, + group_id, + ) + for actor in actors + ] + + _, unready = ray.wait(destroy_tasks, timeout=30, num_returns=len(destroy_tasks)) + if unready: + logger.warning( + "Communicator group destruction not done after 30s. Communicator" + "group destruction may be hung." + ) + + del ctx.communicator_handles[group_id] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/torch_tensor_type.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/torch_tensor_type.py new file mode 100644 index 0000000000000000000000000000000000000000..21220acf995970431211792cc0cd1744f15cd9c0 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/torch_tensor_type.py @@ -0,0 +1,193 @@ +import logging +from typing import TYPE_CHECKING, List, Optional, Tuple, Union + +import ray +from ray.experimental.channel import ChannelContext, ChannelOutputType +from ray.experimental.channel.communicator import Communicator +from ray.experimental.channel.shared_memory_channel import SharedMemoryType +from ray.experimental.util.types import Device +from ray.util.annotations import PublicAPI + +if TYPE_CHECKING: + from ray.experimental.channel.shared_memory_channel import Channel + +logger = logging.getLogger(__name__) + + +@PublicAPI(stability="alpha") +class TorchTensorType(ChannelOutputType): + AUTO = "auto" + CPU = "cpu" + ACCELERATOR = "accelerator" + + def __init__( + self, + transport: Optional[Union[str, Communicator]] = AUTO, + device: Device = Device.DEFAULT, + _static_shape: bool = False, + _direct_return: Optional[bool] = False, + ): + """ + A type hint that can be used to annotate DAG nodes that return a + torch.Tensor. + + NOTE: Use of this type in the DAG will register a custom serializer for + torch.Tensor that moves the tensor to the correct device on the + receiver. If you are using ray.cloudpickle to serialize objects and you + do not want this behavior, deregister the custom serializer using + ray.util.serialization.deregister_serializer(torch.Tensor). + + Args: + transport: "auto" (default) means that tensors will be passed via + host memory, using numpy as the serialization format. Pass + TorchTensorType.ACCELERATOR or "accelerator" to use accelerator + instead, avoiding the host memory copy. + device: Target device for tensor transport. Options: + - "default": Retains the same device type as the sender. + - "cpu": Moves tensor to CPU on the receiver. Not compatible + with accelerator transport. + - "gpu" or "cuda": Moves tensor to GPU on the receiver. + _static_shape: A hint indicating whether the shape(s) and dtype(s) + of tensor(s) contained in this value always remain the same + across different executions of the DAG. + _direct_return: Whether the tensor is sent directly or inside of + other data. If a non-default `transport` is used, this allows + the sender and receiver to eliminate performance overhead from + an additional data transfer. + + NOTE: Setting static_shape=True and _direct_return=True can improve + performance if a non-default transport is used. However, if either flag + is set, then the user must ensure that the condition is met. + + If using this type as a Compiled Graph annotation, an exception will + be thrown in the following cases, and the DAG will be torn down. To + continue execution, a new DAG must be created: + 1. If _static_shape=True, and the found tensors don't match the + previous shape or dtype(s). + 2. If _direct_return=True, and the returned value is not a + torch.Tensor. + """ + super().__init__() + + self._device = device + self._static_shape = _static_shape + self._direct_return = _direct_return + + self._communicator: Optional[Communicator] = None + if isinstance(transport, Communicator): + self._communicator = transport + transport = transport.get_transport_name() + + if transport not in [self.AUTO, self.CPU, self.ACCELERATOR]: + raise ValueError( + "`transport` must be TorchTensorType.AUTO, TorchTensorType.ACCELERATOR " + "or TorchTensorType.CPU" + ) + if device == Device.CPU and transport == self.ACCELERATOR: + raise ValueError( + "accelerator transport is not supported with CPU target device." + ) + self.transport = transport + + self._communicator_id: Optional[str] = None + + if self._static_shape and self.transport == self.AUTO: + logger.info( + "TorchTensorType(_static_shape=True) has no effect when " + "`transport` is TorchTensorType.AUTO (default)." + ) + if self._direct_return and self.transport == self.AUTO: + logger.info( + "TorchTensorType(_direct_return=True) has no effect when " + "`transport` is TorchTensorType.AUTO (default)." + ) + + @property + def device(self) -> Device: + return self._device + + @property + def static_shape(self): + return self._static_shape + + @property + def direct_return(self): + return self._direct_return + + def register_custom_serializer(self) -> None: + super().register_custom_serializer() + + import torch + + def serialize(t): + ctx = ChannelContext.get_current() + return ctx.serialization_context.serialize_tensor(t) + + def deserialize(b): + ctx = ChannelContext.get_current() + return ctx.serialization_context.deserialize_tensor(b, self.device) + + ray.util.serialization.register_serializer( + torch.Tensor, + serializer=serialize, + deserializer=deserialize, + ) + + def create_channel( + self, + writer: Optional["ray.actor.ActorHandle"], + reader_and_node_list: List[Tuple["ray.actor.ActorHandle", str]], + driver_actor_id: Optional[str] = None, + _cpu_data_channel: Optional["Channel"] = None, + _tensor_metadata_channel: Optional["Channel"] = None, + ) -> type: + if self.requires_accelerator(): + from ray.experimental.channel.torch_tensor_accelerator_channel import ( + TorchTensorAcceleratorChannel, + ) + + return TorchTensorAcceleratorChannel( + writer, + reader_and_node_list, + self, + driver_actor_id, + _tensor_metadata_channel, + _cpu_data_channel, + ) + + # Data does not require accelerator. Transfer via host memory using a + # shared-memory channel. + # TODO(swang): Allow the initial max buffer size to be overridden. + typ = SharedMemoryType() + return typ.create_channel(writer, reader_and_node_list, driver_actor_id) + + def requires_accelerator(self) -> bool: + return self.transport == self.ACCELERATOR + + def get_custom_communicator(self) -> Optional[Communicator]: + """ + Return the communicator group if one is specified. + """ + return self._communicator + + def set_communicator_id(self, group_id: str) -> None: + self._communicator_id = group_id + + @property + def communicator_id(self) -> Optional[str]: + return self._communicator_id + + def __deepcopy__(self, memo): + """ + Deep copy all the fields except for the communicator group. The communicator + group should not be deep copied because it can be shared across `TorchTensorType` + instances. + """ + copy = TorchTensorType( + transport=self.transport, + _static_shape=self._static_shape, + _direct_return=self._direct_return, + ) + copy._communicator = self._communicator + copy._communicator_id = self._communicator_id + return copy diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6df57828130a803f680dc2164784eb2082b39a72 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/channel/utils.py @@ -0,0 +1,92 @@ +from typing import List, Optional, Tuple + +import ray + + +def get_self_actor() -> Optional["ray.actor.ActorHandle"]: + """ + Get the current actor handle in this worker. + If this is called in a driver process, it will return None. + """ + try: + return ray.get_runtime_context().current_actor + except RuntimeError: + return None + + +def split_readers_by_locality( + writer: "ray.actor.ActorHandle", + reader_and_node_list: List[Tuple["ray.actor.ActorHandle", str]], +) -> Tuple[ + List[Tuple["ray.actor.ActorHandle", str]], List[Tuple["ray.actor.ActorHandle", str]] +]: + """Split readers into remote and local readers based on writer. + + Args: + writer: The actor handle of the writer + reader_and_node_list: List of (reader, node) tuples + + Returns: + Tuple containing: + - List of (reader, node) tuples for remote readers + - List of (reader, node) tuples for local readers + """ + remote_readers = [] + local_readers = [] + + for reader, node in reader_and_node_list: + if reader != writer: + remote_readers.append((reader, node)) + else: + local_readers.append((reader, node)) + + return remote_readers, local_readers + + +def split_actors_by_node_locality( + node: str, + actor_and_node_list: List[Tuple["ray.actor.ActorHandle", str]], +) -> Tuple[ + List[Tuple["ray.actor.ActorHandle", str]], List[Tuple["ray.actor.ActorHandle", str]] +]: + """Split actors into remote and local actors based on node. The local actors will be + on the same node as the given node. The remote actors will be on a different node. + + Args: + writer_node: The node of the writer + actor_and_node_list: List of (actor, node) tuples + + Returns: + Tuple containing: + - List of (actor, node) tuples for actors on the same node + - List of (actor, node) tuples for actors on a different node + """ + actors_on_same_node = [] + actors_on_different_node = [] + + for actor, actor_node in actor_and_node_list: + if node == actor_node: + actors_on_same_node.append((actor, actor_node)) + else: + actors_on_different_node.append((actor, actor_node)) + + return actors_on_same_node, actors_on_different_node + + +def get_actor_node(actor: Optional["ray.actor.ActorHandle"]) -> str: + """Get the node of the actor. + + Args: + actor: The actor handle of the actor + + Returns: + The node of the actor + """ + if actor is None or actor == ray.get_runtime_context().current_actor: + return ray.get_runtime_context().get_node_id() + else: + return ray.get( + actor.__ray_call__.remote( + lambda self: ray.get_runtime_context().get_node_id() + ) + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..de2314acf6ab442f15d2a2d1b1f22526edd8c7f2 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/__init__.py @@ -0,0 +1,21 @@ +from ray.experimental.collective.operations import ( + allgather, + allreduce, + reducescatter, +) +from ray.experimental.collective.collective import ( + get_collective_groups, + create_collective_group, + destroy_collective_group, + destroy_all_collective_groups, +) + +__all__ = [ + "allgather", + "allreduce", + "reducescatter", + "get_collective_groups", + "create_collective_group", + "destroy_collective_group", + "destroy_all_collective_groups", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27dbf0bc5463df1bb0fc318009af1fb54bd9d63e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/__pycache__/collective.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/__pycache__/collective.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9fbdb8529ba40d481140ed7a17dab01f4a8bf20c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/__pycache__/collective.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/__pycache__/communicator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/__pycache__/communicator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..884d89676b69f753dda73248d11aff122e0ab599 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/__pycache__/communicator.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/__pycache__/conftest.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/__pycache__/conftest.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2935ed6b15299f162769b8642cba55a9a5d505c4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/__pycache__/conftest.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/__pycache__/operations.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/__pycache__/operations.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7963dfe072f674b99fe92aa3e39a3280d1cf49a0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/__pycache__/operations.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/__pycache__/util.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/__pycache__/util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b384241a602d74a3e0089f99cc4518965cfece8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/__pycache__/util.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/collective.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/collective.py new file mode 100644 index 0000000000000000000000000000000000000000..b2b05a931d3900d7eb6f8af7d3d24795833ab781 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/collective.py @@ -0,0 +1,227 @@ +from typing import Dict, List, Optional, Union +import threading +import uuid + +import ray +from ray.experimental.collective.communicator import CommunicatorHandle +from ray.experimental.collective.util import get_address_and_port +import ray.experimental.internal_kv as internal_kv +from ray.util.collective.types import Backend +from ray.util.collective.collective_group.torch_gloo_collective_group import ( + get_master_address_metadata_key, +) +from ray.util.annotations import PublicAPI + + +_remote_communicator_manager: "Optional[RemoteCommunicatorManager]" = None +_remote_communicator_manager_lock = threading.Lock() + + +class RemoteCommunicatorManager: + """Singleton class to store the mapping between actors and communicators + that the actors are a part of. + """ + + def __init__(self): + # Handles to communicators that we created. Key is a user-provided + # name or UUID. + self._remote_communicators: Dict[str, CommunicatorHandle] = {} + + @staticmethod + def get() -> "RemoteCommunicatorManager": + global _remote_communicator_manager + with _remote_communicator_manager_lock: + if _remote_communicator_manager is None: + _remote_communicator_manager = RemoteCommunicatorManager() + return _remote_communicator_manager + + def add_remote_communicator(self, comm_handle: CommunicatorHandle): + self._remote_communicators[comm_handle.name] = comm_handle + + def remove_remote_communicator(self, name: str): + return self._remote_communicators.pop(name, None) + + def get_collective_groups( + self, + actors: Optional[List[ray.actor.ActorHandle]] = None, + backend: Optional[str] = None, + ): + """ + Get the collective groups that the given actors are a subset of. Filter by + backend if provided. + """ + actors = actors or [] + actors = set(actors) + + collectives = [] + # Find all collective groups that the given actors are a subset + # of, with the matching backend if provided. + for collective in self._remote_communicators.values(): + if actors.issubset(set(collective.actors)): + if backend is None or collective.backend == backend: + collectives.append(collective) + return collectives + + +def _do_init_collective_group( + self, + world_size: int, + rank: int, + backend: str = Backend.NCCL, + name: str = "default", +): + """Helper method that runs as a task on a remote actor to create a + collective group. + """ + ray.util.collective.init_collective_group( + world_size, rank, backend, group_name=name + ) + + +def _do_destroy_collective_group(self, name): + """Helper method that runs as a task on a remote actor to destroy a + collective group. + """ + ray.util.collective.destroy_collective_group(name) + + +@PublicAPI(stability="alpha") +def get_collective_groups( + actors: List[ray.actor.ActorHandle], backend: Optional[str] = None +) -> List[CommunicatorHandle]: + """ + Get the collective groups that the given actors are a subset of. Filter by + backend if provided. + + Args: + actors: List of actors. Return handles to all collective groups that + these actors are a subset of. + backend: An optional backend to filter by. See + ray.util.collective.types.Backend for valid backends. + + Returns: + A list of communicator handles that the actors are a subset of. + """ + manager = RemoteCommunicatorManager.get() + return manager.get_collective_groups(actors, backend) + + +@PublicAPI(stability="alpha") +def create_collective_group( + actors: List[ray.actor.ActorHandle], + backend: str, + name: Optional[str] = None, +) -> CommunicatorHandle: + """Create a collective group on the given list of actors. If this function + returns successfully, then the collective group has been initialized on all + actors, using the given order of actors as the ranks. + + Currently, an actor can only participate in one collective group per + backend at a time. To reuse an actor, destroy its collective group and + create a new one. + + Args: + actors: The actors to participate in the collective group. + backend: The backend to use. See ray.util.collective.types.Backend for + valid backends. + name: A name to use for the collective group. If None is provided, a + random name will be generated. + + Returns: + Handle to the communicator. + """ + manager = RemoteCommunicatorManager.get() + + if name is None: + name = str(uuid.uuid4()) + + # Validate the backend. + backend = Backend(backend) + + world_size = len(actors) + + for actor in actors: + if manager.get_collective_groups([actor], backend): + raise RuntimeError( + f"Actor {actor} already in group for backend {backend}. Actors can currently only participate in at most one group per backend." + ) + + actor_ids = [actor._ray_actor_id for actor in actors] + if len(set(actor_ids)) != len(actor_ids): + raise ValueError(f"All actors must be unique, got: {actors}") + + metadata_key = None + if backend == Backend.TORCH_GLOO: + # Perform extra setup for torch.distributed. + # torch.distributed requires a master address and port. Find a suitable + # port on one of the actors. + master_addr, master_port = ray.get( + actors[0].__ray_call__.remote(lambda self: get_address_and_port()) + ) + + # Store the metadata on a named actor that all of the other + # actors can access. + metadata_key = get_master_address_metadata_key(name) + internal_kv._internal_kv_put(metadata_key, f"{master_addr}:{master_port}") + + try: + init_tasks = [ + actor.__ray_call__.remote( + _do_init_collective_group, world_size, rank, backend, name + ) + for rank, actor in enumerate(actors) + ] + ray.get(init_tasks) + finally: + # Clean up the metadata once collective group is initialized + # (or failed to initialize). + if metadata_key is not None: + internal_kv._internal_kv_del(metadata_key) + + # Group was successfully created. + comm = CommunicatorHandle(actors, name, backend) + manager.add_remote_communicator(comm) + return comm + + +@PublicAPI(stability="alpha") +def destroy_collective_group(group_or_name: Union[CommunicatorHandle, str]): + """ + Destroy a collective group. If this functions returns successfully, then + the actors that were in the collective can be reused to create a new + collective group. + + Args: + group_or_name: Either a communicator handle or the name of the group to + destroy. + """ + if isinstance(group_or_name, CommunicatorHandle): + name = group_or_name.name + elif isinstance(group_or_name, str): + name = group_or_name + else: + raise ValueError("Expected CommunicatorHandle or str (group name).") + + manager = RemoteCommunicatorManager.get() + group = manager.remove_remote_communicator(name) + if group is not None: + destroy_tasks = [ + actor.__ray_call__.remote(_do_destroy_collective_group, name) + for actor in group.actors + ] + ray.get(destroy_tasks) + else: + raise ValueError(f"No group with name {name} found.") + + +@PublicAPI(stability="alpha") +def destroy_all_collective_groups(): + """ + Destroy all collective groups. This will destroy all collective groups that + were previously created by this process. After this function returns, the + actors participating in those collective groups can be reused to create a + new collective group. + """ + manager = RemoteCommunicatorManager.get() + for collective in manager.get_collective_groups(): + destroy_collective_group(collective.name) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/communicator.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/communicator.py new file mode 100644 index 0000000000000000000000000000000000000000..ba4aaecb87aef99f7d18d68210d0190fca73f079 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/communicator.py @@ -0,0 +1,63 @@ +from typing import List +from dataclasses import dataclass + +import ray +from ray.util.collective.types import Backend + + +@dataclass +class Communicator: + """ + A handle to a communicator that we are a member of. + """ + + # The name of the communicator. + name: str + # Our rank in the collective group. + rank: int + # A valid backend, as defined by + # ray.util.collective.types.Backend. + backend: str + + +class CommunicatorHandle: + """ + A communicator handle used by the driver to store handles to the + actors in the communicator. + """ + + def __init__(self, actors: List[ray.actor.ActorHandle], name: str, backend: str): + """ + Initializes the CommunicatorHandle with the given actor handles. + Assumes that the communicator has already been initialized on all actors. + + Args: + actors: A list of actor handles to be stored. + name: Name of the communicator. + backend: Communicator backend. See + ray.util.collective.types for valid values. + """ + self._actors = actors + self._name = name + self._backend = Backend(backend) + + def get_rank(self, actor: ray.actor.ActorHandle): + for i, a in enumerate(self._actors): + if a == actor: + return i + return -1 + + @property + def actors(self) -> List[ray.actor.ActorHandle]: + """ + Return all actor handles in this communicator. + """ + return self._actors[:] + + @property + def name(self) -> str: + return self._name + + @property + def backend(self) -> str: + return self._backend diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/conftest.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..4544931a9fd0bd8f775039eaa4b967cf85950752 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/conftest.py @@ -0,0 +1,243 @@ +import uuid +from typing import Dict, FrozenSet, List, Optional, Set, Tuple, Type + +import torch + +import ray +from ray.experimental.channel.common import ChannelContext +from ray.experimental.channel.communicator import ( + Communicator, + ReduceOp, + TorchTensorAllocator, +) + + +class AbstractNcclGroup(Communicator): + """ + A dummy NCCL group for testing. + """ + + def __init__(self, actor_handles: List[ray.actor.ActorHandle]): + self._actor_handles = actor_handles + self._rank = None + + def initialize(self, rank: int) -> None: + self._rank = rank + + def get_rank(self, actor: ray.actor.ActorHandle) -> int: + return self._actor_handles.index(actor) + + def get_world_size(self) -> int: + return len(self._actor_handles) + + def get_self_rank(self) -> Optional[int]: + return self._rank + + def get_actor_handles(self) -> List["ray.actor.ActorHandle"]: + return self._actor_handles + + def send(self, value: "torch.Tensor", peer_rank: int) -> None: + raise NotImplementedError + + def recv( + self, + shape: Tuple[int], + dtype: "torch.dtype", + peer_rank: int, + allocator: Optional[TorchTensorAllocator] = None, + ) -> "torch.Tensor": + raise NotImplementedError + + def allgather( + self, + send_buf: "torch.Tensor", + recv_buf: "torch.Tensor", + ) -> None: + raise NotImplementedError + + def allreduce( + self, + send_buf: "torch.Tensor", + recv_buf: "torch.Tensor", + op: ReduceOp = ReduceOp.SUM, + ) -> None: + raise NotImplementedError + + def reducescatter( + self, + send_buf: "torch.Tensor", + recv_buf: "torch.Tensor", + op: ReduceOp = ReduceOp.SUM, + ) -> None: + raise NotImplementedError + + @property + def recv_stream(self): + return None + + @property + def send_stream(self): + return None + + def destroy(self) -> None: + pass + + def get_transport_name(self) -> str: + return "accelerator" + + @classmethod + def generate_communicator_id(cls) -> str: + pass + + +class MockNcclGroupSet: + def __init__(self): + # Represents a mapping from a NCCL group ID to a set of actors and a custom + # NCCL group. + self.ids_to_actors_and_custom_comms: Dict[ + str, Tuple[FrozenSet["ray.actor.ActorHandle"], Optional[Communicator]] + ] = {} + + def __call__( + self, + actors: List["ray.actor.ActorHandle"], + custom_nccl_group: Optional[Communicator] = None, + use_communication_streams: bool = False, + accelerator_module_name: Optional[str] = None, + accelerator_communicator_cls: Optional[Type[Communicator]] = None, + ) -> str: + group_id = str(uuid.uuid4()) + self.ids_to_actors_and_custom_comms[group_id] = ( + frozenset(actors), + custom_nccl_group, + ) + + if custom_nccl_group is None: + ranks = list(range(len(actors))) + else: + ranks = [custom_nccl_group.get_rank(actor) for actor in actors] + init_tasks = [ + actor.__ray_call__.remote( + mock_do_init_nccl_group, + group_id, + rank, + actors, + custom_nccl_group, + ) + for rank, actor in zip(ranks, actors) + ] + ray.get(init_tasks, timeout=30) + + ctx = ChannelContext.get_current() + if custom_nccl_group is not None: + ctx.communicators[group_id] = custom_nccl_group + else: + ctx.communicators[group_id] = AbstractNcclGroup(actors) + + return group_id + + def mock_destroy_nccl_group(self, group_id: str) -> None: + ctx = ChannelContext.get_current() + if group_id not in ctx.communicators: + return + + actors, _ = self.ids_to_actors_and_custom_comms[group_id] + destroy_tasks = [ + actor.__ray_call__.remote( + mock_do_destroy_nccl_group, + group_id, + ) + for actor in actors + ] + ray.wait(destroy_tasks, timeout=30) + + if group_id in self.ids_to_actors_and_custom_comms: + del self.ids_to_actors_and_custom_comms[group_id] + ctx.communicators[group_id].destroy() + del ctx.communicators[group_id] + + def check_teardown(self, nccl_group_ids: List[str]) -> None: + ctx = ChannelContext.get_current() + for nccl_group_id in nccl_group_ids: + assert nccl_group_id not in self.ids_to_actors_and_custom_comms + assert nccl_group_id not in ctx.communicators + + +@ray.remote +class CPUTorchTensorWorker: + def __init__(self): + self.device = "cpu" + + def return_tensor( + self, size: int, dtype: Optional[torch.dtype] = None + ) -> torch.Tensor: + return torch.ones(size, dtype=dtype, device=self.device) + + def recv(self, tensor: torch.Tensor) -> Tuple[int, int]: + assert tensor.device == self.device + return tensor.shape, tensor[0] + + def recv_tensors(self, *tensors) -> Tuple[torch.Tensor, ...]: + return tuple(tensors) + + +def mock_do_init_nccl_group( + self, + group_id: str, + rank: int, + actors: List[ray.actor.ActorHandle], + custom_nccl_group: Optional[Communicator], +) -> None: + ctx = ChannelContext.get_current() + if custom_nccl_group is None: + nccl_group = AbstractNcclGroup(actors) + nccl_group.initialize(rank) + ctx.communicators[group_id] = nccl_group + else: + custom_nccl_group.initialize(rank) + ctx.communicators[group_id] = custom_nccl_group + + +def mock_do_destroy_nccl_group(self, group_id: str) -> None: + ctx = ChannelContext.get_current() + if group_id not in ctx.communicators: + return + ctx.communicators[group_id].destroy() + del ctx.communicators[group_id] + + +def check_nccl_group_init( + monkeypatch, + dag: "ray.dag.DAGNode", + actors_and_custom_comms: Set[ + Tuple[FrozenSet["ray.actor.ActorHandle"], Optional[Communicator]] + ], +) -> "ray.dag.CompiledDAG": + mock_nccl_group_set = MockNcclGroupSet() + monkeypatch.setattr( + "ray.dag.compiled_dag_node._init_communicator", + mock_nccl_group_set, + ) + + compiled_dag = dag.experimental_compile() + assert ( + set(mock_nccl_group_set.ids_to_actors_and_custom_comms.values()) + == actors_and_custom_comms + ) + + return compiled_dag, mock_nccl_group_set + + +def check_nccl_group_teardown( + monkeypatch, + compiled_dag: "ray.dag.CompiledDAG", + mock_nccl_group_set: MockNcclGroupSet, +): + monkeypatch.setattr( + "ray.dag.compiled_dag_node._destroy_communicator", + mock_nccl_group_set.mock_destroy_nccl_group, + ) + + created_communicator_ids = compiled_dag._actors_to_created_communicator_id.values() + compiled_dag.teardown() + mock_nccl_group_set.check_teardown(created_communicator_ids) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/operations.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/operations.py new file mode 100644 index 0000000000000000000000000000000000000000..31edbcb9eb2892c737eae88d2d931f7fc2857a01 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/operations.py @@ -0,0 +1,203 @@ +import logging +from typing import List, Optional, Union + +import ray +from ray.dag.collective_node import CollectiveOutputNode, _CollectiveOperation +from ray.dag.constants import ( + BIND_INDEX_KEY, + COLLECTIVE_OPERATION_KEY, + PARENT_CLASS_NODE_KEY, + IS_CLASS_METHOD_OUTPUT_KEY, +) +from ray.experimental.channel.torch_tensor_type import Communicator, TorchTensorType +from ray.experimental.util.types import ( + ReduceOp, + AllGatherOp, + AllReduceOp, + ReduceScatterOp, + _CollectiveOp, +) +from ray.util.collective.types import ReduceOp as RayReduceOp + +logger = logging.getLogger(__name__) + + +def _bind( + inputs: Union[List["ray.dag.DAGNode"], List[List["ray.dag.DAGNode"]]], + op: _CollectiveOp, + transport: Optional[Union[str, Communicator]] = None, +): + """ + Bind inputs (input nodes or lists of input nodes) with a collective operation. + The collective operation is applied to each list of input nodes. The output nodes + will have the same shape as the input nodes. + + Example of binding a list of input node: + with InputNode() as inp: + res_comp1 = [actor.comp1.bind(inp) for actor in actors] + res_comp2 = [actor.comp2.bind(inp) for actor in actors] + res_ar = allreduce.bind([res_comp1, res_comp2]) + + Requirements: + 1. Each input node returns a torch tensor. + 2. Each input node within a list is from a different actor. + 3. If lists of input nodes are provided, the order of actors should + be the same for each nested list. + 4. If a custom transport is specified, its actor set matches the actor + set of the input nodes. + 5. If input nodes are provided, then all tensors have the same shape. + If lists of input nodes are provided, then all tensors in each + list have the same shape. + + Requirements 1-3 are checked in the `CollectiveGroup` constructor. + Requirement 4 is not checked yet. + + Args: + inputs: A list of DAG nodes or a list of lists of DAG nodes. Each leaf list + should contain one object per actor. + op: The collective operation. + transport: GPU communicator for the collective operation. If not + specified, the default ACCELERATOR is used. + + Returns: + A list of collective output nodes or a list of lists of collective output nodes, + with the same shape as the input nodes. Each output node has the same order and + belongs to the same actor as the corresponding input node. + """ + if isinstance(inputs[0], list) and not isinstance(op, AllReduceOp): + raise ValueError( + "Currently binding a nested list of dag nodes is only supported for allreduce" + ) + + # Convert list of DAGNode into nested list for type checking + if not isinstance(inputs[0], list): + inputs = [inputs] + + if transport is None: + transport = TorchTensorType.ACCELERATOR + collective_op = _CollectiveOperation(inputs, op, transport) + collective_output_nodes: List[CollectiveOutputNode] = [] + + if isinstance(op, AllGatherOp): + method_name = "allgather" + elif isinstance(op, AllReduceOp): + method_name = f"allreduce.{op.reduceOp}" + elif isinstance(op, ReduceScatterOp): + method_name = f"reducescatter.{op.reduceOp}" + else: + raise ValueError(f"Expected a collective operation, but got {op}") + + for i in range(len(inputs[0])): + input_node_list = [l[i] for l in inputs if l] + actor_handle: Optional["ray.actor.ActorHandle"] = input_node_list[ + 0 + ]._get_actor_handle() + assert actor_handle is not None + collective_output_node = CollectiveOutputNode( + method_name=method_name, + method_args=tuple(input_node_list), + method_kwargs=dict(), + method_options=dict(), + other_args_to_resolve={ + PARENT_CLASS_NODE_KEY: actor_handle, + BIND_INDEX_KEY: actor_handle._ray_dag_bind_index, + COLLECTIVE_OPERATION_KEY: collective_op, + }, + ) + actor_handle._ray_dag_bind_index += 1 + + if len(input_node_list) > 1: + output_nodes: List[CollectiveOutputNode] = [] + for i in range(len(input_node_list)): + output_node = CollectiveOutputNode( + f"return_idx_{i}", + (collective_output_node, i), + dict(), + dict(), + { + BIND_INDEX_KEY: collective_output_node._get_bind_index(), + IS_CLASS_METHOD_OUTPUT_KEY: True, + PARENT_CLASS_NODE_KEY: actor_handle, + }, + ) + output_nodes.append(output_node) + collective_output_nodes.append(output_nodes) + else: + collective_output_nodes.append(collective_output_node) + return collective_output_nodes + + +class AllGatherWrapper: + """Wrapper for NCCL all-gather.""" + + def bind( + self, + input_nodes: List["ray.dag.DAGNode"], + transport: Optional[Union[str, Communicator]] = None, + ) -> List[CollectiveOutputNode]: + return _bind(input_nodes, AllGatherOp(), transport) + + def __call__( + self, + tensor_list, + tensor, + group_name: str = "default", + ): + from ray.util.collective.collective import allgather + + return allgather(tensor_list, tensor, group_name) + + +class AllReduceWrapper: + """Wrapper for NCCL all-reduce.""" + + def bind( + self, + input_nodes: List["ray.dag.DAGNode"], + op: ReduceOp = ReduceOp.SUM, + transport: Optional[Union[str, Communicator]] = None, + ) -> List[CollectiveOutputNode]: + if not isinstance(op, ReduceOp): + raise ValueError(f"Unexpected operation: {op}") + + return _bind(input_nodes, AllReduceOp(reduceOp=op), transport) + + def __call__( + self, + tensor, + group_name: str = "default", + op: RayReduceOp = RayReduceOp.SUM, + ): + from ray.util.collective.collective import allreduce + + return allreduce(tensor, group_name, op) + + +class ReduceScatterWrapper: + """Wrapper for NCCL reduce-scatter.""" + + def bind( + self, + input_nodes: List["ray.dag.DAGNode"], + op: ReduceOp = ReduceOp.SUM, + transport: Optional[Union[str, Communicator]] = None, + ) -> List[CollectiveOutputNode]: + if not isinstance(op, ReduceOp): + raise ValueError(f"Unexpected operation: {op}") + + return _bind(input_nodes, ReduceScatterOp(reduceOp=op), transport) + + def __call__( + self, + tensor, + group_name: str = "default", + op: RayReduceOp = RayReduceOp.SUM, + ): + from ray.util.collective.collective import reducescatter + + return reducescatter(tensor, group_name, op) + + +allgather = AllGatherWrapper() +allreduce = AllReduceWrapper() +reducescatter = ReduceScatterWrapper() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/util.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/util.py new file mode 100644 index 0000000000000000000000000000000000000000..ea518a002458e8661be6d6b9fc158a777254e6ed --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/collective/util.py @@ -0,0 +1,20 @@ +from typing import Tuple +from contextlib import closing +import socket + +import ray + + +def find_free_port() -> int: + with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s: + s.bind(("", 0)) + s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + return s.getsockname()[1] + + +def get_address_and_port() -> Tuple[str, int]: + """Returns the IP address and a free port on this node.""" + addr = ray.util.get_node_ip_address() + port = find_free_port() + + return addr, port diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/gpu_object_manager/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/gpu_object_manager/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..13be5939544503b51ffcb2b975eb5d787611eb77 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/gpu_object_manager/__init__.py @@ -0,0 +1,6 @@ +from ray.experimental.gpu_object_manager.gpu_object_manager import ( + GPUObjectManager, + wait_tensor_freed, +) + +__all__ = ["GPUObjectManager", "wait_tensor_freed"] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/gpu_object_manager/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/gpu_object_manager/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61b35d6d630dc7b5e7f6eb4d80ac1a8869fa5b13 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/gpu_object_manager/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/gpu_object_manager/__pycache__/gpu_object_manager.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/gpu_object_manager/__pycache__/gpu_object_manager.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b419c2d2c01420a7c4ab0c2994ec59f110c4e5d9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/gpu_object_manager/__pycache__/gpu_object_manager.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/gpu_object_manager/__pycache__/gpu_object_store.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/gpu_object_manager/__pycache__/gpu_object_store.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..629877c45fc04a38efea6b75188c153ee7fff2c8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/gpu_object_manager/__pycache__/gpu_object_store.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/gpu_object_manager/gpu_object_manager.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/gpu_object_manager/gpu_object_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..c45ff36572aadd801452d412962aab1ac7b2e6b5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/gpu_object_manager/gpu_object_manager.py @@ -0,0 +1,316 @@ +from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Tuple +import threading + +import ray +from ray._private.custom_types import TensorTransportEnum +from ray._raylet import ObjectRef +from ray._private import ray_constants + + +if TYPE_CHECKING: + import torch + from ray.experimental.gpu_object_manager.gpu_object_store import ( + GPUObjectStore, + ) + +# GPUObjectMeta is a named tuple containing the source actor, tensor transport +# backend, and tensor metadata. +# - The tensor transport backend is the backend used to transport the tensors. +# Currently, the supported backends are "nccl" and "torch_gloo". +# - The tensor metadata is a list of tuples, each containing the shape and dtype +# of a tensor in the GPU object store. +class GPUObjectMeta(NamedTuple): + src_actor: "ray.actor.ActorHandle" + # Must be a valid backend name as defined in + # `ray.util.collective.types.Backend`. + tensor_transport_backend: str + tensor_meta: List[Tuple["torch.Size", "torch.dtype"]] + + +# TODO(swang): Uncomment and add an API docs page and example usage. +# @PublicAPI(stability="alpha") +def wait_tensor_freed(tensor: "torch.Tensor", timeout: Optional[float] = None): + """ + Wait for the tensor to be freed from this actor's GPU object store. + + This function is useful for cases where an actor keeps a reference to a + tensor after returning the tensor from a task annotated with + `@ray.method(tensor_transport=...)`. Tensors that are returned by these + tasks may be sent to other actors while the corresponding `ray.ObjectRef` is + still in scope. If the actor modifies the tensor while it is still in the + actor's GPU object store, then Ray may end up sending invalid data to other + tasks. Call this function to ensure that the `ray.ObjectRef` has gone out of + scope and therefore the tensor is safe to write to again. + + Args: + tensor: The tensor to wait to be freed. + timeout: The timeout in seconds. Set to None to wait indefinitely. Note + that this function could then hang if the `ray.ObjectRef` that + refers to this tensor never goes out of scope. + """ + gpu_object_manager = ray.worker.global_worker.gpu_object_manager + gpu_object_manager.gpu_object_store.wait_tensor_freed(tensor, timeout) + + +class GPUObjectManager: + def __init__(self): + # A dictionary that maps from owned object's ID to GPUObjectMeta. + # This dictionary is hosted on the "driver" process of the actors that + # store and send/receive GPU objects. + self.managed_gpu_object_metadata: Dict[str, GPUObjectMeta] = {} + # Per-actor local storage for GPU objects. We create the GPU object + # store lazily, if a user specifies a non-default tensor_transport, to + # avoid circular import and because it imports third-party dependencies + # like PyTorch. + self._gpu_object_store: Optional["GPUObjectStore"] = None + # Lock to ensure we only create the GPU object store once. + self.gpu_object_store_lock = threading.Lock() + + @property + def gpu_object_store(self) -> "ray.experimental.GPUObjectStore": + with self.gpu_object_store_lock: + if self._gpu_object_store is None: + from ray.experimental.gpu_object_manager.gpu_object_store import ( + GPUObjectStore, + ) + + self._gpu_object_store = GPUObjectStore() + return self._gpu_object_store + + def _get_tensor_meta( + self, src_actor: "ray.actor.ActorHandle", obj_id: str + ) -> ObjectRef: + from ray.experimental.gpu_object_manager.gpu_object_store import ( + __ray_get_tensor_meta__, + ) + + # Submit a Ray actor task to the source actor to get the tensor metadata. + # The metadata is a list of tuples, where each tuple contains the shape and dtype + # of a tensor in the GPU object store. This function returns an ObjectRef that + # points to the tensor metadata. + # NOTE(swang): We put this task on the background thread to avoid tasks + # executing on the main thread blocking this task. + return src_actor.__ray_call__.options(concurrency_group="_ray_system").remote( + __ray_get_tensor_meta__, obj_id + ) + + def is_managed_object(self, obj_id: str) -> bool: + """ + Check if the GPU object is managed by this process. + + Args: + obj_id: The object ID of the GPU object. + + Returns: + True if the current process is the driver process coordinating the data transfer + of this GPU object. + """ + return obj_id in self.managed_gpu_object_metadata + + def add_gpu_object_ref( + self, + obj_ref: ObjectRef, + src_actor: "ray.actor.ActorHandle", + tensor_transport: TensorTransportEnum, + ): + """Add a GPU object reference to the GPU object manager. This should be + called whenever the current process calls a task that is annotated with + `@ray.method(tensor_transport=...)`. + + Args: + obj_ref: The ObjectRef of the task output. + src_actor: The actor that executes the task and that creates the GPU object. + tensor_transport: The tensor transport protocol to use for the GPU object. + """ + from ray.experimental.gpu_object_manager.gpu_object_store import ( + _tensor_transport_to_collective_backend, + ) + + tensor_transport_backend = _tensor_transport_to_collective_backend( + tensor_transport + ) + obj_id = obj_ref.hex() + tensor_meta = self._get_tensor_meta(src_actor, obj_id) + self.managed_gpu_object_metadata[obj_id] = GPUObjectMeta( + src_actor=src_actor, + tensor_transport_backend=tensor_transport_backend, + tensor_meta=tensor_meta, + ) + + def _get_gpu_object_metadata(self, obj_ref: ObjectRef) -> GPUObjectMeta: + obj_id = obj_ref.hex() + return self.managed_gpu_object_metadata[obj_id] + + def _send_object( + self, + communicator_name: str, + src_actor: "ray.actor.ActorHandle", + obj_id: str, + dst_rank: int, + ): + from ray.experimental.gpu_object_manager.gpu_object_store import __ray_send__ + + # Send tensors stored in the `src_actor`'s GPU object store to the + # destination rank `dst_rank`. + # NOTE(swang): We put this task on the background thread to avoid tasks + # executing on the main thread blocking the data transfer. + src_actor.__ray_call__.options(concurrency_group="_ray_system").remote( + __ray_send__, communicator_name, obj_id, dst_rank + ) + + def _recv_object( + self, + communicator_name: str, + dst_actor: "ray.actor.ActorHandle", + obj_id: str, + src_rank: int, + tensor_meta: List[Tuple["torch.Size", "torch.dtype"]], + ): + from ray.experimental.gpu_object_manager.gpu_object_store import __ray_recv__ + + # Receive tensors from the source rank and store them in the + # `dst_actor`'s GPU object store. + # + # NOTE(swang): We put this task on the background thread to avoid tasks + # executing on the main thread blocking the data transfer. Technically, + # this is only needed for the sender task, but we put the receiver task + # on the same background thread to ensure that all communication + # operations are executed in a global order. + dst_actor.__ray_call__.options(concurrency_group="_ray_system").remote( + __ray_recv__, communicator_name, obj_id, src_rank, tensor_meta + ) + + def fetch_object(self, obj_id: str): + """ + Fetches the GPU object from the source actor's GPU object store via the object store + instead of out-of-band tensor transfer and stores the tensors in the local GPU object store. + + This is useful when the current process does not support the designated out-of-band tensor transport. + For example, if the tensor transport is NCCL but the driver does not have a GPU, we use this call to + fulfill a `ray.get` call. + + Args: + obj_id: The object ID of the GPU object. + + Returns: + None + """ + from ray.experimental.gpu_object_manager.gpu_object_store import ( + __ray_fetch_gpu_object__, + ) + + if self.gpu_object_store.has_object(obj_id): + return + + gpu_object_meta = self.managed_gpu_object_metadata[obj_id] + src_actor = gpu_object_meta.src_actor + tensors = ray.get( + src_actor.__ray_call__.options(concurrency_group="_ray_system").remote( + __ray_fetch_gpu_object__, obj_id + ) + ) + self.gpu_object_store.add_object(obj_id, tensors) + + def trigger_out_of_band_tensor_transfer( + self, dst_actor: "ray.actor.ActorHandle", task_args: Tuple[Any, ...] + ): + """ + Triggers tensor communication operations between actors. When a managed ObjectRef is passed + to another actor task, CPU data will still be passed through the object store, but the in-actor + tensors will be passed out-of-band. + + This function triggers the out-of-band tensor transfer by submitting Ray actor + tasks `__ray_send__` to the sender actor and `__ray_recv__` to the receiver actor to initiate + tensor communication using protocols like NCCL or GLOO. + + Before the receiver actor executes the actor task, the deserializer combines the + CPU data with the tensors from the sender actor to reconstruct the original task output + generated by the sender actor. + + Args: + dst_actor: The target actor to receive tensors + task_args: List of arguments for the target actor task that may contain ObjectRefs. + """ + gpu_object_refs = set() + for arg in task_args: + # If an ObjectRef is managed, it means the actual value is a list of tensors stored + # on a remote actor. Therefore, this function will trigger a tensor communication + # operation between the sender and receiver actors. + if not isinstance(arg, ObjectRef): + continue + if self.is_managed_object(arg.hex()): + gpu_object_refs.add(arg) + + # Count the number of readers for each GPU object. + for obj_ref in gpu_object_refs: + # Import get_collective_groups here to avoid dependency on + # collective libraries for default Ray installation. + from ray.experimental.collective import get_collective_groups + + gpu_object_meta = self._get_gpu_object_metadata(obj_ref) + + src_actor = gpu_object_meta.src_actor + tensor_meta = gpu_object_meta.tensor_meta + communicators = get_collective_groups( + [src_actor, dst_actor], backend=gpu_object_meta.tensor_transport_backend + ) + # TODO(kevin85421): Support multiple communicators. + if len(communicators) == 0: + raise ValueError( + f"No communicators found for actors {src_actor} and {dst_actor}. " + "Create a communicator with " + "`ray.experimental.collective.create_collective_group` " + "before calling actor tasks." + ) + elif len(communicators) > 1: + raise ValueError( + f"There are {len(communicators)} possible communicators that contain actors {src_actor} and {dst_actor}. " + "Currently, GPU objects only support one communicator. Please make sure only " + "one communicator exists." + ) + communicator = communicators[0] + src_rank = communicator.get_rank(src_actor) + if src_rank == -1: + raise ValueError( + f"Sender actor {src_actor} not found in communicator. " + "Please make sure the sender and receiver are in the same communicator." + ) + dst_rank = communicator.get_rank(dst_actor) + if dst_rank == -1: + raise ValueError( + f"Receiver actor {dst_actor} not found in communicator. " + "Please make sure the sender and receiver are in the same communicator." + ) + if src_rank == dst_rank: + # If the source and destination ranks are the same, the tensors can + # be transferred intra-process, so we skip the out-of-band tensor + # transfer. + continue + obj_id = obj_ref.hex() + self._send_object(communicator.name, src_actor, obj_id, dst_rank) + self._recv_object( + communicator.name, dst_actor, obj_id, src_rank, tensor_meta + ) + + def get_gpu_object(self, object_id: str) -> List["torch.Tensor"]: + """ + Get the GPU object for a given object ID. + """ + gpu_object_store = self.gpu_object_store + if self.is_managed_object(object_id): + self.fetch_object(object_id) + + # If the GPU object is the primary copy, it means the transfer is intra-actor. + # In this case, we should not remove the GPU object after it is consumed once, + # because the GPU object reference may be used again. + # Instead, we should wait for the GC callback to clean it up. + pop_object = not gpu_object_store.is_primary_copy(object_id) + if pop_object: + gpu_object = gpu_object_store.wait_and_pop_object( + object_id, timeout=ray_constants.FETCH_FAIL_TIMEOUT_SECONDS + ) + else: + gpu_object = gpu_object_store.wait_and_get_object( + object_id, timeout=ray_constants.FETCH_FAIL_TIMEOUT_SECONDS + ) + return gpu_object diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/gpu_object_manager/gpu_object_store.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/gpu_object_manager/gpu_object_store.py new file mode 100644 index 0000000000000000000000000000000000000000..9a15f0da7cc446a688e3d0f30071ce2615b5d524 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/gpu_object_manager/gpu_object_store.py @@ -0,0 +1,277 @@ +from dataclasses import dataclass +from typing import Dict, List, Optional, Tuple, Set +import threading +from collections import defaultdict + +import ray.util.collective as collective +from ray._private.custom_types import TensorTransportEnum +from ray.util.collective.types import Backend + + +try: + import torch +except ImportError: + raise ImportError( + "`tensor_transport` requires PyTorch. " + "Please install torch with 'pip install torch' to use this feature." + ) + +TENSOR_TRANSPORT_TO_COLLECTIVE_BACKEND = { + TensorTransportEnum.NCCL: Backend.NCCL, + TensorTransportEnum.GLOO: Backend.TORCH_GLOO, +} + +COLLECTIVE_BACKEND_TO_TORCH_DEVICE = { + Backend.NCCL: torch.device("cuda"), + Backend.TORCH_GLOO: torch.device("cpu"), +} + + +def _tensor_transport_to_collective_backend( + tensor_transport: TensorTransportEnum, +) -> Backend: + try: + return TENSOR_TRANSPORT_TO_COLLECTIVE_BACKEND[tensor_transport] + except KeyError: + raise ValueError( + f"Invalid tensor transport {tensor_transport.name}, must be one of {list(TENSOR_TRANSPORT_TO_COLLECTIVE_BACKEND.keys())}." + ) + + +def __ray_send__(self, communicator_name: str, obj_id: str, dst_rank: int): + """Helper function that runs on the src actor to send tensors to the dst actor.""" + from ray._private.worker import global_worker + + gpu_object_store = global_worker.gpu_object_manager._gpu_object_store + assert gpu_object_store.has_object( + obj_id + ), f"obj_id={obj_id} not found in GPU object store" + tensors = gpu_object_store.get_object(obj_id) + + backend = collective.get_group_handle(communicator_name).backend() + device = COLLECTIVE_BACKEND_TO_TORCH_DEVICE[backend] + + for tensor in tensors: + if tensor.device.type != device.type: + # TODO(swang): Right now there is no way to catch this error + # and the receiving Ray task will hang. + raise ValueError( + f"tensor device {tensor.device} does not match device {device}" + ) + collective.send(tensor, dst_rank, group_name=communicator_name) + + +def __ray_recv__( + self, + communicator_name: str, + obj_id: str, + src_rank: int, + tensor_meta: List[Tuple["torch.Size", "torch.dtype"]], +): + """Helper function that runs on the dst actor to receive tensors from the src actor.""" + from ray._private.worker import global_worker + + backend = collective.get_group_handle(communicator_name).backend() + device = COLLECTIVE_BACKEND_TO_TORCH_DEVICE[backend] + + gpu_object_store = global_worker.gpu_object_manager.gpu_object_store + tensors = [] + for meta in tensor_meta: + shape, dtype = meta + tensor = torch.zeros(shape, dtype=dtype, device=device) + collective.recv(tensor, src_rank, group_name=communicator_name) + tensors.append(tensor) + gpu_object_store.add_object(obj_id, tensors) + + +def __ray_get_tensor_meta__(self, obj_id: str): + """Helper function that runs on the src actor to get the tensor metadata.""" + from ray._private.worker import global_worker + + gpu_object_store = global_worker.gpu_object_manager.gpu_object_store + # NOTE: We do not specify a timeout here because the user task that returns + # it could take arbitrarily long and we don't want to trigger a spurious + # timeout. + gpu_object = gpu_object_store.wait_and_get_object(obj_id) + return [(t.shape, t.dtype) for t in gpu_object] + + +def __ray_fetch_gpu_object__(self, obj_id: str): + """Helper function that runs on the src actor to fetch tensors from the GPU object store via the object store.""" + from ray._private.worker import global_worker + + gpu_object_store = global_worker.gpu_object_manager.gpu_object_store + assert gpu_object_store.has_object( + obj_id + ), f"obj_id={obj_id} not found in GPU object store" + gpu_object = gpu_object_store.get_object(obj_id) + return gpu_object + + +@dataclass +class _GPUObject: + # A list of tensors representing the GPU object. + data: List["torch.Tensor"] + # Whether the GPU object is the primary copy. + is_primary: bool + + +class GPUObjectStore: + """ + This class is thread-safe. The GPU object store is meant to be read and + written by the following threads: + 1. The main thread, which is executing user code. This thread may get, put, + and pop objects. + 2. The background _ray_system thread, which executes data transfers. This + thread may get and put objects. + 3. The background CoreWorker server thread, which executes garbage + collection callbacks that pop objects that are no longer in use. + """ + + def __init__(self): + # A dictionary that maps from an object ID to a list of tensors. + # + # Note: Currently, `gpu_object_store` is only supported for Ray Actors. + self._gpu_object_store: Dict[str, _GPUObject] = {} + # Mapping from tensor to the IDs of objects that contain it. + self._tensor_to_object_ids: Dict["torch.Tensor", Set[str]] = defaultdict(set) + # Synchronization for GPU object store. + self._lock = threading.RLock() + # Signal when an object becomes present in the object store. + self._object_present_cv = threading.Condition(self._lock) + # Signal when an object is freed from the object store. + self._object_freed_cv = threading.Condition(self._lock) + + def has_object(self, obj_id: str) -> bool: + with self._lock: + return obj_id in self._gpu_object_store + + def has_tensor(self, tensor: "torch.Tensor") -> bool: + with self._lock: + return tensor in self._tensor_to_object_ids + + def get_object(self, obj_id: str) -> Optional[List["torch.Tensor"]]: + with self._lock: + return self._gpu_object_store[obj_id].data + + def add_object( + self, + obj_id: str, + gpu_object: List["torch.Tensor"], + is_primary: bool = False, + ): + """ + Add a GPU object to the GPU object store. + + Args: + obj_id: The object ID of the GPU object. + gpu_object: A list of tensors representing the GPU object. + is_primary: Whether the GPU object is the primary copy. + """ + with self._object_present_cv: + for tensor in gpu_object: + self._tensor_to_object_ids[tensor].add(obj_id) + self._gpu_object_store[obj_id] = _GPUObject( + gpu_object, + is_primary, + ) + self._object_present_cv.notify_all() + + def is_primary_copy(self, obj_id: str) -> bool: + with self._lock: + return ( + obj_id in self._gpu_object_store + and self._gpu_object_store[obj_id].is_primary + ) + + def wait_and_get_object( + self, obj_id: str, timeout: Optional[float] = None + ) -> List["torch.Tensor"]: + """Atomically waits for the GPU object to be present in the GPU object + store, then gets it. If the object is not present after the optional + timeout, raise a TimeoutError. + + Args: + obj_id: The object ID to wait for. + timeout: The maximum time in seconds to wait for the object to be + present in the GPU object store. If not specified, wait indefinitely. + + Returns: + The tensors in the GPU object. + """ + with self._lock: + self._wait_object(obj_id, timeout) + return self.get_object(obj_id) + + def wait_and_pop_object( + self, obj_id: str, timeout: Optional[float] = None + ) -> List["torch.Tensor"]: + """Atomically waits for the GPU object to be present in the GPU object + store, then pops it. If the object is not present after the optional + timeout, raise a TimeoutError. + + Args: + obj_id: The object ID to wait for. + timeout: The maximum time in seconds to wait for the object to be + present in the GPU object store. If not specified, wait + indefinitely. + + Returns: + The GPU object. + """ + with self._lock: + self._wait_object(obj_id, timeout) + return self.pop_object(obj_id) + + def _wait_object(self, obj_id: str, timeout: Optional[float] = None) -> None: + """Helper method to wait for the GPU object to be present in the GPU object store. + If the object is not present after the optional timeout, raise a + TimeoutError. + + Args: + obj_id: The object ID to wait for. + timeout: The maximum time in seconds to wait for the object to be + present in the GPU object store. If not specified, wait + indefinitely. + """ + with self._object_present_cv: + if not self._object_present_cv.wait_for( + lambda: obj_id in self._gpu_object_store, timeout=timeout + ): + raise TimeoutError( + f"ObjectRef({obj_id}) not found in GPU object store after {timeout}s, transfer may have failed. Please report this issue on GitHub: https://github.com/ray-project/ray/issues/new/choose" + ) + + def pop_object(self, obj_id: str) -> List["torch.Tensor"]: + with self._lock: + assert ( + obj_id in self._gpu_object_store + ), f"obj_id={obj_id} not found in GPU object store" + gpu_object = self._gpu_object_store.pop(obj_id) + for tensor in gpu_object.data: + self._tensor_to_object_ids[tensor].remove(obj_id) + if len(self._tensor_to_object_ids[tensor]) == 0: + self._tensor_to_object_ids.pop(tensor) + self._object_freed_cv.notify_all() + return gpu_object.data + + def wait_tensor_freed( + self, tensor: "torch.Tensor", timeout: Optional[float] = None + ) -> None: + """ + Wait for the object to be freed from the GPU object store. + """ + with self._object_freed_cv: + if not self._object_freed_cv.wait_for( + lambda: tensor not in self._tensor_to_object_ids, timeout=timeout + ): + raise TimeoutError( + f"Tensor {tensor} not freed from GPU object store after {timeout}s. The tensor will not be freed until all ObjectRefs containing the tensor have gone out of scope." + ) + + def get_num_objects(self) -> int: + """ + Return the number of objects in the GPU object store. + """ + with self._lock: + return len(self._gpu_object_store) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/job/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/job/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/job/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/job/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a0e9dc3a29412c19a8600cb72f575071af5e78d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/job/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/job/example_job/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/job/example_job/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/job/example_job/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/job/example_job/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d571fa94aef6f2e3f5fcceae1072e7d7d61f806 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/job/example_job/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/job/example_job/__pycache__/demo_script.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/job/example_job/__pycache__/demo_script.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ad646c968eaf30aa608d8edebcfcd62e671d166 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/job/example_job/__pycache__/demo_script.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/job/example_job/demo_script.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/job/example_job/demo_script.py new file mode 100644 index 0000000000000000000000000000000000000000..8bcc79611e26d404a7f7d0dbd86b22f1424420c9 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/job/example_job/demo_script.py @@ -0,0 +1,77 @@ +# Regular ray application that user wrote and runs on local cluster. +# intermediate status are dumped to GCS +import argparse +import time + +import ray +import ray.experimental.internal_kv as ray_kv + + +@ray.remote +class StepActor: + def __init__(self, interval_s=1, total_steps=3): + self.interval_s = interval_s + self.stopped = False + self.current_step = 1 + self.total_steps = total_steps + + worker = ray._private.worker.global_worker + worker_id = worker.core_worker.get_actor_id() + ray_kv._internal_kv_put(f"JOB:{worker_id}", self.current_step, overwrite=True) + + def run(self): + worker = ray._private.worker.global_worker + worker_id = worker.core_worker.get_actor_id() + + while self.current_step <= self.total_steps: + if not self.stopped: + print( + f"Sleeping {self.interval_s} secs to executing " + f"step {self.current_step}" + ) + time.sleep(self.interval_s) + self.current_step += 1 + ray_kv._internal_kv_put( + f"JOB:{worker_id}", self.current_step, overwrite=True + ) + else: + print("Stop called or reached final step.") + break + + self.stopped = True + ray_kv._internal_kv_put(f"JOB:{worker_id}", "DONE", overwrite=True) + return "DONE" + + def get_step(self): + return self.current_step + + def stop(self): + self.stopped = True + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--interval-s", + required=False, + type=int, + default=1, + help="Address to use to connect to Ray", + ) + parser.add_argument( + "--total-steps", + required=False, + type=int, + default=3, + help="Password for connecting to Redis", + ) + args, _ = parser.parse_known_args() + + ray.init() + step_actor = StepActor.remote( + interval_s=args.interval_s, total_steps=args.total_steps + ) + ref = step_actor.run.remote() + print(ray.get([ref])) + job_key = ray_kv._internal_kv_list("JOB:")[0] + print(f"{job_key}, {ray_kv._internal_kv_get(job_key)}") diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/multiprocessing/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/multiprocessing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f9b741f1ebfc72812a214fe4c52b2894bd965602 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/multiprocessing/__init__.py @@ -0,0 +1,5 @@ +from multiprocessing import TimeoutError + +from .pool import Pool + +__all__ = ["Pool", "TimeoutError"] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/multiprocessing/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/multiprocessing/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..067f25ba766ad65527823ae45f27f282784807e9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/multiprocessing/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/multiprocessing/__pycache__/pool.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/multiprocessing/__pycache__/pool.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d114f62c1dcbdee1c30475dee1f15f978b615019 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/multiprocessing/__pycache__/pool.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/multiprocessing/pool.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/multiprocessing/pool.py new file mode 100644 index 0000000000000000000000000000000000000000..bf0e442ff04b11a66baa1ac496d1acf4f6d55299 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/multiprocessing/pool.py @@ -0,0 +1,5 @@ +from ray.util import multiprocessing + + +class Pool(multiprocessing.Pool): + pass # moved to util package diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aef00820d4b9d1ebf6cc210e68d8166a6dd42e53 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/__pycache__/api.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/__pycache__/api.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..101b4f5526ae5d6ea377188386d62cb441c729f2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/__pycache__/api.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/__pycache__/common.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/__pycache__/common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..464616eef58494d8b66e6364b6480175c6cee226 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/__pycache__/common.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/__pycache__/custom_types.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/__pycache__/custom_types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fba1abf59c5397add1323769fa39e07e0d30d41f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/__pycache__/custom_types.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/__pycache__/exception.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/__pycache__/exception.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e88dea01025814fffd56690208f3c786268806a5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/__pycache__/exception.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/__pycache__/state_cli.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/__pycache__/state_cli.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70fc28066c2b8c2f9f41f9cdb49589e928b5d8a3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/__pycache__/state_cli.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/__pycache__/state_manager.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/__pycache__/state_manager.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0829c63e037d90e37d45c3c6dce7a4a334b4d5c2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/__pycache__/state_manager.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/__pycache__/util.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/__pycache__/util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71c3202fa47d2bbc44a724ab4a6375eae31330ca Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/__pycache__/util.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/api.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/api.py new file mode 100644 index 0000000000000000000000000000000000000000..f62f5f2ef7cd375c90224e3f71c3d041d7d029a7 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/api.py @@ -0,0 +1,4 @@ +from ray.util.state import * # noqa: F401 F403 +from ray.util.state.util import record_deprecated_state_api_import + +record_deprecated_state_api_import() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/common.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/common.py new file mode 100644 index 0000000000000000000000000000000000000000..6fbd488cd0fe5fbe200ad981a069c23f5100add3 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/common.py @@ -0,0 +1,4 @@ +from ray.util.state.common import * # noqa: F401 F403 +from ray.util.state.util import record_deprecated_state_api_import + +record_deprecated_state_api_import() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/custom_types.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/custom_types.py new file mode 100644 index 0000000000000000000000000000000000000000..3dd749f793df398d70445af7c8bc50d3aa991608 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/custom_types.py @@ -0,0 +1,4 @@ +from ray._private.custom_types import * # noqa: F401 F403 +from ray.util.state.util import record_deprecated_state_api_import + +record_deprecated_state_api_import() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/exception.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/exception.py new file mode 100644 index 0000000000000000000000000000000000000000..49e7099cf325dc106a1927ccc64a7e3917c7a68c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/exception.py @@ -0,0 +1,4 @@ +from ray.util.state.exception import * # noqa: F401 F403 +from ray.util.state.util import record_deprecated_state_api_import + +record_deprecated_state_api_import() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/state_cli.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/state_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..58bc5d31ebdcc5e523af8da8c8397a464909b742 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/state_cli.py @@ -0,0 +1,4 @@ +from ray.util.state.state_cli import * # noqa: F401 F403 +from ray.util.state.util import record_deprecated_state_api_import + +record_deprecated_state_api_import() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/state_manager.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/state_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..7720606a68b9a6a6862518ce0ebeba01bcdb276f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/state_manager.py @@ -0,0 +1,4 @@ +from ray.util.state.state_manager import * # noqa: F401 F403 +from ray.util.state.util import record_deprecated_state_api_import + +record_deprecated_state_api_import() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/util.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/util.py new file mode 100644 index 0000000000000000000000000000000000000000..24a26dd72982292593f06fb91bca45e7c765cff8 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/state/util.py @@ -0,0 +1,4 @@ +from ray.util.state.util import * # noqa: F401 F403 +from ray.util.state.util import record_deprecated_state_api_import + +record_deprecated_state_api_import() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/util/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/util/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/util/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/util/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..efaa2d2c06962688b7c43c4e926eaa37f0ba873b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/util/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/util/__pycache__/types.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/util/__pycache__/types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c9ebcdeb61af048eb8b14f74159890e66932fc7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/util/__pycache__/types.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/util/types.py b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/util/types.py new file mode 100644 index 0000000000000000000000000000000000000000..92ac6488139878f48e819efd6fab301d28d9a20b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/experimental/util/types.py @@ -0,0 +1,46 @@ +from dataclasses import dataclass +from enum import Enum + +from ray.util.annotations import PublicAPI + + +class _CollectiveOp: + pass + + +@PublicAPI +class ReduceOp(Enum): + SUM = 0 + PRODUCT = 1 + MAX = 2 + MIN = 3 + AVG = 4 + + +@PublicAPI +@dataclass +class AllGatherOp(_CollectiveOp): + pass + + +@PublicAPI +@dataclass +class AllReduceOp(_CollectiveOp): + reduceOp: ReduceOp = ReduceOp.SUM + + +@PublicAPI +@dataclass +class ReduceScatterOp(_CollectiveOp): + reduceOp: ReduceOp = ReduceOp.SUM + + +@PublicAPI(stability="alpha") +class Device(Enum): + DEFAULT = "default" + CPU = "cpu" + GPU = "gpu" + CUDA = "cuda" + + def __str__(self): + return self.value diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/internal/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/internal/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c53815b19166f0e6f51de3d2249034447a90de6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/internal/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/job_submission/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/job_submission/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6a6a513865ef2ad350d549a1475570e2bff5777 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/job_submission/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91a1077dfe0600487cbd9c0f382256d96a288833 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98b644501781c06bd67f94799640b40285d2990a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1a304e84ded93babf08de6fd5d90e4e66d4203e0 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/__init__.py @@ -0,0 +1,13 @@ +from ray.llm._internal.batch.processor import ( + HttpRequestProcessorConfig, + Processor, + ProcessorBuilder, + ProcessorConfig, +) + +__all__ = [ + "Processor", + "ProcessorConfig", + "ProcessorBuilder", + "HttpRequestProcessorConfig", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09f254caedf5d767a9a26230b349e18b0f929be8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/__pycache__/utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a1bca571141ba6b576aa6cfec378ed360b48be3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/__pycache__/utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a6b16daae6757e4368cec4063decb3a92a90d923 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/__init__.py @@ -0,0 +1,23 @@ +from ray.llm._internal.batch.observability.logging.setup import ( + setup_logging, +) +from ray.llm._internal.common.observability.logging_utils import ( + disable_datasets_logger, + disable_vllm_custom_ops_logger_on_cpu_nodes, +) +from ray.llm._internal.common.observability.telemetry_utils import Once + +_setup_observability_once = Once() + + +def _setup_observability(): + setup_logging() + disable_datasets_logger() + disable_vllm_custom_ops_logger_on_cpu_nodes() + + +def setup_observability(): + _setup_observability_once.do_once(_setup_observability) + + +__all__ = ["setup_observability"] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2faef359caed506872f572ceacf36678fac4f4e6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/logging/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/logging/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4a81025a613cbbbd9c1d28c805e7bdb218098b46 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/logging/__init__.py @@ -0,0 +1,40 @@ +import logging +from typing import Optional + +from ray._private.ray_logging.filters import CoreContextFilter + + +def _setup_logger(logger_name: str): + """Setup logger given the logger name. + + This function is idempotent and won't set up the same logger multiple times. It will + also skip the setup if Data logger is already setup and has handlers. + + Args: + logger_name: logger name used to get the logger. + """ + logger = logging.getLogger(logger_name) + llm_logger = logging.getLogger("ray.data") + + # Skip setup if the logger already has handlers setup or if the parent (Data + # logger) has handlers. + if logger.handlers or llm_logger.handlers: + return + + # Set up stream handler, which logs to console as plaintext. + stream_handler = logging.StreamHandler() + stream_handler.addFilter(CoreContextFilter()) + logger.addHandler(stream_handler) + logger.setLevel(logging.INFO) + logger.propagate = False + + +def get_logger(name: Optional[str] = None): + """Get a structured logger inherited from the Ray Data logger. + + Loggers by default are logging to stdout, and are expected to be scraped by an + external process. + """ + logger_name = f"ray.data.{name}" + _setup_logger(logger_name) + return logging.getLogger(logger_name) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/logging/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/logging/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0782211bd862aeef1b7477ceb62fe56e550156bd Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/logging/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/logging/__pycache__/setup.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/logging/__pycache__/setup.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8a2be6ac15bca1a687dfda156c6ef01fc37732d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/logging/__pycache__/setup.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/logging/setup.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/logging/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..0c547e4a63053d5ca457c421ac10f9768ebda650 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/logging/setup.py @@ -0,0 +1,26 @@ +import logging + +from ray._private.ray_logging.filters import CoreContextFilter +from ray._private.ray_logging.formatters import JSONFormatter + + +def _configure_stdlib_logging(): + """Configures stdlib root logger to make sure stdlib loggers (created as + `logging.getLogger(...)`) are using Ray's `JSONFormatter` with Core and Serve + context filters. + """ + + handler = logging.StreamHandler() + handler.addFilter(CoreContextFilter()) + handler.setFormatter(JSONFormatter()) + + root_logger = logging.getLogger() + # NOTE: It's crucial we reset all the handlers of the root logger, + # to make sure that logs aren't emitted twice + root_logger.handlers = [] + root_logger.addHandler(handler) + root_logger.setLevel(logging.INFO) + + +def setup_logging(): + _configure_stdlib_logging() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/usage_telemetry/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/usage_telemetry/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/usage_telemetry/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/usage_telemetry/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e29d565b4e7812640e338961ea299810ef199c8f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/usage_telemetry/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/usage_telemetry/__pycache__/usage.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/usage_telemetry/__pycache__/usage.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0bd19fd3b06841552229d0d0a3bb7f81859054f5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/usage_telemetry/__pycache__/usage.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/usage_telemetry/usage.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/usage_telemetry/usage.py new file mode 100644 index 0000000000000000000000000000000000000000..32d72a87a3574a77bd4bb3032b275b20caf43af5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/observability/usage_telemetry/usage.py @@ -0,0 +1,131 @@ +from enum import Enum +from typing import Callable, Dict, List, Tuple, Union + +import ray +from ray._common.usage.usage_lib import record_extra_usage_tag +from ray.llm._internal.batch.observability.logging import get_logger +from ray.llm._internal.common.base_pydantic import BaseModelExtended + +LLM_BATCH_TELEMETRY_NAMESPACE = "llm_batch_telemetry" +LLM_BATCH_TELEMETRY_ACTOR_NAME = "llm_batch_telemetry" + +logger = get_logger(__name__) + + +class BatchModelTelemetry(BaseModelExtended): + processor_config_name: str = "" + model_architecture: str = "" + batch_size: int = 0 + accelerator_type: str = "" + concurrency: Union[int, Tuple[int, int]] = 0 + task_type: str = "" + + # For the parallel size, 0 means not supported. + pipeline_parallel_size: int = 0 + tensor_parallel_size: int = 0 + data_parallel_size: int = 0 + + +class BatchTelemetryTags(str, Enum): + """Telemetry tags for RayLLM Batch.""" + + LLM_BATCH_PROCESSOR_CONFIG_NAME = "LLM_BATCH_PROCESSOR_CONFIG_NAME" + LLM_BATCH_MODEL_ARCHITECTURE = "LLM_BATCH_MODEL_ARCHITECTURE" + LLM_BATCH_SIZE = "LLM_BATCH_SIZE" + LLM_BATCH_ACCELERATOR_TYPE = "LLM_BATCH_ACCELERATOR_TYPE" + LLM_BATCH_CONCURRENCY = "LLM_BATCH_CONCURRENCY" + LLM_BATCH_TASK_TYPE = "LLM_BATCH_TASK_TYPE" + LLM_BATCH_PIPELINE_PARALLEL_SIZE = "LLM_BATCH_PIPELINE_PARALLEL_SIZE" + LLM_BATCH_TENSOR_PARALLEL_SIZE = "LLM_BATCH_TENSOR_PARALLEL_SIZE" + LLM_BATCH_DATA_PARALLEL_SIZE = "LLM_BATCH_DATA_PARALLEL_SIZE" + + +@ray.remote( + name=LLM_BATCH_TELEMETRY_ACTOR_NAME, + namespace=LLM_BATCH_TELEMETRY_NAMESPACE, + num_cpus=0, + lifetime="detached", +) +class _TelemetryAgent: + """Named Actor to keep the state of all deployed models and record telemetry.""" + + def __init__(self): + self._tracking_telemetries: List[BatchModelTelemetry] = [] + self._record_tag_func = record_extra_usage_tag + + def _update_record_tag_func(self, record_tag_func: Callable) -> None: + self._record_tag_func = record_tag_func + + def generate_report(self) -> Dict[str, str]: + return { + BatchTelemetryTags.LLM_BATCH_PROCESSOR_CONFIG_NAME: ",".join( + [t.processor_config_name for t in self._tracking_telemetries] + ), + BatchTelemetryTags.LLM_BATCH_MODEL_ARCHITECTURE: ",".join( + [t.model_architecture for t in self._tracking_telemetries] + ), + BatchTelemetryTags.LLM_BATCH_SIZE: ",".join( + [str(t.batch_size) for t in self._tracking_telemetries] + ), + BatchTelemetryTags.LLM_BATCH_ACCELERATOR_TYPE: ",".join( + [t.accelerator_type for t in self._tracking_telemetries] + ), + BatchTelemetryTags.LLM_BATCH_CONCURRENCY: ",".join( + [str(t.concurrency) for t in self._tracking_telemetries] + ), + BatchTelemetryTags.LLM_BATCH_TASK_TYPE: ",".join( + [t.task_type for t in self._tracking_telemetries] + ), + BatchTelemetryTags.LLM_BATCH_PIPELINE_PARALLEL_SIZE: ",".join( + [str(t.pipeline_parallel_size) for t in self._tracking_telemetries] + ), + BatchTelemetryTags.LLM_BATCH_TENSOR_PARALLEL_SIZE: ",".join( + [str(t.tensor_parallel_size) for t in self._tracking_telemetries] + ), + BatchTelemetryTags.LLM_BATCH_DATA_PARALLEL_SIZE: ",".join( + [str(t.data_parallel_size) for t in self._tracking_telemetries] + ), + } + + def record(self, telemetry: BatchModelTelemetry) -> None: + """Append and record telemetries.""" + from ray._common.usage.usage_lib import TagKey + + self._tracking_telemetries.append(telemetry) + telemetry_dict = self.generate_report() + for key, value in telemetry_dict.items(): + self._record_tag_func(TagKey.Value(key), value) + + +class TelemetryAgent: + """Wrapper around the telemetry agent that calls the remote method until + push_telemetry_report is called.""" + + def __init__(self): + try: + self.remote_telemetry_agent = ray.get_actor( + LLM_BATCH_TELEMETRY_ACTOR_NAME, namespace=LLM_BATCH_TELEMETRY_NAMESPACE + ) + except ValueError: + from ray._common.constants import HEAD_NODE_RESOURCE_NAME + from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy + + self.remote_telemetry_agent = _TelemetryAgent.options( + # Ensure the actor is created on the head node. + resources={HEAD_NODE_RESOURCE_NAME: 0.001}, + # Ensure the actor is not scheduled with the existing placement group. + scheduling_strategy=PlacementGroupSchedulingStrategy( + placement_group=None + ), + ).remote() + + def _update_record_tag_func(self, record_tag_func: Callable): + self.remote_telemetry_agent._update_record_tag_func.remote(record_tag_func) + + def push_telemetry_report(self, telemetry: BatchModelTelemetry): + ray.get(self.remote_telemetry_agent.record.remote(telemetry)) + + +def get_or_create_telemetry_agent() -> TelemetryAgent: + """Helper to get or create the telemetry agent.""" + return TelemetryAgent() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..99388bbbaaef6c25d77a8a42fc0fdd230d9fffb0 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/__init__.py @@ -0,0 +1,13 @@ +from .base import Processor, ProcessorBuilder, ProcessorConfig +from .http_request_proc import HttpRequestProcessorConfig +from .sglang_engine_proc import SGLangEngineProcessorConfig +from .vllm_engine_proc import vLLMEngineProcessorConfig + +__all__ = [ + "ProcessorConfig", + "ProcessorBuilder", + "HttpRequestProcessorConfig", + "vLLMEngineProcessorConfig", + "SGLangEngineProcessorConfig", + "Processor", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0064dbbf35b3e9f2f6482fd953298fbc79fe18a5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/__pycache__/base.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..205ac8d03608faf1ed5bc07a40bccf33c6483e57 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/__pycache__/base.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/__pycache__/http_request_proc.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/__pycache__/http_request_proc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f62ab12edc4abf724e3c7264e2cc860d0ba92add Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/__pycache__/http_request_proc.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/__pycache__/sglang_engine_proc.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/__pycache__/sglang_engine_proc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a360425e9b88003fdd586bcdd85fb604ba7ac6b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/__pycache__/sglang_engine_proc.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/__pycache__/vllm_engine_proc.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/__pycache__/vllm_engine_proc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34355460a15c43afc71ab59ebaf54cad9ae3f182 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/__pycache__/vllm_engine_proc.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/base.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/base.py new file mode 100644 index 0000000000000000000000000000000000000000..049e5c2685f50877be870ff2ff24324d9047a18c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/base.py @@ -0,0 +1,300 @@ +import logging +from collections import OrderedDict +from typing import Any, Callable, Dict, List, Optional, Type + +from pydantic import Field + +import ray +from ray.data import Dataset +from ray.data.block import UserDefinedFunction +from ray.llm._internal.batch.stages import ( + StatefulStage, + wrap_postprocess, + wrap_preprocess, +) +from ray.llm._internal.common.base_pydantic import BaseModelExtended +from ray.util.annotations import DeveloperAPI, PublicAPI + +logger = logging.getLogger(__name__) + + +# Higher values here are better for prefetching and locality. It's ok for this to be +# fairly high since streaming backpressure prevents us from overloading actors. +DEFAULT_MAX_TASKS_IN_FLIGHT = 4 + + +class ProcessorConfig(BaseModelExtended): + """The processor configuration.""" + + batch_size: int = Field( + default=32, + description="Large batch sizes are likely to saturate the compute resources " + "and could achieve higher throughput. On the other hand, small batch sizes " + "are more fault-tolerant and could reduce bubbles in the data pipeline. " + "You can tune the batch size to balance the throughput and fault-tolerance " + "based on your use case. Defaults to 32.", + ) + resources_per_bundle: Optional[Dict[str, float]] = Field( + default=None, + description="This will override the default resource bundles for placement groups. " + "You can specify a custom device label e.g. {'NPU': 1}. " + "The default resource bundle for LLM Stage is always a GPU resource i.e. {'GPU': 1}.", + ) + accelerator_type: Optional[str] = Field( + default=None, + description="The accelerator type used by the LLM stage in a processor. " + "Default to None, meaning that only the CPU will be used.", + ) + concurrency: Optional[int] = Field( + default=1, + description="The number of workers for data parallelism. Default to 1.", + ) + + experimental: Dict[str, Any] = Field( + default_factory=dict, + description="[Experimental] Experimental configurations." + "Supported keys:\n" + "`max_tasks_in_flight_per_actor`: The maximum number of tasks in flight per actor. Default to 4.", + ) + + class Config: + validate_assignment = True + arbitrary_types_allowed = True + + +class OfflineProcessorConfig(ProcessorConfig): + """The processor configuration for offline processing.""" + + model_source: str = Field( + description="The model source to use for the offline processing.", + ) + runtime_env: Optional[Dict[str, Any]] = Field( + default=None, + description="The runtime environment to use for the offline processing.", + ) + max_pending_requests: Optional[int] = Field( + default=None, + description="The maximum number of pending requests. If not specified, " + "will use the default value from the backend engine.", + ) + max_concurrent_batches: int = Field( + default=8, + description="The maximum number of concurrent batches in the engine. " + "This is to overlap the batch processing to avoid the tail latency of " + "each batch. The default value may not be optimal when the batch size " + "or the batch processing latency is too small, but it should be good " + "enough for batch size >= 32.", + ) + + # Processor stage configurations. + apply_chat_template: bool = Field( + default=True, description="Whether to apply chat template." + ) + chat_template: Optional[str] = Field( + default=None, + description="The chat template to use. This is usually not needed if the " + "model checkpoint already contains the chat template.", + ) + tokenize: bool = Field( + default=True, + description="Whether to tokenize the input before passing it to the " + "backend engine. If not, the backend engine will tokenize the prompt.", + ) + detokenize: bool = Field( + default=True, + description="Whether to detokenize the output.", + ) + has_image: bool = Field( + default=False, + description="Whether the input messages have images.", + ) + + +@PublicAPI(stability="alpha") +class Processor: + """A processor is composed of a preprocess stage, followed by one or more + processing stages, and finally a postprocess stage. We use processor as a + paradigm for processing data using LLMs. + + Args: + config: The processor config. + preprocess: An optional lambda function that takes a row (dict) as input + and returns a preprocessed row (dict). The output row must contain the + required fields for the following processing stages. + postprocess: An optional lambda function that takes a row (dict) as input + and returns a postprocessed row (dict). + """ + + # The internal used data column name ("__data"). Your input + # dataset should not contain this column. If you want to use this column + # in your input dataset, you have to derive and customize Processor. + DATA_COLUMN: str = "__data" + + def __init__( + self, + config: ProcessorConfig, + stages: List[StatefulStage], + preprocess: Optional[UserDefinedFunction] = None, + postprocess: Optional[UserDefinedFunction] = None, + ): + self.config = config + self.preprocess = None + self.postprocess = None + self.stages: OrderedDict[str, StatefulStage] = OrderedDict() + + # FIXES: https://github.com/ray-project/ray/issues/53124 + # TODO (Kourosh): Remove this once the issue is fixed + data_context = ray.data.DataContext.get_current() + data_context.wait_for_min_actors_s = 600 + # TODO: Remove this when https://github.com/ray-project/ray/issues/53169 + # is fixed. + data_context._enable_actor_pool_on_exit_hook = True + + # NOTE (Kourosh): If pre/postprocess is not provided, use the identity function. + # Wrapping is required even if they are identity functions, b/c data_column + # gets inserted/removed via wrap_preprocess/wrap_postprocess. + preprocess = preprocess or (lambda row: row) + postprocess = postprocess or (lambda row: row) + + self.preprocess = wrap_preprocess( + preprocess, + self.DATA_COLUMN, + ) + + self.postprocess = wrap_postprocess( + postprocess, + self.DATA_COLUMN, + ) + + for stage in stages: + self._append_stage(stage) + + def __call__(self, dataset: Dataset) -> Dataset: + """Execute the processor: + preprocess -> stages -> postprocess. + Note that the dataset won't be materialized during the execution. + + Args: + dataset: The input dataset. + + Returns: + The output dataset. + """ + if self.preprocess is not None: + dataset = dataset.map(self.preprocess) + + # Apply stages. + for stage in self.stages.values(): + kwargs = stage.get_dataset_map_batches_kwargs( + batch_size=self.config.batch_size, + data_column=self.DATA_COLUMN, + ) + dataset = dataset.map_batches(stage.fn, **kwargs) + + if self.postprocess is not None: + dataset = dataset.map(self.postprocess) + return dataset + + def _append_stage(self, stage: StatefulStage) -> None: + """Append a stage before postprocess. The stage class name will be used as + the stage name. If there are multiple stages with the same type, a suffix + will be added to the stage name to avoid conflicts. + + Args: + stage: The stage to append. + """ + stage_name = type(stage).__name__ + + # When a processor has multiple stages with the same type, + # append a index suffix to the stage name to avoid conflicts. + if stage_name in self.stages: + num_same_type_stage = len([s for s in self.stages.values() if s is stage]) + stage_name = f"{stage_name}_{num_same_type_stage + 1}" + self.stages[stage_name] = stage + + def list_stage_names(self) -> List[str]: + """List the stage names of this processor in order. Preprocess and postprocess + are not included. + + Returns: + A list of stage names. + """ + return list(self.stages.keys()) + + def get_stage_by_name(self, name: str) -> StatefulStage: + """Get a particular stage by its name. If the stage is not found, + a ValueError will be raised. + + Args: + name: The stage name. + + Returns: + The pipeline stage. + """ + if name in self.stages: + return self.stages[name] + raise ValueError(f"Stage {name} not found") + + def log_input_column_names(self): + """Log.info the input stage and column names of this processor. + If the input dataset does not contain these columns, you have to + provide a preprocess function to bridge the gap. + """ + name, stage = list(self.stages.items())[0] + expected_input_keys = stage.get_required_input_keys() + optional_input_keys = stage.get_optional_input_keys() + + message = f"The first stage of the processor is {name}." + if expected_input_keys: + message += "\nRequired input columns:\n" + message += "\n".join(f"\t{k}: {v}" for k, v in expected_input_keys.items()) + if optional_input_keys: + message += "\nOptional input columns:\n" + message += "\n".join(f"\t{k}: {v}" for k, v in optional_input_keys.items()) + + logger.info(message) + + +@DeveloperAPI +class ProcessorBuilder: + """Build a processor based on the configuration.""" + + _registry: Dict[str, Callable] = {} + + @classmethod + def register(cls, config_type: Type[ProcessorConfig], builder: Callable) -> None: + """A decorator to assoicate a particular pipeline config + with its build function. + """ + type_name = config_type.__name__ + if type_name in cls._registry: + raise ValueError(f"Processor config type {type_name} already registered.") + cls._registry[type_name] = builder + + @classmethod + def build( + cls, + config: ProcessorConfig, + override_stage_config_fn: Optional[Callable] = None, + **kwargs, + ) -> Processor: + """Build a processor. + + Args: + config: The processor config. + override_stage_config_fn: Custom stages configurations. + + Returns: + The built processor. + """ + type_name = type(config).__name__ + if type_name not in cls._registry: + raise ValueError( + f"Processor config type {type_name} not registered. " + f"Available types: {cls._registry.keys()}" + ) + processor = cls._registry[type_name](config, **kwargs) + if override_stage_config_fn is not None: + for name, stage in processor.stages.items(): + override_stage_config_fn(name, stage) + return processor diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/http_request_proc.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/http_request_proc.py new file mode 100644 index 0000000000000000000000000000000000000000..347e786bac80c0bae10a40dedf7a2eea323135c7 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/http_request_proc.py @@ -0,0 +1,107 @@ +"""The HTTP request processor.""" + +from typing import Any, Dict, Optional + +from pydantic import Field + +from ray.data.block import UserDefinedFunction +from ray.llm._internal.batch.observability.usage_telemetry.usage import ( + BatchModelTelemetry, + get_or_create_telemetry_agent, +) +from ray.llm._internal.batch.processor.base import ( + Processor, + ProcessorBuilder, + ProcessorConfig, +) +from ray.llm._internal.batch.stages import HttpRequestStage + + +class HttpRequestProcessorConfig(ProcessorConfig): + """The configuration for the HTTP request processor.""" + + batch_size: int = Field( + default=64, + description="The batch size.", + ) + url: str = Field( + description="The URL to query.", + ) + headers: Optional[Dict[str, Any]] = Field( + default=None, + description="The query header. Note that we will add " + "'Content-Type: application/json' to be the header for sure " + "because we only deal with requests body in JSON.", + ) + qps: Optional[int] = Field( + default=None, + description="The maximum number of requests per second to avoid rate limit. " + "If None, the request will be sent sequentially.", + ) + max_retries: int = Field( + default=0, + description="The maximum number of retries per request in the event of failures.", + ) + base_retry_wait_time_in_s: float = Field( + default=1, + description="The base wait time for a retry during exponential backoff.", + ) + # Since `session_factory` is a callable, we use type Any to avoid pydantic serialization issues + session_factory: Optional[Any] = Field( + default=None, + description="Optional session factory to be used for initializing a client session. Type: Callable[[], ClientSession]", + # exclude from JSON serialization since `session_factory` is a callable + exclude=True, + ) + + +def build_http_request_processor( + config: HttpRequestProcessorConfig, + preprocess: Optional[UserDefinedFunction] = None, + postprocess: Optional[UserDefinedFunction] = None, +) -> Processor: + """Construct a Processor and configure stages. + + Args: + config: The configuration for the processor. + preprocess: An optional lambda function that takes a row (dict) as input + and returns a preprocessed row (dict). The output row must contain the + required fields for the following processing stages. + postprocess: An optional lambda function that takes a row (dict) as input + and returns a postprocessed row (dict). + + Returns: + The constructed processor. + """ + stages = [ + HttpRequestStage( + fn_constructor_kwargs=dict( + url=config.url, + additional_header=config.headers, + qps=config.qps, + max_retries=config.max_retries, + base_retry_wait_time_in_s=config.base_retry_wait_time_in_s, + session_factory=config.session_factory, + ), + map_batches_kwargs=dict( + concurrency=config.concurrency, + ), + ) + ] + telemetry_agent = get_or_create_telemetry_agent() + telemetry_agent.push_telemetry_report( + BatchModelTelemetry( + processor_config_name=type(config).__name__, + concurrency=config.concurrency, + ) + ) + processor = Processor( + config, + stages, + preprocess=preprocess, + postprocess=postprocess, + ) + return processor + + +ProcessorBuilder.register(HttpRequestProcessorConfig, build_http_request_processor) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/sglang_engine_proc.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/sglang_engine_proc.py new file mode 100644 index 0000000000000000000000000000000000000000..1156e830177d80d22633597d8764e61164849617 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/sglang_engine_proc.py @@ -0,0 +1,184 @@ +"""The SGLang engine processor.""" + +from typing import Any, Dict, Optional + +import transformers +from pydantic import Field, root_validator + +import ray +from ray.data.block import UserDefinedFunction +from ray.llm._internal.batch.observability.usage_telemetry.usage import ( + BatchModelTelemetry, + TelemetryAgent, + get_or_create_telemetry_agent, +) +from ray.llm._internal.batch.processor.base import ( + DEFAULT_MAX_TASKS_IN_FLIGHT, + OfflineProcessorConfig, + Processor, + ProcessorBuilder, +) +from ray.llm._internal.batch.stages import ( + ChatTemplateStage, + DetokenizeStage, + SGLangEngineStage, + TokenizeStage, +) +from ray.llm._internal.batch.stages.sglang_engine_stage import SGLangTaskType +from ray.llm._internal.common.observability.telemetry_utils import DEFAULT_GPU_TYPE + +DEFAULT_MODEL_ARCHITECTURE = "UNKNOWN_MODEL_ARCHITECTURE" + + +class SGLangEngineProcessorConfig(OfflineProcessorConfig): + """The configuration for the SGLang engine processor.""" + + # SGLang stage configurations. + engine_kwargs: Dict[str, Any] = Field( + default_factory=dict, + description="The kwargs to pass to the SGLang engine. See " + "https://docs.sglang.ai/backend/server_arguments.html " + "for more details.", + ) + task_type: SGLangTaskType = Field( + default=SGLangTaskType.GENERATE, + description="The task type to use. If not specified, will use " + "'generate' by default.", + ) + + @root_validator(pre=True) + def validate_task_type(cls, values): + task_type_str = values.get("task_type", "generate") + values["task_type"] = SGLangTaskType(task_type_str) + return values + + +def build_sglang_engine_processor( + config: SGLangEngineProcessorConfig, + preprocess: Optional[UserDefinedFunction] = None, + postprocess: Optional[UserDefinedFunction] = None, + telemetry_agent: Optional[TelemetryAgent] = None, +) -> Processor: + """Construct a Processor and configure stages. + Args: + config: The configuration for the processor. + preprocess: An optional lambda function that takes a row (dict) as input + and returns a preprocessed row (dict). The output row must contain the + required fields for the following processing stages. + postprocess: An optional lambda function that takes a row (dict) as input + and returns a postprocessed row (dict). + telemetry_agent: An optional telemetry agent for collecting usage telemetry. + + Returns: + The constructed processor. + """ + ray.init(runtime_env=config.runtime_env, ignore_reinit_error=True) + + stages = [] + + if config.apply_chat_template: + stages.append( + ChatTemplateStage( + fn_constructor_kwargs=dict( + model=config.model_source, + chat_template=config.chat_template, + ), + map_batches_kwargs=dict( + zero_copy_batch=True, + concurrency=(1, config.concurrency), + batch_size=config.batch_size, + runtime_env=config.runtime_env, + ), + ) + ) + + if config.tokenize: + stages.append( + TokenizeStage( + fn_constructor_kwargs=dict( + model=config.model_source, + ), + map_batches_kwargs=dict( + zero_copy_batch=True, + concurrency=(1, config.concurrency), + batch_size=config.batch_size, + runtime_env=config.runtime_env, + ), + ) + ) + + # Core stage -- the SGLang engine. + stages.append( + SGLangEngineStage( + fn_constructor_kwargs=dict( + model=config.model_source, + engine_kwargs=config.engine_kwargs, + task_type=config.task_type, + max_pending_requests=config.max_pending_requests, + ), + map_batches_kwargs=dict( + zero_copy_batch=True, + # The number of running replicas. This is a deprecated field, but + # we need to set `max_tasks_in_flight_per_actor` through `compute`, + # which initiates enough many overlapping UDF calls per actor, to + # saturate `max_concurrency`. + compute=ray.data.ActorPoolStrategy( + min_size=config.concurrency, + max_size=config.concurrency, + max_tasks_in_flight_per_actor=config.experimental.get( + "max_tasks_in_flight_per_actor", DEFAULT_MAX_TASKS_IN_FLIGHT + ), + ), + # The number of running batches "per actor" in Ray Core level. + # This is used to make sure we overlap batches to avoid the tail + # latency of each batch. + max_concurrency=config.max_concurrent_batches, + resources=config.resources_per_bundle, + accelerator_type=config.accelerator_type, + runtime_env=config.runtime_env, + ), + ) + ) + + if config.detokenize: + stages.append( + DetokenizeStage( + fn_constructor_kwargs=dict( + model=config.model_source, + ), + map_batches_kwargs=dict( + zero_copy_batch=True, + concurrency=(1, config.concurrency), + batch_size=config.batch_size, + runtime_env=config.runtime_env, + ), + ) + ) + + hf_config = transformers.AutoConfig.from_pretrained(config.model_source) + architecture = getattr(hf_config, "architectures", [DEFAULT_MODEL_ARCHITECTURE])[0] + + telemetry_agent = get_or_create_telemetry_agent() + telemetry_agent.push_telemetry_report( + BatchModelTelemetry( + processor_config_name=type(config).__name__, + model_architecture=architecture, + batch_size=config.batch_size, + accelerator_type=config.accelerator_type or DEFAULT_GPU_TYPE, + concurrency=config.concurrency, + task_type=SGLangTaskType(config.task_type), + tensor_parallel_size=config.engine_kwargs.get("tp_size", 1), + data_parallel_size=config.engine_kwargs.get("dp_size", 1), + ) + ) + + processor = Processor( + config, + stages, + preprocess=preprocess, + postprocess=postprocess, + ) + return processor + + +ProcessorBuilder.register(SGLangEngineProcessorConfig, build_sglang_engine_processor) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/vllm_engine_proc.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/vllm_engine_proc.py new file mode 100644 index 0000000000000000000000000000000000000000..2fdd80c641d475bcd0802b3203fa4953335c96ca --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/processor/vllm_engine_proc.py @@ -0,0 +1,233 @@ +"""The vLLM engine processor.""" + +from typing import Any, Dict, Optional + +import transformers +from pydantic import Field, root_validator + +import ray +from ray.data.block import UserDefinedFunction +from ray.llm._internal.batch.observability.usage_telemetry.usage import ( + BatchModelTelemetry, + TelemetryAgent, + get_or_create_telemetry_agent, +) +from ray.llm._internal.batch.processor.base import ( + DEFAULT_MAX_TASKS_IN_FLIGHT, + OfflineProcessorConfig, + Processor, + ProcessorBuilder, +) +from ray.llm._internal.batch.stages import ( + ChatTemplateStage, + DetokenizeStage, + PrepareImageStage, + TokenizeStage, + vLLMEngineStage, +) +from ray.llm._internal.batch.stages.vllm_engine_stage import vLLMTaskType +from ray.llm._internal.common.observability.telemetry_utils import DEFAULT_GPU_TYPE +from ray.llm._internal.common.utils.download_utils import ( + NodeModelDownloadable, + download_model_files, +) + +DEFAULT_MODEL_ARCHITECTURE = "UNKNOWN_MODEL_ARCHITECTURE" + + +class vLLMEngineProcessorConfig(OfflineProcessorConfig): + """The configuration for the vLLM engine processor.""" + + # vLLM stage configurations. + engine_kwargs: Dict[str, Any] = Field( + default_factory=dict, + description="The kwargs to pass to the vLLM engine. See " + "https://docs.vllm.ai/en/latest/serving/engine_args.html " + "for more details.", + ) + task_type: vLLMTaskType = Field( + default=vLLMTaskType.GENERATE, + description="The task type to use. If not specified, will use " + "'generate' by default.", + ) + # LoRA configurations. + dynamic_lora_loading_path: Optional[str] = Field( + default=None, + description="The path to the dynamic LoRA adapter. It is expected " + "to hold subfolders each for a different lora checkpoint. If not " + "specified and LoRA is enabled, then the 'model' in LoRA " + "requests will be interpreted as model ID used by HF transformers.", + ) + + @root_validator(pre=True) + def validate_task_type(cls, values): + task_type_str = values.get("task_type", "generate") + values["task_type"] = vLLMTaskType(task_type_str) + return values + + +def build_vllm_engine_processor( + config: vLLMEngineProcessorConfig, + preprocess: Optional[UserDefinedFunction] = None, + postprocess: Optional[UserDefinedFunction] = None, + telemetry_agent: Optional[TelemetryAgent] = None, +) -> Processor: + """Construct a Processor and configure stages. + Args: + config: The configuration for the processor. + preprocess: An optional lambda function that takes a row (dict) as input + and returns a preprocessed row (dict). The output row must contain the + required fields for the following processing stages. + postprocess: An optional lambda function that takes a row (dict) as input + and returns a postprocessed row (dict). + + Returns: + The constructed processor. + """ + ray.init(runtime_env=config.runtime_env, ignore_reinit_error=True) + + stages = [] + if isinstance(config.concurrency, int): + # For CPU-only stages, we leverage auto-scaling to recycle resources. + processor_concurrency = (1, config.concurrency) + else: + raise ValueError( + "``concurrency`` is expected to be set as an integer," + f" but got: {config.concurrency}." + ) + + if config.has_image: + stages.append( + PrepareImageStage( + map_batches_kwargs=dict( + zero_copy_batch=True, + concurrency=processor_concurrency, + batch_size=config.batch_size, + ), + ) + ) + if config.apply_chat_template: + stages.append( + ChatTemplateStage( + fn_constructor_kwargs=dict( + model=config.model_source, + chat_template=config.chat_template, + ), + map_batches_kwargs=dict( + zero_copy_batch=True, + concurrency=processor_concurrency, + batch_size=config.batch_size, + runtime_env=config.runtime_env, + ), + ) + ) + + if config.tokenize: + stages.append( + TokenizeStage( + fn_constructor_kwargs=dict( + model=config.model_source, + ), + map_batches_kwargs=dict( + zero_copy_batch=True, + concurrency=processor_concurrency, + batch_size=config.batch_size, + runtime_env=config.runtime_env, + ), + ) + ) + + # Core stage -- the vLLM engine. + + stages.append( + vLLMEngineStage( + fn_constructor_kwargs=dict( + batch_size=config.batch_size, + max_concurrent_batches=config.max_concurrent_batches, + model=config.model_source, + engine_kwargs=config.engine_kwargs, + task_type=config.task_type, + max_pending_requests=config.max_pending_requests, + dynamic_lora_loading_path=config.dynamic_lora_loading_path, + ), + map_batches_kwargs=dict( + zero_copy_batch=True, + # The number of running replicas. This is a deprecated field, but + # we need to set `max_tasks_in_flight_per_actor` through `compute`, + # which initiates enough many overlapping UDF calls per actor, to + # saturate `max_concurrency`. + compute=ray.data.ActorPoolStrategy( + # vLLM start up time is significant, so if user give fixed + # concurrency, start all instances without auto-scaling. + min_size=config.concurrency, + max_size=config.concurrency, + max_tasks_in_flight_per_actor=config.experimental.get( + "max_tasks_in_flight_per_actor", DEFAULT_MAX_TASKS_IN_FLIGHT + ), + ), + # The number of running batches "per actor" in Ray Core level. + # This is used to make sure we overlap batches to avoid the tail + # latency of each batch. + max_concurrency=config.max_concurrent_batches, + resources=config.resources_per_bundle, + accelerator_type=config.accelerator_type, + runtime_env=config.runtime_env, + ), + ) + ) + + if config.detokenize: + stages.append( + DetokenizeStage( + fn_constructor_kwargs=dict( + model=config.model_source, + ), + map_batches_kwargs=dict( + zero_copy_batch=True, + concurrency=processor_concurrency, + batch_size=config.batch_size, + runtime_env=config.runtime_env, + ), + ) + ) + + model_path = download_model_files( + model_id=config.model_source, + mirror_config=None, + download_model=NodeModelDownloadable.TOKENIZER_ONLY, + download_extra_files=False, + ) + hf_config = transformers.AutoConfig.from_pretrained( + model_path, + trust_remote_code=config.engine_kwargs.get("trust_remote_code", False), + ) + + architectures = getattr(hf_config, "architectures", []) + architecture = architectures[0] if architectures else DEFAULT_MODEL_ARCHITECTURE + + telemetry_agent = get_or_create_telemetry_agent() + telemetry_agent.push_telemetry_report( + BatchModelTelemetry( + processor_config_name=type(config).__name__, + model_architecture=architecture, + batch_size=config.batch_size, + accelerator_type=config.accelerator_type or DEFAULT_GPU_TYPE, + concurrency=config.concurrency, + task_type=vLLMTaskType(config.task_type), + pipeline_parallel_size=config.engine_kwargs.get( + "pipeline_parallel_size", 1 + ), + tensor_parallel_size=config.engine_kwargs.get("tensor_parallel_size", 1), + ) + ) + + processor = Processor( + config, + stages, + preprocess=preprocess, + postprocess=postprocess, + ) + return processor + + +ProcessorBuilder.register(vLLMEngineProcessorConfig, build_vllm_engine_processor) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0742784cf5926d1c8f88de9270eaa0a8ed6f2c15 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__init__.py @@ -0,0 +1,24 @@ +from ray.llm._internal.batch.stages.base import ( + StatefulStage, + wrap_postprocess, + wrap_preprocess, +) +from ray.llm._internal.batch.stages.chat_template_stage import ChatTemplateStage +from ray.llm._internal.batch.stages.http_request_stage import HttpRequestStage +from ray.llm._internal.batch.stages.prepare_image_stage import PrepareImageStage +from ray.llm._internal.batch.stages.sglang_engine_stage import SGLangEngineStage +from ray.llm._internal.batch.stages.tokenize_stage import DetokenizeStage, TokenizeStage +from ray.llm._internal.batch.stages.vllm_engine_stage import vLLMEngineStage + +__all__ = [ + "StatefulStage", + "HttpRequestStage", + "ChatTemplateStage", + "TokenizeStage", + "DetokenizeStage", + "vLLMEngineStage", + "SGLangEngineStage", + "wrap_preprocess", + "wrap_postprocess", + "PrepareImageStage", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..595f259e261ae59c6e88b7be730f65c407563ae8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__pycache__/base.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c612a16f165c1d40512466e7b272d621f3b99555 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__pycache__/base.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__pycache__/chat_template_stage.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__pycache__/chat_template_stage.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8af4e324729ab839536a54ba246036a4b444891d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__pycache__/chat_template_stage.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__pycache__/common.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__pycache__/common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c068b193435ad183e804e40207d21fab7c449f2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__pycache__/common.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__pycache__/http_request_stage.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__pycache__/http_request_stage.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e450d8d43f14a5616e574f2a75e9467dc6a6feb7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__pycache__/http_request_stage.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__pycache__/prepare_image_stage.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__pycache__/prepare_image_stage.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba515fa98671d8ea619f12b18c66fb5f612d58ef Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__pycache__/prepare_image_stage.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__pycache__/sglang_engine_stage.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__pycache__/sglang_engine_stage.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae42ba9f26f6459f9143d1dfca3ad24da65cc6b9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__pycache__/sglang_engine_stage.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__pycache__/tokenize_stage.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__pycache__/tokenize_stage.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a55f1faf2dbd1b26e602d1d4f25abae2794b51f7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__pycache__/tokenize_stage.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__pycache__/vllm_engine_stage.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__pycache__/vllm_engine_stage.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..764ae784c860f4299db6b185d895b800bdd54284 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/__pycache__/vllm_engine_stage.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/base.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/base.py new file mode 100644 index 0000000000000000000000000000000000000000..8e57f173883892223a647a2200ef83bf73c52e90 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/base.py @@ -0,0 +1,287 @@ +"""The base class for all stages.""" +import logging +from typing import Any, AsyncIterator, Callable, Dict, List, Optional, Type + +import pyarrow +from pydantic import BaseModel, Field + +from ray.data.block import UserDefinedFunction + +logger = logging.getLogger(__name__) + + +def wrap_preprocess( + fn: UserDefinedFunction, + processor_data_column: str, +) -> Callable: + """Wrap the preprocess function, so that the output schema of the + preprocess is normalized to {processor_data_column: fn(row), other input columns}. + + Args: + fn: The function to be applied. + processor_data_column: The internal data column name of the processor. + + Returns: + The wrapped function. + """ + + def _preprocess(row: dict[str, Any]) -> dict[str, Any]: + # First put everything into processor_data_column. + outputs = {processor_data_column: row} + + # Then apply the preprocess function and add its outputs. + preprocess_output = fn(row) + outputs[processor_data_column].update(preprocess_output) + return outputs + + return _preprocess + + +def wrap_postprocess( + fn: UserDefinedFunction, + processor_data_column: str, +) -> Callable: + """Wrap the postprocess function to remove the processor_data_column. + Note that we fully rely on users to determine which columns to carry over. + + Args: + fn: The function to be applied. + processor_data_column: The internal data column name of the processor. + + Returns: + The wrapped function. + """ + + def _postprocess(row: dict[str, Any]) -> dict[str, Any]: + if processor_data_column not in row: + raise ValueError( + f"[Internal] {processor_data_column} not found in row {row}" + ) + + return fn(row[processor_data_column]) + + return _postprocess + + +class StatefulStageUDF: + """A stage UDF wrapper that processes the input and output columns + before and after the UDF. + + Args: + data_column: The internal data column name of the processor. The + __call__ method takes the data column as the input of the UDF + method, and encapsulates the output of the UDF method into the data + column for the next stage. + expected_input_keys: The expected input keys of the stage. + """ + + # The internal column name for the index of the row in the batch. + # This is used to align the output of the UDF with the input batch. + IDX_IN_BATCH_COLUMN: str = "__idx_in_batch" + + def __init__( + self, data_column: str, expected_input_keys: Optional[List[str]] = None + ): + self.data_column = data_column + self.expected_input_keys = set(expected_input_keys or []) + + async def __call__(self, batch: Dict[str, Any]) -> AsyncIterator[Dict[str, Any]]: + """A stage UDF wrapper that processes the input and output columns + before and after the UDF. The expected schema of "batch" is: + {data_column: { + dataset columns, + other intermediate columns + }, + ...other metadata columns..., + }. + + The input of the UDF will then [dataset columns and other intermediate columns]. + In addition, while the output of the UDF depends on the UDF implementation, + the output schema is expected to be + {data_column: { + dataset columns, + other intermediate columns, + UDF output columns (will override above columns if they have the same name) + }, + ...other metadata columns..., + }. + And this will become the input of the next stage. + + Examples: + Input dataset columns: {A, B, C} + Preprocess: (lambda row: {"D": row["A"] + 1}) + Input: + UDF input: {A, B, C} + UDF output: {D} + Output: {__data: {A, B, C, D}} + Stage 1: + Input: {__data: {A, B, C, D}} + UDF input: {A, B, C, D} + UDF output: {E} + Output: {__data: {A, B, C, D, E}} + Stage 2: + Input: {__data: {A, B, C, D, E}} + UDF input: {A, B, C, D, E} + UDF output: {F, E} # E is in-place updated. + Output: {__data: {A, B, C, D, E, F}} + Postprocess: (lambda row: {"G": row["F"], "A": row["A"], "E": row["E"]}) + Input: {__data: {A, B, C, D, E, F}} + UDF input: {A, B, C, D, E, F} + UDF output: {G, A, E} + Output: {G, A, E} # User chooses to keep G, A, E. + + Args: + batch: The input batch. + + Returns: + An async iterator of the outputs. + """ + # Handle the case where the batch is empty. + # FIXME: This should not happen. + if isinstance(batch, pyarrow.lib.Table) and batch.num_rows == 0: + yield {} + return + + if self.data_column not in batch: + raise ValueError( + f"[Internal] {self.data_column} not found in batch {batch}" + ) + + inputs = batch.pop(self.data_column) + if hasattr(inputs, "tolist"): + inputs = inputs.tolist() + self.validate_inputs(inputs) + + # Assign the index of the row in the batch to the idx_in_batch_column. + # This is beacuse the UDF output may be out-of-order (if asyncio.as_completed + # is used interanlly for example), and we need to carry over unused input + # columns to the next stage. Thus, we use the row index in batch to match + # the output of the UDF with the input. + for idx, row in enumerate(inputs): + row[self.IDX_IN_BATCH_COLUMN] = idx + + # Collect all outputs first, then return them in the original order + # This is a requirement set by https://github.com/ray-project/ray/pull/54190/ + not_outputed_rows = set(range(len(inputs))) + async for output in self.udf(inputs): + if self.IDX_IN_BATCH_COLUMN not in output: + raise ValueError( + "The output of the UDF must contain the column " + f"{self.IDX_IN_BATCH_COLUMN}." + ) + idx_in_batch = output.pop(self.IDX_IN_BATCH_COLUMN) + if idx_in_batch not in not_outputed_rows: + raise ValueError( + f"The row {idx_in_batch} is outputed twice. " + "This is likely due to the UDF is not one-to-one." + ) + not_outputed_rows.remove(idx_in_batch) + + # Add stage outputs to the data column of the row. + inputs[idx_in_batch].pop(self.IDX_IN_BATCH_COLUMN) + inputs[idx_in_batch].update(output) + + if not_outputed_rows: + raise ValueError(f"The rows {not_outputed_rows} are not outputed.") + + # Return all updated inputs in the original order + yield {self.data_column: inputs} + + def validate_inputs(self, inputs: List[Dict[str, Any]]): + """Validate the inputs to make sure the required keys are present. + + Args: + inputs: The inputs. + + Raises: + ValueError: If the required keys are not found. + """ + for inp in inputs: + input_keys = set(inp.keys()) + + if self.IDX_IN_BATCH_COLUMN in input_keys: + raise ValueError( + f"The input column {self.IDX_IN_BATCH_COLUMN} is reserved " + "for internal use." + ) + + if not self.expected_input_keys: + continue + + missing_required = self.expected_input_keys - input_keys + if missing_required: + raise ValueError( + f"Required input keys {missing_required} not found at the input of " + f"{self.__class__.__name__}. Input keys: {input_keys}" + ) + + async def udf(self, rows: List[Dict[str, Any]]) -> AsyncIterator[Dict[str, Any]]: + raise NotImplementedError("StageUDF must implement the udf method") + + +class StatefulStage(BaseModel): + """ + A basic building block to compose a Processor. + """ + + fn: Type[StatefulStageUDF] = Field( + description="The well-optimized stateful UDF for this stage." + ) + fn_constructor_kwargs: Dict[str, Any] = Field( + default_factory=dict, + description="The keyword arguments of the UDF constructor.", + ) + map_batches_kwargs: Dict[str, Any] = Field( + default_factory=lambda: {"concurrency": 1}, + description="The arguments of .map_batches(). Default {'concurrency': 1}.", + ) + + def get_required_input_keys(self) -> Dict[str, str]: + """The required input keys of the stage and their descriptions.""" + return {} + + def get_optional_input_keys(self) -> Dict[str, str]: + """The optional input keys of the stage and their descriptions.""" + return {} + + def get_dataset_map_batches_kwargs( + self, + batch_size: int, + data_column: str, + ) -> Dict[str, Any]: + """We separate fn and fn_constructor_kwargs in Stage for better UX, + so we combine them with other map_batches_kwargs together in this method. + + Args: + batch_size: The batch size set by the processor config. + data_column: The data column name set by the processor. + + Returns: + The dataset map_batches kwargs. + """ + kwargs = self.map_batches_kwargs.copy() + batch_size_in_kwargs = kwargs.get("batch_size", batch_size) + if batch_size_in_kwargs != batch_size: + logger.warning( + "batch_size is set to %d in map_batches_kwargs, but it will be " + "overridden by the batch size configured by the processor %d.", + batch_size_in_kwargs, + batch_size, + ) + kwargs["batch_size"] = batch_size + + kwargs.update({"fn_constructor_kwargs": self.fn_constructor_kwargs.copy()}) + if "data_column" in kwargs["fn_constructor_kwargs"]: + raise ValueError( + "'data_column' cannot be used as in fn_constructor_kwargs." + ) + + kwargs["fn_constructor_kwargs"]["data_column"] = data_column + kwargs["fn_constructor_kwargs"]["expected_input_keys"] = list( + self.get_required_input_keys().keys() + ) + return kwargs + + class Config: + arbitrary_types_allowed = True + validate_assignment = True diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/chat_template_stage.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/chat_template_stage.py new file mode 100644 index 0000000000000000000000000000000000000000..c2df95ac42540eb9afcc8cd88e7116ed85ef3ad7 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/chat_template_stage.py @@ -0,0 +1,126 @@ +"""Apply chat template stage""" + +from typing import TYPE_CHECKING, Any, AsyncIterator, Dict, List, Optional, Type, Union + +from ray.llm._internal.batch.stages.base import ( + StatefulStage, + StatefulStageUDF, +) +from ray.llm._internal.common.utils.download_utils import ( + NodeModelDownloadable, + download_model_files, +) + + +class ChatTemplateUDF(StatefulStageUDF): + def __init__( + self, + data_column: str, + expected_input_keys: List[str], + model: str, + chat_template: Optional[str] = None, + ): + """ + Initialize the ChatTemplateUDF. + + Args: + data_column: The data column name. + expected_input_keys: The expected input keys of the stage. + model: The model to use for the chat template. + chat_template: The chat template in Jinja template format. This is + usually not needed if the model checkpoint already contains the + chat template. + """ + from transformers import AutoProcessor + + super().__init__(data_column, expected_input_keys) + + # NOTE: We always use processor instead of tokenizer in this stage, + # because tokenizers of VLM models may not have chat template attribute. + # However, this may not be a reliable solution, because processors and + # tokenizers are not standardized across different models. + model_path = download_model_files( + model_id=model, + mirror_config=None, + download_model=NodeModelDownloadable.TOKENIZER_ONLY, + download_extra_files=False, + ) + if TYPE_CHECKING: + from transformers.processing_utils import ProcessorMixin + from transformers.tokenization_utils_base import PreTrainedTokenizerBase + + self.processor: Union[ + "PreTrainedTokenizerBase", "ProcessorMixin" + ] = AutoProcessor.from_pretrained(model_path, trust_remote_code=True) + self.chat_template = chat_template + + async def udf(self, batch: List[Dict[str, Any]]) -> AsyncIterator[Dict[str, Any]]: + """ + Apply chat template to the given batch. + + Args: + batch: A list of rows to send. + + Yields: + A generator of rows with the chat template applied. + """ + prompts = [] + for row in batch: + # PyArrow cannot handle the messages with images, so Ray Data + # will fallback to use pickle for serialization. In this case, + # the "messages" column is already a list of dicts and does not + # have .tolist() method. + if hasattr(row["messages"], "tolist"): + conversation = row["messages"].tolist() + else: + conversation = row["messages"] + add_generation_prompt = self._should_add_generation_prompt(conversation) + # If we don't add a generation prompt, we should continue the final message. + continue_final_message = not add_generation_prompt + prompts.append( + self.processor.apply_chat_template( + conversation, + tokenize=False, + chat_template=self.chat_template, + add_generation_prompt=add_generation_prompt, + continue_final_message=continue_final_message, + ) + ) + assert len(batch) == len(prompts) + + for row, prompt in zip(batch, prompts): + yield { + self.IDX_IN_BATCH_COLUMN: row[self.IDX_IN_BATCH_COLUMN], + "prompt": prompt, + } + + def _should_add_generation_prompt(self, conversation: List[Dict[str, Any]]) -> bool: + """Determines if the generation prompt should be added for the given conversation. + + Adds the generation prompt only if the last message is from the user. + This is useful in cases where the user provides an assistant prefill + message. + + Args: + conversation: The conversation to check. + + Returns: + True if the generation prompt should be added, False otherwise. + """ + return conversation[-1]["role"] == "user" + + +class ChatTemplateStage(StatefulStage): + """ + A stage that applies chat template. + """ + + fn: Type[StatefulStageUDF] = ChatTemplateUDF + + def get_required_input_keys(self) -> Dict[str, str]: + """The required input keys of the stage and their descriptions.""" + return { + "messages": "A list of messages in OpenAI chat format. " + "See https://platform.openai.com/docs/api-reference/chat/create " + "for details." + } diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/common.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/common.py new file mode 100644 index 0000000000000000000000000000000000000000..fb0869642991a93c1bba932ec831f1550886cf8c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/common.py @@ -0,0 +1,29 @@ +""" +Shared utilities for stages. +""" + +from typing import Any, Dict, List, Union + +import numpy as np + + +def maybe_convert_ndarray_to_list( + params: Union[np.ndarray, List[Any], Dict[str, Any]] +) -> Union[List[Any], Dict[str, Any]]: + """Convert all ndarray to list in the params. This is because Ray Data + by default converts all lists to ndarrays when passing data around, but + vLLM expects lists. + + Args: + params: The parameters to convert. + + Returns: + The converted parameters. + """ + if isinstance(params, dict): + return {k: maybe_convert_ndarray_to_list(v) for k, v in params.items()} + elif isinstance(params, list): + return [maybe_convert_ndarray_to_list(v) for v in params] + elif isinstance(params, np.ndarray): + return params.tolist() + return params diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/http_request_stage.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/http_request_stage.py new file mode 100644 index 0000000000000000000000000000000000000000..25240fbee89f33f38515342b8d91ceaacc29e1cc --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/http_request_stage.py @@ -0,0 +1,168 @@ +"""HTTP Request Stage""" + +import asyncio +import time +import traceback +from typing import Any, AsyncIterator, Callable, Dict, List, Optional, Type + +import aiohttp +import aiohttp.web_exceptions +import numpy as np +from aiohttp.client_exceptions import ClientPayloadError + +from ray.llm._internal.batch.stages.base import StatefulStage, StatefulStageUDF + + +class HttpRequestUDF(StatefulStageUDF): + RETRYABLE_STATUS_CODES = [429, 408, 504, 502, 503] + + def __init__( + self, + data_column: str, + expected_input_keys: List[str], + url: str, + additional_header: Optional[Dict[str, Any]] = None, + qps: Optional[int] = None, + max_retries: int = 0, + base_retry_wait_time_in_s: float = 1.0, + session_factory: Optional[Callable[[], aiohttp.ClientSession]] = None, + ): + """ + Initialize the HttpRequestUDF. + + Args: + data_column: The data column name. + expected_input_keys: The expected input keys of the stage. + url: The URL to send the HTTP request to. + additional_header: The additional headers to send with the HTTP request. + qps: The maximum number of requests per second. + max_retries: The maximum number of retries per request in the event of failures. We retry with exponential backoff upto this specific maximum retries. + base_retry_wait_time_in_s: The base retry wait time during exponential backoff. + session_factory: Optional session factory to be used for initializing a client session. + """ + super().__init__(data_column, expected_input_keys) + self.url = url + self.additional_header = additional_header or {} + self.qps = qps + self.max_retries = max_retries + self.base_retry_wait_time_in_s = base_retry_wait_time_in_s + self.session_factory = session_factory or aiohttp.ClientSession + + async def udf(self, batch: List[Dict[str, Any]]) -> AsyncIterator[Dict[str, Any]]: + """ + Send HTTP requests to the given URL. + + Args: + batch: A list of rows to send. + + Yields: + A generator of rows of the response of the HTTP request. + """ + # preprocess to get request body for the given batch + request_bodies = [None] * len(batch) + for row in batch: + # Normalize the row to a JSON body. + json_body = {} + for key, value in row["payload"].items(): + if isinstance(value, np.ndarray): + json_body[key] = value.tolist() + else: + json_body[key] = value + request_bodies[row[self.IDX_IN_BATCH_COLUMN]] = json_body + + async with self.session_factory() as session: + start_time = time.time() + request_count = 0 + pending_requests = [] + headers = { + "Content-Type": "application/json", + **self.additional_header, + } + + # First send all requests based on QPS + for row in batch: + # Rate limit based on qps if specified + if self.qps is not None: + request_count += 1 + expected_time = request_count / self.qps + elapsed = time.time() - start_time + if elapsed < expected_time: + await asyncio.sleep(expected_time - elapsed) + + # self.IDX_IN_BATCH_COLUMN is the index of row in the batch + json_body = request_bodies[row[self.IDX_IN_BATCH_COLUMN]] + # Create request but don't await it yet + request = session.post( + self.url, + headers=headers, + json=json_body, + ) + pending_requests.append((row[self.IDX_IN_BATCH_COLUMN], request)) + + # Now receive all responses + for idx_in_batch_column, request in pending_requests: + resp_json = None + last_exception = None + last_exception_traceback = None + for retry_count in range(self.max_retries + 1): + if retry_count > 0: + json_body = request_bodies[idx_in_batch_column] + request = session.post( + self.url, + headers=headers, + json=json_body, + ) + try: + async with await request as response: + status_code = response.status + # check status and see if it's retry worthy + if status_code in self.RETRYABLE_STATUS_CODES: + last_exception = aiohttp.web_exceptions.HTTPException( + reason=response.reason + ) + last_exception.status_code = status_code + wait_time = self.base_retry_wait_time_in_s * ( + 2**retry_count + ) + await asyncio.sleep(wait_time) + continue + resp_json = await response.json() + if self.IDX_IN_BATCH_COLUMN in resp_json: + raise ValueError( + "The response of the HTTP request must not contain " + f"the column {self.IDX_IN_BATCH_COLUMN}." + ) + break + except ( + asyncio.TimeoutError, + aiohttp.ClientConnectionError, + ClientPayloadError, + ) as e: + last_exception_traceback = traceback.format_exc() + last_exception = type(e).__name__ + wait_time = self.base_retry_wait_time_in_s * (2**retry_count) + await asyncio.sleep(wait_time) + continue + if not resp_json: + raise RuntimeError( + f"Reached maximum retries of {self.max_retries} for input row {batch[idx_in_batch_column]}. Previous Exception: {last_exception}. Full Traceback: \n{last_exception_traceback}" + ) + yield { + self.IDX_IN_BATCH_COLUMN: idx_in_batch_column, + "http_response": resp_json, + } + + +class HttpRequestStage(StatefulStage): + """ + A stage that sends HTTP requests. + """ + + fn: Type[StatefulStageUDF] = HttpRequestUDF + + def get_required_input_keys(self) -> Dict[str, str]: + """The required input keys of the stage and their descriptions.""" + return { + "payload": "The payload to send to the HTTP request. " + "It should be in JSON format." + } diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/prepare_image_stage.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/prepare_image_stage.py new file mode 100644 index 0000000000000000000000000000000000000000..8b1989863c4260b6a18bacae661e382791b1e6c9 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/prepare_image_stage.py @@ -0,0 +1,381 @@ +"""Prepare Image Stage""" +import asyncio +import base64 +import importlib +import logging +from io import BytesIO +from pathlib import Path +from typing import ( + TYPE_CHECKING, + Any, + AsyncIterator, + Dict, + List, + Mapping, + MutableMapping, + Optional, + Union, +) +from urllib.parse import urlparse + +import aiohttp +import requests + +from ray.llm._internal.batch.stages.base import ( + StatefulStage, + StatefulStageUDF, +) + +# TODO: Remove the guard once Pillow is added into the dependencies. +if TYPE_CHECKING: + from PIL import Image + +logger = logging.getLogger(__name__) + +_ImageType = Union[str, "Image.Image"] + + +class HTTPConnection: + """Adapted from vllm.connections.HTTPConnection. + Helper class to send HTTP requests. + """ + + def __init__(self, *, reuse_client: bool = True) -> None: + super().__init__() + + self.reuse_client = reuse_client + + self._sync_client: Optional[requests.Session] = None + self._async_client: Optional[aiohttp.ClientSession] = None + + def get_sync_client(self) -> requests.Session: + if self._sync_client is None or not self.reuse_client: + self._sync_client = requests.Session() + + return self._sync_client + + # NOTE: We intentionally use an async function even though it is not + # required, so that the client is only accessible inside async event loop + async def get_async_client(self) -> aiohttp.ClientSession: + if self._async_client is None or not self.reuse_client: + self._async_client = aiohttp.ClientSession() + + return self._async_client + + def _validate_http_url(self, url: str): + parsed_url = urlparse(url) + + if parsed_url.scheme not in ("http", "https"): + raise ValueError( + "Invalid HTTP URL: A valid HTTP URL " + "must have scheme 'http' or 'https'." + ) + + def _headers(self, **extras: str) -> MutableMapping[str, str]: + return {"User-Agent": "RayLLM-Batch", **extras} + + def get_response( + self, + url: str, + *, + stream: bool = False, + timeout: Optional[float] = None, + extra_headers: Optional[Mapping[str, str]] = None, + ): + self._validate_http_url(url) + + client = self.get_sync_client() + extra_headers = extra_headers or {} + + return client.get( + url, headers=self._headers(**extra_headers), stream=stream, timeout=timeout + ) + + async def get_async_response( + self, + url: str, + *, + timeout: Optional[float] = None, + extra_headers: Optional[Mapping[str, str]] = None, + ): + self._validate_http_url(url) + + client = await self.get_async_client() + extra_headers = extra_headers or {} + + return client.get(url, headers=self._headers(**extra_headers), timeout=timeout) + + def get_bytes(self, url: str, *, timeout: Optional[float] = None) -> bytes: + with self.get_response(url, timeout=timeout) as r: + r.raise_for_status() + + return r.content + + async def async_get_bytes( + self, + url: str, + *, + timeout: Optional[float] = None, + ) -> bytes: + async with await self.get_async_response(url, timeout=timeout) as r: + r.raise_for_status() + + return await r.read() + + def get_text(self, url: str, *, timeout: Optional[float] = None) -> str: + with self.get_response(url, timeout=timeout) as r: + r.raise_for_status() + + return r.text + + async def async_get_text( + self, + url: str, + *, + timeout: Optional[float] = None, + ) -> str: + async with await self.get_async_response(url, timeout=timeout) as r: + r.raise_for_status() + + return await r.text() + + def get_json(self, url: str, *, timeout: Optional[float] = None) -> str: + with self.get_response(url, timeout=timeout) as r: + r.raise_for_status() + + return r.json() + + async def async_get_json( + self, + url: str, + *, + timeout: Optional[float] = None, + ) -> str: + async with await self.get_async_response(url, timeout=timeout) as r: + r.raise_for_status() + + return await r.json() + + def download_file( + self, + url: str, + save_path: Path, + *, + timeout: Optional[float] = None, + chunk_size: int = 128, + ) -> Path: + with self.get_response(url, timeout=timeout) as r: + r.raise_for_status() + + with save_path.open("wb") as f: + for chunk in r.iter_content(chunk_size): + f.write(chunk) + + return save_path + + async def async_download_file( + self, + url: str, + save_path: Path, + *, + timeout: Optional[float] = None, + chunk_size: int = 128, + ) -> Path: + async with await self.get_async_response(url, timeout=timeout) as r: + r.raise_for_status() + + with save_path.open("wb") as f: + async for chunk in r.content.iter_chunked(chunk_size): + f.write(chunk) + + return save_path + + +class ImageProcessor: + """Download and load images.""" + + def __init__(self): + self.Image = importlib.import_module("PIL.Image") + self.http_connection = HTTPConnection() + + async def download_image_from_url(self, image_url: str) -> Optional[bytes]: + """Download the image from the Internet with up to 3 retries. + + Args: + image_url: The image URL to download. + + Returns: + The image bytes (None if failed to download). + """ + for _ in range(3): + try: + image_raw = await self.http_connection.async_get_bytes( + image_url, timeout=5 + ) + return image_raw + except Exception: + await asyncio.sleep(1) + return None + + async def load_image_bytes_from_url(self, image_urls: List[str]) -> List[bytes]: + """Load an image from a URL. + + Args: + image_urls: The image URLs to load. + + Returns: + The image bytes. + """ + return await asyncio.gather( + *[self.download_image_from_url(image_url) for image_url in image_urls] + ) + + async def fetch_images( + self, image_urls: List[str], *, image_mode: Optional[str] = None + ) -> List["Image.Image"]: + """ + Adapted from vllm.multimodal.utils.fetch_image. + Load a PIL image from a HTTP or base64 data URL. + + Args: + image_urls: A list of URLs of the images. + image_mode: The mode of the image. If None, the image is not converted. + + Returns: + A list of loaded images. + """ + + def _load_image_from_bytes(b: bytes): + image = self.Image.open(BytesIO(b)) + image.load() + return image + + def _load_image_from_data_url(image_url: str): + # Only split once and assume the second part is the base64 encoded image + _, image_base64 = image_url.split(",", 1) + return _load_image_from_bytes(base64.b64decode(image_base64)) + + # Check if all image URLs are of the same type. + if image_urls[0].startswith("http"): + image_url_prefix = "http" + elif image_urls[0].startswith("data:image"): + image_url_prefix = "data:image" + else: + raise ValueError(f"Invalid image URL prefix: {image_urls[0]}") + + if not all(url.startswith(image_url_prefix) for url in image_urls): + raise ValueError( + f"All image URLs must have the same prefix, got {image_url_prefix=}" + ) + + if image_url_prefix == "http": + image_raws = await self.load_image_bytes_from_url(image_urls) + images = [_load_image_from_bytes(image_raw) for image_raw in image_raws] + elif image_url_prefix == "data:image": + images = [_load_image_from_data_url(image_url) for image_url in image_urls] + else: + raise ValueError( + "Invalid 'image_url': A valid 'image_url' must start " + "with either 'data:image' or 'http'." + ) + + if image_mode is not None and images[0].mode != image_mode: + images = [image.convert(image_mode) for image in images] + return images + + async def process(self, images: List[_ImageType]) -> List["Image.Image"]: + """Load and resize an image for the model. + Args: + image: A list of images. + + Returns: + A list of processed images. + """ + if not images: + return [] + + # Check if all images are of the same type. + image_type = type(images[0]) + if not all(isinstance(img, image_type) for img in images): + raise ValueError(f"All images must be of the same type, got {image_type=}") + + if not issubclass(image_type, self.Image.Image): + images = await self.fetch_images(images) + return images + + +class PrepareImageUDF(StatefulStageUDF): + def __init__(self, data_column: str, expected_input_keys: List[str]): + super().__init__(data_column, expected_input_keys) + self.Image = importlib.import_module("PIL.Image") + self.image_processor = ImageProcessor() + + def extract_image_info(self, messages: List[Dict]) -> List[_ImageType]: + """Extract vision information such as image and video from chat messages. + + Args: + messages: List of chat messages. + + Returns: + List of _ImageType. + """ + + image_info: List[_ImageType] = [] + for message in messages: + if not isinstance(message["content"], list): + continue + for content in message["content"]: + if content["type"] not in ("image", "image_url"): + continue + image = content[content["type"]] + if not isinstance(image, str) and not isinstance( + image, self.Image.Image + ): + raise ValueError(f"Cannot handle image type {type(image)}") + image_info.append(image) + return image_info + + async def udf(self, batch: List[Dict[str, Any]]) -> AsyncIterator[Dict[str, Any]]: + messages = [row["messages"] for row in batch] + + # Process all images in this batch. + all_image_info = [self.extract_image_info(message) for message in messages] + flat_all_image_info = [img for imgs in all_image_info for img in imgs] + flat_all_images = await self.image_processor.process(flat_all_image_info) + + # TODO: We now use asyncio.gather to process all images in this batch, + # so the outputs here must be in order. However, it is more efficient + # to support out-of-order outputs so that we won't be blocked by slow + # downloaded images. + img_start_idx = 0 + idx_in_batch = 0 + for image_info_per_req in all_image_info: + num_images_in_req = len(image_info_per_req) + ret = {self.IDX_IN_BATCH_COLUMN: idx_in_batch} + idx_in_batch += 1 + if num_images_in_req > 0: + images = flat_all_images[ + img_start_idx : img_start_idx + num_images_in_req + ] + ret.update( + { + "image": images, + "image_sizes": [(img.width, img.height) for img in images], + } + ) + img_start_idx += num_images_in_req + yield ret + + +class PrepareImageStage(StatefulStage): + """A stage to prepare images from OpenAI chat template messages.""" + + fn: StatefulStageUDF = PrepareImageUDF + + def get_required_input_keys(self) -> Dict[str, str]: + """The required input keys of the stage and their descriptions.""" + return { + "messages": "A list of messages in OpenAI chat format. " + "See https://platform.openai.com/docs/api-reference/chat/create " + "for details." + } diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/sglang_engine_stage.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/sglang_engine_stage.py new file mode 100644 index 0000000000000000000000000000000000000000..a49ef7c18bce6250b7e62692e730af598914c542 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/sglang_engine_stage.py @@ -0,0 +1,402 @@ +"""The stage that runs SGLang engine.""" + +import asyncio +import logging +import time +import uuid +from contextlib import nullcontext +from enum import Enum +from typing import Any, AsyncIterator, Dict, List, Optional, Tuple, Type + +from pydantic import BaseModel, root_validator + +from ray.llm._internal.batch.stages.base import ( + StatefulStage, + StatefulStageUDF, +) +from ray.llm._internal.batch.stages.common import maybe_convert_ndarray_to_list + +logger = logging.getLogger(__name__) + + +class SGLangTaskType(str, Enum): + """The type of task to run on the SGLang engine.""" + + """Generate text.""" + GENERATE = "generate" + + +class SGLangEngineRequest(BaseModel): + """A request to the SGLang engine.""" + + # The request ID for the LLM engine (unique per replica). + request_id: int + # The index of the request in the batch. + idx_in_batch: int + # The input prompt. + prompt: Optional[str] + # Alternative to text. Specify the input as token IDs instead of text. + prompt_token_ids: Optional[List[int]] + # The sampling parameters (more details can be seen in https://docs.sglang.ai/backend/sampling_params.html). + params: Optional[Dict[str, Any]] + + class Config: + validate_assignment = True + arbitrary_types_allowed = True + + +class SGLangOutputData(BaseModel): + """The output of the SGLang engine.""" + + prompt: Optional[str] + prompt_token_ids: Optional[List[int]] + num_input_tokens: int + + # Generate fields. + generated_tokens: Optional[List[int]] + generated_text: Optional[str] + num_generated_tokens: int + + # Metrics fields. + metrics: Optional[Dict[str, Any]] = None + + @classmethod + def from_sglang_engine_output(cls, output: Dict[str, Any]) -> "SGLangOutputData": + """Create a SGLangOutputData from a SGLang engine output.""" + + # Set by `_generate_async`. + assert "prompt" in output + assert "prompt_token_ids" in output + + # Returned in the native output of the SGLang engine. + assert "meta_info" in output + assert "prompt_tokens" in output["meta_info"] + assert "completion_tokens" in output["meta_info"] + + data = cls( + prompt=output["prompt"], + prompt_token_ids=output["prompt_token_ids"], + num_input_tokens=output["meta_info"]["prompt_tokens"], + generated_tokens=output["output_ids"] if "output_ids" in output else None, + generated_text=output["text"] if "text" in output else None, + num_generated_tokens=output["meta_info"]["completion_tokens"], + ) + + return data + + class Config: + validate_assignment = True + arbitrary_types_allowed = True + + +class SGLangEngineWrapper: + """Wrapper around the SGLang engine to handle async requests. + + Args: + *args: The positional arguments for the engine. + max_pending_requests: The maximum number of pending requests in the queue. + **kwargs: The keyword arguments for the engine. + """ + + def __init__( + self, + idx_in_batch_column: str, + max_pending_requests: int = -1, + **kwargs, + ): + self.request_id = 0 + self.idx_in_batch_column = idx_in_batch_column + self.task_type = kwargs.pop("task", SGLangTaskType.GENERATE) + self.model = kwargs.pop("model", None) + assert self.model is not None + # We need to rename the `model` to `model_path` for SGLang. + kwargs["model_path"] = self.model + + # Set the skip_tokenizer_init to True by default for SGLang engine + # because we will not use the tokenizer/detokenizer in SGLang engine + # by default. + self.skip_tokenizer_init = kwargs.pop("skip_tokenizer_init", True) + kwargs["skip_tokenizer_init"] = self.skip_tokenizer_init + + try: + import sglang + except ImportError as e: + raise ImportError( + "SGLang is not installed or failed to import. Please run " + "`pip install sglang[all]` to install required dependencies." + ) from e + + # Initialize the SGLang engine + self.engine = sglang.Engine(**kwargs) + + # The performance gets really bad if there are too many requests in the pending queue. + # We work around it with semaphore to limit the number of concurrent requests in the engine. + self.max_pending_requests = max_pending_requests + if self.max_pending_requests > 0: + self.semaphore = asyncio.Semaphore(self.max_pending_requests) + else: + # Use contextlib.nullcontext which works for both sync and async contexts. + self.semaphore = nullcontext() + + async def _prepare_llm_request(self, row: Dict[str, Any]) -> SGLangEngineRequest: + """Prepare the inputs for LLM inference. + + Args: + row: The row. + + Returns: + A single SGLangEngineRequest. + """ + prompt = row.pop("prompt") + + if "tokenized_prompt" in row: + tokenized_prompt = row.pop("tokenized_prompt").tolist() + else: + tokenized_prompt = None + + # Prepare sampling parameters. + if self.task_type == SGLangTaskType.GENERATE: + params = maybe_convert_ndarray_to_list(row.pop("sampling_params")) + else: + raise ValueError(f"Unsupported task type: {self.task_type}") + + if tokenized_prompt is not None and not self.skip_tokenizer_init: + raise ValueError( + "To use a token-in-token-out mode of SGLang Engine, please set engine_kwargs['skip_tokenizer_init'] to True." + ) + + request = SGLangEngineRequest( + request_id=self.request_id, + idx_in_batch=row[self.idx_in_batch_column], + prompt=prompt, + prompt_token_ids=tokenized_prompt, + params=params, + ) + self.request_id += 1 + return request + + async def generate_async( + self, row: Dict[str, Any] + ) -> Tuple[SGLangEngineRequest, Dict[str, Any]]: + """Process a single request. + + Args: + request: The request. + + Returns: + A tuple of index in batch, request output and bypassed custom fields. + """ + request = await self._prepare_llm_request(row) + + async with self.semaphore: + output = await self._generate_async(request) + + output_data = SGLangOutputData.from_sglang_engine_output(output) + return request, output_data.model_dump() + + async def _generate_async(self, request: SGLangEngineRequest) -> Any: + """Process a single request. + + Args: + request: The request. + + Returns: + The output of the request. + """ + + # Send the request to the LLM engine. + stream = await self.engine.async_generate( + prompt=request.prompt, + input_ids=request.prompt_token_ids, + sampling_params=request.params, + stream=True, + ) + + # Consume the stream until the request is finished. + async for output in stream: + if output["meta_info"]["finish_reason"] is not None: + output["prompt"] = request.prompt + output["prompt_token_ids"] = request.prompt_token_ids + return output + + raise RuntimeError( + "[SGLang] The request is not finished. This should not happen. Please report this issue to the Ray team." + ) + + def shutdown(self): + """Shutdown the SGLang engine.""" + if hasattr(self.engine, "shutdown"): + logger.info("Shutting down SGLang engine") + self.engine.shutdown() + + +class SGLangEngineStageUDF(StatefulStageUDF): + def __init__( + self, + data_column: str, + expected_input_keys: List[str], + model: str, + engine_kwargs: Dict[str, Any], + task_type: SGLangTaskType = SGLangTaskType.GENERATE, + max_pending_requests: Optional[int] = None, + ): + """ + Initialize the SGLangEngineStageUDF. + + Args: + data_column: The data column name. + expected_input_keys: The expected input keys of the stage. + model: The path to the model to use for the SGLang engine. + engine_kwargs: The kwargs to pass to the SGLang engine. + task_type: The task to use for the SGLang engine (e.g., "generate", "embed", "reward"). + max_pending_requests: The maximum number of pending requests. If None, + it will be set to a default value based on engine settings. + """ + super().__init__(data_column, expected_input_keys) + self.model = model + + # Setup SGLang engine kwargs. + self.task_type = task_type + self.engine_kwargs = self.normalize_engine_kwargs(task_type, engine_kwargs) + + # Set up the max pending requests. + # Disable the semaphore if max_pending_requests is not set. + self.max_pending_requests = max_pending_requests or -1 + if self.max_pending_requests > 0: + logger.info("Max pending requests is set to %d", self.max_pending_requests) + + # Create an LLM engine. + self.llm = SGLangEngineWrapper( + model=self.model, + idx_in_batch_column=self.IDX_IN_BATCH_COLUMN, + max_pending_requests=self.max_pending_requests, + **self.engine_kwargs, + ) + + def normalize_engine_kwargs( + self, + task_type: SGLangTaskType, + engine_kwargs: Dict[str, Any], + ) -> Dict[str, Any]: + """ + Normalize the engine kwargs. + + Args: + task_type: The task to use for the SGLang engine (e.g., "generate", etc). + engine_kwargs: The kwargs to normalize. + + Returns: + The normalized kwargs. + """ + # Remove model from engine kwargs if set. + model = engine_kwargs.pop("model", None) + if model is not None and model != self.model: + logger.warning( + "The model set in engine kwargs (%s) is different from the " + "stage (%s). Please remove 'model' from engine kwargs.", + model, + self.model, + ) + + # Override the task if it is different from the stage. + task = SGLangTaskType(engine_kwargs.get("task", task_type)) + if task != task_type: + logger.warning( + "The task set in engine kwargs (%s) is different from the " + "stage (%s). Overriding the task in engine kwargs to %s.", + task, + task_type, + task_type, + ) + engine_kwargs["task"] = task_type + return engine_kwargs + + async def udf(self, batch: List[Dict[str, Any]]) -> AsyncIterator[Dict[str, Any]]: + """Run the SGLang engine. + + Args: + batch: A list of rows to run the SGLang engine on. + + Returns: + The response of the SGLang engine. + """ + batch_uuid = uuid.uuid4() + t = time.perf_counter() + + tasks = [asyncio.create_task(self.llm.generate_async(row)) for row in batch] + + time_taken = -1.0 + for resp in asyncio.as_completed(tasks): + request, output = await resp + time_taken = time.perf_counter() - t + + yield { + **output, + "request_id": request.request_id, + self.IDX_IN_BATCH_COLUMN: request.idx_in_batch, + "batch_uuid": batch_uuid.hex, + "time_taken_llm": time_taken, + "params": str(request.params), + } + + logger.info( + "[SGLang] Elapsed time for batch %s with size %d: %s", + batch_uuid.hex, + len(batch), + time_taken, + ) + + def __del__(self): + if hasattr(self, "llm"): + self.llm.shutdown() + + +class SGLangEngineStage(StatefulStage): + """ + A stage that runs SGLang engine. + """ + + fn: Type[StatefulStageUDF] = SGLangEngineStageUDF + + @root_validator(pre=True) + def post_init(cls, values): + """Post-initialize the stage. Specifically, + this function determines the num_gpus and Ray remote args + for the .map_batches() call in this stage. + + Args: + values: The raw stage values. + Returns: + The updated values. + """ + map_batches_kwargs = values["map_batches_kwargs"] + accelerator_type = map_batches_kwargs.get("accelerator_type", "") + fn_constructor_kwargs = values["fn_constructor_kwargs"] + engine_kwargs = fn_constructor_kwargs.get("engine_kwargs", {}) + + ray_remote_args = {} + if accelerator_type: + ray_remote_args["accelerator_type"] = accelerator_type + + # Setup num_gpus required per SGLang engine. + tp_size = engine_kwargs.get("tp_size", 1) + dp_size = engine_kwargs.get("dp_size", 1) + num_gpus = tp_size * dp_size + + map_batches_kwargs["num_gpus"] = num_gpus + map_batches_kwargs.update(ray_remote_args) + return values + + def get_required_input_keys(self) -> Dict[str, str]: + """The required input keys of the stage and their descriptions.""" + ret = {"prompt": "The text prompt (str)."} + task_type = self.fn_constructor_kwargs.get("task_type", SGLangTaskType.GENERATE) + if task_type == SGLangTaskType.GENERATE: + ret[ + "sampling_params" + ] = "The sampling parameters. See https://docs.sglang.ai/backend/sampling_params.htmlfor details." + return ret + + def get_optional_input_keys(self) -> Dict[str, str]: + """The optional input keys of the stage and their descriptions.""" + return {} diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/tokenize_stage.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/tokenize_stage.py new file mode 100644 index 0000000000000000000000000000000000000000..b6b64e29052e212b06d8a5ac4d6171b307fd3ec5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/tokenize_stage.py @@ -0,0 +1,142 @@ +"""Tokenize and detokenize stage""" + +from typing import Any, AsyncIterator, Dict, List, Type + +from ray.llm._internal.batch.stages.base import ( + StatefulStage, + StatefulStageUDF, +) +from ray.llm._internal.batch.utils import get_cached_tokenizer +from ray.llm._internal.common.utils.download_utils import ( + NodeModelDownloadable, + download_model_files, +) + + +class TokenizeUDF(StatefulStageUDF): + def __init__( + self, + data_column: str, + expected_input_keys: List[str], + model: str, + ): + """ + Initialize the TokenizeUDF. + + Args: + data_column: The data column name. + expected_input_keys: The expected input keys of the stage. + model: The model to use for the chat template. + """ + from transformers import AutoTokenizer + + super().__init__(data_column, expected_input_keys) + model_path = download_model_files( + model_id=model, + mirror_config=None, + download_model=NodeModelDownloadable.TOKENIZER_ONLY, + download_extra_files=False, + ) + self.tokenizer = get_cached_tokenizer( + AutoTokenizer.from_pretrained( + model_path, + trust_remote_code=True, + ) + ) + + async def udf(self, batch: List[Dict[str, Any]]) -> AsyncIterator[Dict[str, Any]]: + """ + Tokenize the given batch. + + Args: + batch: A list of rows to send. + + Yields: + A generator of rows with the tokenized prompt. + """ + for row, prompt_token_ids in zip( + batch, + self.tokenizer([row["prompt"] for row in batch])["input_ids"], + ): + yield { + self.IDX_IN_BATCH_COLUMN: row[self.IDX_IN_BATCH_COLUMN], + "tokenized_prompt": prompt_token_ids, + } + + +class TokenizeStage(StatefulStage): + """ + A stage that tokenizes the input. + """ + + fn: Type[StatefulStageUDF] = TokenizeUDF + + def get_required_input_keys(self) -> Dict[str, str]: + """The required input keys of the stage and their descriptions.""" + return {"prompt": "The text prompt (str) to tokenize."} + + +class DetokenizeUDF(StatefulStageUDF): + def __init__( + self, + data_column: str, + expected_input_keys: List[str], + model: str, + ): + """ + Initialize the DetokenizeUDF. + + Args: + data_column: The data column name. + expected_input_keys: The expected input keys of the stage. + model: The model to use for the chat template. + """ + from transformers import AutoTokenizer + + super().__init__(data_column, expected_input_keys) + model_path = download_model_files( + model_id=model, + mirror_config=None, + download_model=NodeModelDownloadable.TOKENIZER_ONLY, + download_extra_files=False, + ) + self.tokenizer = get_cached_tokenizer( + AutoTokenizer.from_pretrained( + model_path, + trust_remote_code=True, + ) + ) + + async def udf(self, batch: List[Dict[str, Any]]) -> AsyncIterator[Dict[str, Any]]: + """ + Detokenize the given batch. + + Args: + batch: A list of rows to send. + + Yields: + A generator of rows with the detokenized prompt. + """ + for row, generated_text in zip( + batch, + self.tokenizer.batch_decode( + [row["generated_tokens"] for row in batch], + skip_special_tokens=True, + ), + ): + yield { + self.IDX_IN_BATCH_COLUMN: row[self.IDX_IN_BATCH_COLUMN], + "generated_text": generated_text, + } + + +class DetokenizeStage(StatefulStage): + """ + A stage that detokenizes the input. + """ + + fn: Type[StatefulStageUDF] = DetokenizeUDF + + def get_required_input_keys(self) -> Dict[str, str]: + """The required input keys of the stage and their descriptions.""" + return {"generated_tokens": "A list of generated tokens (int) to detokenize."} diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/vllm_engine_stage.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/vllm_engine_stage.py new file mode 100644 index 0000000000000000000000000000000000000000..481da600da7b9623db4400a1be2671042b22c2a3 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/stages/vllm_engine_stage.py @@ -0,0 +1,707 @@ +"""The stage that runs vLLM engine.""" + +import asyncio +import dataclasses +import logging +import math +import time +import uuid +from enum import Enum +from functools import partial +from typing import Any, AsyncIterator, Dict, List, Optional, Tuple, Type + +import numpy as np +from pydantic import BaseModel, Field, root_validator + +import ray +from ray.llm._internal.batch.stages.base import ( + StatefulStage, + StatefulStageUDF, +) +from ray.llm._internal.batch.stages.common import maybe_convert_ndarray_to_list +from ray.llm._internal.common.utils.cloud_utils import is_remote_path +from ray.llm._internal.common.utils.download_utils import ( + NodeModelDownloadable, + download_model_files, +) +from ray.llm._internal.common.utils.lora_utils import download_lora_adapter +from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy + +logger = logging.getLogger(__name__) + + +class vLLMTaskType(str, Enum): + """The type of task to run on the vLLM engine.""" + + """Generate text.""" + GENERATE = "generate" + + """Generate embeddings.""" + EMBED = "embed" + + +class vLLMEngineRequest(BaseModel): + """A request to the vLLM engine.""" + + # The request ID for the LLM engine (unique per replica). + request_id: int + # The index of the request in the batch. + idx_in_batch: int + # The full prompt string (with chat template applied if any). + prompt: str + # The images inputs for the multimodal model. Use Any to avoid importing PIL. + images: List[Any] + # The tokenized prompt IDs. If None, then the string prompt will be + # tokenized by the LLM engine. This is not recommended for performance reasons. + prompt_token_ids: Optional[List[int]] + # The sampling or pooling parameters. Use Any to avoid importing vLLM. + params: Any + # LoRA request. + lora_request: Optional[Any] = None + + class Config: + validate_assignment = True + arbitrary_types_allowed = True + + +class vLLMOutputData(BaseModel): + """The output of the vLLM engine.""" + + prompt: str + prompt_token_ids: Optional[List[int]] + num_input_tokens: int + + # Generate fields. + generated_tokens: List[int] = Field(default_factory=list) + generated_text: str = Field(default="") + num_generated_tokens: int = Field(default=0) + + # Embed fields. The type should be torch.Tensor, but we use Any to avoid + # importing torch because of an error in sphinx-build with an unknown reason. + embeddings: Optional[Any] = None + + # Metrics fields. + metrics: Optional[Dict[str, Any]] = None + + @classmethod + def from_vllm_engine_output(cls, output: Any) -> "vLLMOutputData": + """Create a vLLMOutputData from a vLLM engine output.""" + + prompt_token_ids = output.prompt_token_ids + if isinstance(prompt_token_ids, np.ndarray): + prompt_token_ids = prompt_token_ids.tolist() + + data = cls( + prompt=output.prompt, + prompt_token_ids=prompt_token_ids, + num_input_tokens=len(prompt_token_ids), + ) + + import vllm + + if isinstance(output, vllm.outputs.RequestOutput): + metrics = {} + if output.metrics is not None: + metrics = dict(dataclasses.asdict(output.metrics)) + data.metrics = metrics + data.generated_tokens = output.outputs[0].token_ids + data.generated_text = output.outputs[0].text + data.num_generated_tokens = len(output.outputs[0].token_ids) + elif isinstance(output, vllm.outputs.PoolingRequestOutput): + data.embeddings = output.outputs.data.cpu() + else: + raise ValueError(f"Unknown output type: {type(output)}") + + return data + + class Config: + validate_assignment = True + arbitrary_types_allowed = True + + +class vLLMEngineWrapper: + """Wrapper around the vLLM engine to handle async requests. + + Args: + *args: The positional arguments for the engine. + max_pending_requests: The maximum number of pending requests in the queue. + dynamic_lora_loading_path: The S3 path to the dynamic LoRA adapter. + **kwargs: The keyword arguments for the engine. + """ + + def __init__( + self, + idx_in_batch_column: str, + max_pending_requests: int = -1, + dynamic_lora_loading_path: Optional[str] = None, + **kwargs, + ): + self.request_id = 0 + self.idx_in_batch_column = idx_in_batch_column + self.task_type = kwargs.get("task", vLLMTaskType.GENERATE) + + # Use model_source in kwargs["model"] because "model" is actually + # the model source in vLLM. + self.model = kwargs.pop("model", None) + self.model_source = kwargs.pop("model_source", None) + assert self.model is not None and self.model_source is not None + kwargs["model"] = self.model_source + + # LoRA related. + self.dynamic_lora_loading_path = dynamic_lora_loading_path + self.lora_lock = asyncio.Lock() + self.lora_name_to_request = {} + + # Convert the task type back to a string to pass to the engine. + kwargs["task"] = self.task_type.value + + try: + import vllm + except ImportError as e: + raise ImportError( + "vLLM is not installed or failed to import. Please run " + "`pip install ray[llm]` to install required dependencies." + ) from e + + # Construct PoolerConfig if override_pooler_config is specified. + if self.task_type == vLLMTaskType.EMBED and "override_pooler_config" in kwargs: + kwargs["override_pooler_config"] = vllm.config.PoolerConfig( + **kwargs["override_pooler_config"] + ) + + # Initialize the vLLM engine. + engine_args = vllm.AsyncEngineArgs( + **kwargs, + ) + # create_engine_config will set default values including `max_num_seqs`. + self._vllm_config = engine_args.create_engine_config() + self.engine = vllm.AsyncLLMEngine.from_engine_args(engine_args) + + # Determine the generate function based on vLLM v0 or v1. + self.vllm_use_v1 = vllm.envs.VLLM_USE_V1 + if self.vllm_use_v1: + self._generate_async = self.generate_async_v1 + else: + self._generate_async = self.generate_async_v0 + + # The performance gets really bad if there are too many requests in the pending queue. + # We work around it with semaphore to limit the number of concurrent requests in the engine. + self.max_pending_requests = max_pending_requests + if self.max_pending_requests > 0: + self.semaphore = asyncio.Semaphore(self.max_pending_requests) + else: + self.semaphore = asyncio.NullContext() + + async def _maybe_get_lora_request( + self, + row: Dict[str, Any], + ) -> Optional[Any]: + """Get the LoRA request for the given row. + Specifically, if the model name is given and is different from the model + set in the config, then this request has LoRA. + + Args: + row: The row. + + Returns: + The LoRA request (vllm.lora.request.LoRARequest), + or None if there is no LoRA. We use Any in type hint to + pass doc build in the environment without vLLM. + """ + import vllm + + lora_request = None + if "model" in row and row["model"] != self.model: + + lora_name = row["model"] + if lora_name not in self.lora_name_to_request: + if is_remote_path(lora_name): + raise ValueError( + "LoRA name cannot be a remote path (s3:// or gs://). " + "Please specify dynamic_lora_loading_path in the processor config." + ) + + async with self.lora_lock: + if lora_name not in self.lora_name_to_request: + # Load a new LoRA adapter if it is not loaded yet. + lora_path = download_lora_adapter( + lora_name, + remote_path=self.dynamic_lora_loading_path, + ) + logger.info( + "Downloaded LoRA adapter for %s to %s", lora_name, lora_path + ) + lora_request = vllm.lora.request.LoRARequest( + lora_name=lora_name, + # LoRA ID starts from 1. + lora_int_id=len(self.lora_name_to_request) + 1, + lora_path=lora_path, + ) + self.lora_name_to_request[lora_name] = lora_request + lora_request = self.lora_name_to_request[lora_name] + return lora_request + + async def _prepare_llm_request(self, row: Dict[str, Any]) -> vLLMEngineRequest: + """Prepare the inputs for LLM inference. + + Args: + row: The row. + + Returns: + A single vLLMEngineRequest. + """ + prompt = row.pop("prompt") + + if "tokenized_prompt" in row: + tokenized_prompt = maybe_convert_ndarray_to_list( + row.pop("tokenized_prompt") + ) + else: + tokenized_prompt = None + + if "image" in row: + image = row.pop("image") + else: + image = [] + + lora_request = await self._maybe_get_lora_request(row) + + # Prepare sampling parameters. + import vllm + + if self.task_type == vLLMTaskType.GENERATE: + sampling_params = row.pop("sampling_params") + if "guided_decoding" in sampling_params: + guided_decoding = vllm.sampling_params.GuidedDecodingParams( + **maybe_convert_ndarray_to_list( + sampling_params.pop("guided_decoding") + ) + ) + else: + guided_decoding = None + params = vllm.SamplingParams( + **maybe_convert_ndarray_to_list(sampling_params), + guided_decoding=guided_decoding, + ) + elif self.task_type == vLLMTaskType.EMBED: + params = vllm.PoolingParams(task=self.task_type.value) + else: + raise ValueError(f"Unsupported task type: {self.task_type}") + + request = vLLMEngineRequest( + request_id=self.request_id, + idx_in_batch=row[self.idx_in_batch_column], + prompt=prompt, + prompt_token_ids=tokenized_prompt, + images=image, + params=params, + lora_request=lora_request, + ) + self.request_id += 1 + return request + + async def generate_async( + self, row: Dict[str, Any] + ) -> Tuple[vLLMEngineRequest, Dict[str, Any]]: + """Process a single request. + + Args: + request: The request. + + Returns: + A tuple of index in batch, request output and bypassed custom fields. + """ + request = await self._prepare_llm_request(row) + + async with self.semaphore: + output = await self._generate_async(request) + + output_data = vLLMOutputData.from_vllm_engine_output(output) + return request, output_data.model_dump() + + async def generate_async_v0(self, request: vLLMEngineRequest) -> Any: + """Process a single request. + + Args: + request: The request. + + Returns: + The output of the request. + """ + + import vllm + + if request.images: + # FIXME: The latest vLLM does not support multi-modal inputs + # with tokenized prompt. + assert request.prompt + llm_prompt = vllm.inputs.data.TextPrompt( + prompt=request.prompt, multi_modal_data={"image": request.images} + ) + else: + if request.prompt_token_ids is not None: + llm_prompt = vllm.inputs.data.TokensPrompt( + prompt_token_ids=request.prompt_token_ids + ) + else: + assert request.prompt + llm_prompt = vllm.inputs.data.TextPrompt(prompt=request.prompt) + + # Send the request to the LLM engine. + stream = await self.engine.add_request( + request_id=str(request.request_id), + prompt=llm_prompt, + params=request.params, + lora_request=request.lora_request, + ) + # Consume the stream until the request is finished. + async for request_output in stream: + if request_output.finished: + # Bypass the original full prompt. + request_output.prompt = request.prompt + return request_output + + raise RuntimeError( + "[vLLM] The request is not finished. This should not happen. Please report this issue to the Ray team." + ) + + async def generate_async_v1(self, request: vLLMEngineRequest) -> Any: + """Process a single request. + + Args: + request: The request. + + Returns: + The output of the request. + """ + + # NOTE: vLLM v1 tighly couples tokenizer and detokenizer to the engine. + # We should investigate whether decoupling them could lead to better + # performance. Given that v1 tokenizer and detokenizer are already + # in a separate process, the benefit of decoupling them in the Processor + # may be limited. + assert request.prompt + import vllm + + multi_modal_data = {"image": request.images} if request.images else None + llm_prompt = vllm.inputs.data.TextPrompt( + prompt=request.prompt, multi_modal_data=multi_modal_data + ) + + # Send the request to the LLM engine. + stream = self.engine.generate( + request_id=str(request.request_id), + prompt=llm_prompt, + sampling_params=request.params, + ) + + # Consume the stream until the request is finished. + async for request_output in stream: + if request_output.finished: + # Bypass the original full prompt. + request_output.prompt = request.prompt + return request_output + + raise RuntimeError( + "[vLLM] The request is not finished. This should not happen. Please report this issue to the Ray team." + ) + + def shutdown(self): + """Shutdown the vLLM v1 engine. This kills child processes forked + by the vLLM engine. If not called, the child processes will be + orphaned and will not be killed when the parent process exits, + and they won't be able to be tracked by Ray anymore. + """ + if hasattr(self.engine, "shutdown"): + logger.info("Shutting down vLLM engine") + self.engine.shutdown() + + def get_scheduler_config(self): + return self._vllm_config.scheduler_config + + +class vLLMEngineStageUDF(StatefulStageUDF): + def __init__( + self, + data_column: str, + expected_input_keys: List[str], + batch_size: int, + max_concurrent_batches: int, + model: str, + engine_kwargs: Dict[str, Any], + task_type: vLLMTaskType = vLLMTaskType.GENERATE, + max_pending_requests: Optional[int] = None, + dynamic_lora_loading_path: Optional[str] = None, + ): + """ + Initialize the vLLMEngineStageUDF. + + Args: + data_column: The data column name. + expected_input_keys: The expected input keys of the stage. + model: The model to use for the vLLM engine. + engine_kwargs: The kwargs to pass to the vLLM engine. + task_type: The task to use for the vLLM engine (e.g., "generate", "embed", etc). + max_pending_requests: The maximum number of pending requests. If None, + it will be set to 1.1 * max_num_seqs * pipeline_parallel_size. + dynamic_lora_loading_path: The path to the dynamic LoRA adapter. It is expected + to hold subfolders each for a different lora checkpoint. + """ + super().__init__(data_column, expected_input_keys) + self.model = model + + # Setup vLLM engine kwargs. + self.task_type = task_type + self.engine_kwargs = self.normalize_engine_kwargs(task_type, engine_kwargs) + + # Set up the max pending requests. + pp_size = self.engine_kwargs.get("pipeline_parallel_size", 1) + self.max_pending_requests = max_pending_requests or math.ceil( + self.engine_kwargs.get("max_num_seqs", 128) * pp_size * 1.1 + ) + if self.max_pending_requests > 0: + logger.info("Max pending requests is set to %d", self.max_pending_requests) + + # Download the model if needed. + model_source = download_model_files( + model_id=self.model, + mirror_config=None, + download_model=NodeModelDownloadable.MODEL_AND_TOKENIZER, + download_extra_files=False, + ) + + # Create an LLM engine. + self.llm = vLLMEngineWrapper( + model=self.model, + model_source=model_source, + idx_in_batch_column=self.IDX_IN_BATCH_COLUMN, + disable_log_requests=True, + max_pending_requests=self.max_pending_requests, + dynamic_lora_loading_path=dynamic_lora_loading_path, + **self.engine_kwargs, + ) + + max_num_seqs = self.llm.get_scheduler_config().max_num_seqs + if batch_size * max_concurrent_batches < max_num_seqs: + logger.warning( + f"The product of batch_size ({batch_size}) and " + f"max_concurrent_batches ({max_concurrent_batches}) is too small " + "to saturate vLLM engine. This may lead to suboptimal " + "throughput. Please increase max_concurrent_batches to at least " + f"{math.ceil(max_num_seqs / batch_size)}." + ) + + def normalize_engine_kwargs( + self, + task_type: vLLMTaskType, + engine_kwargs: Dict[str, Any], + ) -> Dict[str, Any]: + """ + Normalize the engine kwargs. + + Args: + task_type: The task to use for the vLLM engine (e.g., "generate", "embed", etc). + engine_kwargs: The kwargs to normalize. + + Returns: + The normalized kwargs. + """ + # Remove model from engine kwargs if set. + model = engine_kwargs.pop("model", None) + if model is not None and model != self.model: + logger.warning( + "The model set in engine kwargs (%s) is different from the " + "stage (%s). Please remove 'model' from engine kwargs.", + model, + self.model, + ) + + # Override the task if it is different from the stage. + task = vLLMTaskType(engine_kwargs.get("task", task_type)) + if task != task_type: + logger.warning( + "The task set in engine kwargs (%s) is different from the " + "stage (%s). Overriding the task in engine kwargs to %s.", + task, + task_type, + task_type, + ) + engine_kwargs["task"] = task_type + return engine_kwargs + + async def udf(self, batch: List[Dict[str, Any]]) -> AsyncIterator[Dict[str, Any]]: + """Run the vLLM engine. + + Args: + batch: A list of rows to run the vLLM engine on. + + Returns: + The response of the vLLM engine. + """ + batch_uuid = uuid.uuid4() + t = time.perf_counter() + + tasks = [asyncio.create_task(self.llm.generate_async(row)) for row in batch] + + time_taken = -1.0 + for resp in asyncio.as_completed(tasks): + request, output = await resp + time_taken = time.perf_counter() - t + + yield { + **output, + "request_id": request.request_id, + self.IDX_IN_BATCH_COLUMN: request.idx_in_batch, + "batch_uuid": batch_uuid.hex, + "time_taken_llm": time_taken, + "params": str(request.params), + } + + # TODO: Add metrics to the UDf wrapper so that we don't need + # timer in UDFs anymore. + logger.info( + "[vLLM] Elapsed time for batch %s with size %d: %s", + batch_uuid.hex, + len(batch), + time_taken, + ) + + # Log engine stats after each batch is done conditioned on the flag + # passed to the engine. + if not self.engine_kwargs.get("disable_log_stats", False): + await self.llm.engine.do_log_stats() + + def __del__(self): + if hasattr(self, "llm"): + # Kill the engine processes. + self.llm.shutdown() + + +def _ray_scheduling_strategy_fn( + num_bundles_per_replica: int, + accelerator_type: Optional[str] = None, + resources_per_bundle: Optional[Dict[str, float]] = None, +): + """Create a Ray scheduling strategy for the engine. + + Args: + num_bundles_per_replica: The number of device bundles per + engine replica. + accelerator_type: The accelerator type. If None, the + accelerator_type label will not be set. + resources_per_bundle: The custom resources per bundle. + If None, we default to 1xGPU + 1xCPU bundle. + + Returns: + The Ray scheduling strategy. + """ + + def _get_bundle() -> Dict[str, float]: + bundle = {} + # Custom resources + if resources_per_bundle: + bundle = resources_per_bundle + else: + # GPU bundles + bundle = {"GPU": 1, "CPU": 1} + + # Accelerator type + if accelerator_type: + bundle[f"accelerator_type:{accelerator_type}"] = 0.001 + return bundle + + pg = ray.util.placement_group( + [_get_bundle()] * num_bundles_per_replica, + strategy="STRICT_PACK", + ) + return dict( + scheduling_strategy=PlacementGroupSchedulingStrategy( + pg, placement_group_capture_child_tasks=True + ) + ) + + +class vLLMEngineStage(StatefulStage): + """ + A stage that runs vLLM engine. + """ + + fn: Type[StatefulStageUDF] = vLLMEngineStageUDF + + @root_validator(pre=True) + def post_init(cls, values): + """Post-initialize the stage. Specifically, + this function determines the num_gpus and Ray remote args + for the .map_batches() call in this stage. + + Args: + values: The raw stage values. + Returns: + The updated values. + """ + map_batches_kwargs = values["map_batches_kwargs"] + accelerator_type = map_batches_kwargs.get("accelerator_type", "") + fn_constructor_kwargs = values["fn_constructor_kwargs"] + engine_kwargs = fn_constructor_kwargs.get("engine_kwargs", {}) + + ray_remote_args = {} + if accelerator_type: + ray_remote_args["accelerator_type"] = accelerator_type + + # Setup num_workers required per vLLM engine. + tp_size = engine_kwargs.get("tensor_parallel_size", 1) + pp_size = engine_kwargs.get("pipeline_parallel_size", 1) + num_bundles_per_replica = tp_size * pp_size + + # Use the MP backend by default. + engine_kwargs.setdefault("distributed_executor_backend", "mp") + executor_backend = engine_kwargs.get("distributed_executor_backend") + + # When Ray is used in the vLLM engine, we set num_devices to 0 so that + # Ray Data won't reserve GPUs in advance. Instead, we specify scheduling + # strategy in .map_batches() arguments and let vLLM Ray executor to + # create placement groups for each TP/PP worker. + resources_per_bundle = map_batches_kwargs.pop("resources", None) + if executor_backend == "ray" and num_bundles_per_replica > 1: + # Note that we have to use partial() to pass a function + # instead of an object. + map_batches_kwargs["ray_remote_args_fn"] = partial( + _ray_scheduling_strategy_fn, + num_bundles_per_replica, + accelerator_type, + resources_per_bundle, + ) + ray_remote_args["num_gpus"] = 0 + else: + if not resources_per_bundle: + # Default to GPUs per bundle if custom resources are not specified. + ray_remote_args["num_gpus"] = num_bundles_per_replica + else: + ray_remote_args["resources"] = { + resource_key: resource_count * num_bundles_per_replica + for resource_key, resource_count in resources_per_bundle.items() + } + + map_batches_kwargs.update(ray_remote_args) + return values + + def get_required_input_keys(self) -> Dict[str, str]: + """The required input keys of the stage and their descriptions.""" + ret = {"prompt": "The text prompt (str)."} + task_type = self.fn_constructor_kwargs.get("task_type", vLLMTaskType.GENERATE) + if task_type == vLLMTaskType.GENERATE: + ret["sampling_params"] = ( + "The sampling parameters. See " + "https://docs.vllm.ai/en/latest/api/inference_params.html#sampling-parameters " + "for details." + ) + return ret + + def get_optional_input_keys(self) -> Dict[str, str]: + """The optional input keys of the stage and their descriptions.""" + return { + "tokenized_prompt": "The tokenized prompt. If provided, the prompt will not be tokenized by the vLLM engine.", + "images": "The images to generate text from. If provided, the prompt will be a multimodal prompt.", + "model": "The model to use for this request. If the model is different from the " + "model set in the stage, then this is a LoRA request.", + } diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5cca5d3dd880cfaa635b40d2cfa43219b9c9c53c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/batch/utils.py @@ -0,0 +1,62 @@ +"""Utility functions for batch processing.""" +import logging +from typing import TYPE_CHECKING, Any, Union + +if TYPE_CHECKING: + from transformers import PreTrainedTokenizer, PreTrainedTokenizerFast + +AnyTokenizer = Union["PreTrainedTokenizer", "PreTrainedTokenizerFast", Any] + +logger = logging.getLogger(__name__) + + +def get_cached_tokenizer(tokenizer: AnyTokenizer) -> AnyTokenizer: + """Get tokenizer with cached properties. + This will patch the tokenizer object in place. + By default, transformers will recompute multiple tokenizer properties + each time they are called, leading to a significant slowdown. This + function caches these properties for faster access. + Args: + tokenizer: The tokenizer object. + Returns: + The patched tokenizer object. + """ + chat_template = getattr(tokenizer, "chat_template", None) + # For VLM, the text tokenizer is wrapped by a processor. + if hasattr(tokenizer, "tokenizer"): + tokenizer = tokenizer.tokenizer + # Some VLM's tokenizer has chat_template attribute (e.g. Qwen/Qwen2-VL-7B-Instruct), + # however some other VLM's tokenizer does not have chat_template attribute (e.g. + # mistral-community/pixtral-12b). Therefore, we cache the processor's chat_template. + if chat_template is None: + chat_template = getattr(tokenizer, "chat_template", None) + + tokenizer_all_special_ids = set(tokenizer.all_special_ids) + tokenizer_all_special_tokens_extended = tokenizer.all_special_tokens_extended + tokenizer_all_special_tokens = set(tokenizer.all_special_tokens) + tokenizer_len = len(tokenizer) + + class CachedTokenizer(tokenizer.__class__): # type: ignore + @property + def all_special_ids(self): + return tokenizer_all_special_ids + + @property + def all_special_tokens(self): + return tokenizer_all_special_tokens + + @property + def all_special_tokens_extended(self): + return tokenizer_all_special_tokens_extended + + @property + def chat_template(self): + return chat_template + + def __len__(self): + return tokenizer_len + + CachedTokenizer.__name__ = f"Cached{tokenizer.__class__.__name__}" + + tokenizer.__class__ = CachedTokenizer + return tokenizer diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eaa5967f9d3339646bfe982b4f8a13894264f329 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/__pycache__/base_pydantic.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/__pycache__/base_pydantic.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae11dfd4e58db7975afc1f9ea9a922b5088404a0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/__pycache__/base_pydantic.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/__pycache__/constants.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/__pycache__/constants.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97f9f35e4cf43bd1f0892a2bf3c1d2a7b9c917dd Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/__pycache__/constants.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/__pycache__/models.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/__pycache__/models.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16ca99967b523427ef11ffa4f6894e7ca9449791 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/__pycache__/models.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/base_pydantic.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/base_pydantic.py new file mode 100644 index 0000000000000000000000000000000000000000..ce4d49d8f955ca7cb3974f7544537a33851b0e4e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/base_pydantic.py @@ -0,0 +1,25 @@ +from typing import Type, TypeVar + +import yaml +from pydantic import BaseModel, ConfigDict + +ModelT = TypeVar("ModelT", bound=BaseModel) + + +class BaseModelExtended(BaseModel): + # NOTE(edoakes): Pydantic protects the namespace `model_` by default and prints + # warnings if you define fields with that prefix. However, we added such fields + # before this behavior existed. To avoid spamming user-facing logs, we mark the + # namespace as not protected. This means we need to be careful about overriding + # internal attributes starting with `model_`. + # See: https://github.com/anyscale/ray-llm/issues/1425 + model_config = ConfigDict( + protected_namespaces=tuple(), + extra="forbid", + ) + + @classmethod + def parse_yaml(cls: Type[ModelT], file, **kwargs) -> ModelT: + kwargs.setdefault("Loader", yaml.SafeLoader) + dict_args = yaml.load(file, **kwargs) + return cls.model_validate(dict_args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/constants.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..0b33ecad77ce78ca45a40cd40dfc8e0045e4a5ae --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/constants.py @@ -0,0 +1,13 @@ +""" +Generic constants for common utilities. + +These constants are used by generic utilities and should not contain +serve-specific or batch-specific values. +""" + +# Cloud object caching timeouts (in seconds) +CLOUD_OBJECT_EXISTS_EXPIRE_S = 300 # 5 minutes +CLOUD_OBJECT_MISSING_EXPIRE_S = 30 # 30 seconds + +# LoRA adapter configuration file name +LORA_ADAPTER_CONFIG_NAME = "adapter_config.json" diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/models.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/models.py new file mode 100644 index 0000000000000000000000000000000000000000..f5bc3360a2891913c8bc5ab4a51d130552bf576d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/models.py @@ -0,0 +1,49 @@ +""" +Generic model definitions for common utilities. + +These models represent generic concepts that can be used by both +serve and batch components. +""" + +import asyncio +import threading +from functools import partial +from typing import Awaitable, Callable, TypeVar + +T = TypeVar("T") + + +# DiskMultiplexConfig removed - it's serve-specific and belongs in serve/configs/server_models.py + + +class GlobalIdManager: + """Thread-safe global ID manager for assigning unique IDs.""" + + def __init__(self): + self._counter = 0 + self._lock = threading.Lock() + + def next(self) -> int: + """Get the next unique ID.""" + with self._lock: + self._counter += 1 + return self._counter + + +# Global instance +global_id_manager = GlobalIdManager() + + +def make_async(_func: Callable[..., T]) -> Callable[..., Awaitable[T]]: + """Take a blocking function, and run it on in an executor thread. + + This function prevents the blocking function from blocking the asyncio event loop. + The code in this function needs to be thread safe. + """ + + def _async_wrapper(*args, **kwargs) -> asyncio.Future: + loop = asyncio.get_event_loop() + func = partial(_func, *args, **kwargs) + return loop.run_in_executor(executor=None, func=func) + + return _async_wrapper diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84b27539b4c8560b455a1d445b4d833b9547ee91 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/__pycache__/logging_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/__pycache__/logging_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7cb174a9a153cde9628f929061837fc695727810 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/__pycache__/logging_utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/__pycache__/telemetry_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/__pycache__/telemetry_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..195727a06f1dcb01ef60f7c9164af2cf8e63187e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/__pycache__/telemetry_utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/logging/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/logging/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cc1e3ce04cfd3ff0ce67f3b8322c49812401c0d5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/logging/__init__.py @@ -0,0 +1,40 @@ +import logging +from typing import Optional + +from ray._private.ray_logging.filters import CoreContextFilter + + +def _setup_logger(logger_name: str): + """Setup logger given the logger name. + + This function is idempotent and won't set up the same logger multiple times. It will + also skip the setup if logger is already setup and has handlers. + + Args: + logger_name: logger name used to get the logger. + """ + logger = logging.getLogger(logger_name) + llm_logger = logging.getLogger("ray.llm") + + # Skip setup if the logger already has handlers setup or if the parent (Data + # logger) has handlers. + if logger.handlers or llm_logger.handlers: + return + + # Set up stream handler, which logs to console as plaintext. + stream_handler = logging.StreamHandler() + stream_handler.addFilter(CoreContextFilter()) + logger.addHandler(stream_handler) + logger.setLevel(logging.INFO) + logger.propagate = False + + +def get_logger(name: Optional[str] = None): + """Get a structured logger inherited from the Ray Data logger. + + Loggers by default are logging to stdout, and are expected to be scraped by an + external process. + """ + logger_name = f"ray.llm.{name}" + _setup_logger(logger_name) + return logging.getLogger(logger_name) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/logging/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/logging/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81796bd8b886563b55ccabe20ab5f9ba8356056a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/logging/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/logging/__pycache__/setup.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/logging/__pycache__/setup.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..494d3591f473652558fb548036f6bb3cb566ea30 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/logging/__pycache__/setup.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/logging/setup.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/logging/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..0c547e4a63053d5ca457c421ac10f9768ebda650 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/logging/setup.py @@ -0,0 +1,26 @@ +import logging + +from ray._private.ray_logging.filters import CoreContextFilter +from ray._private.ray_logging.formatters import JSONFormatter + + +def _configure_stdlib_logging(): + """Configures stdlib root logger to make sure stdlib loggers (created as + `logging.getLogger(...)`) are using Ray's `JSONFormatter` with Core and Serve + context filters. + """ + + handler = logging.StreamHandler() + handler.addFilter(CoreContextFilter()) + handler.setFormatter(JSONFormatter()) + + root_logger = logging.getLogger() + # NOTE: It's crucial we reset all the handlers of the root logger, + # to make sure that logs aren't emitted twice + root_logger.handlers = [] + root_logger.addHandler(handler) + root_logger.setLevel(logging.INFO) + + +def setup_logging(): + _configure_stdlib_logging() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/logging_utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/logging_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e0b86e7dbfe7da1c4ff5f8bc16cc98744fe7d006 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/logging_utils.py @@ -0,0 +1,48 @@ +"""Utilities for logging.""" + +import logging + +import ray + + +def disable_vllm_custom_ops_logger_on_cpu_nodes(): + """This disables a log line in the "vllm._custom_ops" logger on CPU nodes. + + vllm._custom_ops is automatically imported when vllm is imported. It checks + for CUDA binaries that don't exist in CPU-only nodes. This makes rayllm + raise a scary-looking (but harmless) warning when imported on CPU nodes, + such as when running the generate_config.py script or running the + build-app task. + """ + + class SkipVLLMWarningFilter(logging.Filter): + def filter(self, record: logging.LogRecord): + """Only allow CRITICAL logs from the datasets/config.py file.""" + + log_fragment = "Failed to import from vllm._C with" + + return log_fragment not in record.getMessage() + + if not ray.is_initialized() or len(ray.get_gpu_ids()) == 0: + logging.getLogger("vllm._custom_ops").addFilter(SkipVLLMWarningFilter()) + + +def disable_datasets_logger(): + """This disables "datasets" logs from its "config.py" file. + + Upon import, rayllm imports vllm which calls datasets. The datasets package + emits a log from its config.py file. + + The file that emits this log uses the root "datasets" logger, so we use a + filter to prevent logs from only the config.py file. + """ + + class SkipDatasetsConfigLogFilter(logging.Filter): + def filter(self, record: logging.LogRecord): + """Only allow CRITICAL logs from the datasets/config.py file.""" + return ( + record.levelno >= logging.CRITICAL + or "datasets/config.py" not in record.pathname + ) + + logging.getLogger("datasets").addFilter(SkipDatasetsConfigLogFilter()) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/telemetry_utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/telemetry_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..54e3ffa6d8be41f30690b001f34a44aed0f9e75b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/observability/telemetry_utils.py @@ -0,0 +1,42 @@ +"""Utilities for telemetry.""" + +from threading import Lock +from typing import Callable + +DEFAULT_GPU_TYPE = "UNSPECIFIED" + + +class Once: + """Execute a function exactly once and block all callers until the function returns + + Same as golang's `sync.Once `_ + + Took this directly from OpenTelemetry's Python SDK: + Ref: https://github.com/open-telemetry/opentelemetry-python/blob + /c6fab7d4c339dc5bf9eb9ef2723caad09d69bfca/opentelemetry-api/src/opentelemetry + /util/_once.py + """ + + def __init__(self) -> None: + self._lock = Lock() + self._done = False + + def do_once(self, func: Callable[[], None]) -> bool: + """Execute ``func`` if it hasn't been executed or return. + + Will block until ``func`` has been called by one thread. + + Returns: + Whether or not ``func`` was executed in this call + """ + + # fast path, try to avoid locking + if self._done: + return False + + with self._lock: + if not self._done: + func() + self._done = True + return True + return False diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0dbfe5073ecbb4bd6fa711107e901fb95ad86af Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/__pycache__/cloud_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/__pycache__/cloud_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98a3d798aeb929bd671785f9dce42d9fba68a973 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/__pycache__/cloud_utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/__pycache__/download_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/__pycache__/download_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c7935452fee0d55fd84b61013f09944274a8974 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/__pycache__/download_utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/__pycache__/import_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/__pycache__/import_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3c045996a35de43f94c10ea1591604a4608cb5c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/__pycache__/import_utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/__pycache__/lora_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/__pycache__/lora_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7858ab91209d9f30c25ab8c39ce29cff2df51887 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/__pycache__/lora_utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/__pycache__/upload_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/__pycache__/upload_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb389ce52af02d6511cad3f33ed8ac9d843dd341 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/__pycache__/upload_utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/cloud_utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/cloud_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f654e044cd6e82d931ad375e41e3c6c97315243b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/cloud_utils.py @@ -0,0 +1,598 @@ +import asyncio +import inspect +import os +import time +from pathlib import Path +from typing import ( + Any, + Awaitable, + Callable, + Dict, + List, + NamedTuple, + Optional, + Tuple, + TypeVar, + Union, +) + +# Use pyarrow for cloud storage access +import pyarrow.fs as pa_fs +from pydantic import Field, field_validator + +from ray.llm._internal.common.base_pydantic import BaseModelExtended +from ray.llm._internal.common.observability.logging import get_logger + +T = TypeVar("T") + +logger = get_logger(__name__) + + +def is_remote_path(path: str) -> bool: + """Check if the path is a remote path. + + Args: + path: The path to check. + + Returns: + True if the path is a remote path, False otherwise. + """ + return path.startswith("s3://") or path.startswith("gs://") + + +class ExtraFiles(BaseModelExtended): + bucket_uri: str + destination_path: str + + +class CloudMirrorConfig(BaseModelExtended): + """Unified mirror config for cloud storage (S3 or GCS). + + Args: + bucket_uri: URI of the bucket (s3:// or gs://) + extra_files: Additional files to download + """ + + bucket_uri: Optional[str] = None + extra_files: List[ExtraFiles] = Field(default_factory=list) + + @field_validator("bucket_uri") + @classmethod + def check_uri_format(cls, value): + if value is None: + return value + + if not is_remote_path(value): + raise ValueError( + f'Got invalid value "{value}" for bucket_uri. ' + 'Expected a URI that starts with "s3://" or "gs://".' + ) + return value + + @property + def storage_type(self) -> str: + """Returns the storage type ('s3' or 'gcs') based on the URI prefix.""" + if self.bucket_uri is None: + return None + elif self.bucket_uri.startswith("s3://"): + return "s3" + elif self.bucket_uri.startswith("gs://"): + return "gcs" + return None + + +class LoraMirrorConfig(BaseModelExtended): + lora_model_id: str + bucket_uri: str + max_total_tokens: Optional[int] + sync_args: Optional[List[str]] = None + + @field_validator("bucket_uri") + @classmethod + def check_uri_format(cls, value): + if value is None: + return value + + if not is_remote_path(value): + raise ValueError( + f'Got invalid value "{value}" for bucket_uri. ' + 'Expected a URI that starts with "s3://" or "gs://".' + ) + return value + + @property + def _bucket_name_and_path(self) -> str: + for prefix in ["s3://", "gs://"]: + if self.bucket_uri.startswith(prefix): + return self.bucket_uri[len(prefix) :] + return self.bucket_uri + + @property + def bucket_name(self) -> str: + return self._bucket_name_and_path.split("/")[0] + + @property + def bucket_path(self) -> str: + return "/".join(self._bucket_name_and_path.split("/")[1:]) + + +class CloudFileSystem: + """A unified interface for cloud file system operations using PyArrow. + + This class provides a simple interface for common operations on cloud storage + systems (S3, GCS) using PyArrow's filesystem interface. + """ + + @staticmethod + def get_fs_and_path(object_uri: str) -> Tuple[pa_fs.FileSystem, str]: + """Get the appropriate filesystem and path from a URI. + + Args: + object_uri: URI of the file (s3:// or gs://) + If URI contains 'anonymous@', anonymous access is used. + Example: s3://anonymous@bucket/path + + Returns: + Tuple of (filesystem, path) + """ + anonymous = False + # Check for anonymous access pattern + # e.g. s3://anonymous@bucket/path + if "@" in object_uri: + parts = object_uri.split("@", 1) + # Check if the first part ends with "anonymous" + if parts[0].endswith("anonymous"): + anonymous = True + # Remove the anonymous@ part, keeping the scheme + scheme = parts[0].split("://")[0] + object_uri = f"{scheme}://{parts[1]}" + + if object_uri.startswith("s3://"): + fs = pa_fs.S3FileSystem(anonymous=anonymous) + path = object_uri[5:] # Remove "s3://" + elif object_uri.startswith("gs://"): + fs = pa_fs.GcsFileSystem(anonymous=anonymous) + path = object_uri[5:] # Remove "gs://" + else: + raise ValueError(f"Unsupported URI scheme: {object_uri}") + + return fs, path + + @staticmethod + def get_file( + object_uri: str, decode_as_utf_8: bool = True + ) -> Optional[Union[str, bytes]]: + """Download a file from cloud storage into memory. + + Args: + object_uri: URI of the file (s3:// or gs://) + decode_as_utf_8: If True, decode the file as UTF-8 + + Returns: + File contents as string or bytes, or None if file doesn't exist + """ + try: + fs, path = CloudFileSystem.get_fs_and_path(object_uri) + + # Check if file exists + if not fs.get_file_info(path).type == pa_fs.FileType.File: + logger.info(f"URI {object_uri} does not exist.") + return None + + # Read file + with fs.open_input_file(path) as f: + body = f.read() + + if decode_as_utf_8: + body = body.decode("utf-8") + return body + except Exception as e: + logger.info(f"Error reading {object_uri}: {e}") + return None + + @staticmethod + def list_subfolders(folder_uri: str) -> List[str]: + """List the immediate subfolders in a cloud directory. + + Args: + folder_uri: URI of the directory (s3:// or gs://) + + Returns: + List of subfolder names (without trailing slashes) + """ + # Ensure that the folder_uri has a trailing slash. + folder_uri = f"{folder_uri.rstrip('/')}/" + + try: + fs, path = CloudFileSystem.get_fs_and_path(folder_uri) + + # List directory contents + file_infos = fs.get_file_info(pa_fs.FileSelector(path, recursive=False)) + + # Filter for directories and extract subfolder names + subfolders = [] + for file_info in file_infos: + if file_info.type == pa_fs.FileType.Directory: + # Extract just the subfolder name without the full path + subfolder = os.path.basename(file_info.path.rstrip("/")) + subfolders.append(subfolder) + + return subfolders + except Exception as e: + logger.info(f"Error listing subfolders in {folder_uri}: {e}") + return [] + + @staticmethod + def download_files( + path: str, + bucket_uri: str, + substrings_to_include: Optional[List[str]] = None, + ) -> None: + """Download files from cloud storage to a local directory. + + Args: + path: Local directory where files will be downloaded + bucket_uri: URI of cloud directory + substrings_to_include: Only include files containing these substrings + """ + try: + fs, source_path = CloudFileSystem.get_fs_and_path(bucket_uri) + + # Ensure the destination directory exists + os.makedirs(path, exist_ok=True) + + # List all files in the bucket + file_selector = pa_fs.FileSelector(source_path, recursive=True) + file_infos = fs.get_file_info(file_selector) + + # Download each file + for file_info in file_infos: + if file_info.type != pa_fs.FileType.File: + continue + + # Get relative path from source prefix + rel_path = file_info.path[len(source_path) :].lstrip("/") + + # Check if file matches substring filters + if substrings_to_include: + if not any( + substring in rel_path for substring in substrings_to_include + ): + continue + + # Create destination directory if needed + if "/" in rel_path: + dest_dir = os.path.join(path, os.path.dirname(rel_path)) + os.makedirs(dest_dir, exist_ok=True) + + # Download the file + dest_path = os.path.join(path, rel_path) + with fs.open_input_file(file_info.path) as source_file: + with open(dest_path, "wb") as dest_file: + dest_file.write(source_file.read()) + + except Exception as e: + logger.exception(f"Error downloading files from {bucket_uri}: {e}") + raise + + @staticmethod + def download_model( + destination_path: str, bucket_uri: str, tokenizer_only: bool + ) -> None: + """Download a model from cloud storage. + + This downloads a model in the format expected by the HuggingFace transformers + library. + + Args: + destination_path: Path where the model will be stored + bucket_uri: URI of the cloud directory containing the model + tokenizer_only: If True, only download tokenizer-related files + """ + try: + fs, source_path = CloudFileSystem.get_fs_and_path(bucket_uri) + + # Check for hash file + hash_path = os.path.join(source_path, "hash") + hash_info = fs.get_file_info(hash_path) + + if hash_info.type == pa_fs.FileType.File: + # Download and read hash file + with fs.open_input_file(hash_path) as f: + f_hash = f.read().decode("utf-8").strip() + logger.info( + f"Detected hash file in bucket {bucket_uri}. " + f"Using {f_hash} as the hash." + ) + else: + f_hash = "0000000000000000000000000000000000000000" + logger.info( + f"Hash file does not exist in bucket {bucket_uri}. " + f"Using {f_hash} as the hash." + ) + + # Write hash to refs/main + main_dir = os.path.join(destination_path, "refs") + os.makedirs(main_dir, exist_ok=True) + with open(os.path.join(main_dir, "main"), "w") as f: + f.write(f_hash) + + # Create destination directory + destination_dir = os.path.join(destination_path, "snapshots", f_hash) + os.makedirs(destination_dir, exist_ok=True) + + logger.info(f'Downloading model files to directory "{destination_dir}".') + + # Download files + tokenizer_file_substrings = ( + ["tokenizer", "config.json"] if tokenizer_only else [] + ) + CloudFileSystem.download_files( + path=destination_dir, + bucket_uri=bucket_uri, + substrings_to_include=tokenizer_file_substrings, + ) + + except Exception as e: + logger.exception(f"Error downloading model from {bucket_uri}: {e}") + raise + + @staticmethod + def upload_files( + local_path: str, + bucket_uri: str, + ) -> None: + """Upload files to cloud storage. + + Args: + local_path: The local path of the files to upload. + bucket_uri: The bucket uri to upload the files to, must start with `s3://` or `gs://`. + """ + try: + fs, dest_path = CloudFileSystem.get_fs_and_path(bucket_uri) + + pa_fs.copy_files( + source=local_path, + destination=dest_path, + source_filesystem=pa_fs.LocalFileSystem(), + destination_filesystem=fs, + ) + except Exception as e: + logger.exception(f"Error uploading files to {bucket_uri}: {e}") + raise + + @staticmethod + def upload_model( + local_path: str, + bucket_uri: str, + ) -> None: + """Upload a model to cloud storage. + + Args: + local_path: The local path of the model. + bucket_uri: The bucket uri to upload the model to, must start with `s3://` or `gs://`. + """ + try: + # If refs/main exists, upload as hash, and treat snapshots/ as the model. + # Otherwise, this is a custom model, we do not assume folder hierarchy. + refs_main = Path(local_path, "refs", "main") + if refs_main.exists(): + model_path = os.path.join( + local_path, "snapshots", refs_main.read_text().strip() + ) + CloudFileSystem.upload_files( + local_path=model_path, bucket_uri=bucket_uri + ) + CloudFileSystem.upload_files( + local_path=str(refs_main), + bucket_uri=os.path.join(bucket_uri, "hash"), + ) + else: + CloudFileSystem.upload_files( + local_path=local_path, bucket_uri=bucket_uri + ) + logger.info(f"Uploaded model files to {bucket_uri}.") + except Exception as e: + logger.exception(f"Error uploading model to {bucket_uri}: {e}") + raise + + +class _CacheEntry(NamedTuple): + value: Any + expire_time: Optional[float] + + +class CloudObjectCache: + """A cache that works with both sync and async fetch functions. + + The purpose of this data structure is to cache the result of a function call + usually used to fetch a value from a cloud object store. + + The idea is this: + - Cloud operations are expensive + - In LoRA specifically, we would fetch remote storage to download the model weights + at each request. + - If the same model is requested many times, we don't want to inflate the time to first token. + - We control the cache via not only the least recently used eviction policy, but also + by expiring cache entries after a certain time. + - If the object is missing, we cache the missing status for a small duration while if + the object exists, we cache the object for a longer duration. + """ + + def __init__( + self, + max_size: int, + fetch_fn: Union[Callable[[str], Any], Callable[[str], Awaitable[Any]]], + missing_expire_seconds: Optional[int] = None, + exists_expire_seconds: Optional[int] = None, + missing_object_value: Any = object(), + ): + """Initialize the cache. + + Args: + max_size: Maximum number of items to store in cache + fetch_fn: Function to fetch values (can be sync or async) + missing_expire_seconds: How long to cache missing objects (None for no expiration) + exists_expire_seconds: How long to cache existing objects (None for no expiration) + """ + self._cache: Dict[str, _CacheEntry] = {} + self._max_size = max_size + self._fetch_fn = fetch_fn + self._missing_expire_seconds = missing_expire_seconds + self._exists_expire_seconds = exists_expire_seconds + self._is_async = inspect.iscoroutinefunction(fetch_fn) or ( + callable(fetch_fn) and inspect.iscoroutinefunction(fetch_fn.__call__) + ) + self._missing_object_value = missing_object_value + # Lock for thread-safe cache access + self._lock = asyncio.Lock() + + async def aget(self, key: str) -> Any: + """Async get value from cache or fetch it if needed.""" + + if not self._is_async: + raise ValueError("Cannot use async get() with sync fetch function") + + async with self._lock: + value, should_fetch = self._check_cache(key) + if not should_fetch: + return value + + # Fetch new value + value = await self._fetch_fn(key) + self._update_cache(key, value) + return value + + def get(self, key: str) -> Any: + """Sync get value from cache or fetch it if needed.""" + if self._is_async: + raise ValueError("Cannot use sync get() with async fetch function") + + # For sync access, we use a simple check-then-act pattern + # This is safe because sync functions are not used in async context + value, should_fetch = self._check_cache(key) + if not should_fetch: + return value + + # Fetch new value + value = self._fetch_fn(key) + self._update_cache(key, value) + return value + + def _check_cache(self, key: str) -> tuple[Any, bool]: + """Check if key exists in cache and is valid. + + Returns: + Tuple of (value, should_fetch) + where should_fetch is True if we need to fetch a new value + """ + now = time.monotonic() + + if key in self._cache: + value, expire_time = self._cache[key] + if expire_time is None or now < expire_time: + return value, False + + return None, True + + def _update_cache(self, key: str, value: Any) -> None: + """Update cache with new value.""" + now = time.monotonic() + + # Calculate expiration + expire_time = None + if ( + self._missing_expire_seconds is not None + or self._exists_expire_seconds is not None + ): + if value is self._missing_object_value: + expire_time = ( + now + self._missing_expire_seconds + if self._missing_expire_seconds + else None + ) + else: + expire_time = ( + now + self._exists_expire_seconds + if self._exists_expire_seconds + else None + ) + + # Enforce size limit by removing oldest entry if needed + # This is an O(n) operation but it's fine since the cache size is usually small. + if len(self._cache) >= self._max_size: + oldest_key = min( + self._cache, key=lambda k: self._cache[k].expire_time or float("inf") + ) + del self._cache[oldest_key] + + self._cache[key] = _CacheEntry(value, expire_time) + + def __len__(self) -> int: + return len(self._cache) + + +class CloudModelAccessor: + """Unified accessor for models stored in cloud storage (S3 or GCS). + + Args: + model_id: The model id to download or upload. + mirror_config: The mirror config for the model. + """ + + def __init__(self, model_id: str, mirror_config: CloudMirrorConfig): + self.model_id = model_id + self.mirror_config = mirror_config + + def _get_lock_path(self, suffix: str = "") -> Path: + return Path( + "~", f"{self.model_id.replace('/', '--')}{suffix}.lock" + ).expanduser() + + def _get_model_path(self) -> Path: + if Path(self.model_id).exists(): + return Path(self.model_id) + # Delayed import to avoid circular dependencies + from transformers.utils.hub import TRANSFORMERS_CACHE + + return Path( + TRANSFORMERS_CACHE, f"models--{self.model_id.replace('/', '--')}" + ).expanduser() + + +def remote_object_cache( + max_size: int, + missing_expire_seconds: Optional[int] = None, + exists_expire_seconds: Optional[int] = None, + missing_object_value: Any = None, +) -> Callable[[Callable[..., T]], Callable[..., T]]: + """A decorator that provides async caching using CloudObjectCache. + + This is a direct replacement for the remote_object_cache/cachetools combination, + using CloudObjectCache internally to maintain cache state. + + Args: + max_size: Maximum number of items to store in cache + missing_expire_seconds: How long to cache missing objects + exists_expire_seconds: How long to cache existing objects + missing_object_value: Value to use for missing objects + """ + + def decorator(func: Callable[..., T]) -> Callable[..., T]: + # Create a single cache instance for this function + cache = CloudObjectCache( + max_size=max_size, + fetch_fn=func, + missing_expire_seconds=missing_expire_seconds, + exists_expire_seconds=exists_expire_seconds, + missing_object_value=missing_object_value, + ) + + async def wrapper(*args, **kwargs): + # Extract the key from either first positional arg or object_uri kwarg + key = args[0] if args else kwargs.get("object_uri") + return await cache.aget(key) + + return wrapper + + return decorator diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/download_utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/download_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2d4e0db908d05ae38b2826926f049a16f748c43f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/download_utils.py @@ -0,0 +1,291 @@ +import enum +import os +from pathlib import Path +from typing import List, Optional + +from filelock import FileLock + +from ray.llm._internal.common.observability.logging import get_logger +from ray.llm._internal.common.utils.cloud_utils import ( + CloudFileSystem, + CloudMirrorConfig, + CloudModelAccessor, + is_remote_path, +) +from ray.llm._internal.common.utils.import_utils import try_import + +torch = try_import("torch") + +logger = get_logger(__name__) + + +class NodeModelDownloadable(enum.Enum): + """Defines which files to download from cloud storage.""" + + MODEL_AND_TOKENIZER = enum.auto() + TOKENIZER_ONLY = enum.auto() + NONE = enum.auto() + + def __bool__(self): + return self != NodeModelDownloadable.NONE + + def union(self, other: "NodeModelDownloadable") -> "NodeModelDownloadable": + """Return a NodeModelDownloadable that is a union of this and the other.""" + if ( + self == NodeModelDownloadable.MODEL_AND_TOKENIZER + or other == NodeModelDownloadable.MODEL_AND_TOKENIZER + ): + return NodeModelDownloadable.MODEL_AND_TOKENIZER + + if ( + self == NodeModelDownloadable.TOKENIZER_ONLY + or other == NodeModelDownloadable.TOKENIZER_ONLY + ): + return NodeModelDownloadable.TOKENIZER_ONLY + + return NodeModelDownloadable.NONE + + +def get_model_entrypoint(model_id: str) -> str: + """Get the path to entrypoint of the model on disk if it exists, otherwise return the model id as is. + + Entrypoint is typically /models--/ + + Args: + model_id: Hugging Face model ID. + + Returns: + The path to the entrypoint of the model on disk if it exists, otherwise the model id as is. + """ + from transformers.utils.hub import TRANSFORMERS_CACHE + + model_dir = Path( + TRANSFORMERS_CACHE, f"models--{model_id.replace('/', '--')}" + ).expanduser() + if not model_dir.exists(): + return model_id + return str(model_dir.absolute()) + + +def get_model_location_on_disk(model_id: str) -> str: + """Get the location of the model on disk if exists, otherwise return the model id as is. + + Args: + model_id: Hugging Face model ID. + """ + model_dir = Path(get_model_entrypoint(model_id)) + model_id_or_path = model_id + + model_dir_refs_main = Path(model_dir, "refs", "main") + + if model_dir.exists(): + if model_dir_refs_main.exists(): + # If refs/main exists, use the snapshot hash to find the model + # and check if *config.json (could be config.json for general models + # or adapter_config.json for LoRA adapters) exists to make sure it + # follows HF model repo structure. + with open(model_dir_refs_main, "r") as f: + snapshot_hash = f.read().strip() + + snapshot_hash_path = Path(model_dir, "snapshots", snapshot_hash) + if snapshot_hash_path.exists() and list( + Path(snapshot_hash_path).glob("*config.json") + ): + model_id_or_path = str(snapshot_hash_path.absolute()) + else: + # If it doesn't have refs/main, it is a custom model repo + # and we can just return the model_dir. + model_id_or_path = str(model_dir.absolute()) + + return model_id_or_path + + +class CloudModelDownloader(CloudModelAccessor): + """Unified downloader for models stored in cloud storage (S3 or GCS). + + Args: + model_id: The model id to download. + mirror_config: The mirror config for the model. + """ + + def get_model( + self, + tokenizer_only: bool, + ) -> str: + """Gets a model from cloud storage and stores it locally. + + Args: + tokenizer_only: whether to download only the tokenizer files. + + Returns: file path of model if downloaded, else the model id. + """ + bucket_uri = self.mirror_config.bucket_uri + + if bucket_uri is None: + return self.model_id + + lock_path = self._get_lock_path() + path = self._get_model_path() + storage_type = self.mirror_config.storage_type + + try: + # Timeout 0 means there will be only one attempt to acquire + # the file lock. If it cannot be acquired, a TimeoutError + # will be thrown. + # This ensures that subsequent processes don't duplicate work. + with FileLock(lock_path, timeout=0): + try: + CloudFileSystem.download_model( + destination_path=path, + bucket_uri=bucket_uri, + tokenizer_only=tokenizer_only, + ) + logger.info( + "Finished downloading %s for %s from %s storage", + "tokenizer" if tokenizer_only else "model and tokenizer", + self.model_id, + storage_type.upper() if storage_type else "cloud", + ) + except RuntimeError: + logger.exception( + "Failed to download files for model %s from %s storage", + self.model_id, + storage_type.upper() if storage_type else "cloud", + ) + except TimeoutError: + # If the directory is already locked, then wait but do not do anything. + with FileLock(lock_path, timeout=-1): + pass + return get_model_location_on_disk(self.model_id) + + def get_extra_files(self) -> List[str]: + """Gets user-specified extra files from cloud storage and stores them in + provided paths. + + Returns: list of file paths of extra files if downloaded. + """ + paths = [] + extra_files = self.mirror_config.extra_files or [] + if not extra_files: + return paths + + lock_path = self._get_lock_path(suffix="-extra_files") + storage_type = self.mirror_config.storage_type + + logger.info( + f"Downloading extra files for {self.model_id} from {storage_type} storage" + ) + try: + # Timeout 0 means there will be only one attempt to acquire + # the file lock. If it cannot be acquired, a TimeoutError + # will be thrown. + # This ensures that subsequent processes don't duplicate work. + with FileLock(lock_path, timeout=0): + for extra_file in extra_files: + path = Path( + os.path.expandvars(extra_file.destination_path) + ).expanduser() + paths.append(path) + CloudFileSystem.download_files( + path=path, + bucket_uri=extra_file.bucket_uri, + ) + except TimeoutError: + # If the directory is already locked, then wait but do not do anything. + with FileLock(lock_path, timeout=-1): + pass + return paths + + +def _log_download_info( + *, source: str, download_model: NodeModelDownloadable, download_extra_files: bool +): + if download_model == NodeModelDownloadable.NONE: + if download_extra_files: + logger.info("Downloading extra files from %s", source) + else: + logger.info("Not downloading anything from %s", source) + elif download_model == NodeModelDownloadable.TOKENIZER_ONLY: + if download_extra_files: + logger.info("Downloading tokenizer and extra files from %s", source) + else: + logger.info("Downloading tokenizer from %s", source) + elif download_model == NodeModelDownloadable.MODEL_AND_TOKENIZER: + if download_extra_files: + logger.info("Downloading model, tokenizer, and extra files from %s", source) + else: + logger.info("Downloading model and tokenizer from %s", source) + + +def download_model_files( + model_id: Optional[str] = None, + mirror_config: Optional[CloudMirrorConfig] = None, + download_model: NodeModelDownloadable = NodeModelDownloadable.MODEL_AND_TOKENIZER, + download_extra_files: bool = True, +) -> Optional[str]: + """ + Download the model files from the cloud storage. We support two ways to specify + the remote model path in the cloud storage: + Approach 1: + - model_id: The vanilla model id such as "meta-llama/Llama-3.1-8B-Instruct". + - mirror_config: Config for downloading model from cloud storage. + + Approach 2: + - model_id: The remote path (s3:// or gs://) in the cloud storage. + - mirror_config: None. + In this approach, we will create a CloudMirrorConfig from the model_id and use that + to download the model. + + Args: + model_id: The model id. + mirror_config: Config for downloading model from cloud storage. + download_model: What parts of the model to download. + download_extra_files: Whether to download extra files specified in the mirror config. + + Returns: + The local path to the downloaded model, or the original model ID + if no cloud storage mirror is configured or if the model is not downloaded. + """ + + # Create the torch cache kernels directory if it doesn't exist. + # This is a workaround for a torch issue, where the kernels directory + # cannot be created by torch if the parent directory doesn't exist. + torch_cache_home = torch.hub._get_torch_home() + os.makedirs(os.path.join(torch_cache_home, "kernels"), exist_ok=True) + model_path_or_id = None + + if model_id is None: + return None + + if mirror_config is None: + if is_remote_path(model_id): + logger.info( + "Creating a CloudMirrorConfig from remote model path %s", model_id + ) + mirror_config = CloudMirrorConfig(bucket_uri=model_id) + else: + logger.info("No cloud storage mirror configured") + return model_id + + storage_type = mirror_config.storage_type + source = ( + f"{storage_type.upper()} mirror" if storage_type else "Cloud storage mirror" + ) + + _log_download_info( + source=source, + download_model=download_model, + download_extra_files=download_extra_files, + ) + + downloader = CloudModelDownloader(model_id, mirror_config) + + if download_model != NodeModelDownloadable.NONE: + model_path_or_id = downloader.get_model( + tokenizer_only=download_model == NodeModelDownloadable.TOKENIZER_ONLY + ) + + if download_extra_files: + downloader.get_extra_files() + + return model_path_or_id diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/import_utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/import_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fbb40d319c754531c7c9722f08119b1455d1b86a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/import_utils.py @@ -0,0 +1,34 @@ +"""Utility functions for importing modules in the LLM module.""" +import importlib +import logging +from types import ModuleType +from typing import Optional + +logger = logging.getLogger(__name__) + + +def try_import( + name: str, warning: bool = False, error: bool = False +) -> Optional[ModuleType]: + """Try importing the module and returns the module (or None). + + Args: + name: The name of the module to import. + warning: Whether to log a warning if the module cannot be imported. The + priority is higher than error. + error: Whether to raise an error if the module cannot be imported. + + Returns: + The module, or None if it cannot be imported. + + Raises: + ImportError: If error=True and the module is not installed. + """ + try: + return importlib.import_module(name) + except ImportError: + if warning: + logger.warning("Could not import %s", name) + elif error: + raise ImportError(f"Could not import {name}") + return None diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/lora_utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/lora_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4f53705778d3d3bb9ced0fe7f538dd333d0cd6c8 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/lora_utils.py @@ -0,0 +1,233 @@ +""" +Generic LoRA utilities and abstractions. + +This module provides canonical LoRA utility functions for both serve and batch components. +It serves as the single source of truth for LoRA operations and builds on the generic +download primitives from download_utils.py. +""" + +import json +import os +import subprocess +import time +from functools import wraps +from typing import Any, Callable, List, Optional, TypeVar, Union + +from ray.llm._internal.common.constants import ( + CLOUD_OBJECT_EXISTS_EXPIRE_S, + CLOUD_OBJECT_MISSING_EXPIRE_S, + LORA_ADAPTER_CONFIG_NAME, +) + +# Import the global ID manager from common models +from ray.llm._internal.common.models import make_async +from ray.llm._internal.common.observability.logging import get_logger +from ray.llm._internal.common.utils.cloud_utils import ( + CloudFileSystem, + is_remote_path, + remote_object_cache, +) +from ray.llm._internal.common.utils.download_utils import ( + CloudMirrorConfig, + CloudModelDownloader, +) + +logger = get_logger(__name__) + +# Sentinel object for missing cloud objects +CLOUD_OBJECT_MISSING = object() + +DEFAULT_LORA_MAX_TOTAL_TOKENS = 4096 +T = TypeVar("T") + + +def get_base_model_id(model_id: str) -> str: + """Get base model id for a given model id.""" + return model_id.split(":")[0] + + +def get_lora_id(lora_model_id: str) -> str: + """Get lora id for a given lora model id.""" + return ":".join(lora_model_id.split(":")[1:]) + + +def clean_model_id(model_id: str) -> str: + """Clean model ID for filesystem usage by replacing slashes with dashes.""" + return model_id.replace("/", "--") + + +def clear_directory(dir: str) -> None: + """Clear a directory recursively, ignoring missing directories.""" + try: + subprocess.run(f"rm -r {dir}", shell=True, check=False) + except FileNotFoundError: + pass + + +def retry_with_exponential_backoff( + max_tries: int, + exception_to_check: type[Exception], + base_delay: float = 1, + max_delay: float = 32, + exponential_base: float = 2, +) -> Callable[[Callable[..., T]], Callable[..., T]]: + """Retry decorator with exponential backoff.""" + + def decorator(func: Callable[..., T]) -> Callable[..., T]: + @wraps(func) + def wrapper(*args: Any, **kwargs: Any) -> T: + delay = base_delay + last_exception = None + + for attempt in range(max_tries): + try: + return func(*args, **kwargs) + except exception_to_check as e: + last_exception = e + if attempt == max_tries - 1: # Last attempt + raise last_exception + + # Log the failure and retry + logger.warning( + f"Attempt {attempt + 1}/{max_tries} failed: {str(e)}. " + f"Retrying in {delay} seconds..." + ) + time.sleep(delay) + # Calculate next delay with exponential backoff + delay = min(delay * exponential_base, max_delay) + + # This should never be reached due to the raise in the loop + raise last_exception if last_exception else RuntimeError( + "Unexpected error in retry logic" + ) + + return wrapper + + return decorator + + +def sync_files_with_lock( + bucket_uri: str, + local_path: str, + timeout: Optional[float] = None, + substrings_to_include: Optional[List[str]] = None, +) -> None: + """Sync files from bucket_uri to local_path with file locking.""" + from filelock import FileLock + + logger.info("Downloading %s to %s", bucket_uri, local_path) + + with FileLock(local_path + ".lock", timeout=timeout or -1): + try: + CloudFileSystem.download_files( + path=local_path, + bucket_uri=bucket_uri, + substrings_to_include=substrings_to_include, + ) + except Exception as e: + logger.error( + "Failed to sync files from %s to %s: %s", + bucket_uri, + local_path, + str(e), + ) + raise + + +@make_async +def _get_object_from_cloud(object_uri: str) -> Union[str, object]: + """Gets an object from the cloud.""" + if object_uri.endswith("/"): + raise ValueError(f'object_uri {object_uri} must not end with a "/".') + + body_str = CloudFileSystem.get_file(object_uri) + + if body_str is None: + logger.info(f"{object_uri} does not exist.") + return CLOUD_OBJECT_MISSING + else: + return body_str + + +@remote_object_cache( + max_size=4096, + missing_expire_seconds=CLOUD_OBJECT_MISSING_EXPIRE_S, + exists_expire_seconds=CLOUD_OBJECT_EXISTS_EXPIRE_S, + missing_object_value=CLOUD_OBJECT_MISSING, +) +async def get_object_from_cloud(object_uri: str) -> Union[str, object]: + """Gets an object from the cloud with caching.""" + return await _get_object_from_cloud(object_uri) + + +async def get_lora_finetuned_context_length(bucket_uri: str) -> Optional[int]: + """Gets the sequence length used to tune the LoRA adapter.""" + if bucket_uri.endswith("/"): + bucket_uri = bucket_uri.rstrip("/") + object_uri = f"{bucket_uri}/{LORA_ADAPTER_CONFIG_NAME}" + + object_str_or_missing_message = await get_object_from_cloud(object_uri) + + if object_str_or_missing_message is CLOUD_OBJECT_MISSING: + logger.debug(f"LoRA adapter config file not found at {object_uri}") + return None + + try: + adapter_config_str = object_str_or_missing_message + adapter_config = json.loads(adapter_config_str) + return adapter_config.get("max_length") + except (json.JSONDecodeError, AttributeError) as e: + logger.warning(f"Failed to parse LoRA adapter config at {object_uri}: {e}") + return None + + +def get_lora_model_ids( + dynamic_lora_loading_path: str, + base_model_id: str, +) -> List[str]: + """Get the model IDs of all the LoRA models. + + The dynamic_lora_loading_path is expected to hold subfolders each for + a different lora checkpoint. Each subfolder name will correspond to + the unique identifier for the lora checkpoint. The lora model is + accessible via :. Therefore, we prepend + the base_model_id to each subfolder name. + + Args: + dynamic_lora_loading_path: the cloud folder that contains all the LoRA + weights. + base_model_id: model ID of the base model. + + Returns: + List of LoRA fine-tuned model IDs. Does not include the base model + itself. + """ + lora_subfolders = CloudFileSystem.list_subfolders(dynamic_lora_loading_path) + + lora_model_ids = [] + for subfolder in lora_subfolders: + lora_model_ids.append(f"{base_model_id}:{subfolder}") + + return lora_model_ids + + +def download_lora_adapter( + lora_name: str, + remote_path: Optional[str] = None, +) -> str: + """Download a LoRA adapter from remote storage. + + This maintains backward compatibility with existing code. + """ + + assert not is_remote_path( + lora_name + ), "lora_name cannot be a remote path (s3:// or gs://)" + + if remote_path is None: + return lora_name + + lora_path = os.path.join(remote_path, lora_name) + mirror_config = CloudMirrorConfig(bucket_uri=lora_path) + downloader = CloudModelDownloader(lora_name, mirror_config) + return downloader.get_model(tokenizer_only=False) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/upload_utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/upload_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d2ba379544cc77454f3fcad79553c0f329c567f4 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/common/utils/upload_utils.py @@ -0,0 +1,126 @@ +from pathlib import Path + +import typer +from filelock import FileLock +from typing_extensions import Annotated + +from ray.llm._internal.common.observability.logging import get_logger +from ray.llm._internal.common.utils.cloud_utils import ( + CloudFileSystem, + CloudMirrorConfig, + CloudModelAccessor, + is_remote_path, +) +from ray.llm._internal.common.utils.download_utils import ( + get_model_entrypoint, +) + +logger = get_logger(__name__) + + +class CloudModelUploader(CloudModelAccessor): + """Unified uploader to upload models to cloud storage (S3 or GCS). + + Args: + model_id: The model id to upload. + mirror_config: The mirror config for the model. + """ + + def upload_model(self) -> str: + """Upload the model to cloud storage (s3 or gcs). + + Returns: + The remote path of the uploaded model. + """ + bucket_uri = self.mirror_config.bucket_uri + + lock_path = self._get_lock_path() + path = self._get_model_path() + storage_type = self.mirror_config.storage_type + + try: + # Timeout 0 means there will be only one attempt to acquire + # the file lock. If it cannot be acquired, a TimeoutError + # will be thrown. + # This ensures that subsequent processes don't duplicate work. + with FileLock(lock_path, timeout=0): + try: + CloudFileSystem.upload_model( + local_path=path, + bucket_uri=bucket_uri, + ) + logger.info( + "Finished uploading %s to %s storage", + self.model_id, + storage_type.upper() if storage_type else "cloud", + ) + except RuntimeError: + logger.exception( + "Failed to upload model %s to %s storage", + self.model_id, + storage_type.upper() if storage_type else "cloud", + ) + except TimeoutError: + # If the directory is already locked, then wait but do not do anything. + with FileLock(lock_path, timeout=-1): + pass + return bucket_uri + + +def upload_model_files(model_id: str, bucket_uri: str) -> str: + """Upload the model files to cloud storage (s3 or gcs). + + If `model_id` is a local path, the files will be uploaded to the cloud storage. + If `model_id` is a huggingface model id, the model will be downloaded from huggingface + and then uploaded to the cloud storage. + + Args: + model_id: The huggingface model id, or local model path to upload. + bucket_uri: The bucket uri to upload the model to, must start with `s3://` or `gs://`. + + Returns: + The remote path of the uploaded model. + """ + assert not is_remote_path( + model_id + ), f"model_id must NOT be a remote path: {model_id}" + assert is_remote_path(bucket_uri), f"bucket_uri must be a remote path: {bucket_uri}" + + if not Path(model_id).exists(): + maybe_downloaded_model_path = get_model_entrypoint(model_id) + if not Path(maybe_downloaded_model_path).exists(): + logger.info( + "Assuming %s is huggingface model id, and downloading it.", model_id + ) + import huggingface_hub + + huggingface_hub.snapshot_download(repo_id=model_id) + # Try to get the model path again after downloading. + maybe_downloaded_model_path = get_model_entrypoint(model_id) + assert Path( + maybe_downloaded_model_path + ).exists(), f"Failed to download the model {model_id} to {maybe_downloaded_model_path}" + return upload_model_files(maybe_downloaded_model_path, bucket_uri) + else: + return upload_model_files(maybe_downloaded_model_path, bucket_uri) + + uploader = CloudModelUploader(model_id, CloudMirrorConfig(bucket_uri=bucket_uri)) + return uploader.upload_model() + + +def upload_model_cli( + model_source: Annotated[ + str, + typer.Option( + help="HuggingFace model ID to download, or local model path to upload", + ), + ], + bucket_uri: Annotated[ + str, + typer.Option( + help="The bucket uri to upload the model to, must start with `s3://` or `gs://`", + ), + ], +): + """Upload the model files to cloud storage (s3 or gcs).""" + upload_model_files(model_source, bucket_uri) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7a44581bf5f39a2b7c3307863450d512c8867f7e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/__init__.py @@ -0,0 +1,14 @@ +from ray.llm._internal.common.observability.logging_utils import ( + disable_vllm_custom_ops_logger_on_cpu_nodes, +) +from ray.llm._internal.serve.observability import setup_observability + +# Set up observability +disable_vllm_custom_ops_logger_on_cpu_nodes() +setup_observability() + + +def _worker_process_setup_hook(): + """Noop setup hook used for ENABLE_WORKER_PROCESS_SETUP_HOOK + (see python/ray/llm/_internal/serve/configs/constants.py).""" + pass diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4812bcba456c1d95dcaadd826846bd671c6e583f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/builders/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/builders/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..64d34496f2482cfe03c33168e600f9e63718646f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/builders/__init__.py @@ -0,0 +1,6 @@ +from ray.llm._internal.serve.builders.application_builders import ( + build_llm_deployment, + build_openai_app, +) + +__all__ = ["build_llm_deployment", "build_openai_app"] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/builders/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/builders/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e88964b53d26cd4031e510c6b8510f276fcd5e8f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/builders/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/builders/__pycache__/application_builders.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/builders/__pycache__/application_builders.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66bc9748c4c2e233876f3858ca7a801ae24e238c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/builders/__pycache__/application_builders.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/builders/application_builders.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/builders/application_builders.py new file mode 100644 index 0000000000000000000000000000000000000000..769477044e1dc8a7d3e85da52ec504d6ca433605 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/builders/application_builders.py @@ -0,0 +1,77 @@ +from typing import Any, Dict, List, Optional, Sequence, overload + +from ray.llm._internal.serve.configs.server_models import ( + LLMConfig, + LLMEngine, + LLMServingArgs, +) +from ray.llm._internal.serve.deployments.llm.llm_server import LLMDeployment +from ray.llm._internal.serve.deployments.routers.router import ( + LLMRouter, +) +from ray.llm._internal.serve.observability.logging import get_logger +from ray.serve.deployment import Application +from ray.serve.handle import DeploymentHandle + +logger = get_logger(__name__) + + +def build_llm_deployment( + llm_config: LLMConfig, + *, + name_prefix: Optional[str] = None, + deployment_kwargs: Optional[dict] = None, +) -> Application: + name_prefix = name_prefix or "LLMServer:" + deployment_kwargs = deployment_kwargs or {} + + deployment_options = llm_config.get_serve_options( + name_prefix=name_prefix, + ) + + return LLMDeployment.options(**deployment_options).bind( + llm_config=llm_config, **deployment_kwargs + ) + + +def _get_llm_deployments( + llm_base_models: Sequence[LLMConfig], + deployment_kwargs: Optional[dict] = None, +) -> List[DeploymentHandle]: + llm_deployments = [] + for llm_config in llm_base_models: + if llm_config.llm_engine == LLMEngine.vLLM: + llm_deployments.append( + build_llm_deployment(llm_config, deployment_kwargs=deployment_kwargs) + ) + else: + # Note (genesu): This should never happen because we validate the engine + # in the config. + raise ValueError(f"Unsupported engine: {llm_config.llm_engine}") + + return llm_deployments + + +@overload +def build_openai_app(llm_serving_args: Dict[str, Any]) -> Application: + ... + + +def build_openai_app(llm_serving_args: LLMServingArgs) -> Application: + rayllm_args = LLMServingArgs.model_validate(llm_serving_args).parse_args() + + llm_configs = rayllm_args.llm_configs + model_ids = {m.model_id for m in llm_configs} + if len(model_ids) != len(llm_configs): + raise ValueError("Duplicate models found. Make sure model ids are unique.") + + if len(llm_configs) == 0: + logger.error( + "List of models is empty. Maybe some parameters cannot be parsed into the LLMConfig config." + ) + + llm_deployments = _get_llm_deployments(llm_configs) + + return LLMRouter.as_deployment(llm_configs=llm_configs).bind( + llm_deployments=llm_deployments + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b4c2a1199883bfa93c8f315aac0e71541fd4371 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/__pycache__/generator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/__pycache__/generator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00765544b154644f1163c7e3c63be4cfece8887a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/__pycache__/generator.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/__pycache__/inputs.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/__pycache__/inputs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b7a81c9d46c42679b744368331218322b80615e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/__pycache__/inputs.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/__pycache__/start.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/__pycache__/start.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ea46522f8384e1c5d3b85c66838fa269f40b944 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/__pycache__/start.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/base_configs/templates/base_serve_config.yaml b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/base_configs/templates/base_serve_config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f60950477256d5cf84197ff5ed387cf87143f29c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/base_configs/templates/base_serve_config.yaml @@ -0,0 +1,6 @@ +applications: + - name: llm-endpoint + route_prefix: / + import_path: ray.serve.llm:build_openai_app + args: + llm_configs: [] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/base_configs/templates/default_deployment_configs.yaml b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/base_configs/templates/default_deployment_configs.yaml new file mode 100644 index 0000000000000000000000000000000000000000..66da8729b54986d4389009d47940dfbe0321a721 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/base_configs/templates/default_deployment_configs.yaml @@ -0,0 +1,83 @@ +model_id_to_gpu_deployment_configs: + meta-llama/Meta-Llama-3.1-8B-Instruct: + A10G: &base_llama_31_8b_config + model_loading_config: + model_id: meta-llama/Meta-Llama-3.1-8B-Instruct + engine_kwargs: + # Llama 3.1's context length is 128k, but we set a lower one to avoid GPU OOM. + max_model_len: 8192 + max_num_batched_tokens: 2048 + tensor_parallel_size: 1 + enable_chunked_prefill: true + L4: *base_llama_31_8b_config + L40S: *base_llama_31_8b_config + A100-40G: *base_llama_31_8b_config + A100-80G: *base_llama_31_8b_config + H100: *base_llama_31_8b_config + + meta-llama/Meta-Llama-3.1-70B-Instruct: + A100-40G: + model_loading_config: &meta_llama_31_70b_model_loading_config + model_id: meta-llama/Meta-Llama-3.1-70B-Instruct + engine_kwargs: + # Llama 3.1's context length is 128k, but we set a lower one to avoid GPU OOM. + max_model_len: 8192 + max_num_batched_tokens: 2048 + tensor_parallel_size: 8 + enable_chunked_prefill: true + A100-80G: + model_loading_config: *meta_llama_31_70b_model_loading_config + engine_kwargs: + # Llama 3.1's context length is 128k, but we set a lower one to avoid GPU OOM. + max_model_len: 8192 + max_num_batched_tokens: 2048 + tensor_parallel_size: 4 + enable_chunked_prefill: true + H100: + model_loading_config: *meta_llama_31_70b_model_loading_config + engine_kwargs: + # Llama 3.1's context length is 128k, but we set a lower one to avoid GPU OOM. + max_model_len: 8192 + max_num_batched_tokens: 2048 + tensor_parallel_size: 4 + enable_chunked_prefill: true + + meta-llama/Meta-Llama-3.1-405B-Instruct-FP8: + H100: + model_loading_config: &meta_llama_31_405b_model_loading_config + model_id: meta-llama/Meta-Llama-3.1-405B-Instruct-FP8 + engine_kwargs: + # Llama 3.1's context length is 128k, but we set a lower one to avoid GPU OOM. + max_model_len: 8192 + max_num_batched_tokens: 2048 + tensor_parallel_size: 8 + enable_chunked_prefill: true + + mistral-community/pixtral-12b: + L40S: &pixtral_base_12b_config + model_loading_config: &pixtral_base_12b_model_loading_config + model_id: mistral-community/pixtral-12b + engine_kwargs: + tensor_parallel_size: 1 + A100-40G: *pixtral_base_12b_config + A100-80G: *pixtral_base_12b_config + H100: *pixtral_base_12b_config + + meta-llama/Llama-3.2-11B-Vision-Instruct: + L40S: &llama_32_base_11b_config + model_loading_config: &llama_32_base_11b_model_loading_config + model_id: meta-llama/Llama-3.2-11B-Vision-Instruct + engine_kwargs: + tensor_parallel_size: 1 + A100-40G: *llama_32_base_11b_config + A100-80G: *llama_32_base_11b_config + H100: *llama_32_base_11b_config + + meta-llama/Llama-3.2-90B-Vision-Instruct: + A100-40G: &llama_32_base_90b_config + model_loading_config: &llama_32_base_90b_model_loading_config + model_id: meta-llama/Llama-3.2-90B-Vision-Instruct + engine_kwargs: + tensor_parallel_size: 1 + A100-80G: *llama_32_base_90b_config + H100: *llama_32_base_90b_config diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/generator.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/generator.py new file mode 100644 index 0000000000000000000000000000000000000000..2b00f9f85417b05b0d1fe6707571ffa1444ecfae --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/generator.py @@ -0,0 +1,124 @@ +import copy +import os +from typing import Any, Dict + +import yaml + +from ray.llm._internal.serve.config_generator.utils.constants import TEMPLATE_DIR +from ray.llm._internal.serve.config_generator.utils.models import ( + TextCompletionModelConfig, +) +from ray.llm._internal.serve.config_generator.utils.overrides import ( + ask_and_merge_model_overrides, +) +from ray.llm._internal.serve.config_generator.utils.text_completion import ( + populate_text_completion_model_config, +) +from ray.serve._private.constants import DEFAULT_TARGET_ONGOING_REQUESTS +from ray.serve.config import AutoscalingConfig + + +def get_model_base_config( + input_model_config: TextCompletionModelConfig, +) -> Dict[str, Any]: + """ + This method returns the base model config based on user inputs. + """ + return populate_text_completion_model_config(input_model_config) + + +def get_model_config(input_model_config: TextCompletionModelConfig) -> Dict[str, Any]: + """ + This method decorates the base model config based on serving type, such as Lora or function calling. + """ + + model_config = get_model_base_config(input_model_config) + + model_config = maybe_get_lora_enabled_config( + input_model_config, + model_config, + ) + + return model_config + + +def get_serve_config( + model_config_path: str, +): + """ + This util method constructs the final serve config. + + It doesn't inline the model config and, instead, just puts the file path based on the type of models. + """ + serve_config = get_serve_base_config() + serve_config["applications"][0]["args"]["llm_configs"] = [model_config_path] + return serve_config + + +def override_model_configs(base_model_config: Dict[str, Any]) -> Dict[str, Any]: + existing_autoscaling_config = base_model_config["deployment_config"].setdefault( + "autoscaling_config", {} + ) + # Getting the default target ongoing requests from the base model config. + # If not present, default to 2 (same as Ray Serve's default). + default_ongoing_requests = ( + base_model_config.get("deployment_config", {}) + .get("autoscaling_config", {}) + .get("target_ongoing_requests", DEFAULT_TARGET_ONGOING_REQUESTS) + ) + final_autoscaling_config = ask_and_merge_model_overrides( + existing_configs=existing_autoscaling_config, + model_cls=AutoscalingConfig, + fields=["min_replicas", "max_replicas", "target_ongoing_requests"], + defaults={"target_ongoing_requests": default_ongoing_requests}, + ) + final_autoscaling_config["initial_replicas"] = final_autoscaling_config[ + "min_replicas" + ] + base_model_config["deployment_config"][ + "autoscaling_config" + ] = final_autoscaling_config + + # Make sure max_ongoing request is always double of target_ongoing_requests + base_model_config["deployment_config"]["max_ongoing_requests"] = ( + 2 * final_autoscaling_config["target_ongoing_requests"] + ) + + return base_model_config + + +def maybe_get_lora_enabled_config( + input_model_config: TextCompletionModelConfig, + base_config: Dict[str, Any], +): + """ + If the input model contains lora config, this method decorates the base + config with lora-specific configurations. + """ + if input_model_config.lora_config: + max_num_adapters_per_replica = ( + input_model_config.lora_config.max_num_lora_per_replica + ) + + res = copy.deepcopy(base_config) + res["lora_config"] = { + "dynamic_lora_loading_path": input_model_config.lora_config.uri, + "max_num_adapters_per_replica": max_num_adapters_per_replica, + } + + res.setdefault("engine_kwargs", {})["enable_lora"] = True + res.setdefault("engine_kwargs", {})["max_lora_rank"] = 32 + res.setdefault("engine_kwargs", {})["max_loras"] = max_num_adapters_per_replica + return res + else: + return base_config + + +_BASE_SERVE_CONFIG = "base_serve_config.yaml" + + +def get_serve_base_config() -> Dict[str, Any]: + # Construct the full path to the YAML file + file_path = os.path.join(TEMPLATE_DIR, _BASE_SERVE_CONFIG) + with open(file_path, "r") as stream: + return yaml.safe_load(stream) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/inputs.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/inputs.py new file mode 100644 index 0000000000000000000000000000000000000000..706fbb2502c7a1eeba67e24d537a732ac21545d9 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/inputs.py @@ -0,0 +1,220 @@ +from typing import List, Optional + +from huggingface_hub import repo_info +from pydantic import BaseModel +from rich import print +from rich.prompt import Confirm, Prompt + +from ray.llm._internal.serve.config_generator.utils.constants import ( + get_lora_storage_uri, +) +from ray.llm._internal.serve.config_generator.utils.files import ( + clear_hf_token, + get_hf_token, +) +from ray.llm._internal.serve.config_generator.utils.gpu import ( + DEFAULT_MODEL_ID_TO_GPU, + GPUType, + get_available_gpu_types, +) +from ray.llm._internal.serve.config_generator.utils.input_converter import ( + convert_inputs_to_text_completion_model, +) +from ray.llm._internal.serve.config_generator.utils.models import ( + TEXT_COMPLETION_MODEL_TYPE, + ModelType, + TextCompletionLoraModelConfig, + TextCompletionModelConfig, +) +from ray.llm._internal.serve.config_generator.utils.prompt import ( + BoldIntPrompt, + BoldPrompt, +) +from ray.llm._internal.serve.config_generator.utils.text_completion import ( + get_default_llm_config, +) + + +def _get_user_input_from_list(prompt: str, options: List[GPUType]): + while True: + user_input = BoldPrompt.ask( + f"{prompt}", + choices=[option.value for option in options], + ) + for option in options: + if user_input.lower() == option.value.lower(): + return option + print(f"Please enter a valid option from {options}") + + +class BaseModelInfo(BaseModel): + id: str + hf_token: Optional[str] = None + type: ModelType + import_model_storage_uri: Optional[str] = None + reference_model_id: Optional[str] = None + + +def _get_user_input_from_lists( + prompt: str, options: List[str], allow_any_user_input: bool +): + while True: + res = Prompt.ask(prompt) + if allow_any_user_input or res in options: + return res + else: + print("Please enter a valid option.") + + +def _get_model_id(): + model_list = list(DEFAULT_MODEL_ID_TO_GPU.keys()) + model_ids = "\n".join(model_list) + prompt_message = f"""[bold]We have provided the defaults for the following models[not bold]: +{model_ids} +[bold]Please enter the model ID you would like to serve, or enter your own custom model ID. For multi-lora serving, enter only the base model ID""" + + model_id = _get_user_input_from_lists( + prompt_message, model_list, allow_any_user_input=True + ) + return model_id + + +def _get_validated_model_info(): + """ + If the model is supposed to be loaded from huggingface, we make an API call to confirm that + user's credentials work. + """ + while True: + ref_model_id = None + + model_id = _get_model_id() + model_type = TEXT_COMPLETION_MODEL_TYPE + if model_id not in DEFAULT_MODEL_ID_TO_GPU: + ref_model_id = "other" + import_model = Confirm.ask( + "Do you have the model weights stored in your cloud buckets? " + "If not, model weights will be downloaded from HuggingFace.", + default=False, + ) + + if import_model: + # No need to validate since the model is loaded from remote uri + remote_storage_uri = BoldPrompt.ask("Storage uri of your model: ") + return BaseModelInfo( + id=model_id, + hf_token=None, + type=model_type, + import_model_storage_uri=remote_storage_uri, + reference_model_id=ref_model_id, + ) + + hf_token = get_hf_token() + + # Need to validate + try: + repo_info(model_id, token=hf_token) + print( + f"Verified that you can access {model_id} with your HuggingFace token." + ) + return BaseModelInfo( + id=model_id, + hf_token=hf_token, + type=model_type, + reference_model_id=ref_model_id, + ) + except Exception as e: + print(f"An error occurred: {e}") + # Clear cached tf token in case it was incorrectly entered + clear_hf_token() + + print( + "\nUnable to access the HuggingFace repo based on the " + "provided information. Please confirm that you have access " + "to the model and try again." + ) + + +def _get_default_tensor_parallelism(model_id: str, gpu_type: GPUType) -> int: + if model_id in DEFAULT_MODEL_ID_TO_GPU: + llm_config = get_default_llm_config(model_id=model_id, gpu_type=gpu_type) + return llm_config.engine_kwargs.setdefault("tensor_parallel_size", 1) + + return 1 + + +_DEFAULT_NUM_LORA_PER_REPLICA = 16 + + +def get_input_model_via_args( + model_id: str, + hf_token: Optional[str], + gpu_type: GPUType, + tensor_parallelism: int, + enable_lora: Optional[bool], + num_loras_per_replica: Optional[int], +) -> TextCompletionModelConfig: + if enable_lora: + max_num_lora_per_replica = ( + num_loras_per_replica or _DEFAULT_NUM_LORA_PER_REPLICA + ) + default_lora_uri = get_lora_storage_uri() + lora_config = TextCompletionLoraModelConfig( + max_num_lora_per_replica=max_num_lora_per_replica, + uri=default_lora_uri, + ) + else: + lora_config = None + + return convert_inputs_to_text_completion_model( + model_id=model_id, + hf_token=hf_token, + gpu_type=gpu_type, + tensor_parallelism=tensor_parallelism, + lora_config=lora_config, + ) + + +def get_input_model_via_interactive_inputs() -> TextCompletionModelConfig: + """ + This method constructs a corresponding model object based on user inputs. + + This model object should be used to construct the final serve config. + """ + base_model_info = _get_validated_model_info() + + available_gpu_types = get_available_gpu_types(base_model_info.id) + gpu_type = _get_user_input_from_list("GPU type", available_gpu_types) + + default_tensor_parallelism = _get_default_tensor_parallelism( + base_model_info.id, gpu_type=gpu_type + ) + + tensor_parallelism = BoldIntPrompt.ask( + "Tensor parallelism", default=default_tensor_parallelism + ) + + is_lora_enabled = Confirm.ask("[bold]Enable LoRA serving", default=False) + + if is_lora_enabled: + default_lora_uri = get_lora_storage_uri() + max_num_lora_per_replica = BoldIntPrompt.ask( + "Maximum number of LoRA models per replica", + default=_DEFAULT_NUM_LORA_PER_REPLICA, + ) + lora_uri = BoldPrompt.ask("LoRA storage uri", default=default_lora_uri) + lora_config = TextCompletionLoraModelConfig( + max_num_lora_per_replica=max_num_lora_per_replica, + uri=lora_uri, + ) + else: + lora_config = None + + return convert_inputs_to_text_completion_model( + model_id=base_model_info.id, + hf_token=base_model_info.hf_token, + remote_storage_uri=base_model_info.import_model_storage_uri, + gpu_type=gpu_type, + tensor_parallelism=tensor_parallelism, + lora_config=lora_config, + reference_model_id=base_model_info.reference_model_id, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/start.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/start.py new file mode 100644 index 0000000000000000000000000000000000000000..97c8e6d512669abd02ede09c30af92431f1674bb --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/start.py @@ -0,0 +1,224 @@ +import datetime +import os +from typing import Any, Dict, Optional + +import typer +import yaml +from rich import print +from rich.prompt import Confirm +from typing_extensions import Annotated + +from ray.llm._internal.serve.config_generator.generator import ( + get_model_config, + get_serve_config, + override_model_configs, +) +from ray.llm._internal.serve.config_generator.inputs import ( + get_input_model_via_args, + get_input_model_via_interactive_inputs, +) +from ray.llm._internal.serve.config_generator.utils.gpu import ( + DEFAULT_MODEL_ID_TO_GPU, + GPUType, +) + + +def _format_yaml_dumper(): + """Changes the YAML dumper's format.""" + + # Prompt formats often contain newline characters. We modify the YAML + # dumper here, so it prints newline characters instead of actual newlines. + def newline_representer(dumper, data): + if "\n" in data: + # Only adjust the dumper if a newline is present. + return dumper.represent_scalar("tag:yaml.org,2002:str", data, style='"') + else: + # Use the default dumper otherwise. + return dumper.represent_scalar("tag:yaml.org,2002:str", data) + + yaml.SafeDumper.add_representer(str, newline_representer) + + +def _write_model_config_to_disk( + model_config: Dict[str, Any], model_id: str, timestamp: str +) -> str: + # Set the filename with prefix, timestamp, and suffix + sanitized_model_id = model_id.replace("/", "--").replace(".", "_") + file_name = f"{sanitized_model_id}_{timestamp}.yaml" + file_path = "./model_config" # Directory where the file will be saved + + os.makedirs(file_path, exist_ok=True) + + # Create the full path for the file + full_file_path = f"{file_path}/{file_name}" + + # Dump the configuration to the file + with open(full_file_path, "w+") as file: + yaml.safe_dump(model_config, file) + return full_file_path + + +def _write_config_to_disk(serve_config: Dict[str, Any], timestamp: str): + # Set the filename with prefix, timestamp, and suffix + file_name = f"serve_{timestamp}.yaml" + file_path = "./" # Directory where the file will be saved + + # Create the full path for the file + full_file_path = f"{file_path}{file_name}" + + # Dump the configuration to the file + with open(full_file_path, "w+") as file: + yaml.safe_dump(serve_config, file) + + return full_file_path + + +def _get_model_with_validation( + model_id: Optional[str], + hf_token: Optional[str], + gpu_type: Optional[GPUType], + tensor_parallelism: Optional[int], + enable_lora: Optional[bool], + num_loras_per_replica: Optional[int], +): + if model_id and model_id not in DEFAULT_MODEL_ID_TO_GPU: + raise RuntimeError( + "In non-interactive CLI mode, please only specify model ID whose configs are provided by default." + ) + + if model_id and gpu_type and tensor_parallelism: + return get_input_model_via_args( + model_id, + hf_token=hf_token, + gpu_type=gpu_type, + tensor_parallelism=tensor_parallelism, + enable_lora=enable_lora, + num_loras_per_replica=num_loras_per_replica, + ) + else: + raise RuntimeError( + "If specifying args, please make sure all arguments are specified." + ) + + +def gen_config( + model_id: Annotated[ + Optional[str], + typer.Option( + help="HuggingFace model ID to download and run", + hidden=True, + ), + ] = None, + hf_token: Annotated[ + Optional[str], typer.Option(help="Huggingface token", hidden=True) + ] = None, + gpu_type: Annotated[ + Optional[GPUType], typer.Option(help="Type of GPU", hidden=True) + ] = None, + tensor_parallelism: Annotated[ + Optional[int], typer.Option(help="Number of tensor parallelism", hidden=True) + ] = None, + enable_lora: Annotated[ + Optional[bool], typer.Option(help="Whether to enable LoRA serving", hidden=True) + ] = False, + # TODO (shrekris): Expose these hidden options after the API stabilizes. + external_model_id: Annotated[ + Optional[str], + typer.Option( + help="[EXPERIMENTAL] Model ID to expose to end users. Defaults to model_id.", + hidden=True, + ), + ] = None, + override_lora_uri: Annotated[ + Optional[str], + typer.Option(help="[EXPERIMENTAL] URI to LoRA weights", hidden=True), + ] = None, + num_loras_per_replica: Annotated[ + Optional[int], + typer.Option( + help="[EXPERIMENTAL] Number of LoRA weights per replica", hidden=True + ), + ] = None, + enable_chunk_prefill: Annotated[ + Optional[bool], + typer.Option( + "--enable-chunked-prefill/--disable-chunked-prefill", + help="Whether to enable chunked prefill", + hidden=True, + ), + ] = None, + max_num_batched_tokens: Annotated[ + Optional[int], + typer.Option(help="Max Number of batched tokens", hidden=True), + ] = None, +): + """Starts an interactive session to generate RayLLM YAML configs.""" + + if (override_lora_uri or num_loras_per_replica) and not enable_lora: + raise ValueError( + "--enable-lora is not set. --enable-lora must be set " + "to use --override-lora-uri or --num-loras-per-replica." + ) + + if model_id or gpu_type or tensor_parallelism: + interactive_mode = False + input_model_config = _get_model_with_validation( + model_id=model_id, + hf_token=hf_token, + gpu_type=gpu_type, + tensor_parallelism=tensor_parallelism, + enable_lora=enable_lora, + num_loras_per_replica=num_loras_per_replica, + ) + else: + # sets up conditional vars for the interactive mode to not skip prompts + interactive_mode = True + input_model_config = get_input_model_via_interactive_inputs() + + model_config = get_model_config(input_model_config) + if interactive_mode and Confirm.ask( + "[bold]Further customize the auto-scaling config", default=False + ): + model_config = override_model_configs(model_config) + + if external_model_id: + model_config["model_loading_config"]["model_id"] = external_model_id + + if override_lora_uri: + model_config["lora_config"]["dynamic_lora_loading_path"] = override_lora_uri + + if enable_chunk_prefill is not None: + model_config["engine_kwargs"]["enable_chunked_prefill"] = enable_chunk_prefill + + if max_num_batched_tokens is not None: + model_config["engine_kwargs"]["max_num_batched_tokens"] = max_num_batched_tokens + + timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S") + + _format_yaml_dumper() + + # Write the model config file to disk + model_config_path = _write_model_config_to_disk( + model_config, input_model_config.id, timestamp + ) + serve_config = get_serve_config(model_config_path) + + full_file_path = _write_config_to_disk(serve_config, timestamp) + + print( + f"\nYour serve configuration file is successfully written to {full_file_path}\n" + ) + + if input_model_config.id not in DEFAULT_MODEL_ID_TO_GPU: + print( + f"Note: we don't have serving defaults for {input_model_config.id} " + "and we generally recommend you going over engine_kwargs in the yaml before serving. " + ) + + # Define the serve run command + command_str = f"serve run {full_file_path}" + print(f"Start the RayLLM app on this workspace by running: {command_str}") + + +if __name__ == "__main__": + typer.run(gen_config) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e957fb675158c34b6c74f72d035fd271c20f0853 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__pycache__/constants.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__pycache__/constants.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94a7b638250c56ec7c0b1d4f2eb27d8becd1b34e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__pycache__/constants.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__pycache__/files.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__pycache__/files.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2ac9e18a9e111d65e67589443312f4d2576c3cc Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__pycache__/files.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__pycache__/gpu.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__pycache__/gpu.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..403fd5728bfdc3bd091e0b411d7a0c58bf5dcdc2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__pycache__/gpu.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__pycache__/input_converter.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__pycache__/input_converter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e205499429699c7a9b19aefd95a59df7f28e132 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__pycache__/input_converter.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__pycache__/models.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__pycache__/models.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6d26098f2d68f4c0bfe19db83e272d4c90765e7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__pycache__/models.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__pycache__/overrides.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__pycache__/overrides.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f22751e6010176b862f810667310e3943e97d23 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__pycache__/overrides.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__pycache__/prompt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__pycache__/prompt.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85474f6dc5a122ed9a259b89c9850bbd388f402a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__pycache__/prompt.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__pycache__/text_completion.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__pycache__/text_completion.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75061bff6c6f44de3d543475fdc4656374a8bd97 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/__pycache__/text_completion.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/constants.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..b3858c098391c124e359954964ecf4bfed556e77 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/constants.py @@ -0,0 +1,20 @@ +import os + +from ray.llm._internal.serve.configs.constants import RAYLLM_HOME_DIR + +TEMPLATE_DIR = os.path.normpath( + os.path.join( + os.path.dirname(os.path.abspath(__file__)), "..", "base_configs", "templates" + ) +) + +HF_TOKEN_FILE = os.path.join(RAYLLM_HOME_DIR, ".HF_TOKEN") + +DEFAULT_DEPLOYMENT_CONFIGS_FILE = "default_deployment_configs.yaml" + + +def get_lora_storage_uri(): + lora_path = os.environ.get( + "RAYLLM_LORA_STORAGE_URI", os.path.join(RAYLLM_HOME_DIR, "lora_ckpts") + ) + return lora_path diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/files.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/files.py new file mode 100644 index 0000000000000000000000000000000000000000..34ef8879eb471aa28bd2556712ed20d5df640412 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/files.py @@ -0,0 +1,48 @@ +import os +from typing import Optional + +from rich import print + +from ray.llm._internal.serve.config_generator.utils.constants import HF_TOKEN_FILE +from ray.llm._internal.serve.config_generator.utils.prompt import BoldPrompt + + +def _read_persisted_hf_token() -> Optional[str]: + if os.path.exists(HF_TOKEN_FILE): + with open(HF_TOKEN_FILE, "r") as file: + token = file.read().strip() + if token: + return token + else: + return None + else: + return None + + +def clear_hf_token(): + if os.path.isfile(HF_TOKEN_FILE): + os.remove(HF_TOKEN_FILE) + + +def _write_hf_token(token: str): + os.makedirs(os.path.dirname(HF_TOKEN_FILE), exist_ok=True) + with open(HF_TOKEN_FILE, "w") as file: + file.write(token) + + +_HF_TOKEN_PROMPT = "Please provide Hugging Face Access Token. Please get your token at https://huggingface.co/settings/tokens" + + +def get_hf_token(): + """ + Read from the local file if HF token is already persisted. If not, ask users for it. + """ + stored_hf_token = _read_persisted_hf_token() + + if stored_hf_token: + print(f"Your HuggingFace token is read from {HF_TOKEN_FILE}") + return stored_hf_token + else: + hf_token = BoldPrompt.ask(_HF_TOKEN_PROMPT, default=None) + _write_hf_token(hf_token) + return hf_token diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/gpu.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/gpu.py new file mode 100644 index 0000000000000000000000000000000000000000..74d57723ad82f002b283210555e022c27ce85383 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/gpu.py @@ -0,0 +1,45 @@ +import os +from typing import Dict, List + +import yaml + +from ray.llm._internal.serve.config_generator.utils.constants import ( + DEFAULT_DEPLOYMENT_CONFIGS_FILE, + TEMPLATE_DIR, +) +from ray.llm._internal.serve.configs.server_models import GPUType + +# All practical GPUs +ALL_GPU_TYPES = [ + GPUType.NVIDIA_L4, + GPUType.NVIDIA_L40S, + GPUType.NVIDIA_TESLA_A10G, + GPUType.NVIDIA_A100_40G, + GPUType.NVIDIA_A100_80G, + GPUType.NVIDIA_H100, +] + + +def read_model_id_to_gpu_mapping() -> Dict[str, List[str]]: + file_path = os.path.join(TEMPLATE_DIR, DEFAULT_DEPLOYMENT_CONFIGS_FILE) + with open(file_path, "r") as stream: + configs = yaml.safe_load(stream) + model_id_configs = configs["model_id_to_gpu_deployment_configs"] + return { + model_id: list(model_config.keys()) + for model_id, model_config in model_id_configs.items() + } + + +DEFAULT_MODEL_ID_TO_GPU: Dict[str, str] = read_model_id_to_gpu_mapping() + + +def get_available_gpu_types(model_id: str) -> List[GPUType]: + """ + If we know the models run only on larger GPUs, we exclude the smaller GPUs from the options. + """ + if model_id in DEFAULT_MODEL_ID_TO_GPU: + gpus = [GPUType(gpu) for gpu in DEFAULT_MODEL_ID_TO_GPU[model_id]] + else: + gpus = ALL_GPU_TYPES + return gpus diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/input_converter.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/input_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..b9965c77bd08163d18f4ef50d155655feb41bfc5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/input_converter.py @@ -0,0 +1,28 @@ +from typing import Optional + +from ray.llm._internal.serve.config_generator.utils.gpu import GPUType +from ray.llm._internal.serve.config_generator.utils.models import ( + TextCompletionLoraModelConfig, + TextCompletionModelConfig, +) + + +def convert_inputs_to_text_completion_model( + *, + model_id: str, + gpu_type: GPUType, + tensor_parallelism: int, + hf_token: Optional[str] = None, + remote_storage_uri: Optional[str] = None, + lora_config: Optional[TextCompletionLoraModelConfig] = None, + reference_model_id: Optional[str] = None, +) -> TextCompletionModelConfig: + return TextCompletionModelConfig( + id=model_id, + hf_token=hf_token, + remote_storage_uri=remote_storage_uri, + gpu_type=gpu_type, + tensor_parallelism=tensor_parallelism, + lora_config=lora_config, + reference_model_id=reference_model_id, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/models.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/models.py new file mode 100644 index 0000000000000000000000000000000000000000..70e2fdd34f1406ce71f01d587fdbe5d66c0458d2 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/models.py @@ -0,0 +1,35 @@ +from typing import Literal, Optional + +from pydantic import BaseModel, Field + +from ray.llm._internal.serve.config_generator.utils.gpu import GPUType + +TEXT_COMPLETION_MODEL_TYPE: Literal["TextCompletion"] = "TextCompletion" + +ModelType = Literal["TextCompletion"] + + +class ServeModel(BaseModel): + id: str + hf_token: Optional[str] = None + remote_storage_uri: Optional[str] = None + gpu_type: GPUType + + +class TextCompletionLoraModelConfig(BaseModel): + max_num_lora_per_replica: int + uri: Optional[str] = Field( + None, + description="If not provided, we default to `/lora_ckpts`", + ) + + +class TextCompletionModelConfig(ServeModel): + type: Literal["TextCompletion"] = TEXT_COMPLETION_MODEL_TYPE + + reference_model_id: Optional[str] = Field( + None, + description="This field only exists for custom user entered models whose serving defaults we don't have.", + ) + tensor_parallelism: int + lora_config: Optional[TextCompletionLoraModelConfig] = None diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/overrides.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/overrides.py new file mode 100644 index 0000000000000000000000000000000000000000..9397d68b30ab3e0a297beedee0b0ccf5d7ac0e43 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/overrides.py @@ -0,0 +1,107 @@ +import copy +import inspect +from typing import Any, Dict, List, Type, TypeVar + +from pydantic import BaseModel +from pydantic.fields import FieldInfo + +from ray.llm._internal.serve.config_generator.utils.prompt import ( + BoldIntPrompt, + BoldPrompt, +) + +Model = TypeVar("Model", bound=BaseModel) + + +def _is_type_or_subclass(obj, target_type) -> bool: + """Check if obj is target_type or a subclass of target_type.""" + return obj is target_type or (inspect.isclass(obj) and issubclass(obj, target_type)) + + +def _check_type_in_optional(type_obj, target_type) -> bool: + """Check if an Optional type contains target_type or its subclass.""" + if ( + hasattr(type_obj, "__args__") + and len(type_obj.__args__) == 2 + and type(None) in type_obj.__args__ + ): + # Check each non-None argument + for arg in type_obj.__args__: + if arg is not type(None) and _is_type_or_subclass(arg, target_type): + return True + return False + + +def _is_type_expected(field_info: FieldInfo, target_type) -> bool: + """Generic function to check if a field expects a specific type or its subclasses. + + This handles both direct types and Optional[type] types. + """ + # For Pydantic v2 + if hasattr(field_info, "annotation"): + annotation = field_info.annotation + # Direct type check + if _is_type_or_subclass(annotation, target_type): + return True + # Optional type check + if _check_type_in_optional(annotation, target_type): + return True + + # For Pydantic v1 + elif hasattr(field_info, "type_"): + type_ = field_info.type_ + # Direct type check + if _is_type_or_subclass(type_, target_type): + return True + # Optional type check + if _check_type_in_optional(type_, target_type): + return True + + return False + + +def ask_and_merge_model_overrides( + existing_configs: Dict[str, Any], + model_cls: Type[Model], + fields: List[str], + defaults: Dict[str, Any] = None, +) -> Dict[str, Any]: + """ + Given the existing values and the specified overrideable pydantic fields, + this method constructs a new dict with the override values. + """ + overrides = copy.deepcopy(existing_configs) + # Check if we're using Pydantic v1 or v2 + cls_fields = getattr(model_cls, "model_fields", None) or getattr( + model_cls, "__fields__", {} + ) + + defaults = defaults or {} + for field in fields: + if field in cls_fields: + field_info = cls_fields[field] + # Get description - handle both v1 and v2 + description = "" + if hasattr(field_info, "description"): # v2 + description = field_info.description or "" + elif hasattr(field_info, "field_info") and hasattr( + field_info.field_info, "description" + ): # v1 + description = field_info.field_info.description or "" + + # Get default - handle both v1 and v2 + default = defaults.get(field) or field_info.default + + if _is_type_expected(field_info, int) or _is_type_expected( + field_info, float + ): + val = BoldIntPrompt.ask( + f"{description} Please provide a value for {field}", default=default + ) + val = float(val) + else: + val = BoldPrompt.ask( + f"{description} Please provide a value for {field}", default=default + ) + overrides[field] = val + return overrides diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/prompt.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..110cf5dfdeb3e7782568b7c0cef9888c0b366143 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/prompt.py @@ -0,0 +1,15 @@ +from rich.prompt import IntPrompt, Prompt + + +class BoldPrompt(Prompt): + @classmethod + def ask(cls, prompt: str, **kwargs): + # Automatically apply bold style to the BoldPrompt + return Prompt.ask(f"[bold]{prompt}[/bold]", **kwargs) + + +class BoldIntPrompt(IntPrompt): + @classmethod + def ask(cls, prompt: str, **kwargs): + # Automatically apply bold style to the BoldPrompt + return IntPrompt.ask(f"[bold]{prompt}[/bold]", **kwargs) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/text_completion.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/text_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..8f3f6e155d36572cfb810570177e3d406204d430 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/config_generator/utils/text_completion.py @@ -0,0 +1,113 @@ +import os +from functools import cache +from typing import Any, Dict, Optional, Union + +import yaml + +from ray.llm._internal.serve.config_generator.utils.constants import ( + DEFAULT_DEPLOYMENT_CONFIGS_FILE, + TEMPLATE_DIR, +) +from ray.llm._internal.serve.config_generator.utils.gpu import ( + DEFAULT_MODEL_ID_TO_GPU, + GPUType, +) +from ray.llm._internal.serve.config_generator.utils.models import ( + TextCompletionModelConfig, +) +from ray.llm._internal.serve.configs.server_models import LLMConfig + + +def get_model_default_config(model_id: str) -> Dict[str, Any]: + return { + "model_loading_config": { + "model_id": model_id, + }, + } + + +@cache +def get_default_llm_config(model_id: str, gpu_type: GPUType) -> LLMConfig: + file_path = os.path.join(TEMPLATE_DIR, DEFAULT_DEPLOYMENT_CONFIGS_FILE) + with open(file_path, "r") as stream: + configs = yaml.safe_load(stream) + return LLMConfig.model_validate( + configs["model_id_to_gpu_deployment_configs"][model_id][gpu_type.value] + ) + + +def populate_text_completion_model_config( + input_model_config: TextCompletionModelConfig, +) -> Dict[str, Any]: + """ + This method constructs the model config for text completion models. + + If the model configs are provided, we read the files from disks. + If the reference model id is 'other', we use the default config for the model. + """ + if input_model_config.id in DEFAULT_MODEL_ID_TO_GPU: + base_config = get_model_default_config(input_model_config.id) + llm_config = get_default_llm_config( + model_id=input_model_config.id, gpu_type=input_model_config.gpu_type + ) + else: + assert input_model_config.reference_model_id + base_config = get_model_default_config(input_model_config.id) + llm_config = LLMConfig.model_validate(base_config) + + if input_model_config.hf_token: + base_config.setdefault("runtime_env", {}).setdefault("env_vars", {})[ + "HF_TOKEN" + ] = input_model_config.hf_token + + base_config["accelerator_type"] = input_model_config.gpu_type.value + + base_config["deployment_config"] = _populate_deployment_config( + base_config.setdefault("deployment_config", {}), + llm_config, + ) + base_config["model_loading_config"] = _populate_model_loading_config( + model_id=input_model_config.id, + remote_storage_uri=input_model_config.remote_storage_uri, + tp_degree=input_model_config.tensor_parallelism, + ) + _populate_engine_kwargs(base_config, llm_config, input_model_config) + + return base_config + + +def _populate_deployment_config( + deployment_config: Dict[str, Any], + llm_config: LLMConfig, +) -> Dict[str, Any]: + deployment_config.update(llm_config.deployment_config) + return deployment_config + + +def _populate_model_loading_config( + *, model_id: str, remote_storage_uri: Optional[str], tp_degree: int +) -> Dict[str, Union[str, Dict[str, str]]]: + model_loading_config = {"model_id": model_id} + if remote_storage_uri: + model_loading_config["model_source"] = {"bucket_uri": remote_storage_uri} + else: + model_loading_config["model_source"] = model_id + + return model_loading_config + + +def _populate_engine_kwargs( + configs: Dict[str, Any], + llm_config: LLMConfig, + input_model_config: TextCompletionModelConfig, +) -> None: + + engine_kwargs = configs.setdefault("engine_kwargs", {}) + engine_kwargs.update(llm_config.engine_kwargs) + engine_kwargs.update( + { + "tensor_parallel_size": input_model_config.tensor_parallelism, + } + ) + + return engine_kwargs diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/configs/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/configs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/configs/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/configs/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc64de871753009917893372144a82225329b5ad Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/configs/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/configs/__pycache__/constants.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/configs/__pycache__/constants.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..77277ed6ced10451e553d7bb1ad6d05d21ded25f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/configs/__pycache__/constants.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/configs/__pycache__/openai_api_models.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/configs/__pycache__/openai_api_models.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1f7e5643e623c3017d6146db53d89b07f35837d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/configs/__pycache__/openai_api_models.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/configs/__pycache__/server_models.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/configs/__pycache__/server_models.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89e6c829024066d39c9f25f9995454f1896fceb5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/configs/__pycache__/server_models.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/configs/constants.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/configs/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..f5571a402f8dc5a791d43d91e1969313e474246d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/configs/constants.py @@ -0,0 +1,103 @@ +import os + +ALLOW_NEW_PLACEMENT_GROUPS_IN_DEPLOYMENT = int( + os.getenv("RAYLLM_ALLOW_NEW_PLACEMENT_GROUPS_IN_DEPLOYMENT", "1") +) + + +# Timeout before download in multiplex deployment fails. <=0 means no timeout. +DEFAULT_MULTIPLEX_DOWNLOAD_TIMEOUT_S = float( + os.getenv("DEFAULT_MULTIPLEX_DOWNLOAD_TIMEOUT_S", "30") +) +if DEFAULT_MULTIPLEX_DOWNLOAD_TIMEOUT_S <= 0: + DEFAULT_MULTIPLEX_DOWNLOAD_TIMEOUT_S = None + + +# Number of retries for downloading a model in multiplex deployment. +DEFAULT_MULTIPLEX_DOWNLOAD_TRIES = int( + os.getenv("DEFAULT_MULTIPLEX_DOWNLOAD_RETRIES", "3") +) + + +# If true, a default runtime_env will be injected to import rayllm on worker startup. +# This is a startup time optimization to avoid the latency penalty of sequentially +# importing rayllm in multiple layers of worker processes. +ENABLE_WORKER_PROCESS_SETUP_HOOK = ( + os.environ.get("RAYLLM_ENABLE_WORKER_PROCESS_SETUP_HOOK", "1") == "1" +) + + +CLOUD_OBJECT_MISSING_EXPIRE_S = 30 +CLOUD_OBJECT_EXISTS_EXPIRE_S = 60 * 60 + +# Sentinel object used to indicate that a LoRA adapter config file is missing. +LORA_ADAPTER_CONFIG_NAME = "adapter_config.json" + +DEFAULT_HEALTH_CHECK_PERIOD_S = int( + os.getenv("RAY_SERVE_LLM_DEFAULT_HEALTH_CHECK_PERIOD_S", "10") +) +DEFAULT_HEALTH_CHECK_TIMEOUT_S = int( + os.getenv("RAY_SERVE_LLM_DEFAULT_HEALTH_CHECK_TIMEOUT_S", "10") +) +DEFAULT_MAX_ONGOING_REQUESTS = int( + os.getenv("RAY_SERVE_LLM_DEFAULT_MAX_ONGOING_REQUESTS", str(int(1e9))) +) +DEFAULT_MAX_REPLICAS = int(os.getenv("RAY_SERVE_LLM_DEFAULT_MAX_REPLICAS", "10")) +DEFAULT_MAX_TARGET_ONGOING_REQUESTS = int( + os.getenv("RAY_SERVE_LLM_DEFAULT_MAX_TARGET_ONGOING_REQUESTS", str(int(1e9))) +) + + +ENGINE_START_TIMEOUT_S = int(os.getenv("RAYLLM_ENGINE_START_TIMEOUT_S", str(60 * 60))) + +MIN_NUM_TOPLOGPROBS_ALLOWED = 0 +MAX_NUM_TOPLOGPROBS_ALLOWED = 5 +MODEL_RESPONSE_BATCH_TIMEOUT_MS = float( + os.getenv("RAYLLM_MODEL_RESPONSE_BATCH_TIMEOUT_MS", "50") +) +RAYLLM_ENABLE_REQUEST_PROMPT_LOGS = ( + os.environ.get("RAYLLM_ENABLE_REQUEST_PROMPT_LOGS", "1") == "1" +) +RAYLLM_GUIDED_DECODING_BACKEND = os.environ.get( + "RAYLLM_GUIDED_DECODING_BACKEND", "xgrammar" +) + +MAX_NUM_STOPPING_SEQUENCES = int(os.getenv("RAYLLM_MAX_NUM_STOPPING_SEQUENCES", "8")) +ENV_VARS_TO_PROPAGATE = { + "HUGGING_FACE_HUB_TOKEN", + "HF_TOKEN", +} +# timeout in 10 minutes. Streaming can take longer than 3 min +DEFAULT_LLM_ROUTER_HTTP_TIMEOUT = float( + os.environ.get("RAY_SERVE_LLM_ROUTER_HTTP_TIMEOUT", 600) +) + +ENABLE_VERBOSE_TELEMETRY = bool(int(os.getenv("RAYLLM_ENABLE_VERBOSE_TELEMETRY", "0"))) + +RAYLLM_VLLM_ENGINE_CLS_ENV = "RAYLLM_VLLM_ENGINE_CLS" + +# The ratio of number of router replicas to number of model replicas. +# Default to 2 meaning that there are 2 router replicas for every model replica. +DEFAULT_ROUTER_TO_MODEL_REPLICA_RATIO = float( + os.getenv("RAY_SERVE_LLM_ROUTER_TO_MODEL_REPLICA_RATIO", "2") +) + +DEFAULT_LLM_ROUTER_MIN_REPLICAS = int( + os.environ.get("RAY_SERVE_LLM_ROUTER_MIN_REPLICAS", 0) +) +DEFAULT_LLM_ROUTER_INITIAL_REPLICAS = int( + os.environ.get("RAY_SERVE_LLM_ROUTER_INITIAL_REPLICAS", 2) +) +DEFAULT_LLM_ROUTER_MAX_REPLICAS = int( + os.environ.get("RAY_SERVE_LLM_ROUTER_MAX_REPLICAS", 16) +) +DEFAULT_LLM_ROUTER_TARGET_ONGOING_REQUESTS = int( + os.environ.get( + "RAY_SERVE_LLM_ROUTER_TARGET_ONGOING_REQUESTS", + DEFAULT_MAX_TARGET_ONGOING_REQUESTS, + ) +) + + +# HOME DIR +RAYLLM_HOME_DIR = os.environ.get("RAYLLM_HOME_DIR", os.path.expanduser("~/.ray/llm")) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/configs/openai_api_models.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/configs/openai_api_models.py new file mode 100644 index 0000000000000000000000000000000000000000..bb0b195d93f4b7ce5f376f471aeb6c1fe5ebd24d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/configs/openai_api_models.py @@ -0,0 +1,177 @@ +"""This module contains the wrapper classes for vLLM's OpenAI implementation. + +If there are any major differences in the interface, the expectation is that +they will be upstreamed to vLLM. +""" + +from typing import TYPE_CHECKING, Any, AsyncGenerator, Dict, List, Optional, Union + +from pydantic import ( + BaseModel, + ConfigDict, + Field, +) +from vllm.entrypoints.openai.protocol import ( + ChatCompletionRequest as vLLMChatCompletionRequest, + ChatCompletionResponse as vLLMChatCompletionResponse, + ChatCompletionStreamResponse as vLLMChatCompletionStreamResponse, + CompletionRequest as vLLMCompletionRequest, + CompletionResponse as vLLMCompletionResponse, + CompletionStreamResponse as vLLMCompletionStreamResponse, + EmbeddingChatRequest as vLLMEmbeddingChatRequest, + EmbeddingCompletionRequest as vLLMEmbeddingCompletionRequest, + EmbeddingResponse as vLLMEmbeddingResponse, + ErrorResponse as vLLMErrorResponse, +) +from vllm.utils import random_uuid + +if TYPE_CHECKING: + from ray.llm._internal.serve.configs.server_models import LLMConfig + + +class ChatCompletionRequest(vLLMChatCompletionRequest): + model_config = ConfigDict(arbitrary_types_allowed=True) + + +class ChatCompletionResponse(vLLMChatCompletionResponse): + model_config = ConfigDict(arbitrary_types_allowed=True) + + +class ChatCompletionStreamResponse(vLLMChatCompletionStreamResponse): + model_config = ConfigDict(arbitrary_types_allowed=True) + + +class ErrorResponse(vLLMErrorResponse): + model_config = ConfigDict(arbitrary_types_allowed=True) + + +# TODO (Kourosh): Upstream +class CompletionRequest(vLLMCompletionRequest): + model_config = ConfigDict(arbitrary_types_allowed=True) + + request_id: str = Field( + default_factory=lambda: f"{random_uuid()}", + description=( + "The request_id related to this request. If the caller does " + "not set it, a random_uuid will be generated. This id is used " + "through out the inference process and return in response." + ), + ) + + +class CompletionResponse(vLLMCompletionResponse): + model_config = ConfigDict(arbitrary_types_allowed=True) + + +class CompletionStreamResponse(vLLMCompletionStreamResponse): + model_config = ConfigDict(arbitrary_types_allowed=True) + + +# TODO (Kourosh): Upstream +class EmbeddingCompletionRequest(vLLMEmbeddingCompletionRequest): + model_config = ConfigDict(arbitrary_types_allowed=True) + + request_id: str = Field( + default_factory=lambda: f"{random_uuid()}", + description=( + "The request_id related to this request. If the caller does " + "not set it, a random_uuid will be generated. This id is used " + "through out the inference process and return in response." + ), + ) + + +class EmbeddingChatRequest(vLLMEmbeddingChatRequest): + model_config = ConfigDict(arbitrary_types_allowed=True) + + +class EmbeddingResponse(vLLMEmbeddingResponse): + model_config = ConfigDict(arbitrary_types_allowed=True) + + +EmbeddingRequest = Union[EmbeddingCompletionRequest, EmbeddingChatRequest] + +LLMEmbeddingsResponse = Union[ + AsyncGenerator[Union[EmbeddingResponse, ErrorResponse], None], +] + +LLMChatResponse = Union[ + AsyncGenerator[Union[str, ChatCompletionResponse, ErrorResponse], None], +] + +LLMCompletionsResponse = Union[ + AsyncGenerator[ + Union[CompletionStreamResponse, CompletionResponse, ErrorResponse], None + ], +] + +# TODO: remove this class +class OpenAIHTTPException(Exception): + def __init__( + self, + status_code: int, + message: str, + type: str = "Unknown", + internal_message: Optional[str] = None, + ) -> None: + self.status_code = status_code + self.message = message + self.type = type + self.internal_message = internal_message + + +# TODO: upstream metadata for ModelData +# Compared to vLLM this has a metadata field. +class ModelCard(BaseModel): + model_config = ConfigDict( + protected_namespaces=tuple(), arbitrary_types_allowed=True + ) + + id: str + object: str + owned_by: str + permission: List[str] + metadata: Dict[str, Any] + + @property + def model_type(self) -> str: + return self.metadata["engine_config"]["model_type"] + + +class ModelList(BaseModel): + model_config = ConfigDict(arbitrary_types_allowed=True) + data: List[ModelCard] + object: str = "list" + + +def to_model_metadata( + model_id: str, + model_config: "LLMConfig", + overrides: Optional[Dict[str, Any]] = None, +) -> ModelCard: + """Creates an OpenAI-compatible ModelData object. + + Args: + model_id: The ID of the model. Should contain the suffix if the model + is LoRA fine-tuned. For example: + meta-llama/Llama-2-7b-chat-hf:my_suffix:aBc1234 + model_config: The model's YAML config. + overrides: should only be set for LoRA fine-tuned models. The + overrides of the fine-tuned model metadata. + """ + metadata = { + "model_id": model_config.model_id, + "input_modality": model_config.input_modality, + "max_request_context_length": model_config.max_request_context_length, + } + + if overrides: + metadata.update(overrides) + + return ModelCard( + id=model_id, + object="model", + owned_by="organization-owner", + permission=[], + metadata=metadata, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/configs/server_models.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/configs/server_models.py new file mode 100644 index 0000000000000000000000000000000000000000..910fce823c0c53fcc0e1d544a59f6ee6d1f859d7 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/configs/server_models.py @@ -0,0 +1,680 @@ +import os +from enum import Enum +from typing import ( + Any, + Dict, + List, + Optional, + Sequence, + TypeVar, + Union, +) + +import pydantic +from pydantic import ( + BaseModel, + Field, + PositiveInt, + PrivateAttr, + field_validator, + model_validator, +) + +import ray +import ray.util.accelerators.accelerators as accelerators +from ray.llm._internal.common.base_pydantic import BaseModelExtended +from ray.llm._internal.common.utils.cloud_utils import ( + CloudMirrorConfig, + is_remote_path, +) +from ray.llm._internal.common.utils.import_utils import try_import +from ray.llm._internal.serve.configs.constants import ( + DEFAULT_MAX_ONGOING_REQUESTS, + DEFAULT_MULTIPLEX_DOWNLOAD_TIMEOUT_S, + DEFAULT_MULTIPLEX_DOWNLOAD_TRIES, + ENABLE_WORKER_PROCESS_SETUP_HOOK, + MODEL_RESPONSE_BATCH_TIMEOUT_MS, +) +from ray.llm._internal.serve.deployments.llm.vllm.kv_transfer_backends import ( + SUPPORTED_BACKENDS as SUPPORTED_KV_CONNECTOR_BACKENDS, +) +from ray.llm._internal.serve.observability.logging import get_logger +from ray.serve._private.config import DeploymentConfig + +transformers = try_import("transformers") + + +GPUType = Enum("GPUType", vars(accelerators)) +ModelT = TypeVar("ModelT", bound=BaseModel) + + +logger = get_logger(__name__) + + +class ServeMultiplexConfig(BaseModelExtended): + max_num_models_per_replica: PositiveInt = Field( + ..., description="The maximum number of models to be loaded on each replica." + ) + download_timeout_s: Optional[float] = Field( + DEFAULT_MULTIPLEX_DOWNLOAD_TIMEOUT_S, + description="How much time the download subprocess has to download a single LoRA before a timeout. None means no timeout.", + ) + max_download_tries: int = Field( + DEFAULT_MULTIPLEX_DOWNLOAD_TRIES, + description="The maximum number of download retries.", + ) + + +class InputModality(str, Enum): + text = "text" + image = "image" + + +class LLMEngine(str, Enum): + """Enum that represents an LLMEngine.""" + + vLLM = "vLLM" + + +class LoraConfig(BaseModelExtended): + dynamic_lora_loading_path: Optional[str] = Field( + default=None, + description="Cloud storage path where LoRA adapter weights are stored.", + ) + max_num_adapters_per_replica: PositiveInt = Field( + default=16, + description="The maximum number of adapters load on each replica.", + ) + download_timeout_s: Optional[float] = Field( + DEFAULT_MULTIPLEX_DOWNLOAD_TIMEOUT_S, + description=( + "How much time the download subprocess has to download a single " + "LoRA before a timeout. None means no timeout." + ), + ) + max_download_tries: int = Field( + DEFAULT_MULTIPLEX_DOWNLOAD_TRIES, + description="The maximum number of download retries.", + ) + + @field_validator("dynamic_lora_loading_path") + def validate_dynamic_lora_loading_path(cls, value: Optional[str]): + if value is None: + return value + + assert is_remote_path(value), ( + "Only AWS S3 and Google Cloud Storage are supported. The " + 'dynamic_lora_loading_path must start with "s3://" or "gs://". ' + f'Got "{value}" instead.' + ) + return value.rstrip("/") + + +class ModelLoadingConfig(BaseModelExtended): + + model_id: str = Field( + description="The ID that should be used by end users to access this model.", + ) + model_source: Optional[Union[str, CloudMirrorConfig]] = Field( + default=None, + description=( + "Where to obtain the model weights from. " + "Should be a HuggingFace model ID, S3 mirror config, GCS mirror config, " + "or a local path. When omitted, defaults to the model_id as a " + "HuggingFace model ID." + ), + ) + tokenizer_source: Optional[str] = Field( + default=None, + description=( + "Where to obtain the tokenizer from. If None, tokenizer is " + "obtained from the model source. Only HuggingFace IDs are " + "supported for now." + ), + ) + + +EngineConfigType = Union[None, "VLLMEngineConfig"] # noqa: F821 + + +class LLMConfig(BaseModelExtended): + + runtime_env: Optional[Dict[str, Any]] = Field( + default=None, + description=( + "The runtime_env to use for the model deployment replica " + "and the engine workers." + ), + ) + + model_loading_config: Union[Dict[str, Any], ModelLoadingConfig] = Field( + description="The settings for how to download and expose the model. Validated against ModelLoadingConfig." + ) + + llm_engine: str = Field( + default=LLMEngine.vLLM.value, + description=f"The LLMEngine that should be used to run the model. Only the following values are supported: {str([t.value for t in LLMEngine])}", + ) + + engine_kwargs: Dict[str, Any] = Field( + default={}, + description=( + "Additional keyword arguments for the engine. In case of vLLM, " + "this will include all the configuration knobs they provide out " + "of the box, except for tensor-parallelism which is set " + "automatically from Ray Serve configs." + ), + ) + + resources_per_bundle: Optional[Dict[str, float]] = Field( + default=None, + description="This will override the default resource bundles for placement groups. " + "You can specify a custom device label e.g. {'NPU': 1}. " + "The default resource bundle for LLM Stage is always a GPU resource i.e. {'GPU': 1}.", + ) + + accelerator_type: Optional[str] = Field( + default=None, + description=f"The type of accelerator runs the model on. Only the following values are supported: {str([t.value for t in GPUType])}", + ) + + lora_config: Optional[Union[Dict[str, Any], LoraConfig]] = Field( + default=None, + description="Settings for LoRA adapter. Validated against LoraConfig.", + ) + + deployment_config: Dict[str, Any] = Field( + default_factory=dict, + description=""" + The Ray @server.deployment options. + Supported fields are: + `name`, `num_replicas`, `ray_actor_options`, `max_ongoing_requests`, + `autoscaling_config`, `max_queued_requests`, `user_config`, + `health_check_period_s`, `health_check_timeout_s`, + `graceful_shutdown_wait_loop_s`, `graceful_shutdown_timeout_s`, + `logging_config`, `request_router_config`. + For more details, see the `Ray Serve Documentation `_. + """, + ) + + experimental_configs: Dict[str, Any] = Field( + default_factory=dict, + description="Experimental configurations for Ray Serve LLM. This is a " + "dictionary of key-value pairs. Current supported keys are:\n" + "- `stream_batching_interval_ms`: Ray Serve LLM batches streaming " + "requests together. This config decides how long to wait for the " + "batch before processing the requests. Defaults to " + f"{MODEL_RESPONSE_BATCH_TIMEOUT_MS}.\n" + "- `num_router_replicas`: The number of replicas for the router. Ray " + "Serve will take the max amount all the replicas. Default would be 2 " + "router replicas per model replica.\n", + ) + + log_engine_metrics: Optional[bool] = Field( + default=False, + description="Enable additional engine metrics via Ray Prometheus port. Only compatible with V1 vLLM engine. NOTE: once v1 is fully rolled out, we will remove this flag and turn it on by default.", + ) + + _supports_vision: bool = PrivateAttr(False) + _model_architecture: str = PrivateAttr("UNSPECIFIED") + _engine_config: EngineConfigType = PrivateAttr(None) + + def _infer_supports_vision(self, model_id_or_path: str) -> None: + """Called in llm node initializer together with other transformers calls. It + loads the model config from huggingface and sets the supports_vision + attribute based on whether the config has `vision_config`. All LVM models has + `vision_config` setup. + """ + try: + hf_config = transformers.PretrainedConfig.from_pretrained(model_id_or_path) + self._supports_vision = hasattr(hf_config, "vision_config") + except Exception as e: + raise ValueError( + f"Failed to load Hugging Face config for model_id='{model_id_or_path}'.\ + Ensure `model_id` is a valid Hugging Face repo or a local path that \ + contains a valid `config.json` file. " + f"Original error: {repr(e)}" + ) from e + + def _set_model_architecture( + self, + model_id_or_path: Optional[str] = None, + model_architecture: Optional[str] = None, + ) -> None: + """Called in llm node initializer together with other transformers calls. It + loads the model config from huggingface and sets the model_architecture + attribute based on whether the config has `architectures`. + """ + if model_id_or_path: + try: + hf_config = transformers.PretrainedConfig.from_pretrained( + model_id_or_path + ) + if ( + hf_config + and hasattr(hf_config, "architectures") + and hf_config.architectures + ): + self._model_architecture = hf_config.architectures[0] + except Exception as e: + raise ValueError( + f"Failed to load Hugging Face config for model_id='{model_id_or_path}'.\ + Ensure `model_id` is a valid Hugging Face repo or a local path that \ + contains a valid `config.json` file. " + f"Original error: {repr(e)}" + ) from e + + if model_architecture: + self._model_architecture = model_architecture + + def apply_checkpoint_info( + self, model_id_or_path: str, trust_remote_code: bool = False + ) -> None: + """Apply the checkpoint info to the model config.""" + self._infer_supports_vision(model_id_or_path) + self._set_model_architecture(model_id_or_path) + + @property + def supports_vision(self) -> bool: + return self._supports_vision + + @property + def model_architecture(self) -> str: + return self._model_architecture + + @property + def input_modality(self) -> str: + """Returns the input modality of the model. There could be more types in the + future. Right now assumes if the model doesn't support version, it'll be text. + """ + if self.supports_vision: + return InputModality.image.value + + return InputModality.text.value + + @property + def model_id(self) -> str: + return self.model_loading_config.model_id + + @property + def max_request_context_length(self) -> Optional[int]: + return self.engine_kwargs.get("max_model_len") + + @field_validator("accelerator_type") + def validate_accelerator_type(cls, value: Optional[str]): + if value is None: + return value + + # Ensure A10 is converted to A10G. + if value == "A10": + value = "A10G" + + if value not in [t.value for t in GPUType]: + raise ValueError(f"Unsupported accelerator type: {value}") + + return value + + @field_validator("llm_engine") + def validate_llm_engine(cls, value: str) -> str: + """Validates the llm_engine string value.""" + try: + # Validate the engine + LLMEngine(value) + except ValueError as e: + raise ValueError(f"Unsupported engine: {value}") from e + return value + + @field_validator("deployment_config") + def validate_deployment_config(cls, value: Dict[str, Any]) -> Dict[str, Any]: + """Validates the deployment config dictionary.""" + try: + DeploymentConfig(**value) + except Exception as e: + raise ValueError(f"Invalid deployment config: {value}") from e + + return value + + @field_validator("model_loading_config") + def validate_model_loading_config( + cls, value: Union[Dict[str, Any], ModelLoadingConfig] + ) -> ModelLoadingConfig: + """Validates the model loading config dictionary.""" + if isinstance(value, ModelLoadingConfig): + return value + + try: + model_loading_config = ModelLoadingConfig(**value) + except Exception as e: + raise ValueError(f"Invalid model_loading_config: {value}") from e + + return model_loading_config + + @field_validator("lora_config") + def validate_lora_config( + cls, value: Optional[Union[Dict[str, Any], LoraConfig]] + ) -> Optional[LoraConfig]: + """Validates the lora config dictionary.""" + if value is None or isinstance(value, LoraConfig): + return value + + try: + lora_config = LoraConfig(**value) + except Exception as e: + raise ValueError(f"Invalid lora_config: {value}") from e + + return lora_config + + @model_validator(mode="after") + def _check_log_stats_with_metrics(self): + # Require disable_log_stats is not set to True when log_engine_metrics is enabled. + if self.log_engine_metrics and self.engine_kwargs.get("disable_log_stats"): + raise ValueError( + "disable_log_stats cannot be set to True when log_engine_metrics is enabled. " + "Engine metrics require log stats to be enabled." + ) + + return self + + def multiplex_config(self) -> ServeMultiplexConfig: + multiplex_config = None + if self.lora_config: + multiplex_config = ServeMultiplexConfig( + max_num_models_per_replica=self.lora_config.max_num_adapters_per_replica, + download_timeout_s=self.lora_config.download_timeout_s, + max_download_tries=self.lora_config.max_download_tries, + ) + return multiplex_config + + def get_engine_config(self) -> EngineConfigType: + """Returns the engine config for the given LLM config. + + LLMConfig not only has engine config but also deployment config, etc. + """ + # Note (genesu): This is important that we cache the engine config as the + # `hf_model_id` attribute on the engine config will be set based on whether + # the model is downloaded from a remote storage and will be set to the + # local path of the model. This is important for vLLM not going to Hugging + # Face to download the model again after it's already downloaded during node + # initialization step. + if self._engine_config: + return self._engine_config + + if self.llm_engine == LLMEngine.vLLM: + from ray.llm._internal.serve.deployments.llm.vllm.vllm_models import ( + VLLMEngineConfig, + ) + + self._engine_config = VLLMEngineConfig.from_llm_config(self) + else: + # Note (genesu): This should never happen because we validate the engine + # in the config. + raise ValueError(f"Unsupported engine: {self.llm_engine}") + + return self._engine_config + + def update_engine_kwargs(self, **kwargs: Any) -> None: + """Update the engine_kwargs and the engine_config engine_kwargs. + + This is typically called during engine starts, when certain engine_kwargs + (e.g., data_parallel_rank) become available. + """ + self.engine_kwargs.update(kwargs) + # engine_config may be created before engine starts, this makes sure + # the engine_config is updated with the latest engine_kwargs. + if self._engine_config: + self._engine_config.engine_kwargs.update(kwargs) + + def _set_deployment_placement_options(self) -> Dict[str, Any]: + deployment_config = self.deployment_config + engine_config = self.get_engine_config() + + ray_actor_options = deployment_config.get("ray_actor_options", {}) + deployment_config["ray_actor_options"] = ray_actor_options + + replica_actor_resources = { + "CPU": ray_actor_options.get("num_cpus", 1), + "GPU": ray_actor_options.get("num_gpus", 0), + **ray_actor_options.get("resources", {}), + } + if "memory" in ray_actor_options: + replica_actor_resources["memory"] = ray_actor_options["memory"] + + if ( + "placement_group_bundles" in deployment_config + or "placement_group_strategy" in deployment_config + ): + raise ValueError( + "placement_group_bundles and placement_group_strategy must not be specified in deployment_config. " + "Use scaling_config to configure replica placement group." + ) + + try: + bundles = engine_config.placement_bundles + except ValueError: + # May happen if all bundles are empty. + bundles = [] + + bundles = [replica_actor_resources] + bundles + deployment_config.update( + { + "placement_group_bundles": bundles, + "placement_group_strategy": engine_config.placement_strategy, + } + ) + + return deployment_config + + def _get_deployment_name(self) -> str: + return self.model_id.replace("/", "--").replace(".", "_") + + def get_serve_options( + self, + *, + name_prefix: Optional[str] = None, + ) -> Dict[str, Any]: + """Get the Serve options for the given LLM config. + + This method is used to generate the Serve options for the given LLM config. + + + Examples: + .. testcode:: + :skipif: True + + from ray import serve + from ray.serve.llm import LLMConfig, LLMServer + + llm_config = LLMConfig( + model_loading_config=dict(model_id="test_model"), + accelerator_type="L4", + runtime_env={"env_vars": {"FOO": "bar"}}, + ) + serve_options = llm_config.get_serve_options(name_prefix="Test:") + llm_app = LLMServer.as_deployment().options(**serve_options).bind(llm_config) + serve.run(llm_app) + + Args: + name_prefix: Optional prefix to be used for the deployment name. + + Returns: + The dictionary to use in .options() when creating the deployment. + """ + + deployment_options = self._set_deployment_placement_options() + + default_runtime_env = ray.get_runtime_context().runtime_env + if ENABLE_WORKER_PROCESS_SETUP_HOOK: + default_runtime_env[ + "worker_process_setup_hook" + ] = "ray.llm._internal.serve._worker_process_setup_hook" + + ray_actor_options = deployment_options.get("ray_actor_options", {}) + ray_actor_options["runtime_env"] = { + **default_runtime_env, + # Existing runtime_env should take precedence over the default. + **ray_actor_options.get("runtime_env", {}), + **(self.runtime_env if self.runtime_env else {}), + } + deployment_options["ray_actor_options"] = ray_actor_options + + # Set the name of the deployment config to map to the model ID. + if "name" not in deployment_options: + deployment_options["name"] = self._get_deployment_name() + if name_prefix: + deployment_options["name"] = name_prefix + deployment_options["name"] + + # Configure DP deployment options. + # TODO(rui): move the following to DPServer, e.g., + # deployment_options = DPServer.get_deployment_options(llm_config) + dp_size = self.engine_kwargs.get("data_parallel_size", None) + if dp_size is not None: + if "num_replicas" in deployment_options: + raise ValueError( + "num_replicas should not be specified for DP deployment, " + "use engine_kwargs.data_parallel_size instead." + ) + if "autoscaling_config" in deployment_options: + raise ValueError( + "autoscaling_config is not supported for DP deployment, " + "use engine_kwargs.data_parallel_size to set a fixed number " + "of replicas instead." + ) + deployment_options["num_replicas"] = dp_size + deployment_options["max_ongoing_requests"] = DEFAULT_MAX_ONGOING_REQUESTS + if deployment_options["placement_group_strategy"] != "STRICT_PACK": + logger.warning( + f"DP deployment with placement_strategy={deployment_options['placement_group_strategy']} " + "is not supported. Using STRICT_PACK instead." + ) + deployment_options["placement_group_strategy"] = "STRICT_PACK" + + return deployment_options + + def setup_engine_backend(self): + self._setup_kv_connector_backend() + + def _setup_kv_connector_backend(self): + """Private method to setup kv connector depending on the local deployment state""" + # 1. validate that the backend is one of the backends supported (Nixl or LMCache) + kv_transfer_config = self.engine_kwargs.get("kv_transfer_config") + if not kv_transfer_config: + return + + kv_connector = kv_transfer_config.get("kv_connector") + if not kv_connector: + raise ValueError("Connector type is not specified.") + + kv_connector_backend_class = SUPPORTED_KV_CONNECTOR_BACKENDS.get(kv_connector) + if not kv_connector_backend_class: + raise ValueError(f"Unsupported connector type: {kv_connector}") + + # 2. Setup the backend + kv_connector_backend = kv_connector_backend_class(kv_transfer_config) + kv_connector_backend.setup() + + +def _is_yaml_file(filename: str) -> bool: + yaml_extensions = [".yml", ".yaml", ".json"] + for s in yaml_extensions: + if filename.endswith(s): + return True + return False + + +def _parse_path_args(path: str) -> List[LLMConfig]: + assert os.path.exists( + path + ), f"Could not load model from {path}, as it does not exist." + if os.path.isfile(path): + with open(path, "r") as f: + llm_config = LLMConfig.parse_yaml(f) + return [llm_config] + elif os.path.isdir(path): + apps = [] + for root, _dirs, files in os.walk(path): + for p in files: + if _is_yaml_file(p): + with open(os.path.join(root, p), "r") as f: + llm_config = LLMConfig.parse_yaml(f) + apps.append(llm_config) + return apps + else: + raise ValueError( + f"Could not load model from {path}, as it is not a file or directory." + ) + + +def parse_args( + args: Union[str, LLMConfig, Any, Sequence[Union[LLMConfig, str, Any]]], +) -> List[LLMConfig]: + """Parse the input args and return a standardized list of LLMConfig objects + + Supported args format: + 1. The path to a yaml file defining your LLMConfig + 2. The path to a folder containing yaml files, which define your LLMConfigs + 3. A list of yaml files defining multiple LLMConfigs + 4. A dict or LLMConfig object + 5. A list of dicts or LLMConfig objects + """ + + raw_models = [args] + if isinstance(args, list): + raw_models = args + + # For each + models: List[LLMConfig] = [] + for raw_model in raw_models: + if isinstance(raw_model, str): + if os.path.exists(raw_model): + parsed_models = _parse_path_args(raw_model) + else: + try: + llm_config = LLMConfig.parse_yaml(raw_model) + parsed_models = [llm_config] + except pydantic.ValidationError as e: + raise ValueError( + f"Could not parse string as yaml. If you are " + "specifying a path, make sure it exists and can be " + f"reached. raw_model: {raw_model}" + ) from e + else: + try: + llm_config = LLMConfig.model_validate(raw_model) + parsed_models = [llm_config] + except pydantic.ValidationError: + parsed_models = [LLMConfig.model_validate(raw_model)] + models += parsed_models + + return models + + +class LLMServingArgs(BaseModelExtended): + llm_configs: List[Union[str, LLMConfig]] = Field( + description="A list of LLMConfigs, or paths to LLMConfigs, to run.", + ) + + def parse_args(self) -> "LLMServingArgs": + """Converts this LLMServingArgs object into an DeployArgs object.""" + + llm_configs = [] + for config in self.llm_configs: + parsed_config = parse_args(config)[0] + if not isinstance(parsed_config, LLMConfig): + raise ValueError( + "When using the new Serve config format, all model " + "configs must also use the new model config format. Got " + "a model config that doesn't match new format. Type: " + f"{type(parsed_config)}. Contents: {parsed_config}." + ) + llm_configs.append(parsed_config) + + return LLMServingArgs(llm_configs=llm_configs) + + +class DiskMultiplexConfig(BaseModelExtended): + model_id: str + max_total_tokens: Optional[int] + local_path: str + + # this is a per process id assigned to the model + lora_assigned_int_id: int diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f807579ca01b9fcfdea4439664d5365f77318a0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/data_parallel/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/data_parallel/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/data_parallel/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/data_parallel/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d834566541ee5788854edb1ade68f586bd33795 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/data_parallel/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/data_parallel/__pycache__/dp_rank_assigner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/data_parallel/__pycache__/dp_rank_assigner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a25ea8d15815549ea4fdc358a846a8c969312ca Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/data_parallel/__pycache__/dp_rank_assigner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/data_parallel/__pycache__/dp_server.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/data_parallel/__pycache__/dp_server.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..947b951944a3f6c70ac314f8d70307741fb7d109 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/data_parallel/__pycache__/dp_server.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/data_parallel/dp_rank_assigner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/data_parallel/dp_rank_assigner.py new file mode 100644 index 0000000000000000000000000000000000000000..f48496796e4da3545a6b006559eca4e73bc56060 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/data_parallel/dp_rank_assigner.py @@ -0,0 +1,42 @@ +import asyncio + +from ray import serve + + +@serve.deployment(num_replicas=1) +class DPRankAssigner: + """ + Data Parallel Rank Assigner. + + This class is used to assign a rank to each replica in the data parallel + deployment. + """ + + def __init__(self, dp_size: int): + self.dp_size = dp_size + self.lock = asyncio.Lock() + self.next_rank = 0 + self.dp_address = None + self.dp_rpc_port = None + self.master_info_event = asyncio.Event() + + async def register(self, replica_ctx: "serve.context.ReplicaContext"): + async with self.lock: + if self.next_rank >= self.dp_size: + raise ValueError( + f"Attempted to assign rank {self.next_rank} but dp_size is {self.dp_size}" + ) + # TODO(rui): instead of using the naive increment approach, + # we should use the Ray Serve Replica Rank API to assign ranks. + rank = self.next_rank + self.next_rank += 1 + return rank + + async def set_dp_master_info(self, dp_address: str, dp_rpc_port: int): + self.dp_address = dp_address + self.dp_rpc_port = dp_rpc_port + self.master_info_event.set() + + async def get_dp_master_info(self): + await self.master_info_event.wait() + return self.dp_address, self.dp_rpc_port diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/data_parallel/dp_server.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/data_parallel/dp_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7fb1cc2f49a143b2983342eca413fea6d0c3ce14 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/data_parallel/dp_server.py @@ -0,0 +1,88 @@ +import logging +import time +from typing import Optional + +from ray import serve +from ray.experimental.collective.util import get_address_and_port +from ray.llm._internal.serve.configs.server_models import LLMConfig +from ray.llm._internal.serve.deployments.data_parallel.dp_rank_assigner import ( + DPRankAssigner, +) +from ray.llm._internal.serve.deployments.llm.llm_server import LLMServer +from ray.serve.deployment import Application +from ray.serve.handle import DeploymentHandle + +logger = logging.getLogger(__name__) + + +class DPServer(LLMServer): + """ + Data Parallel LLM Server. + + This class is used to serve data parallel attention (DP Attention) + deployment paradigm, where the attention layers are replicated and + the MoE layers are sharded. DP Attention is typically used for models + like DeepSeek-V3. + """ + + async def __init__(self, llm_config: LLMConfig, dp_rank_assigner: DeploymentHandle): + self.dp_rank_assigner = dp_rank_assigner + + replica_ctx = serve.get_replica_context() + self.dp_rank = await self.dp_rank_assigner.register.remote(replica_ctx) + logger.info(f"DP rank {self.dp_rank} registered with rank assigner") + + if self.dp_rank == 0: + self.dp_address, self.dp_rpc_port = get_address_and_port() + await self.dp_rank_assigner.set_dp_master_info.remote( + self.dp_address, self.dp_rpc_port + ) + logger.info( + f"DP rank {self.dp_rank} has set DP master info: " + f"data_parallel_address={self.dp_address}, " + f"data_parallel_rpc_port={self.dp_rpc_port}" + ) + else: + timestamp = time.time() + ( + self.dp_address, + self.dp_rpc_port, + ) = await self.dp_rank_assigner.get_dp_master_info.remote() + logger.info( + f"DP rank {self.dp_rank} got DP master info: " + f"data_parallel_address={self.dp_address}, " + f"data_parallel_rpc_port={self.dp_rpc_port}, " + f"waited {time.time() - timestamp:.3f} seconds" + ) + + # Update the engine_kwargs to assign the DP information + llm_config.update_engine_kwargs( + data_parallel_rank=self.dp_rank, + data_parallel_address=self.dp_address, + data_parallel_rpc_port=self.dp_rpc_port, + ) + + await super().__init__(llm_config) + + @classmethod + def as_deployment(cls, deployment_options: dict) -> serve.Deployment: + return serve.deployment(cls).options(**deployment_options) + + +def build_dp_deployment( + llm_config: LLMConfig, + *, + name_prefix: Optional[str] = None, +) -> Application: + """Build a data parallel LLM deployment.""" + dp_size = llm_config.engine_kwargs.get("data_parallel_size", 1) + if dp_size == 1: + raise ValueError( + "data_parallel_size should be greater than 1 for DP deployment." + ) + + deployment_options = llm_config.get_serve_options(name_prefix=name_prefix) + dp_rank_assigner = DPRankAssigner.bind(dp_size=dp_size) + return DPServer.as_deployment(deployment_options).bind( + llm_config=llm_config, dp_rank_assigner=dp_rank_assigner + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..405d8ef0906b83094a8ee022767f71c6ef30951e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/__pycache__/llm_engine.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/__pycache__/llm_engine.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8103043827be3998257bc969e143b738ca2c43c8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/__pycache__/llm_engine.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/__pycache__/llm_server.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/__pycache__/llm_server.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..260f2fcabb5308c2c850c7f62c82c90f6777ad5b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/__pycache__/llm_server.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/llm_engine.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/llm_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..89bf1a2f5cc9ae14a240e410a1bb74114703b3b9 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/llm_engine.py @@ -0,0 +1,147 @@ +import abc +from typing import TYPE_CHECKING, AsyncGenerator, Union + +from ray.llm._internal.serve.configs.server_models import ( + DiskMultiplexConfig, + LLMConfig, +) + +if TYPE_CHECKING: + from ray.llm._internal.serve.configs.openai_api_models import ( + ChatCompletionRequest, + ChatCompletionResponse, + CompletionRequest, + CompletionResponse, + EmbeddingRequest, + EmbeddingResponse, + ErrorResponse, + ) + + +class LLMEngine(abc.ABC): + """Base protocol class for all LLM engines.""" + + @abc.abstractmethod + def __init__(self, llm_config: LLMConfig): + """Initialize the engine with the llm config""" + pass + + @abc.abstractmethod + async def start(self): + """Start the engine""" + pass + + @abc.abstractmethod + async def resolve_lora(self, lora_model: DiskMultiplexConfig): + """Mounts the LoRA model on the engine, given the local disk path.""" + pass + + @abc.abstractmethod + async def reset_prefix_cache(self) -> None: + """Reset the prefix cache of the underlying engine""" + + @abc.abstractmethod + async def chat( + self, request: "ChatCompletionRequest" + ) -> AsyncGenerator[Union[str, "ChatCompletionResponse", "ErrorResponse"], None]: + """Run a ChatCompletion with the engine. + + To implement this method, you need to take a openAI compatible chat request, internally cast it to the target engine request type, and then call the engine's chat method. + + This method is an async generator, so it yields chunks of response and when it is done, it returns None. We have the following convention: + + - In case of streaming, yield a string representing data: \n\n for each chunk. This should be already openAI compatible, so the higher level can just yield it to the client. + - In case of non-streaming, yield a single object of type ChatCompletionResponse. + - In case of error, yield a single object of type ErrorResponse. + + Args: + request: The chat completion request. + + Yields: + Union[str, ChatCompletionResponse, ErrorResponse]: A string representing a chunk of the response, a ChatCompletionResponse object, or an ErrorResponse object. + + Returns: + None when the generator is done. + """ + pass + + @abc.abstractmethod + async def completions( + self, request: "CompletionRequest" + ) -> AsyncGenerator[Union[str, "CompletionResponse", "ErrorResponse"], None]: + """Run a Completion with the engine. + + Similar to chat, this method is an async generator, so it yields chunks + of response and when it is done, it returns None. We have the following + convention: + + * In case of streaming, yield a string representing data: + \n\n for each chunk. This should be already openAI compatible + with completion response format, so the higher level can just yield it + directly to the client. + * In case of non-streaming, yield a single object of type + CompletionResponse. + * In case of error, yield a single object of type ErrorResponse. + + Args: + request: The completion request. + + Yields: + Union[str, CompletionResponse, ErrorResponse]: A string + representing a chunk of the response, a CompletionResponse object, + or an ErrorResponse object. + + Returns: + None when the generator is done. + """ + pass + + @abc.abstractmethod + async def embeddings( + self, request: "EmbeddingRequest" + ) -> AsyncGenerator[Union["EmbeddingResponse", "ErrorResponse"], None]: + """Run an Embedding with the engine. + + This method is different from chat and completion in that it does not + have streaming, but still it is an async generator that yields response + objects and when it is done, it returns None. We have the following + convention: + + * yield a single object of type EmbeddingResponse. + * For errors, yield a single object of type ErrorResponse. + + Args: + request: The embedding request. + + Returns: + An async generator that yields EmbeddingResponse objects or ErrorResponse objects, and returns None when the generator is done. + """ + pass + + async def check_health(self) -> None: + """Check the health of the engine. + + Does not return anything. Raise error when the engine is dead and needs + to be restarted. + """ + return + + ############################################################## + # Optional methods + # These methods will be implemented in the future to allow + # more granular life-cycle management of the engine. + # e.g. in usecases like RL training, we need to put the engine + # to sleep during training and wake up during rollouts. + ############################################################## + + async def sleep(self): + """Puts the engine to sleep""" + pass + + async def wakeup(self): + """Wakes up the engine""" + pass + + def shutdown(self): + """Shuts down the engine""" + pass diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/llm_server.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/llm_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f7f4d274e6114d6984571a10faaf4558ac334364 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/llm_server.py @@ -0,0 +1,448 @@ +import asyncio +import os +from abc import ABC, abstractmethod +from typing import ( + TYPE_CHECKING, + Any, + AsyncGenerator, + Dict, + List, + Optional, + Type, + TypeVar, + Union, +) + +from ray import serve +from ray._common.utils import import_attr +from ray.llm._internal.serve.configs.constants import ( + DEFAULT_HEALTH_CHECK_PERIOD_S, + DEFAULT_HEALTH_CHECK_TIMEOUT_S, + DEFAULT_MAX_ONGOING_REQUESTS, + DEFAULT_MAX_REPLICAS, + DEFAULT_MAX_TARGET_ONGOING_REQUESTS, + ENGINE_START_TIMEOUT_S, + MODEL_RESPONSE_BATCH_TIMEOUT_MS, + RAYLLM_VLLM_ENGINE_CLS_ENV, +) +from ray.llm._internal.serve.configs.server_models import ( + DiskMultiplexConfig, + LLMConfig, +) +from ray.llm._internal.serve.deployments.llm.llm_engine import LLMEngine +from ray.llm._internal.serve.deployments.llm.vllm.vllm_engine import VLLMEngine +from ray.llm._internal.serve.deployments.utils.batcher import Batcher +from ray.llm._internal.serve.deployments.utils.server_utils import ( + get_serve_request_id, +) +from ray.llm._internal.serve.observability.logging import get_logger +from ray.llm._internal.serve.observability.usage_telemetry.usage import ( + push_telemetry_report_for_all_models, +) +from ray.llm._internal.serve.utils.lora_serve_utils import ( + LoraModelLoader, +) + +if TYPE_CHECKING: + from ray.llm._internal.serve.configs.openai_api_models import ( + ChatCompletionRequest, + ChatCompletionResponse, + CompletionRequest, + CompletionResponse, + EmbeddingRequest, + EmbeddingResponse, + ErrorResponse, + ) + +logger = get_logger(__name__) +T = TypeVar("T") + + +class _LLMServerBase(ABC): + """ + This is the common interface between all the llm deployment. All llm deployments + need to implement a sync constructor, an async start method, and check_health method. + """ + + def __init__(self): + """ + Constructor takes basic setup that doesn't require async operations. + """ + + @abstractmethod + async def start(self): + """ + Start the underlying engine. This handles async initialization. + """ + ... + + @abstractmethod + async def chat( + self, request: "ChatCompletionRequest" + ) -> AsyncGenerator[Union[str, "ChatCompletionResponse", "ErrorResponse"], None]: + """ + Inferencing to the engine for chat, and return the response. + """ + ... + + @abstractmethod + async def completions( + self, request: "CompletionRequest" + ) -> AsyncGenerator[ + Union[List[Union[str, "ErrorResponse"]], "CompletionResponse"], None + ]: + """ + Inferencing to the engine for completion api, and return the response. + """ + ... + + @abstractmethod + async def check_health(self) -> None: + """ + Check the health of the replica. Does not return anything. + Raise error when the engine is dead and needs to be restarted. + """ + ... + + @abstractmethod + async def reset_prefix_cache(self) -> None: + """Reset the prefix cache of the underlying engine""" + + # TODO (Kourosh): This does not belong here. + async def llm_config(self) -> Optional[LLMConfig]: + return None + + +class LLMServer(_LLMServerBase): + """This is a shim layer to decouple the LLM engine from the ingress + deployment. + + It has a very similar API as the engine. Almost all of the abstractions are + implemented by the engine. This class just a little bit more logic on top: + + 1. Logic for serve multiplexing (e.g. LoRA loading). + 2. Request id handing from serve context. + 3. Batching in case of streaming (only for chat and completions). + 4. Telemetry reporting. + + Usage Patterns: + + 1. Basic pattern (for testing): + server = LLMServer.sync_init(llm_config) # Sync constructor, unstarted + await server.start() # Must explicitly start + + 2. Async context (default, used by Ray Serve): + server = await LLMServer(llm_config) # Async constructor, fully started + + 3. Ray Serve deployment: + # Ray Serve calls the async constructor directly + deployment = serve.deployment(LLMServer).bind(llm_config) + """ + + _default_engine_cls = VLLMEngine + + async def __init__( + self, + llm_config: LLMConfig, + *, + engine_cls: Optional[Type[LLMEngine]] = None, + model_downloader: Optional[Type[LoraModelLoader]] = None, + ): + """Asynchronous constructor that returns a fully started instance. + + This is the default constructor used by Ray Serve deployments. + + Args: + llm_config: LLMConfig for the model. + engine_cls: Dependency injection for the vllm engine class. + Defaults to `VLLMEngine`. + model_downloader: Dependency injection for the model downloader. + Defaults to `LoraModelLoader`. + """ + super().__init__() + self._init_shared(llm_config, engine_cls, model_downloader) + await self.start() + + def _init_shared( + self, + llm_config: LLMConfig, + engine_cls: Optional[Type[LLMEngine]] = None, + model_downloader: Optional[Type[LoraModelLoader]] = None, + ): + """Shared initialization logic between constructors.""" + self._llm_config = llm_config + self._engine_cls = engine_cls or self._get_default_engine_class() + self.engine: Optional[LLMEngine] = None + self._init_multiplex_loader(model_downloader) + + @classmethod + def sync_init( + cls, + llm_config: LLMConfig, + *, + engine_cls: Optional[Type[LLMEngine]] = None, + model_downloader: Optional[Type[LoraModelLoader]] = None, + ) -> "LLMServer": + """Synchronous constructor that returns an unstarted instance. + + This is used for testing the new pattern where initialization + and starting are explicitly separated. + + Args: + llm_config: LLMConfig for the model. + engine_cls: Dependency injection for the vllm engine class. + Defaults to `VLLMEngine`. + model_downloader: Dependency injection for the model downloader. + Defaults to `LoraModelLoader`. + + Returns: + An unstarted LLMServer instance. Caller must call await start(). + """ + instance = cls.__new__(cls) + _LLMServerBase.__init__(instance) + instance._init_shared(llm_config, engine_cls, model_downloader) + return instance + + async def start(self): + """Start the underlying engine. This handles async initialization.""" + if self._engine_cls is not None: + self.engine = self._engine_cls(self._llm_config) + await asyncio.wait_for(self._start_engine(), timeout=ENGINE_START_TIMEOUT_S) + + def _init_multiplex_loader( + self, model_downloader_cls: Optional[Type[LoraModelLoader]] = None + ): + """Initialize the multiplex loader.""" + + model_downloader_cls = model_downloader_cls or LoraModelLoader + mx_config = self._llm_config.multiplex_config() + + if mx_config is not None: + model_downloader = model_downloader_cls( + download_timeout_s=mx_config.download_timeout_s, + max_tries=mx_config.max_download_tries, + ) + + async def _load_model(lora_model_id: str) -> DiskMultiplexConfig: + return await model_downloader.load_model_from_config( + lora_model_id=lora_model_id, + llm_config=self._llm_config, + ) + + self._load_model = serve.multiplexed( + max_num_models_per_replica=mx_config.max_num_models_per_replica + )(_load_model) + else: + + async def _load_model(lora_model_id: str) -> DiskMultiplexConfig: + raise ValueError("LoRA config is not set in the LLMConfig") + + self._load_model = _load_model + + def _get_default_engine_class(self) -> Type[LLMEngine]: + """Helper to load the engine class from the environment variable. + This is used for testing or escape-hatch for patching purposes. + If env variable is not set, it will fallback to the default engine class. + """ + engine_cls_path = os.environ.get(RAYLLM_VLLM_ENGINE_CLS_ENV) + if engine_cls_path: + return import_attr(engine_cls_path) + return self._default_engine_cls + + async def _start_engine(self): + if self.engine is None: + raise ValueError("Engine is not set") + + await self.engine.start() + + # Push telemetry reports for the model in the current deployment. + push_telemetry_report_for_all_models(all_models=[self._llm_config]) + + def _get_batch_interval_ms(self, stream: bool = True) -> int: + """Calculate the batching interval for responses.""" + stream_batching_interval_ms = self._llm_config.experimental_configs.get( + "stream_batching_interval_ms" + ) + if stream_batching_interval_ms is None: + stream_batching_interval_ms = MODEL_RESPONSE_BATCH_TIMEOUT_MS + return stream_batching_interval_ms if stream else None + + async def _maybe_add_request_id_to_request( + self, + request: Union[ + "ChatCompletionRequest", "CompletionRequest", "EmbeddingRequest" + ], + ): + """Add the request id to the request.""" + request_id = get_serve_request_id() + if request_id: + request.request_id = request_id + + async def _maybe_resolve_lora_from_multiplex(self) -> None: + """Handle the lora model for the request.""" + multiplexed_model_id = serve.get_multiplexed_model_id() + if multiplexed_model_id: + if self._llm_config.lora_config is None: + raise ValueError("Must setup lora config for multiplexed requests.") + disk_lora_model = await self._load_model(multiplexed_model_id) + await self.engine.resolve_lora(disk_lora_model) + + def _batch_output_stream( + self, generator: AsyncGenerator[T, None] + ) -> AsyncGenerator[List[T], None]: + return Batcher( + generator, + interval_ms=self._get_batch_interval_ms(), + ).stream() + + async def _run_request( + self, + request: Union[ + "ChatCompletionRequest", "CompletionRequest", "EmbeddingRequest" + ], + *, + engine_method: str, + batch_output_stream: bool = False, + ) -> AsyncGenerator[Any, None]: + """Run the engine method on the request + perform batching when stream=True. + + Args: + request: The request to run. + engine_method: The method to call on the engine. + batch_output_stream: Whether to batch the output stream. + + Returns: + An AsyncGenerator of the response. If stream is True and batching is enabled, then the generator will yield a list of streaming responses (strings of the format data: {response_json}\n\n). Otherwise, it will yield the non-streaming response from engine directly. + """ + + await self._maybe_add_request_id_to_request(request) + await self._maybe_resolve_lora_from_multiplex() + + is_stream = hasattr(request, "stream") and request.stream + if is_stream and batch_output_stream: + stream = self._batch_output_stream( + getattr(self.engine, engine_method)(request) + ) + else: + stream = getattr(self.engine, engine_method)(request) + + return stream + + async def chat( + self, request: "ChatCompletionRequest" + ) -> AsyncGenerator[ + Union[List[Union[str, "ErrorResponse"]], "ChatCompletionResponse"], None + ]: + """Runs a chat request to the LLM engine and returns the response. + + Args: + request: A ChatCompletionRequest object. + + Returns: + An AsyncGenerator of the response. If stream is True and batching is enabled, then the generator will yield a list of chat streaming responses (strings of the format data: {response_json}\n\n). Otherwise, it will yield the ChatCompletionResponse object directly. + """ + return await self._run_request( + request, + engine_method="chat", + batch_output_stream=True, + ) + + async def completions( + self, request: "CompletionRequest" + ) -> AsyncGenerator[ + Union[List[Union[str, "ErrorResponse"]], "CompletionResponse"], None + ]: + """Runs a completion request to the LLM engine and returns the response. + + Args: + request: A CompletionRequest object. + + Returns: + An AsyncGenerator of the response. If stream is True and batching is enabled, then the generator will yield a list of completion streaming responses (strings of the format data: {response_json}\n\n). Otherwise, it will yield the CompletionResponse object directly. + """ + return await self._run_request( + request, + engine_method="completions", + batch_output_stream=True, + ) + + async def embeddings( + self, request: "EmbeddingRequest" + ) -> AsyncGenerator[Union[List["ErrorResponse"], "EmbeddingResponse"], None]: + """Runs an embeddings request to the engine and returns the response. + + Returns an AsyncGenerator over the EmbeddingResponse object. This is so that the caller can have a consistent interface across all the methods of chat, completions, and embeddings. + + Args: + request: An EmbeddingRequest object. + + Returns: + An AsyncGenerator over the EmbeddingResponse object. + """ + # NOTE: Embeddings does not need batching. + return await self._run_request( + request, engine_method="embeddings", batch_output_stream=False + ) + + async def check_health(self) -> None: + """ + Check the health of the replica. Does not return anything. Raise error when + the engine is dead and needs to be restarted. + """ + if self.engine is None: + return + try: + return await self.engine.check_health() + except Exception as e: + logger.error("Engine health check failed in LLMServer.check_health: %s", e) + raise e + + async def reset_prefix_cache(self) -> None: + """Reset the prefix cache of the underlying engine""" + if self.engine is None: + return + try: + await self.engine.reset_prefix_cache() + except Exception as e: + logger.error( + "Engine reset prefix cache failed in LLMServer.reset_prefix_cache: %s", + e, + ) + raise e + + async def llm_config(self) -> Optional[LLMConfig]: + return self._llm_config + + @classmethod + def as_deployment( + cls, deployment_options: Optional[Dict[str, Any]] = None + ) -> serve.Deployment: + """Convert the LLMServer to a Ray Serve deployment. + + Args: + deployment_options: A dictionary of deployment options. + + Returns: + A Ray Serve deployment. + """ + deployment_options = deployment_options or {} + return LLMDeployment.options(**deployment_options) + + +@serve.deployment( + autoscaling_config={ + "min_replicas": 1, + "initial_replicas": 1, + "max_replicas": DEFAULT_MAX_REPLICAS, + "target_ongoing_requests": DEFAULT_MAX_TARGET_ONGOING_REQUESTS, + }, + max_ongoing_requests=DEFAULT_MAX_ONGOING_REQUESTS, + health_check_period_s=DEFAULT_HEALTH_CHECK_PERIOD_S, + health_check_timeout_s=DEFAULT_HEALTH_CHECK_TIMEOUT_S, +) +class LLMDeployment(LLMServer): + # Note (genesu): We are separating the LLMServer and LLMDeployment just + # to give developers an ability to test the implementation outside the Ray Serve. + # But in practice we should always test the LLMDeployment class as a Serve + # deployment to ensure all functionalities can be run remotely asynchronously. + pass diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f58b97e42f1a5c4316dda320e32fa0805c54ce53 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/__pycache__/vllm_engine.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/__pycache__/vllm_engine.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60c463a20b1d7a69a03648be57c2997a7ad8a143 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/__pycache__/vllm_engine.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/__pycache__/vllm_models.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/__pycache__/vllm_models.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..553e4d39373f5836468485550a79fdb43a3c87c4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/__pycache__/vllm_models.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/kv_transfer_backends/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/kv_transfer_backends/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..72e24a18bad597a5dd8b057c6f331295b7ab7555 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/kv_transfer_backends/__init__.py @@ -0,0 +1,16 @@ +from typing import Dict + +from ray.llm._internal.serve.deployments.llm.vllm.kv_transfer_backends.base import ( + BaseConnectorBackend, +) +from ray.llm._internal.serve.deployments.llm.vllm.kv_transfer_backends.lmcache_connector_v1 import ( + LMCacheConnectorV1Backend, +) +from ray.llm._internal.serve.deployments.llm.vllm.kv_transfer_backends.nixl_connector import ( + NixlConnectorBackend, +) + +SUPPORTED_BACKENDS: Dict[str, BaseConnectorBackend] = { + "LMCacheConnectorV1": LMCacheConnectorV1Backend, + "NixlConnector": NixlConnectorBackend, +} diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/kv_transfer_backends/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/kv_transfer_backends/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75c6645c609bf4887cddf98c1d9b6a54d2dae568 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/kv_transfer_backends/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/kv_transfer_backends/__pycache__/base.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/kv_transfer_backends/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d9fbd4545909d37687d8002cde3037b22dbda24 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/kv_transfer_backends/__pycache__/base.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/kv_transfer_backends/__pycache__/lmcache_connector_v1.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/kv_transfer_backends/__pycache__/lmcache_connector_v1.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b12f88611c59ae5d30a15a549936f593a557d3af Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/kv_transfer_backends/__pycache__/lmcache_connector_v1.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/kv_transfer_backends/__pycache__/nixl_connector.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/kv_transfer_backends/__pycache__/nixl_connector.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e20017a5a87944cf115be80b15261779d5d5fee7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/kv_transfer_backends/__pycache__/nixl_connector.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/kv_transfer_backends/base.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/kv_transfer_backends/base.py new file mode 100644 index 0000000000000000000000000000000000000000..420f7f44a06f24ee1b9b7eba1373104712019e14 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/kv_transfer_backends/base.py @@ -0,0 +1,32 @@ +import abc +import random +import string +from typing import Any, Dict + + +class BaseConnectorBackend(abc.ABC): + def __init__(self, kv_transfer_config: Dict[str, Any]): + """Base class for connector backends. + + Args: + kv_transfer_config: Configuration for the KV transfer. + """ + self.kv_transfer_config = kv_transfer_config + + def _get_unique_suffix(self, len: int = 6) -> str: + """Generates unique alphanumeric suffix. + + Args: + len: Length of the suffix to generate. + Returns: + A unique alphanumeric suffix string of specified length. + """ + return "".join(random.choices(string.ascii_letters + string.digits, k=len)) + + @abc.abstractmethod + def setup(self) -> None: + """Setup the connector backend. + + This method is called to setup the connector backend. + """ + pass diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/kv_transfer_backends/lmcache_connector_v1.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/kv_transfer_backends/lmcache_connector_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..85945c30eb14fc557051c4e2e85de54365276c15 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/kv_transfer_backends/lmcache_connector_v1.py @@ -0,0 +1,61 @@ +from ray.llm._internal.serve.deployments.llm.vllm.kv_transfer_backends.base import ( + BaseConnectorBackend, +) +from ray.llm._internal.serve.observability.logging import get_logger + +logger = get_logger(__name__) + + +def _check_lmcache_installed(): + try: + import lmcache # noqa: F401 + except ImportError: + raise ImportError( + "LMCache is not installed. Please install it with `pip install lmcache`." + ) + + +class LMCacheConnectorV1Backend(BaseConnectorBackend): + + KV_CONNECTOR_EXTRA_CONFIG_FIELD_NAME = "kv_connector_extra_config" + LMCACHE_RPC_PORT_FIELD_NAME = "lmcache_rpc_port" + DEFAULT_LMCACHE_RPC_PORT_NAME = "lmcache_rpc_port" + + def setup(self) -> None: + """Initialize the LMCache connector backend. + This method sets up the LMCache connector by: + 1. Checking if LMCache is installed. + 2. Configuring the LMCache RPC port if not already set. + 3. Creating a unique LMCache RPC port across replicas. + Raises: + ImportError: If LMCache is not installed. + """ + _check_lmcache_installed() + + if ( + LMCacheConnectorV1Backend.KV_CONNECTOR_EXTRA_CONFIG_FIELD_NAME + not in self.kv_transfer_config + ): + return + + kv_connector_extra_config = self.kv_transfer_config[ + LMCacheConnectorV1Backend.KV_CONNECTOR_EXTRA_CONFIG_FIELD_NAME + ] + lmcache_rpc_port = ( + kv_connector_extra_config.get( + LMCacheConnectorV1Backend.LMCACHE_RPC_PORT_FIELD_NAME, + LMCacheConnectorV1Backend.DEFAULT_LMCACHE_RPC_PORT_NAME, + ) + + self._get_unique_suffix() + ) + if ( + LMCacheConnectorV1Backend.LMCACHE_RPC_PORT_FIELD_NAME + in kv_connector_extra_config + ): + logger.info( + f"Setting unique {lmcache_rpc_port=} for current replica LMCacheConnectorV1." + ) + + kv_connector_extra_config[ + LMCacheConnectorV1Backend.LMCACHE_RPC_PORT_FIELD_NAME + ] = lmcache_rpc_port diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/kv_transfer_backends/nixl_connector.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/kv_transfer_backends/nixl_connector.py new file mode 100644 index 0000000000000000000000000000000000000000..5cdbb37f744ec8c1c1c0c86eb84bbb4811d582bb --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/kv_transfer_backends/nixl_connector.py @@ -0,0 +1,45 @@ +import os + +from ray.llm._internal.serve.deployments.llm.vllm.kv_transfer_backends.base import ( + BaseConnectorBackend, +) + + +class NixlConnectorBackend(BaseConnectorBackend): + def setup(self) -> None: + """Initialize the NIXL connector backend. + + This method sets up the NIXL (Network Interface for eXtended LLM) connector by: + 1. Verifying that the required vLLM environment variables are supported + 2. Configuring the side channel port and host if not already set + 3. Creating a unique engine ID across replicas + + The side channel is used for KV cache transfer between vLLM instances. + + Raises: + ValueError: If the current vLLM version doesn't support the required + NIXL environment variables. + """ + from vllm import envs as vllm_envs, utils as vllm_utils + + if ( + "VLLM_NIXL_SIDE_CHANNEL_PORT" not in vllm_envs.environment_variables + or "VLLM_NIXL_SIDE_CHANNEL_HOST" not in vllm_envs.environment_variables + ): + raise ValueError( + "This vLLM version does not support VLLM_NIXL_SIDE_CHANNEL_PORT" + "or VLLM_NIXL_SIDE_CHANNEL_HOST environment variable. It's likely" + "that you are using an older version of vLLM." + ) + + if not vllm_envs.is_set("VLLM_NIXL_SIDE_CHANNEL_PORT"): + port: int = vllm_utils.get_open_port() + os.environ["VLLM_NIXL_SIDE_CHANNEL_PORT"] = str(port) + if not vllm_envs.is_set("VLLM_NIXL_SIDE_CHANNEL_HOST"): + os.environ["VLLM_NIXL_SIDE_CHANNEL_HOST"] = vllm_utils.get_ip() + + # We need to overwrite the engine_id to make it unique across replicas. + engine_id = self.kv_transfer_config.get("engine_id", self._get_unique_suffix()) + host = vllm_envs.VLLM_NIXL_SIDE_CHANNEL_HOST + port = vllm_envs.VLLM_NIXL_SIDE_CHANNEL_PORT + self.kv_transfer_config["engine_id"] = "-".join([engine_id, host, str(port)]) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/vllm_engine.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/vllm_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..28ad58b09bb56153c0458d1e0b2de37aef072dd3 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/vllm_engine.py @@ -0,0 +1,456 @@ +import argparse +import os +from typing import TYPE_CHECKING, AsyncGenerator, Optional, Tuple, Union + +from starlette.datastructures import State +from starlette.requests import Request +from transformers.dynamic_module_utils import init_hf_modules +from vllm.engine.arg_utils import AsyncEngineArgs +from vllm.entrypoints.openai.cli_args import FrontendArgs +from vllm.entrypoints.openai.protocol import ErrorResponse as VLLMErrorResponse + +import ray +from ray.llm._internal.common.utils.import_utils import try_import +from ray.llm._internal.serve.configs.openai_api_models import ( + ChatCompletionRequest, + ChatCompletionResponse, + CompletionRequest, + CompletionResponse, + EmbeddingRequest, + EmbeddingResponse, + ErrorResponse, +) +from ray.llm._internal.serve.configs.server_models import ( + DiskMultiplexConfig, + LLMConfig, +) +from ray.llm._internal.serve.deployments.llm.llm_engine import LLMEngine +from ray.llm._internal.serve.deployments.llm.vllm.vllm_models import ( + VLLMEngineConfig, +) +from ray.llm._internal.serve.deployments.utils.node_initialization_utils import ( + InitializeNodeOutput, + initialize_node, +) +from ray.llm._internal.serve.observability.logging import get_logger +from ray.util.placement_group import PlacementGroup +from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy + +if TYPE_CHECKING: + from vllm.config import VllmConfig + from vllm.engine.protocol import EngineClient + from vllm.entrypoints.openai.serving_chat import OpenAIServingChat + from vllm.entrypoints.openai.serving_completion import OpenAIServingCompletion + from vllm.entrypoints.openai.serving_embedding import OpenAIServingEmbedding + from vllm.entrypoints.openai.serving_models import OpenAIServingModels + +vllm = try_import("vllm") +logger = get_logger(__name__) + + +def _get_vllm_engine_config( + llm_config: LLMConfig, +) -> Tuple["AsyncEngineArgs", "VllmConfig"]: + engine_config = llm_config.get_engine_config() + async_engine_args = vllm.engine.arg_utils.AsyncEngineArgs( + **engine_config.get_initialization_kwargs() + ) + from vllm.usage.usage_lib import UsageContext + + vllm_engine_config = async_engine_args.create_engine_config( + usage_context=UsageContext.OPENAI_API_SERVER + ) + return async_engine_args, vllm_engine_config + + +def _clear_current_platform_cache(): + """Clear the cache of the current platform. + + vllm current has an lru cache for getting device compatibility + that will not have the correct returned value if + CUDA_VISIBLE_DEVICES is not set properly. In RayLLM eventually + when we want to create the engine the env will be set properly, + but till then, upon the import of vllm somewhere + (which is a mystery) the lru cache will have the wrong value. + This function will clear the cache so that the next time the + cache is accessed, it will be re-evaluated. + + Related issues: + https://github.com/vllm-project/vllm/issues/8402 + https://github.com/vllm-project/vllm/issues/7890 + """ + from vllm.platforms import current_platform + + # TODO(seiji): remove this once https://github.com/vllm-project/vllm/pull/18979 is merged + if ( + "CUDA_VISIBLE_DEVICES" in os.environ + and os.environ["CUDA_VISIBLE_DEVICES"] == "" + ): + del os.environ["CUDA_VISIBLE_DEVICES"] + + # This check is just to future proof this implementation + # in case vllm removes their lru_cache decorator + if hasattr(current_platform.get_device_capability, "cache_clear"): + logger.info("Clearing the current platform cache ...") + current_platform.get_device_capability.cache_clear() + + +class VLLMEngine(LLMEngine): + def __init__( + self, + llm_config: LLMConfig, + ): + """Create a vLLM Engine class + + Args: + llm_config: The llm configuration for this engine + """ + super().__init__(llm_config) + + # Ensure transformers_modules is initialized early in worker processes. + # This is critical for models with trust_remote_code=True to avoid pickle errors. + init_hf_modules() + + self.llm_config = llm_config + + if vllm is None: + raise ImportError( + "vLLM is not installed. Please install it with `pip install ray[llm]`." + ) + from vllm import envs as vllm_envs + + if not vllm_envs.VLLM_USE_V1: + logger.warning( + "vLLM v0 is getting fully deprecated. As a result in Ray Serve LLM only v1 is supported. Only when you know what you are doing, you can set VLLM_USE_V1=0" + ) + + self.llm_config.setup_engine_backend() + + self._running = False + + # vLLM Integration points. Will be set through .start() + self._engine_client = None + self._oai_models: Optional["OpenAIServingModels"] = None + self._oai_serving_chat: Optional["OpenAIServingChat"] = None + self._oai_serving_completion: Optional["OpenAIServingCompletion"] = None + self._oai_serving_embedding: Optional["OpenAIServingEmbedding"] = None + + async def start(self) -> None: + """Start the vLLM engine. + + If the engine is already running, do nothing. + """ + + if self._running: + # The engine is already running! + logger.info("Skipping engine restart because the engine is already running") + return + + from vllm.entrypoints.openai.api_server import init_app_state + + node_initialization = await initialize_node(self.llm_config) + + ( + vllm_engine_args, + vllm_frontend_args, + vllm_engine_config, + ) = self._prepare_engine_config(node_initialization) + + # Apply checkpoint info to the llm_config. + # This is needed for capturing model capabilities + # (e.g. supports vision, etc.) on the llm_config. + config = self.llm_config.get_engine_config() + self.llm_config.apply_checkpoint_info( + config.actual_hf_model_id, + trust_remote_code=config.trust_remote_code, + ) + + self._engine_client = self._start_async_llm_engine( + vllm_engine_args, + vllm_engine_config, + node_initialization.placement_group, + ) + + state = State() + # TODO (Kourosh): There might be some variables that needs protection? + args = argparse.Namespace( + **vllm_frontend_args.__dict__, + **vllm_engine_args.__dict__, + ) + + await init_app_state( + engine_client=self._engine_client, + vllm_config=vllm_engine_config, + state=state, + args=args, + ) + + self._oai_models = state.openai_serving_models + self._oai_serving_chat = state.openai_serving_chat + self._oai_serving_completion = state.openai_serving_completion + self._oai_serving_embedding = state.openai_serving_embedding + + self._validate_openai_serving_models() + self._validate_engine_client() + + self._running = True + + logger.info("Started vLLM engine.") + + def _validate_openai_serving_models(self): + assert self._oai_models is not None, "oai_models is not initialized" + assert hasattr( + self._oai_models, "lora_requests" + ), "oai_models must have a lora_requests attribute" + assert hasattr( + self._oai_models, "load_lora_adapter" + ), "oai_models must have a load_lora_adapter attribute" + + def _validate_openai_serving_chat(self): + assert hasattr( + self._oai_serving_chat, "create_chat_completion" + ), "oai_serving_chat must have a create_chat_completion attribute" + + def _validate_openai_serving_completion(self): + assert hasattr( + self._oai_serving_completion, "create_completion" + ), "oai_serving_completion must have a create_completion attribute" + + def _validate_openai_serving_embedding(self): + assert hasattr( + self._oai_serving_embedding, "create_embedding" + ), "oai_serving_embedding must have a create_embedding attribute" + + def _validate_engine_client(self): + assert hasattr( + self._engine_client, "check_health" + ), "engine_client must have a check_health attribute" + + def _prepare_engine_config( + self, node_initialization: InitializeNodeOutput + ) -> Tuple["AsyncEngineArgs", "FrontendArgs", "VllmConfig"]: + """Prepare the engine config to start the engine. + + Args: + node_initialization: The node initialization output. + + Returns: + A tuple of: + engine_args: The vLLM's internal engine arguments that is flattened. + frontend_args: The vLLM's internal frontend arguments that is flattened. + engine_config: The vLLM's internal engine config that is nested. + """ + + engine_config: VLLMEngineConfig = self.llm_config.get_engine_config() + + if engine_config.use_gpu: + # Create engine config on a task with access to GPU, + # as GPU capability may be queried. + ref = ( + ray.remote( + num_cpus=0, + num_gpus=0.001, + accelerator_type=self.llm_config.accelerator_type, + )(_get_vllm_engine_config) + .options( + runtime_env=node_initialization.runtime_env, + scheduling_strategy=PlacementGroupSchedulingStrategy( + placement_group=node_initialization.placement_group, + ), + ) + .remote(self.llm_config) + ) + vllm_engine_args, vllm_engine_config = ray.get(ref) + else: + vllm_engine_args, vllm_engine_config = _get_vllm_engine_config( + self.llm_config + ) + + vllm_frontend_args = FrontendArgs(**engine_config.frontend_kwargs) + return vllm_engine_args, vllm_frontend_args, vllm_engine_config + + def _start_async_llm_engine_v0( + self, + engine_args: "AsyncEngineArgs", + vllm_config: "VllmConfig", + placement_group: PlacementGroup, + ) -> "EngineClient": + + from vllm.engine.async_llm_engine import AsyncLLMEngine + from vllm.executor.ray_distributed_executor import RayDistributedExecutor + + vllm_config.parallel_config.placement_group = placement_group + + _clear_current_platform_cache() + + engine_client = AsyncLLMEngine( + vllm_config=vllm_config, + executor_class=RayDistributedExecutor, + log_stats=not engine_args.disable_log_stats, + ) + + return engine_client + + def _start_async_llm_engine( + self, + vllm_engine_args: "AsyncEngineArgs", + vllm_engine_config: "VllmConfig", + placement_group: PlacementGroup, + ) -> "EngineClient": + """Creates an async LLM engine from the engine arguments.""" + from vllm import envs as vllm_envs + + # NOTE: This is a temporary solution until vLLM v1 supports embeddings. + if not vllm_envs.VLLM_USE_V1: + return self._start_async_llm_engine_v0( + vllm_engine_args, vllm_engine_config, placement_group + ) + + from vllm.v1.engine.async_llm import AsyncLLM + from vllm.v1.executor.abstract import Executor + + vllm_engine_config.parallel_config.placement_group = placement_group + + _clear_current_platform_cache() + + custom_stat_loggers = None + if self.llm_config.log_engine_metrics: + from vllm.v1.metrics.ray_wrappers import RayPrometheusStatLogger + + # V1 AsyncLLM does not yet support add_logger: https://github.com/vllm-project/vllm/issues/17702 + # Use `disable_log_stats: False` and `log_engine_metrics: False` as + # a workaround to enable PrometheusStatLogger instead. + custom_stat_loggers = [RayPrometheusStatLogger] + + executor_class = Executor.get_class(vllm_engine_config) + logger.info(f"Using executor class: {executor_class}") + engine_client = AsyncLLM( + vllm_config=vllm_engine_config, + executor_class=executor_class, + log_stats=not vllm_engine_args.disable_log_stats, + stat_loggers=custom_stat_loggers, + ) + + return engine_client + + async def resolve_lora(self, disk_lora_model: DiskMultiplexConfig): + from vllm.entrypoints.openai.protocol import LoadLoRAAdapterRequest + + self._validate_openai_serving_models() + + if disk_lora_model.model_id in self._oai_models.lora_requests: + # Lora is already loaded, return + return + + lora_request = await self._oai_models.load_lora_adapter( # type: ignore[attr-defined] + request=LoadLoRAAdapterRequest( + lora_name=disk_lora_model.model_id, + lora_path=disk_lora_model.local_path, + ) + ) + + if isinstance(lora_request, VLLMErrorResponse): + raise ValueError(f"Failed to load lora model: {lora_request.message}") + + def _create_raw_request( + self, + request: Union[CompletionRequest, ChatCompletionRequest, EmbeddingRequest], + path: str, + ) -> Request: + scope = { + "type": "http", + "method": "POST", + "path": path, + "headers": [(b"x-request-id", getattr(request, "request_id", "").encode())], + "query_string": b"", + } + return Request(scope) + + async def chat( + self, request: ChatCompletionRequest + ) -> AsyncGenerator[Union[str, ChatCompletionResponse, ErrorResponse], None]: + self._validate_openai_serving_chat() + + # TODO (Kourosh): Remove when we upstream request_id attribute to vLLM. + # PR: https://github.com/vllm-project/vllm/pull/21009 + # Create a fake starlette.Request object with the x-request-id header + # so that the create_chat_completion API can assign the request_id properly. + raw_request = self._create_raw_request(request, "/chat/completions") + + chat_response = await self._oai_serving_chat.create_chat_completion( # type: ignore[attr-defined] + request, raw_request=raw_request + ) + + if isinstance(chat_response, AsyncGenerator): + async for response in chat_response: + if not isinstance(response, str): + raise ValueError( + f"Expected create_chat_completion to return a stream of strings, got and item with type {type(response)}" + ) + yield response + else: + if isinstance(chat_response, VLLMErrorResponse): + yield ErrorResponse(**chat_response.model_dump()) + else: + yield ChatCompletionResponse(**chat_response.model_dump()) + + async def completions( + self, request: CompletionRequest + ) -> AsyncGenerator[Union[str, CompletionResponse, ErrorResponse], None]: + self._validate_openai_serving_completion() + + # TODO (Kourosh): Remove when we upstream request_id attribute to vLLM. + # PR: https://github.com/vllm-project/vllm/pull/21009 + # Create a fake starlette.Request object with the x-request-id header + # so that the create_completion API can assign the request_id properly. + raw_request = self._create_raw_request(request, "/completions") + + completion_response = await self._oai_serving_completion.create_completion( # type: ignore[attr-defined] + request, + raw_request=raw_request, + ) + + if isinstance(completion_response, AsyncGenerator): + async for response in completion_response: + if not isinstance(response, str): + raise ValueError( + f"Expected create_completion to return a stream of strings, got and item with type {type(response)}" + ) + yield response + else: + if isinstance(completion_response, VLLMErrorResponse): + yield ErrorResponse(**completion_response.model_dump()) + else: + yield CompletionResponse(**completion_response.model_dump()) + + async def embeddings( + self, request: EmbeddingRequest + ) -> AsyncGenerator[Union[EmbeddingResponse, ErrorResponse], None]: + self._validate_openai_serving_embedding() + + # TODO (Kourosh): Remove when upstream is fixed to accept req_id. + # Create a fake starlette.Request object with the x-request-id header + # so that the create_embedding API can assign the request_id properly. + raw_request = self._create_raw_request(request, "/embeddings") + + embedding_response = await self._oai_serving_embedding.create_embedding( # type: ignore[attr-defined] + request, raw_request=raw_request + ) + + if isinstance(embedding_response, VLLMErrorResponse): + yield ErrorResponse(**embedding_response.model_dump()) + else: + yield EmbeddingResponse(**embedding_response.model_dump()) + + async def check_health(self) -> None: + assert self._engine_client is not None, "engine_client is not initialized" + + try: + await self._engine_client.check_health() + except BaseException as e: + logger.error("Healthcheck failed. The replica will be restarted") + raise e from None + + async def reset_prefix_cache(self) -> None: + assert self._engine_client is not None, "engine_client is not initialized" + await self._engine_client.reset_prefix_cache() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/vllm_models.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/vllm_models.py new file mode 100644 index 0000000000000000000000000000000000000000..081b0b2b6807c3303efb3c013a8826a4fae3a0b5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/llm/vllm/vllm_models.py @@ -0,0 +1,266 @@ +import dataclasses +import os +from typing import Any, Dict, List, Optional + +from pydantic import ConfigDict, Field +from vllm.engine.arg_utils import AsyncEngineArgs +from vllm.entrypoints.openai.cli_args import FrontendArgs + +from ray.llm._internal.common.base_pydantic import BaseModelExtended +from ray.llm._internal.common.utils.cloud_utils import CloudMirrorConfig +from ray.llm._internal.common.utils.import_utils import try_import +from ray.llm._internal.serve.configs.constants import ( + ALLOW_NEW_PLACEMENT_GROUPS_IN_DEPLOYMENT, + ENV_VARS_TO_PROPAGATE, +) +from ray.llm._internal.serve.configs.server_models import ( + GPUType, + LLMConfig, +) +from ray.llm._internal.serve.observability.logging import get_logger +from ray.util.placement_group import ( + PlacementGroup, + get_current_placement_group, + placement_group, + placement_group_table, +) + +# The key for the kv_transfer_params in the internal metadata. +KV_TRANSFER_PARAMS_KEY = "kv_transfer_params" +vllm = try_import("vllm") +logger = get_logger(__name__) + + +class VLLMEngineConfig(BaseModelExtended): + model_config = ConfigDict( + use_enum_values=True, + ) + + model_id: str = Field( + description="The identifier for the model. This is the id that will be used to query the model.", + ) + hf_model_id: Optional[str] = Field( + None, description="The Hugging Face model identifier." + ) + mirror_config: Optional[CloudMirrorConfig] = Field( + None, + description="Configuration for cloud storage mirror. This is for where the weights are downloaded from.", + ) + resources_per_bundle: Optional[Dict[str, float]] = Field( + default=None, + description="This overrides the vLLM engine worker's default resource configuration, " + "the number of resources returned by `placement_bundles`.", + ) + accelerator_type: Optional[GPUType] = Field( + None, + description="The type of accelerator to use. This is used to determine the placement group strategy.", + ) + runtime_env: Optional[Dict[str, Any]] = None + engine_kwargs: Dict[str, Any] = {} + frontend_kwargs: Dict[str, Any] = {} + + @property + def actual_hf_model_id(self) -> str: + return self.hf_model_id or self.model_id + + @property + def trust_remote_code(self) -> bool: + return self.engine_kwargs.get("trust_remote_code", False) + + def get_initialization_kwargs(self) -> dict: + """ + Get kwargs that will be actually passed to the LLMInitializer + constructor. + """ + engine_kwargs = self.engine_kwargs.copy() + + if "model" in engine_kwargs or "served_model_name" in engine_kwargs: + raise ValueError( + "model or served_model_name is not allowed in engine_kwargs when using Ray Serve LLM. Please use `model_loading_config` in LLMConfig instead." + ) + + engine_kwargs["model"] = self.actual_hf_model_id + engine_kwargs["served_model_name"] = [self.model_id] + + if ( + "distributed_executor_backend" in engine_kwargs + and engine_kwargs["distributed_executor_backend"] != "ray" + ): + raise ValueError( + "distributed_executor_backend != 'ray' is not allowed in engine_kwargs when using Ray Serve LLM Configs." + ) + else: + engine_kwargs["distributed_executor_backend"] = "ray" + + # TODO(lk-chen): Remove the logic once we require vllm>=0.10.1 + # vLLM 0.10.1 replaces `disable_log_requests` with + # `enable_log_requests`. Here we are trying to be compatible with both. + if hasattr(AsyncEngineArgs, "enable_log_requests"): + if "disable_log_requests" in engine_kwargs: + logger.warning( + "disable_log_requests is set in engine_kwargs, but vLLM " + "does not support it. Converting to enable_log_requests." + ) + engine_kwargs["enable_log_requests"] = not engine_kwargs.pop( + "disable_log_requests" + ) + else: + engine_kwargs["enable_log_requests"] = False + elif "disable_log_requests" not in engine_kwargs: + logger.info( + "Disabling request logging by default. To enable, set to False" + " in engine_kwargs." + ) + engine_kwargs["disable_log_requests"] = True + + return engine_kwargs + + def get_runtime_env_with_local_env_vars(self) -> dict: + runtime_env = self.runtime_env or {} + runtime_env.setdefault("env_vars", {}) + + # Propagate env vars to the runtime env + for env_var in ENV_VARS_TO_PROPAGATE: + if env_var in os.environ: + runtime_env["env_vars"][env_var] = os.getenv(env_var) + return runtime_env + + @classmethod + def from_llm_config(cls, llm_config: LLMConfig) -> "VLLMEngineConfig": + """Converts the LLMConfig to a VLLMEngineConfig.""" + # Set up the model downloading configuration. + hf_model_id, mirror_config = None, None + if llm_config.model_loading_config.model_source is None: + hf_model_id = llm_config.model_id + elif isinstance(llm_config.model_loading_config.model_source, str): + hf_model_id = llm_config.model_loading_config.model_source + else: + # If it's a CloudMirrorConfig (or subtype) + mirror_config = llm_config.model_loading_config.model_source + + all_engine_kwargs = llm_config.engine_kwargs.copy() + engine_kwargs = {} + frontend_kwargs = {} + + # Get field names from dataclasses + frontend_field_names = { + field.name for field in dataclasses.fields(FrontendArgs) + } + async_engine_field_names = { + field.name for field in dataclasses.fields(AsyncEngineArgs) + } + + for key, value in all_engine_kwargs.items(): + if key in frontend_field_names: + frontend_kwargs[key] = value + elif key in async_engine_field_names: + engine_kwargs[key] = value + else: + raise ValueError(f"Unknown engine argument: {key}") + + return VLLMEngineConfig( + model_id=llm_config.model_id, + hf_model_id=hf_model_id, + mirror_config=mirror_config, + resources_per_bundle=llm_config.resources_per_bundle, + accelerator_type=llm_config.accelerator_type, + engine_kwargs=engine_kwargs, + frontend_kwargs=frontend_kwargs, + runtime_env=llm_config.runtime_env, + ) + + def ray_accelerator_type(self) -> str: + """Converts the accelerator type to the Ray Core format.""" + return f"accelerator_type:{self.accelerator_type}" + + @property + def tensor_parallel_degree(self) -> int: + return self.engine_kwargs.get("tensor_parallel_size", 1) + + @property + def pipeline_parallel_degree(self) -> int: + return self.engine_kwargs.get("pipeline_parallel_size", 1) + + @property + def num_devices(self) -> int: + return self.tensor_parallel_degree * self.pipeline_parallel_degree + + @property + def placement_strategy(self) -> str: + # If pp <= 1, it's TP so we should make sure all replicas are on the same node. + if self.pipeline_parallel_degree > 1: + return "PACK" + return "STRICT_PACK" + + @property + def placement_bundles(self) -> List[Dict[str, float]]: + + if self.resources_per_bundle: + bundle = self.resources_per_bundle + else: + bundle = {"GPU": 1} + if self.accelerator_type: + bundle[self.ray_accelerator_type()] = 0.001 + bundles = [bundle for _ in range(self.num_devices)] + + return bundles + + @property + def use_gpu(self) -> bool: + """ + Returns True if vLLM is configured to use GPU resources. + """ + if self.resources_per_bundle and self.resources_per_bundle.get("GPU", 0) > 0: + return True + if not self.accelerator_type: + # By default, GPU resources are used + return True + + return self.accelerator_type in ( + GPUType.NVIDIA_TESLA_V100.value, + GPUType.NVIDIA_TESLA_P100.value, + GPUType.NVIDIA_TESLA_T4.value, + GPUType.NVIDIA_TESLA_P4.value, + GPUType.NVIDIA_TESLA_K80.value, + GPUType.NVIDIA_TESLA_A10G.value, + GPUType.NVIDIA_L4.value, + GPUType.NVIDIA_L40S.value, + GPUType.NVIDIA_A100.value, + GPUType.NVIDIA_H100.value, + GPUType.NVIDIA_H200.value, + GPUType.NVIDIA_H20.value, + GPUType.NVIDIA_A100_40G.value, + GPUType.NVIDIA_A100_80G.value, + ) + + def get_or_create_pg(self) -> PlacementGroup: + """Gets or a creates a placement group. + + If we are already in a placement group, return the existing placement group. + Else, create a new placement group based on the scaling config. + """ + dp_rank = self.engine_kwargs.get("data_parallel_rank", None) + pg = get_current_placement_group() + if pg: + logger.debug( + "Using existing placement group %s, details: %s", + pg.id, + placement_group_table(pg), + ) + else: + if not ALLOW_NEW_PLACEMENT_GROUPS_IN_DEPLOYMENT: + raise RuntimeError( + "Creating new placement groups is not allowed. " + "Change RAYLLM_ALLOW_NEW_PLACEMENT_GROUPS_IN_DEPLOYMENT " + "if this is not intended." + ) + name = "" if dp_rank is None else f"dp_{dp_rank}" + + pg = placement_group( + bundles=self.placement_bundles, + strategy=self.placement_strategy, + name=name, + ) + + logger.info(f"Using new placement group {pg}. {placement_group_table(pg)}") + return pg diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/prefill_decode_disagg/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/prefill_decode_disagg/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/prefill_decode_disagg/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/prefill_decode_disagg/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7fc1e301ca73be39a60e2d52f33c91325023100e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/prefill_decode_disagg/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/prefill_decode_disagg/__pycache__/prefill_decode_disagg.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/prefill_decode_disagg/__pycache__/prefill_decode_disagg.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53b5d2c4b438a958975786ff2d9c2cd56fa26200 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/prefill_decode_disagg/__pycache__/prefill_decode_disagg.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/prefill_decode_disagg/prefill_decode_disagg.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/prefill_decode_disagg/prefill_decode_disagg.py new file mode 100644 index 0000000000000000000000000000000000000000..0c0ff2cff4508b070ae3af014f620096cf53d1cd --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/prefill_decode_disagg/prefill_decode_disagg.py @@ -0,0 +1,211 @@ +"""Using Ray Serve to deploy LLM models with P/D disaggregation. +""" +import logging +import uuid +from typing import Any, AsyncGenerator, Dict, Union + +from pydantic import Field + +from ray import serve +from ray.llm._internal.common.base_pydantic import BaseModelExtended +from ray.llm._internal.serve.configs.openai_api_models import ( + ChatCompletionRequest, + ChatCompletionResponse, + CompletionRequest, + CompletionResponse, + EmbeddingRequest, + EmbeddingResponse, + ErrorResponse, +) +from ray.llm._internal.serve.configs.server_models import ( + parse_args as parse_llm_configs, +) +from ray.serve.deployment import Application +from ray.serve.handle import DeploymentHandle +from ray.serve.llm import ( + LLMConfig, + LLMRouter, + LLMServer, + build_llm_deployment, +) + +logger = logging.getLogger(__name__) +RequestType = Union[ChatCompletionRequest, CompletionRequest] + + +class PDServingArgs(BaseModelExtended): + """Schema for P/D serving args.""" + + prefill_config: Union[str, LLMConfig] + decode_config: Union[str, LLMConfig] + proxy_deployment_config: Dict[str, Any] = Field( + default_factory=dict, + description=""" + The Ray @server.deployment options for the proxy server. + """, + ) + + def parse_args(self) -> "PDServingArgs": + """Converts this LLMServingArgs object into an DeployArgs object.""" + + def parse_configs_and_cast_type(config: Union[str, LLMConfig]) -> LLMConfig: + # ray.serve.llm.__init__ imports internal LLMConfig, and extends it to external-facing LLMConfig. + # parse_llm_configs returns internal LLMConfig, while {prefill, decode}_configs expect external-facing LLMConfig. + # So the model_dump() here is to convert the type, to satisfy pydantic. + # TODO(lk-chen): refactor llm_config parsing to avoid this model_dump, and make llm_config more reusable. + config = parse_llm_configs([config])[0] + return LLMConfig(**config.model_dump()) + + return PDServingArgs( + # Parse string file path into LLMConfig + prefill_config=parse_configs_and_cast_type(self.prefill_config), + decode_config=parse_configs_and_cast_type(self.decode_config), + proxy_deployment_config=self.proxy_deployment_config, + ) + + +class PDProxyServer(LLMServer): + _default_engine_cls = None + """Proxy between P/D LLM servers. + + For chat and completions, proxy sends the request to the prefill server and + then parses the response to send to the decode server. + + Args: + prefill_server: The prefill server deployment handle. + decode_server: The decode server deployment handle. + """ + + async def __init__( + self, + prefill_server: DeploymentHandle, + decode_server: DeploymentHandle, + ): + + # We pass `llm_config` here to let super() extract the model_id, + # such that /v1/models endpoint can work correctly. + # TODO(lk-chen): refactor LLMRouter <-> LLMServer such that router + # query model_id through API, instead of passing it in as an argument. + # We can obtain llm_config from prefill_server for obtaining model_id + # assuming there is no mismatch between prefill and decode server. + llm_config = await prefill_server.llm_config.remote() + await super().__init__(llm_config) + self.prefill_server = prefill_server.options(stream=True) + self.decode_server = decode_server.options(stream=True) + + async def embeddings( + self, request: EmbeddingRequest + ) -> AsyncGenerator[EmbeddingResponse, None]: + raise NotImplementedError("Embedding is not supported for P/D disaggregation") + + def _prepare_prefill_request(self, request: RequestType) -> RequestType: + assert ( + getattr(request, "kv_transfer_params", None) is None + ), "kv_transfer_params should be empty before proxy" + prefill_request = request.model_copy(deep=True) + prefill_request.kv_transfer_params = { + "do_remote_decode": True, + "do_remote_prefill": False, + "remote_engine_id": None, + "remote_block_ids": None, + "remote_host": None, + "remote_port": None, + } + prefill_request.max_tokens = 1 + prefill_request.stream = False + + return prefill_request + + def _prepare_decode_request( + self, + request: RequestType, + prefill_chunk: Union[ChatCompletionResponse, CompletionResponse], + ) -> RequestType: + decode_request = request.model_copy(deep=True) + decode_request.kv_transfer_params = prefill_chunk.kv_transfer_params + + return decode_request + + async def _handle_request( + self, + request: RequestType, + ) -> AsyncGenerator[ + Union[str, ChatCompletionResponse, CompletionResponse, ErrorResponse], None + ]: + + await self._maybe_add_request_id_to_request(request) + + if isinstance(request, ChatCompletionRequest): + method = "chat" + elif isinstance(request, CompletionRequest): + method = "completions" + else: + raise ValueError(f"Unsupported request type: {type(request)}") + + prefill_request = self._prepare_prefill_request(request) + prefill_gen = getattr(self.prefill_server, method).remote(prefill_request) + + prefill_chunk = await prefill_gen.__anext__() + + if isinstance(prefill_chunk, ErrorResponse): + logger.error(f"Prefill returned error: {prefill_chunk}") + yield prefill_chunk + return + + decode_request = self._prepare_decode_request(request, prefill_chunk) + decode_gen = getattr(self.decode_server, method).remote(decode_request) + + async for chunk in decode_gen: + yield chunk + + async def chat( + self, request: ChatCompletionRequest + ) -> AsyncGenerator[Union[str, ChatCompletionResponse, ErrorResponse], None]: + return self._handle_request(request) + + async def completions( + self, request: CompletionRequest + ) -> AsyncGenerator[Union[str, CompletionResponse, ErrorResponse], None]: + return self._handle_request(request) + + @classmethod + def as_deployment(cls) -> serve.Deployment: + """Turns PDProxyServer into a Ray Serve deployment.""" + return serve.deployment()(cls) + + +def build_pd_openai_app(pd_serving_args: dict) -> Application: + """Build a deployable application utilizing prefill/decode disaggregation.""" + + pd_config = PDServingArgs.model_validate(pd_serving_args).parse_args() + + model_id = pd_config.decode_config.model_id + assert model_id == pd_config.prefill_config.model_id, "P/D model id mismatch" + + for config in [pd_config.prefill_config, pd_config.decode_config]: + if "kv_transfer_config" not in config.engine_kwargs: + config.update_engine_kwargs( + kv_transfer_config=dict( + kv_connector="NixlConnector", + kv_role="kv_both", + engine_id=str(uuid.uuid4()), + ) + ) + + prefill_deployment = build_llm_deployment( + pd_config.prefill_config, name_prefix="Prefill:" + ) + decode_deployment = build_llm_deployment( + pd_config.decode_config, name_prefix="Decode:" + ) + + proxy_server_deployment = ( + PDProxyServer.as_deployment() + .options(**pd_config.proxy_deployment_config) + .bind( + prefill_server=prefill_deployment, + decode_server=decode_deployment, + ) + ) + + return LLMRouter.as_deployment().bind(llm_deployments=[proxy_server_deployment]) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/routers/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/routers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/routers/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/routers/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb0bf974ba6c526127e293a275712c61573db952 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/routers/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/routers/__pycache__/middleware.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/routers/__pycache__/middleware.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb9e5fec02f0d0bddc0ca5700d254d7db6615c3a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/routers/__pycache__/middleware.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/routers/__pycache__/router.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/routers/__pycache__/router.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4cf539c3540d292271194d873823933e2717fe44 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/routers/__pycache__/router.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/routers/middleware.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/routers/middleware.py new file mode 100644 index 0000000000000000000000000000000000000000..961e199332ffcaa25f96d33c1dca248565ab7d0f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/routers/middleware.py @@ -0,0 +1,165 @@ +import uuid +from asyncio import CancelledError +from typing import Optional + +from fastapi import FastAPI, Request, status +from fastapi.exceptions import RequestValidationError +from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint +from starlette.responses import JSONResponse, Response + +from ray.llm._internal.serve.deployments.utils.server_utils import ( + get_response_for_error, +) +from ray.llm._internal.serve.observability.logging import get_logger + +logger = get_logger(__file__) + + +def get_request_id(request) -> str: + """Fetches request-id from Starlette's request object. + + NOTE: This method relies on "request_id" value to be injected into the + Starlette's `request.state` via `inject_request_id` middleware + + :param request: Starlette request object + :return: (optional) Id allowing to identify particular user + """ + return getattr(request.state, "request_id", None) + + +async def _handle_validation_error( + request: Request, exc: RequestValidationError +) -> JSONResponse: + """Handle pydantic validation errors in an OpenAI-like format.""" + error_details = exc.errors()[0] if exc.errors() else {"msg": "Invalid request"} + + error_msg = error_details.get("msg", "Unknown validation error") + error_loc = error_details.get("loc", ("body")) + error_input = error_details.get("input", None) + msg = f"Invalid request format: {error_msg} at {error_loc}" + + error_response = { + "error": { + "message": msg, + "type": error_details.get("type", "invalid_request_error"), + "param": error_input, + "code": "invalid_parameter", + } + } + + return JSONResponse(status_code=status.HTTP_400_BAD_REQUEST, content=error_response) + + +def _uncaught_exception_handler(request: Request, e: Exception): + """This method serves as an uncaught exception handler being + the last resort to return properly formatted response. + + NOTE: Exceptions from application handlers should NOT be reaching this point, + this handler is here to intercept "fly-away" exceptions and should not + be handled for handling of converting application exceptions into + appropriate responses + """ + + if isinstance(e, CancelledError): + return JSONResponse(content={}, status_code=204) + + request_id = get_request_id(request) + + logger.error(f"Uncaught exception while handling request {request_id}", exc_info=e) + + response_payload = get_response_for_error(e, request_id) + + return JSONResponse( + content=response_payload.model_dump(), status_code=response_payload.code + ) + + +def add_exception_handling_middleware(router: FastAPI): + # NOTE: PLEASE READ CAREFULLY BEFORE CHANGING + # + # Starlette has different behavior depending on the Exception class being handled + # that we unfortunately have to take into account here: + # + # - Handler for `Exception` will be added as uncaught exception handler (of last resort) + # that is going to be executed absolute last, making sure that in case of any fly-away + # (uncaught) exception + # - Handlers for any other classes of exceptions will be executed as last middleware layer, + # therefore being to intercept any exceptions originating from the handler before it + # propagates to the middleware above it + # + # As such we're aiming for 2 goals here: + # - Intercepting exceptions from the handlers, converting them into proper user-facing + # response (avoiding exception propagation up the middleware stack) + # - Adding uncaught exception handler (of last resort) to intercept any exceptions that + # might be originating from the middleware itself + + async def _handle_application_exceptions( + request: Request, call_next: RequestResponseEndpoint + ) -> Response: + """This method intercepts application level exceptions not handled by the + application code converting them into appropriately formatted (JSON) response + """ + + try: + return await call_next(request) + except CancelledError as ce: + # NOTE: We re-raise CancelledError as is to let other middleware handle it. + # Since no response is expected in this case, it's deferred to uncaught + # exception handler to ultimately handle it + raise ce + except RequestValidationError as e: + return await _handle_validation_error(request, e) + except Exception as e: + request_id = get_request_id(request) + response_payload = get_response_for_error(e, request_id) + + return JSONResponse( + content=response_payload.model_dump(), + status_code=response_payload.code, + ) + + # This adds last-resort uncaught exception handler into Starlette + router.add_exception_handler(Exception, _uncaught_exception_handler) + # Add validation error handler + router.add_exception_handler(RequestValidationError, _handle_validation_error) + # This adds application exception handler, allowing to convert application + # exceptions into properly formatted responses + router.add_middleware( + BaseHTTPMiddleware, + dispatch=_handle_application_exceptions, + ) + + +class SetRequestIdMiddleware: + """Injects request ID into the request's state. + + The ID is either: + 1. the value of the request's "x-request-id" header, set by Ray + Serve's Proxy, or + 2. if "x-request-id" header is unavailable, this middleware creates + a UUIDv4 request ID. + """ + + def __init__(self, app): + self.app = app + + async def __call__(self, scope, receive, send): + if scope["type"] == "http": + request = Request(scope) + request.state.request_id = request.headers.get("x-request-id", None) or str( + uuid.uuid4() + ) + + return await self.app(scope, receive, send) + + +def get_user_id(request) -> Optional[str]: + """Fetches user id inside Starlette's request object. + + NOTE: This method relies on "user_id" value to be injected into the + Starlette's `request.state` via authentication middleware + + :param request: Starlette request object + :return: (optional) Id identifying particular user + """ + return getattr(request.state, "user_id", None) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/routers/router.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/routers/router.py new file mode 100644 index 0000000000000000000000000000000000000000..0d22410c6ef8e3390de852605f6df3c2ae1da9f5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/routers/router.py @@ -0,0 +1,548 @@ +import asyncio +import json +import sys +from typing import ( + Any, + AsyncGenerator, + Awaitable, + Callable, + Dict, + List, + Optional, + Tuple, + TypeVar, + Union, +) + +from fastapi import FastAPI, HTTPException, status +from fastapi.middleware.cors import CORSMiddleware +from starlette.responses import JSONResponse, Response, StreamingResponse + +from ray import serve +from ray._common.utils import get_or_create_event_loop +from ray.llm._internal.common.utils.lora_utils import ( + get_base_model_id, + get_lora_model_ids, +) +from ray.llm._internal.serve.configs.constants import ( + DEFAULT_LLM_ROUTER_HTTP_TIMEOUT, + DEFAULT_LLM_ROUTER_INITIAL_REPLICAS, + DEFAULT_LLM_ROUTER_MAX_REPLICAS, + DEFAULT_LLM_ROUTER_MIN_REPLICAS, + DEFAULT_LLM_ROUTER_TARGET_ONGOING_REQUESTS, + DEFAULT_MAX_ONGOING_REQUESTS, + DEFAULT_ROUTER_TO_MODEL_REPLICA_RATIO, +) +from ray.llm._internal.serve.configs.openai_api_models import ( + ChatCompletionRequest, + ChatCompletionResponse, + ChatCompletionStreamResponse, + CompletionRequest, + CompletionResponse, + CompletionStreamResponse, + EmbeddingRequest, + EmbeddingResponse, + ErrorResponse, + LLMChatResponse, + LLMCompletionsResponse, + LLMEmbeddingsResponse, + ModelCard, + ModelList, + OpenAIHTTPException, + to_model_metadata, +) +from ray.llm._internal.serve.configs.server_models import LLMConfig +from ray.llm._internal.serve.deployments.routers.middleware import ( + SetRequestIdMiddleware, + add_exception_handling_middleware, +) +from ray.llm._internal.serve.deployments.utils.server_utils import replace_prefix +from ray.llm._internal.serve.observability.logging import get_logger +from ray.llm._internal.serve.observability.metrics.fast_api_metrics import ( + add_http_metrics_middleware, + metrics_lifespan, +) +from ray.llm._internal.serve.utils.lora_serve_utils import ( + get_lora_model_metadata, +) +from ray.serve.config import AutoscalingConfig +from ray.serve.handle import DeploymentHandle + +# Import asyncio timeout depends on python version +if sys.version_info >= (3, 11): + from asyncio import timeout +else: + from async_timeout import timeout + +logger = get_logger(__name__) + +T = TypeVar("T") + + +def _sanitize_chat_completion_request( + request: ChatCompletionRequest, +) -> ChatCompletionRequest: + """Sanitize ChatCompletionRequest to fix Pydantic ValidatorIterator serialization issue. + + This addresses a known Pydantic bug where tool_calls fields become ValidatorIterator + objects that cannot be pickled for Ray remote calls. + + References: + - vLLM PR that introduces the workaround: https://github.com/vllm-project/vllm/pull/9951 + - Pydantic Issue: https://github.com/pydantic/pydantic/issues/9467 + - Related Issue: https://github.com/pydantic/pydantic/issues/9541 + - Official Workaround: https://github.com/pydantic/pydantic/issues/9467#issuecomment-2442097291 + + TODO(seiji): Remove when we update to Pydantic v2.11+ with the fix. + """ + from vllm.transformers_utils.tokenizers.mistral import maybe_serialize_tool_calls + + maybe_serialize_tool_calls(request) + + return request + + +StreamResponseType = Union[ + ChatCompletionStreamResponse, + CompletionStreamResponse, +] +BatchedStreamResponseType = List[StreamResponseType] + + +def init() -> FastAPI: + _fastapi_router_app = FastAPI(lifespan=metrics_lifespan) + + # NOTE: PLEASE READ CAREFULLY BEFORE MODIFYING + # + # FastAPI middleware is executed in LIFO (last-in, first-out) order, + # hence maintaining current ordering is crucial as some of the middleware + # might have data dependency on the other: for ex, telemetry middleware + # depends on middleware generating request-id + # + # Add exception handling middleware + # NOTE: This middleware should be added first such that it's intercepting + # exceptions from the handlers, avoiding them propagating to other + # middleware (for ex, telemetry) + add_exception_handling_middleware(_fastapi_router_app) + # Configure CORS middleware + _fastapi_router_app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], + ) + # Add HTTP metrics middleware + add_http_metrics_middleware(_fastapi_router_app) + + # Inject unique per-request ID + # + # NOTE: This middleware should be executed among the last (since + # middleware is executed in LIFO). + _fastapi_router_app.add_middleware(SetRequestIdMiddleware) + + return _fastapi_router_app + + +fastapi_router_app = init() + + +def _apply_openai_json_format( + response: Union[StreamResponseType, BatchedStreamResponseType] +) -> str: + """Converts the stream response to OpenAI format. + + Each model response is converted to the string: + data: \n\n + + The converted strings are concatenated and returned: + data: \n\ndata: \n\n... + """ + if isinstance(response, list): + first_response = next(iter(response)) + if isinstance(first_response, str): + return "".join(response) + if isinstance(first_response, dict): + return "".join(f"data: {json.dumps(r)}\n\n" for r in response) + if hasattr(first_response, "model_dump_json"): + return "".join(f"data: {r.model_dump_json()}\n\n" for r in response) + raise ValueError( + f"Unexpected response type: {type(first_response)}, {first_response=}" + ) + if hasattr(response, "model_dump_json"): + return f"data: {response.model_dump_json()}\n\n" + if isinstance(response, str): + return response + raise ValueError(f"Unexpected response type: {type(response)}, {response=}") + + +async def _peek_at_generator( + gen: AsyncGenerator[T, None] +) -> Tuple[T, AsyncGenerator[T, None]]: + # Peek at the first element + first_item = await gen.__anext__() + + # Create a new generator that yields the peeked item first + async def new_generator() -> AsyncGenerator[T, None]: + yield first_item + async for item in gen: + yield item + + return first_item, new_generator() + + +async def _openai_json_wrapper( + generator: AsyncGenerator[ + Union[StreamResponseType, BatchedStreamResponseType], None + ], +) -> AsyncGenerator[str, None]: + """Wrapper that converts stream responses into OpenAI JSON strings. + + Args: + generator: an async generator that yields either individual stream responses + (StreamResponseType) or batches of stream responses (BatchedStreamResponseType). + Each response is converted into OpenAI JSON format and streamed to the client. + For batched responses, the items are concatenated together as a single string. + + Yields: + String chunks in OpenAI SSE format: "data: {json}\n\n", with a final + "data: [DONE]\n\n" to indicate completion. + """ + async for response in generator: + packet = _apply_openai_json_format(response) + yield packet + + yield "data: [DONE]\n\n" + + +class LLMRouter: + def __init__( + self, + llm_deployments: List[DeploymentHandle], + *, + _get_lora_model_metadata_func: Optional[ + Callable[[str, LLMConfig], Awaitable[Dict[str, Any]]] + ] = None, + ): + self._default_serve_handles: Dict[str, DeploymentHandle] = {} + self._llm_configs: Dict[str, LLMConfig] = {} + + # Configuring a ServeHandle with .options() creates a new ServeHandle + # object, which contains a new metrics pusher and long-polling call. + # Creating too many ServeHandles can impact event-loop and Serve Controller + # performance, so we save configured ServeHandles here and reuse them. + self._configured_serve_handles: Dict[str, DeploymentHandle] = {} + self._get_lora_model_metadata_func = ( + _get_lora_model_metadata_func or self._default_get_lora_model_metadata_func + ) + + # Setup _default_serve_handles and _llm_configs asynchronously. + self._init_completed = asyncio.Event() + self.running_setup_task = get_or_create_event_loop().create_task( + self._setup_handle_and_config_maps(llm_deployments=llm_deployments) + ) + + async def _default_get_lora_model_metadata_func( + self, model_id: str, llm_config: LLMConfig + ) -> Dict[str, Any]: + return await get_lora_model_metadata(model_id, llm_config) + + async def _setup_handle_and_config_maps( + self, llm_deployments: List[DeploymentHandle] + ): + for handle in llm_deployments: + llm_config = await handle.llm_config.remote() + self._default_serve_handles[llm_config.model_id] = handle + self._llm_configs[llm_config.model_id] = llm_config + + # Note (genesu): Even though we have already checked model id uniqueness in + # `router_application()` under run.py. When we OSS this router component, users + # would be able to directly use the lower level api and bypass that check. We + # check it again here to ensure all the model ids are unique. + if len(llm_deployments) != len(self._llm_configs): + raise ValueError("Duplicate models found. Make sure model ids are unique.") + + self._init_completed.set() + + async def check_health(self): + await self._init_completed.wait() + + def _get_configured_serve_handle(self, model_id: str): + """Gets a ServeHandle to a model deployment. + + Configures the handle's options, and stores it in a cache. + + If the model_id includes LoRA suffix, we set the model ID as + the multiplexed_model_id, so the request uses Serve's multiplexed + routing logic. + + If the model_id is a base model- even if the model has LoRA + adapters- we don't set multiplexed_model_id. Setting + multiplexed_model_id would cause base model requests to be + sent to a single model replica, instead of being load + balanced across all replicas. This is undesirable for base + model requests (unlike LoRA requests) because all the replicas + have a copy of the base model. + """ + + if model_id not in self._configured_serve_handles: + base_model_id = get_base_model_id(model_id) + if base_model_id in self._default_serve_handles: + if model_id == base_model_id: + default_handle = self._default_serve_handles[model_id] + configured_handle = default_handle.options(stream=True) + self._configured_serve_handles[model_id] = configured_handle + else: + default_handle = self._default_serve_handles[base_model_id] + configured_handle = default_handle.options( + stream=True, + multiplexed_model_id=model_id, + ) + self._configured_serve_handles[model_id] = configured_handle + else: + raise HTTPException( + status.HTTP_404_NOT_FOUND, + f'Could not find model with id "{model_id}".', + ) + + return self._configured_serve_handles[model_id] + + async def _get_response( + self, + *, + body: Union[CompletionRequest, ChatCompletionRequest, EmbeddingRequest], + call_method: str, + ) -> AsyncGenerator[ + Union[LLMChatResponse, LLMCompletionsResponse, LLMEmbeddingsResponse], None + ]: + """Calls the model deployment and returns the stream.""" + model: str = body.model + base_model_id = get_base_model_id(model) + if base_model_id not in self._llm_configs: + raise HTTPException( + status.HTTP_404_NOT_FOUND, + f'Got request for model "{model}". ' + f'Could not find base model with ID "{base_model_id}".', + ) + + model_handle = self._get_configured_serve_handle(model) + + # TODO(seiji): Remove when we update to Pydantic v2.11+ with the fix + # for tool calling ValidatorIterator serialization issue. + if isinstance(body, ChatCompletionRequest): + body = _sanitize_chat_completion_request(body) + + async for response in getattr(model_handle, call_method).remote(body): + yield response + + async def model(self, model_id: str) -> Optional[ModelCard]: + if model_id in self._llm_configs: + return to_model_metadata(model_id, self._llm_configs[model_id]) + + base_model_id = get_base_model_id(model_id) + if ( + base_model_id in self._llm_configs + and self._llm_configs[base_model_id].lora_config + ): + try: + overrides = await self._get_lora_model_metadata_func( + model_id, self._llm_configs[base_model_id] + ) + + return to_model_metadata( + model_id=model_id, + model_config=self._llm_configs[base_model_id], + overrides=overrides, + ) + except HTTPException: + logger.exception( + "Unable to retrieve LoRA adapter config file for " + f'"{model_id}". Omitting it from list of available models. ' + "Check that adapter config file exists in cloud bucket." + ) + + @fastapi_router_app.get("/v1/models", response_model=ModelList) + async def models(self) -> ModelList: + """OpenAI API-compliant endpoint to get all rayllm models.""" + all_models = dict() + for base_model_id, llm_config in self._llm_configs.items(): + # Add the base model. + all_models[base_model_id] = await self.model(base_model_id) + + if llm_config.lora_config is not None: + # Add all the fine-tuned models. + lora_model_ids = get_lora_model_ids( + dynamic_lora_loading_path=llm_config.lora_config.dynamic_lora_loading_path, + base_model_id=base_model_id, + ) + for lora_id in lora_model_ids: + model_data = await self.model(lora_id) + if model_data is not None: + all_models[lora_id] = model_data + + return ModelList(data=list(all_models.values())) + + # :path allows us to have slashes in the model name + @fastapi_router_app.get("/v1/models/{model:path}", response_model=ModelCard) + async def model_data(self, model: str) -> ModelCard: + """OpenAI API-compliant endpoint to get one rayllm model. + + :param model: The model ID (e.g. "amazon/LightGPT") + """ + model = replace_prefix(model) + model_data = await self.model(model) + if model_data is None: + raise OpenAIHTTPException( + message=f"Unable to find {model}. Please ensure that the model exists and you have permission.", + status_code=status.HTTP_404_NOT_FOUND, + type="InvalidModel", + ) + return model_data + + async def _process_llm_request( + self, body: Union[CompletionRequest, ChatCompletionRequest], is_chat: bool + ) -> Response: + NoneStreamingResponseType = ( + ChatCompletionResponse if is_chat else CompletionResponse + ) + call_method = "chat" if is_chat else "completions" + + async with timeout(DEFAULT_LLM_ROUTER_HTTP_TIMEOUT): + + gen = self._get_response(body=body, call_method=call_method) + + # In streaming with batching enabled, this first response can be a list of chunks. + initial_response, gen = await _peek_at_generator(gen) + + if isinstance(initial_response, list): + first_chunk = initial_response[0] + else: + first_chunk = initial_response + + if isinstance(first_chunk, ErrorResponse): + raise OpenAIHTTPException( + message=first_chunk.message, + status_code=first_chunk.code, + type=first_chunk.type, + ) + + if isinstance(first_chunk, NoneStreamingResponseType): + # Not streaming, first chunk should be a single response + return JSONResponse(content=first_chunk.model_dump()) + + # In case of streaming we need to iterate over the chunks and yield them + openai_stream_generator = _openai_json_wrapper(gen) + + return StreamingResponse( + openai_stream_generator, media_type="text/event-stream" + ) + + @fastapi_router_app.post("/v1/completions") + async def completions(self, body: CompletionRequest) -> Response: + """Given a prompt, the model will return one or more predicted completions, + and can also return the probabilities of alternative tokens at each position. + + Returns: + A response object with completions. + """ + return await self._process_llm_request(body, is_chat=False) + + @fastapi_router_app.post("/v1/chat/completions") + async def chat(self, body: ChatCompletionRequest) -> Response: + """Given a prompt, the model will return one or more predicted completions, + and can also return the probabilities of alternative tokens at each position. + + Returns: + A response object with completions. + """ + + return await self._process_llm_request(body, is_chat=True) + + @fastapi_router_app.post("/v1/embeddings") + async def embeddings(self, body: EmbeddingRequest) -> Response: + """Create embeddings for the provided input. + + Returns: + A response object with embeddings. + """ + async with timeout(DEFAULT_LLM_ROUTER_HTTP_TIMEOUT): + results = self._get_response(body=body, call_method="embeddings") + result = await results.__anext__() + if isinstance(result, ErrorResponse): + raise OpenAIHTTPException( + message=result.message, + status_code=result.code, + type=result.type, + ) + + if isinstance(result, EmbeddingResponse): + return JSONResponse(content=result.model_dump()) + + @classmethod + def as_deployment( + cls, llm_configs: Optional[List[LLMConfig]] = None + ) -> serve.Deployment: + """Converts this class to a Ray Serve deployment with ingress. + + Returns: + A Ray Serve deployment. + """ + min_replicas = DEFAULT_LLM_ROUTER_MIN_REPLICAS + initial_replicas = DEFAULT_LLM_ROUTER_INITIAL_REPLICAS + max_replicas = DEFAULT_LLM_ROUTER_MAX_REPLICAS + num_router_replicas = 0 + + # Note (genesu): Based on our internal benchmark, we are currently bottleneck + # by the router replicas during high concurrency situation. We are setting the + # router replicas to be ~2x the total model replicas and making it scale faster. + if llm_configs: + model_min_replicas = 0 + model_initial_replicas = 0 + model_max_replicas = 0 + for llm_config in llm_configs: + num_router_replicas = max( + num_router_replicas, + llm_config.experimental_configs.get("num_router_replicas", 0), + ) + + if "autoscaling_config" in llm_config.deployment_config: + autoscaling_config = llm_config.deployment_config[ + "autoscaling_config" + ] + if isinstance(autoscaling_config, dict): + autoscaling_config = AutoscalingConfig( + **llm_config.deployment_config["autoscaling_config"] + ) + else: + # When autoscaling config is not provided, we use the default. + autoscaling_config = AutoscalingConfig() + model_min_replicas += autoscaling_config.min_replicas + model_initial_replicas += ( + autoscaling_config.initial_replicas + or autoscaling_config.min_replicas + ) + model_max_replicas += autoscaling_config.max_replicas + min_replicas = num_router_replicas or int( + model_min_replicas * DEFAULT_ROUTER_TO_MODEL_REPLICA_RATIO + ) + initial_replicas = num_router_replicas or int( + model_initial_replicas * DEFAULT_ROUTER_TO_MODEL_REPLICA_RATIO + ) + max_replicas = num_router_replicas or int( + model_max_replicas * DEFAULT_ROUTER_TO_MODEL_REPLICA_RATIO + ) + + ingress_cls = serve.ingress(fastapi_router_app)(cls) + deployment_decorator = serve.deployment( + autoscaling_config={ + "min_replicas": min_replicas, + "initial_replicas": initial_replicas, + "max_replicas": max_replicas, + "target_ongoing_requests": DEFAULT_LLM_ROUTER_TARGET_ONGOING_REQUESTS, + }, + max_ongoing_requests=DEFAULT_MAX_ONGOING_REQUESTS, + ) + + deployment_cls = deployment_decorator(ingress_cls) + + return deployment_cls diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/utils/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/utils/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12762d4414a6e07ed8871cff253b6dd9f1c4fe97 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/utils/__pycache__/batcher.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/utils/__pycache__/batcher.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d8a4f1d8875318b1ea6215ea184b57a1cdef5dc Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/utils/__pycache__/batcher.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/utils/__pycache__/node_initialization_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/utils/__pycache__/node_initialization_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6ba34142fca95958ddd28013c1fca88e802ccd2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/utils/__pycache__/node_initialization_utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/utils/__pycache__/server_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/utils/__pycache__/server_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4aff41e6464c8bbf8c1d276dc60588ab7bedfd8e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/utils/__pycache__/server_utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/utils/batcher.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/utils/batcher.py new file mode 100644 index 0000000000000000000000000000000000000000..f52e9f62cc7dcb011db5d7a3d6b43006159ba3c7 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/utils/batcher.py @@ -0,0 +1,111 @@ +import asyncio +from typing import AsyncGenerator, Generic, Iterable, List, Optional, TypeVar + +from ray.llm._internal.serve.configs.constants import ( + MODEL_RESPONSE_BATCH_TIMEOUT_MS, +) +from ray.llm._internal.serve.observability.logging import get_logger + +logger = get_logger(__name__) + +T = TypeVar("T") + + +class Batcher(Generic[T]): + """This class batches multiple responses from a generator into a list of + single responses, at some time interval. + + Args: + generator: the async generator that this class pulls responses + from. + interval_ms: the interval at which this class yields the current batch. + If None, this class will batch all responses from the generator + together and yield the entire batch once. + """ + + def __init__( + self, + generator: AsyncGenerator[T, None], + interval_ms: Optional[float] = MODEL_RESPONSE_BATCH_TIMEOUT_MS, + ): + self.generator = generator + self.queue: asyncio.Queue = asyncio.Queue() + + if interval_ms is None: + self.interval_s = None + else: + self.interval_s = interval_ms / 1000 + + if interval_ms == 0: + return + + self.done_event: asyncio.Event = asyncio.Event() + + # We are okay with this task getting cancelled (to propagate cancellations) + self.read_task = asyncio.create_task(self.read()) + + def _merge_results(self, results: List[T]) -> Iterable[T]: + return results + + async def stream(self) -> AsyncGenerator[Iterable[T], None]: + """Drain from the queue every interval_ms and yield the merged results""" + + if self.interval_s == 0: + async for item in self.generator: + yield [item] + + return + + try: + while True: + # Wait for the interval or until we finish, whichever is faster. + # We use an event to avoid asyncio.wait_for cancelling the real task on timeout. + try: + if self.interval_s is None: + await self.done_event.wait() + else: + await asyncio.wait_for( + self.done_event.wait(), timeout=self.interval_s + ) + except asyncio.TimeoutError: + pass + + # Get all elements from the queue + results, is_done = self.check_done_and_drain() + + # If there are results, merge and yield them + if results: + output = self._merge_results(results) + yield output + + # If the read task is done, exit the stream task + if is_done: + # Raise exception, if any + self.read_task.result() + break + finally: + # If the stream task is done, make sure to exit the read task + if not self.read_task.done(): + self.read_task.cancel() + + def check_done_and_drain(self): + results = self.drain_queue() + return results, self.read_task.done() + + async def read(self): + """Read from the generator and put into the queue in a tight loop""" + try: + async for x in self.generator: + self.queue.put_nowait(x) + finally: + self.done_event.set() + + def drain_queue(self): + """Drain all results currently in the queue""" + results = [] + try: + while True: + results.append(self.queue.get_nowait()) + except asyncio.QueueEmpty: + pass + return results diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/utils/node_initialization_utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/utils/node_initialization_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f91e63c45b513e0e1eea39ce2ebbff5f3dccfda8 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/utils/node_initialization_utils.py @@ -0,0 +1,160 @@ +import asyncio +import os +from typing import Any, Dict, NamedTuple + +import ray +from ray.llm._internal.common.utils.download_utils import ( + NodeModelDownloadable, + download_model_files, +) +from ray.llm._internal.common.utils.import_utils import try_import +from ray.llm._internal.serve.configs.server_models import LLMConfig, LLMEngine +from ray.llm._internal.serve.deployments.llm.vllm.vllm_models import VLLMEngineConfig +from ray.llm._internal.serve.deployments.utils.server_utils import make_async +from ray.llm._internal.serve.observability.logging import get_logger +from ray.util.placement_group import PlacementGroup + +torch = try_import("torch") +transformers = try_import("transformers") + +logger = get_logger(__name__) + + +async def initialize_worker_nodes( + llm_config: LLMConfig, + *, + placement_group: PlacementGroup, + runtime_env: Dict[str, Any], + download_model: NodeModelDownloadable, + download_extra_files: bool, +): + """Runs the download tasks across all the nodes in the placement groups. + + To this we obtain the nodes that the placement groups are spread across. + Then we create a node affinity scheduling strategy for each node and + run the download_model_files task for each node in a separate ray.remote call. + This ensures that we call download_model_files once per node all in parallel. + """ + engine_config = VLLMEngineConfig.from_llm_config(llm_config) + pg_table = ray.util.placement_group_table(placement_group) + + node_set = set(pg_table["bundles_to_node_id"].values()) + download_tasks = [] + for node_id in node_set: + node_affinity_strategy = ( + ray.util.scheduling_strategies.NodeAffinitySchedulingStrategy( + node_id=node_id, + soft=False, + ) + ) + download_tasks.append( + ray.remote(download_model_files).options( + num_cpus=1, + scheduling_strategy=node_affinity_strategy, + runtime_env=runtime_env, + ) + ) + + logger.info("Running tasks to download model files on worker nodes") + await asyncio.gather( + *[ + download_task.remote( + engine_config.actual_hf_model_id, + engine_config.mirror_config, + download_model=download_model, + download_extra_files=download_extra_files, + ) + for download_task in download_tasks + ] + ) + + +class InitializeNodeOutput(NamedTuple): + placement_group: PlacementGroup + runtime_env: Dict[str, Any] + extra_init_kwargs: Dict[str, Any] + + +async def initialize_node(llm_config: LLMConfig) -> InitializeNodeOutput: + """Implements node initialization for LLM engines. + + Downloads model, tokenizer, and extra files as necessary. + + If the placement strategy is STRICT_PACK, all of the initialization will be run locally + (as all of the workers must be colocated with this process). Else, the initialization + will be run across the placement group bundles. + """ + local_node_download_model = NodeModelDownloadable.TOKENIZER_ONLY + worker_node_download_model = NodeModelDownloadable.MODEL_AND_TOKENIZER + extra_init_kwargs = {} + + engine_config = llm_config.get_engine_config() + assert engine_config is not None + pg = engine_config.get_or_create_pg() + runtime_env = engine_config.get_runtime_env_with_local_env_vars() + + if engine_config.placement_strategy == "STRICT_PACK": + # If the placement strategy is STRICT_PACK, we know that all the + # workers run on the same node as the engine. Therefore, we can run + # all initialization steps directly instead of in tasks in the PG. + # This removes the task launching overhead reducing the initialization + # time. + local_node_download_model = local_node_download_model.union( + worker_node_download_model + ) + + await _initialize_local_node( + llm_config, + download_model=local_node_download_model, + download_extra_files=True, + ) + else: + await initialize_worker_nodes( + llm_config, + placement_group=pg, + runtime_env=runtime_env, + download_model=worker_node_download_model, + download_extra_files=True, + ) + + return InitializeNodeOutput( + placement_group=pg, runtime_env=runtime_env, extra_init_kwargs=extra_init_kwargs + ) + + +@make_async +def _initialize_local_node( + llm_config: LLMConfig, + *, + download_model: NodeModelDownloadable, + download_extra_files: bool, +): + engine_config = llm_config.get_engine_config() + local_path = download_model_files( + model_id=engine_config.actual_hf_model_id, + mirror_config=engine_config.mirror_config, + download_model=download_model, + download_extra_files=download_extra_files, + ) + + # Validate that the binary exists + if local_path and local_path != engine_config.actual_hf_model_id: + engine_config.hf_model_id = local_path + + # Download the tokenizer if it isn't a local file path + if not isinstance(local_path, str) or not os.path.exists(local_path): + logger.info(f"Downloading the tokenizer for {engine_config.actual_hf_model_id}") + + if llm_config.llm_engine == LLMEngine.vLLM: + from vllm.transformers_utils.tokenizer import get_tokenizer + + _ = get_tokenizer( + engine_config.actual_hf_model_id, + tokenizer_mode=engine_config.engine_kwargs.get("tokenizer_mode", None), + trust_remote_code=engine_config.trust_remote_code, + ) + else: + _ = transformers.AutoTokenizer.from_pretrained( + engine_config.actual_hf_model_id, + trust_remote_code=engine_config.trust_remote_code, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/utils/server_utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/utils/server_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..121b5ea68118f78db9a7492b3ee0f112f712fd6b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/deployments/utils/server_utils.py @@ -0,0 +1,135 @@ +import asyncio +import traceback +from functools import partial +from typing import Awaitable, Callable, TypeVar + +from fastapi import HTTPException, status +from httpx import HTTPStatusError as HTTPXHTTPStatusError +from pydantic import ValidationError as PydanticValidationError + +from ray import serve +from ray.llm._internal.serve.configs.openai_api_models import ( + ErrorResponse, + OpenAIHTTPException, +) +from ray.llm._internal.serve.observability.logging import get_logger + +logger = get_logger(__name__) + +T = TypeVar("T") + + +def make_async(_func: Callable[..., T]) -> Callable[..., Awaitable[T]]: + """Take a blocking function, and run it on in an executor thread. + + This function prevents the blocking function from blocking the asyncio event loop. + The code in this function needs to be thread safe. + """ + + def _async_wrapper(*args, **kwargs) -> asyncio.Future: + loop = asyncio.get_event_loop() + func = partial(_func, *args, **kwargs) + return loop.run_in_executor(executor=None, func=func) + + return _async_wrapper + + +def extract_message_from_exception(e: Exception) -> str: + # If the exception is a Ray exception, we need to dig through the text to get just + # the exception message without the stack trace + # This also works for normal exceptions (we will just return everything from + # format_exception_only in that case) + message_lines = traceback.format_exception_only(type(e), e)[-1].strip().split("\n") + message = "" + # The stack trace lines will be prefixed with spaces, so we need to start from the bottom + # and stop at the last line before a line with a space + found_last_line_before_stack_trace = False + for line in reversed(message_lines): + if not line.startswith(" "): + found_last_line_before_stack_trace = True + if found_last_line_before_stack_trace and line.startswith(" "): + break + message = line + "\n" + message + message = message.strip() + return message + + +def _extract_message(e): + if isinstance(e, OpenAIHTTPException) and e.internal_message is not None: + internal_message = e.internal_message + else: + internal_message = extract_message_from_exception(e) + + if isinstance(e, HTTPException): + message = e.detail + elif isinstance(e, OpenAIHTTPException): + message = e.message + else: + message = internal_message + + return internal_message, message + + +def get_response_for_error( + e: Exception, + request_id: str, +) -> ErrorResponse: + if isinstance(e, HTTPException): + status_code = e.status_code + elif isinstance(e, OpenAIHTTPException): + status_code = e.status_code + elif isinstance(e, PydanticValidationError): + status_code = 400 + elif isinstance(e, HTTPXHTTPStatusError): + status_code = e.response.status_code + else: + # Try to get the status code attribute from exception, + # if not present, fallback to generic 500 + status_code = int( + getattr(e, "status_code", status.HTTP_500_INTERNAL_SERVER_ERROR) + ) + + log = logger.error if status_code >= 500 else logger.warning + log( + f"Encountered failure while handling request {request_id}", + exc_info=e, + extra={"ray_serve_extra_fields": {"status_code": status_code}}, + ) + + if status_code == status.HTTP_500_INTERNAL_SERVER_ERROR: + internal_message = message = "Internal Server Error" + exc_type = "InternalServerError" + else: + internal_message, message = _extract_message(e) + exc_type = e.__class__.__name__ + + # TODO make this more robust + if "(Request ID: " not in message: + message += f" (Request ID: {request_id})" + + if "(Request ID: " not in internal_message: + internal_message += f" (Request ID: {request_id})" + + error_response = ErrorResponse( + message=f"Message: {message}, Internal exception: {internal_message}, original exception: {str(e)}", + code=status_code, + type=exc_type, + ) + return error_response + + +def get_serve_request_id() -> str: + """Get request id from serve request context.""" + context = serve.context._serve_request_context.get() + if context is not None: + return context.request_id + return "" + + +def get_model_request_id(model: str): + return model + "-" + get_serve_request_id() + + +def replace_prefix(model: str) -> str: + """Replace -- with / in model name to handle slashes within the URL path segment""" + return model.replace("--", "/") diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..22da68f1f549f3dc51a8621171d838a1ae6f3823 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/__init__.py @@ -0,0 +1,23 @@ +from ray.llm._internal.common.observability.logging_utils import ( + disable_datasets_logger, + disable_vllm_custom_ops_logger_on_cpu_nodes, +) +from ray.llm._internal.common.observability.telemetry_utils import Once +from ray.llm._internal.serve.observability.logging.setup import ( + setup_logging, +) + +_setup_observability_once = Once() + + +def _setup_observability(): + setup_logging() + disable_datasets_logger() + disable_vllm_custom_ops_logger_on_cpu_nodes() + + +def setup_observability(): + _setup_observability_once.do_once(_setup_observability) + + +__all__ = ["setup_observability"] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a977056b44ee5664877e27df304779c0e85a768 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/logging/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/logging/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6e684874f33ede9cd003e69c64c91eed19695bff --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/logging/__init__.py @@ -0,0 +1,39 @@ +import logging +from typing import Optional + +from ray._private.ray_logging.filters import CoreContextFilter +from ray.serve._private.logging_utils import ServeContextFilter + + +def _setup_logger(logger_name: str): + """Setup logger given the logger name. + + This function is idempotent and won't set up the same logger multiple times. It will + Also skip the setup if Serve logger is already setup and has handlers. + """ + logger = logging.getLogger(logger_name) + serve_logger = logging.getLogger("ray.serve") + + # Skip setup if the logger already has handlers setup or if the parent (Serve + # logger) has handlers. + if logger.handlers or serve_logger.handlers: + return + + # Set up stream handler, which logs to console as plaintext. + stream_handler = logging.StreamHandler() + stream_handler.addFilter(CoreContextFilter()) + stream_handler.addFilter(ServeContextFilter()) + logger.addHandler(stream_handler) + logger.setLevel(logging.INFO) + logger.propagate = False + + +def get_logger(name: Optional[str] = None): + """Get a structured logger inherited from the Ray Serve logger. + + Loggers by default are logging to stdout, and are expected to be scraped by an + external process. + """ + logger_name = f"ray.serve.{name}" + _setup_logger(logger_name) + return logging.getLogger(logger_name) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/logging/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/logging/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f9b38ef9d90fa77aee4a16e8c04128893bdd38c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/logging/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/logging/__pycache__/setup.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/logging/__pycache__/setup.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..edbdac828b42a8a1c94c25967b5fa280bbe99b47 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/logging/__pycache__/setup.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/logging/setup.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/logging/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..b57f7e1494849bd913081ee610a15cec9b8ed79e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/logging/setup.py @@ -0,0 +1,28 @@ +import logging + +from ray._private.ray_logging.filters import CoreContextFilter +from ray._private.ray_logging.formatters import JSONFormatter +from ray.serve._private.logging_utils import ServeContextFilter + + +def _configure_stdlib_logging(): + """Configures stdlib root logger to make sure stdlib loggers (created as + `logging.getLogger(...)`) are using Ray's `JSONFormatter` with Core and Serve + context filters. + """ + + handler = logging.StreamHandler() + handler.addFilter(CoreContextFilter()) + handler.addFilter(ServeContextFilter()) + handler.setFormatter(JSONFormatter()) + + root_logger = logging.getLogger() + # NOTE: It's crucial we reset all the handlers of the root logger, + # to make sure that logs aren't emitted twice + root_logger.handlers = [] + root_logger.addHandler(handler) + root_logger.setLevel(logging.INFO) + + +def setup_logging(): + _configure_stdlib_logging() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01ade08101efe60a8de7dfda580f59539e4eea3c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/__pycache__/event_loop_monitoring.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/__pycache__/event_loop_monitoring.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a64b238012ad86b656602efd0a90377dce6641cf Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/__pycache__/event_loop_monitoring.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/__pycache__/fast_api_metrics.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/__pycache__/fast_api_metrics.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d51540eb6dab8661b231bc1848d42615c206afe0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/__pycache__/fast_api_metrics.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/__pycache__/fastapi_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/__pycache__/fastapi_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b66d15aadac4323e3b75ad8793150f88d843faf Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/__pycache__/fastapi_utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/__pycache__/middleware.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/__pycache__/middleware.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92d73aa505d9406d82ec5f910053be2a144a2a1d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/__pycache__/middleware.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/__pycache__/utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c183245b87f5b33e6fe9ab2e0b33516dabd2a0b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/__pycache__/utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/event_loop_monitoring.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/event_loop_monitoring.py new file mode 100644 index 0000000000000000000000000000000000000000..ea139c6ab8f7e175dfe2ced23b0213c60c5327ac --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/event_loop_monitoring.py @@ -0,0 +1,77 @@ +import asyncio +import time +from typing import Dict + +from ray.llm._internal.serve.observability.logging import get_logger +from ray.util import metrics + +logger = get_logger(__name__) + +_METRICS_LOOP_INTERVAL = 5 # 5 seconds +EVENT_LOOP_LATENCY_HISTOGRAM_BOUNDARIES = [ + 0.05, + 0.1, + 0.15, + 0.20, + 0.25, + 0.5, + 0.75, + 1.0, + 1.5, + 2.0, + 3.0, + 5.0, + 10.0, + 15.0, + 20.0, + 30.0, + 45.0, + 60.0, + 90.0, + 120.0, + 150.0, + 180.0, + 300.0, + 600.0, +] + + +def setup_event_loop_monitoring( + loop: asyncio.AbstractEventLoop, + scheduling_latency: metrics.Histogram, + iterations: metrics.Counter, + tasks: metrics.Gauge, + tags: Dict[str, str], +) -> asyncio.Task: + return asyncio.create_task( + _run_monitoring_loop( + loop, + schedule_latency=scheduling_latency, + iterations=iterations, + task_gauge=tasks, + tags=tags, + ) + ) + + +async def _run_monitoring_loop( + loop: asyncio.AbstractEventLoop, + schedule_latency: metrics.Histogram, + iterations: metrics.Counter, + task_gauge: metrics.Gauge, + tags: Dict[str, str], +) -> None: + while loop.is_running(): + iterations.inc(1, tags) + num_tasks = len(asyncio.all_tasks()) + task_gauge.set(num_tasks, tags) + yield_time = time.monotonic() + await asyncio.sleep(_METRICS_LOOP_INTERVAL) + elapsed_time = time.monotonic() - yield_time + + # Historically, Ray's implementation of histograms are extremely finicky + # with non-positive values (https://github.com/ray-project/ray/issues/26698). + # Technically it shouldn't be possible for this to be negative, add the + # max just to be safe. + latency = max(0.0, elapsed_time - _METRICS_LOOP_INTERVAL) + schedule_latency.observe(latency, tags) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/fast_api_metrics.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/fast_api_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..0dc043a547b34930a3a276db22f806aeb4327720 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/fast_api_metrics.py @@ -0,0 +1,133 @@ +import asyncio +import os +from contextlib import asynccontextmanager + +from fastapi import FastAPI + +from ray.llm._internal.serve.configs.constants import ENABLE_VERBOSE_TELEMETRY +from ray.llm._internal.serve.observability.logging import get_logger +from ray.llm._internal.serve.observability.metrics.event_loop_monitoring import ( + EVENT_LOOP_LATENCY_HISTOGRAM_BOUNDARIES, + setup_event_loop_monitoring, +) +from ray.llm._internal.serve.observability.metrics.fastapi_utils import ( + FASTAPI_API_SERVER_TAG_KEY, + FASTAPI_BASE_HTTP_METRIC_TAG_KEYS, + get_app_name, +) +from ray.llm._internal.serve.observability.metrics.middleware import ( + MeasureHTTPRequestMetricsMiddleware, +) +from ray.util import metrics + +logger = get_logger(__name__) + +ray_llm_build_info_gauge = metrics.Gauge( + "ray_llm_build_info", + description="Metadata about the ray-llm build.", + tag_keys=("git_commit",), +) + + +_HTTP_HANDLER_LATENCY_S_HISTOGRAM_BUCKETS = [ + 0.01, + 0.05, + 0.1, + 0.25, + 0.5, + 0.75, + 1, + 1.5, + 2, + 5, + 10, + 30, + 60, + 120, + 300, +] + + +async def add_fastapi_event_loop_monitoring(app: FastAPI): + tags = {FASTAPI_API_SERVER_TAG_KEY: get_app_name(app)} + tag_keys = tuple(tags.keys()) + + # Store the task handle to prevent it from being garbage collected + app.state.fastapi_event_loop_schedule_latency = metrics.Histogram( + "fastapi_event_loop_schedule_latency", + description="Latency of getting yielded control on the FastAPI event loop in seconds", + boundaries=EVENT_LOOP_LATENCY_HISTOGRAM_BOUNDARIES, + tag_keys=tag_keys, + ) + app.state.fastapi_event_loop_monitoring_iterations = metrics.Counter( + "fastapi_event_loop_monitoring_iterations", + description="Number of times the FastAPI event loop has iterated to get anyscale_fastapi_event_loop_schedule_latency.", + tag_keys=tag_keys, + ) + app.state.fastapi_event_loop_monitoring_tasks = metrics.Gauge( + "fastapi_event_loop_monitoring_tasks", + description="Number of outstanding tasks on the FastAPI event loop.", + tag_keys=tag_keys, + ) + + app.state.fastapi_event_loop_schedule_latency_metrics_task = ( + setup_event_loop_monitoring( + asyncio.get_running_loop(), + app.state.fastapi_event_loop_schedule_latency, + app.state.fastapi_event_loop_monitoring_iterations, + app.state.fastapi_event_loop_monitoring_tasks, + tags, + ) + ) + + +def add_http_metrics_middleware(app: FastAPI): + if not ENABLE_VERBOSE_TELEMETRY: + logger.debug( + "ENABLE_VERBOSE_TELEMETRY is false, not setting up FastAPI telemetry" + ) + return + + logger.info("ENABLE_VERBOSE_TELEMETRY is true, setting up FastAPI telemetry") + base_tag_keys = FASTAPI_BASE_HTTP_METRIC_TAG_KEYS + + logger.debug("Setting up FastAPI telemetry") + + app.state.http_requests_metrics = metrics.Counter( + "http_requests", + description=( + "Total number of HTTP requests by status code, handler and method." + ), + tag_keys=base_tag_keys, + ) + # NOTE: Custom decorators are not applied to histogram-based metrics + # to make sure we can keep cardinality of those in check + app.state.http_requests_latency_metrics = metrics.Histogram( + "http_request_duration_seconds", + description="Duration in seconds of HTTP requests.", + boundaries=_HTTP_HANDLER_LATENCY_S_HISTOGRAM_BUCKETS, + tag_keys=base_tag_keys, + ) + + app.add_middleware(MeasureHTTPRequestMetricsMiddleware) + + logger.debug("Setting up FastAPI telemetry completed") + + +async def set_ray_llm_build_info(): + git_commit = os.environ.get("GIT_COMMIT") + if git_commit: + tags = {"git_commit": git_commit} + ray_llm_build_info_gauge.set(1, tags) + + +@asynccontextmanager +async def metrics_lifespan(app: FastAPI): + """Lifespan for a FastAPI app that sets up metrics observability.""" + + if ENABLE_VERBOSE_TELEMETRY: + await add_fastapi_event_loop_monitoring(app) + + await set_ray_llm_build_info() + + yield diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/fastapi_utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/fastapi_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ce15928fa42101871b7059e914489df755a4b97a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/fastapi_utils.py @@ -0,0 +1,26 @@ +"""This file contains constants and utility functions for FastAPI.""" + +from fastapi import FastAPI + +# These tag keys are used in metrics for the FastAPI app. +FASTAPI_HTTP_RESPONSE_CODE_TAG_KEY = "code" +FASTAPI_HTTP_HANDLER_TAG_KEY = "handler" +FASTAPI_HTTP_METHOD_TAG_KEY = "method" +FASTAPI_HTTP_PATH_TAG_KEY = "path" +FASTAPI_HTTP_USER_ID_TAG_KEY = "user_id" +FASTAPI_API_SERVER_TAG_KEY = "api_server" + +FASTAPI_BASE_HTTP_METRIC_TAG_KEYS = ( + FASTAPI_HTTP_RESPONSE_CODE_TAG_KEY, + FASTAPI_HTTP_HANDLER_TAG_KEY, + FASTAPI_HTTP_METHOD_TAG_KEY, + FASTAPI_HTTP_PATH_TAG_KEY, + FASTAPI_HTTP_USER_ID_TAG_KEY, + FASTAPI_API_SERVER_TAG_KEY, +) + + +def get_app_name(app: FastAPI) -> str: + """Gets the FastAPI app name.""" + + return getattr(app.state, "name", "unknown") diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/middleware.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/middleware.py new file mode 100644 index 0000000000000000000000000000000000000000..8cfbe07ab6aadeb1ca0ff39e553acc38e38d49b6 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/middleware.py @@ -0,0 +1,156 @@ +import time +from asyncio import CancelledError +from typing import Dict + +from fastapi import FastAPI +from starlette.requests import Request +from starlette.routing import Match +from starlette.types import Message + +from ray.llm._internal.serve.deployments.routers.middleware import ( + get_request_id, + get_user_id, +) +from ray.llm._internal.serve.observability.logging import get_logger +from ray.llm._internal.serve.observability.metrics.fastapi_utils import ( + FASTAPI_API_SERVER_TAG_KEY, + FASTAPI_HTTP_HANDLER_TAG_KEY, + FASTAPI_HTTP_METHOD_TAG_KEY, + FASTAPI_HTTP_PATH_TAG_KEY, + FASTAPI_HTTP_RESPONSE_CODE_TAG_KEY, + FASTAPI_HTTP_USER_ID_TAG_KEY, + get_app_name, +) + +logger = get_logger("ray.serve") + + +class MeasureHTTPRequestMetricsMiddleware: + """Measures and stores HTTP request metrics.""" + + def __init__(self, app): + self.app = app + + async def __call__(self, scope, receive, send): + if scope["type"] not in ("http", "websocket"): + await self.app(scope, receive, send) + + # If the status_code isn't set by send_wrapper, + # we should consider that an error. + status_code = 500 + send_wrapper_failed_exc_info = "Status code was never set by send_wrapper." + exception_info = send_wrapper_failed_exc_info + + async def send_wrapper(message: Message) -> None: + """Wraps the send message. + + Enables this middleware to access the response headers. + """ + + nonlocal status_code, exception_info + if message["type"] == "http.response.start": + status_code = message.get("status", 500) + + # Clear the send_wrapper_failed_exc_info. + if exception_info == send_wrapper_failed_exc_info: + exception_info = None + + await send(message) + + request = Request(scope) + req_id = get_request_id(request) + now = time.monotonic() + try: + logger.info(f"Starting handling of the request {req_id}") + await self.app(scope, receive, send_wrapper) + + except CancelledError as ce: + status_code = -1 + exception_info = ce + raise + + except BaseException as e: + status_code = 500 + exception_info = e + raise + + finally: + duration_s = time.monotonic() - now + + tags = _get_tags(request, status_code, request.app) + # NOTE: Custom decorators are not applied to histogram-based metrics + # to make sure we can keep cardinality of those in check + truncated_tags = { + **tags, + FASTAPI_HTTP_USER_ID_TAG_KEY: "truncated", + } + + request.app.state.http_requests_metrics.inc(1, tags) + request.app.state.http_requests_latency_metrics.observe( + duration_s, truncated_tags + ) + + extra_context = { + "status_code": status_code, + "duration_ms": duration_s * 1000, + } + + if status_code >= 400: + log = logger.error if status_code >= 500 else logger.warning + log( + f"Handling of the request {req_id} failed", + exc_info=exception_info, + extra={"ray_serve_extra_fields": extra_context}, + ) + elif status_code == -1: + logger.info( + f"Handling of the request {req_id} have been cancelled", + extra={"ray_serve_extra_fields": extra_context}, + ) + else: + logger.info( + f"Handling of the request {req_id} successfully completed", + extra={"ray_serve_extra_fields": extra_context}, + ) + + +def _get_route_details(scope): + """ + Function to retrieve Starlette route from scope. + TODO: there is currently no way to retrieve http.route from + a starlette application from scope. + See: https://github.com/encode/starlette/pull/804 + Args: + scope: A Starlette scope + Returns: + A string containing the route or None + """ + app = scope["app"] + route = None + + for starlette_route in app.routes: + match, _ = starlette_route.matches(scope) + if match == Match.FULL: + route = starlette_route.path + break + if match == Match.PARTIAL: + route = starlette_route.path + return route + + +def _get_tags(request: Request, status_code: int, app: FastAPI) -> Dict[str, str]: + """Generates tags for the request's metrics.""" + + route = str(_get_route_details(request.scope)) or "unknown" + path = str(request.url.path) or "unknown" + method = str(request.method) or "unknown" + user_id = str(get_user_id(request) or "unknown") + + return { + FASTAPI_API_SERVER_TAG_KEY: get_app_name(app), + FASTAPI_HTTP_RESPONSE_CODE_TAG_KEY: str(status_code), + FASTAPI_HTTP_PATH_TAG_KEY: path, + FASTAPI_HTTP_HANDLER_TAG_KEY: route, + FASTAPI_HTTP_METHOD_TAG_KEY: method, + FASTAPI_HTTP_USER_ID_TAG_KEY: user_id, + } diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9c49cbcf4d0408637ce8bde474ea7b239dc66d43 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/metrics/utils.py @@ -0,0 +1,144 @@ +import time +from enum import Enum +from typing import ( + AsyncGenerator, + Callable, + List, + Set, + TypeVar, +) + +from ray.util import metrics + +# Histogram buckets for short-range latencies measurements: +# Min=1ms, Max=30s +# +# NOTE: Number of buckets have to be bounded (and not exceed 30) +# to avoid overloading metrics sub-system +SHORT_RANGE_LATENCY_HISTOGRAM_BUCKETS_MS: List[float] = [ + 1, + 5, + 10, + 25, + 50, + 100, + 150, + 250, + 500, + 1000, + 1500, + 2500, + 5000, + 7500, + 10000, + 20000, + 30000, +] + +# Histogram buckets for long-range latencies measurements: +# Min=10ms, Max=300s +LONG_RANGE_LATENCY_HISTOGRAM_BUCKETS_MS = [ + x * 10 for x in SHORT_RANGE_LATENCY_HISTOGRAM_BUCKETS_MS +] + + +class ClockUnit(int, Enum): + ms = 1000 + s = 1 + + +class MsClock: + """A clock that tracks intervals in milliseconds""" + + def __init__(self, unit: ClockUnit = ClockUnit.ms): + self.reset() + self.unit = unit.value + self.start_time = time.perf_counter() + + def reset(self): + self.start_time = time.perf_counter() + + def interval(self): + return (time.perf_counter() - self.start_time) * self.unit + + def reset_interval(self): + interval = self.interval() + self.reset() + return interval + + +T = TypeVar("T") + + +class InstrumentTokenAsyncGenerator: + """This class instruments an asynchronous generator. + + It gathers 3 metrics: + 1. Time to first time + 2. Time between tokens + 3. Total completion time + + Usage: + + @InstrumentTokenAsyncGenerator("my_special_fn") + async def to_instrument(): + yield ... + """ + + all_instrument_names: Set[str] = set() + + def __init__( + self, generator_name: str, latency_histogram_buckets: List[float] = None + ): + self.generator_name = f"rayllm_{generator_name}" + + target_latency_histogram_buckets = ( + latency_histogram_buckets or SHORT_RANGE_LATENCY_HISTOGRAM_BUCKETS_MS + ) + + assert ( + self.generator_name not in self.all_instrument_names + ), "This generator name was already used elsewhere. Please specify another one." + self.all_instrument_names.add(self.generator_name) + + self.token_latency_histogram = metrics.Histogram( + f"{self.generator_name}_per_token_latency_ms", + f"Generator metrics for {self.generator_name}", + boundaries=target_latency_histogram_buckets, + ) + + self.first_token_latency_histogram = metrics.Histogram( + f"{self.generator_name}_first_token_latency_ms", + f"Generator metrics for {self.generator_name}", + boundaries=target_latency_histogram_buckets, + ) + self.total_latency_histogram = metrics.Histogram( + f"{self.generator_name}_total_latency_ms", + f"Generator metrics for {self.generator_name}", + boundaries=target_latency_histogram_buckets, + ) + + def __call__( + self, async_generator_fn: Callable[..., AsyncGenerator[T, None]] + ) -> Callable[..., AsyncGenerator[T, None]]: + async def new_gen(*args, **kwargs): + interval_clock = MsClock() + total_clock = MsClock() + is_first_token = True + try: + async for x in async_generator_fn(*args, **kwargs): + if is_first_token: + self.first_token_latency_histogram.observe( + total_clock.interval() + ) + interval_clock.reset() + is_first_token = False + else: + self.token_latency_histogram.observe( + interval_clock.reset_interval() + ) + yield x + finally: + self.total_latency_histogram.observe(total_clock.interval()) + + return new_gen diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/usage_telemetry/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/usage_telemetry/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/usage_telemetry/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/usage_telemetry/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91c0156769f04363be24a9f001d3ea5007d3532e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/usage_telemetry/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/usage_telemetry/__pycache__/usage.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/usage_telemetry/__pycache__/usage.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4206347cd7ff9296d33b73f2b298a839d7c94470 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/usage_telemetry/__pycache__/usage.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/usage_telemetry/usage.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/usage_telemetry/usage.py new file mode 100644 index 0000000000000000000000000000000000000000..b011db4810cdc857673388724b39cd7fb77dd053 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/observability/usage_telemetry/usage.py @@ -0,0 +1,322 @@ +import random +import time +from enum import Enum +from typing import TYPE_CHECKING, Callable, Dict, List, Optional, Sequence + +import ray +from ray import serve +from ray._common.usage.usage_lib import ( + get_hardware_usages_to_report, + record_extra_usage_tag, +) +from ray.llm._internal.common.base_pydantic import BaseModelExtended +from ray.llm._internal.common.observability.telemetry_utils import DEFAULT_GPU_TYPE +from ray.llm._internal.common.utils.lora_utils import get_lora_model_ids +from ray.llm._internal.serve.observability.logging import get_logger + +if TYPE_CHECKING: + from ray.llm._internal.serve.configs.server_models import LLMConfig + +LLM_SERVE_TELEMETRY_NAMESPACE = "llm_serve_telemetry" +LLM_SERVE_TELEMETRY_ACTOR_NAME = "llm_serve_telemetry" + +logger = get_logger(__name__) + + +class TelemetryTags(str, Enum): + """Telemetry tags for LLM SERVE.""" + + LLM_SERVE_SERVE_MULTIPLE_MODELS = "LLM_SERVE_SERVE_MULTIPLE_MODELS" + LLM_SERVE_SERVE_MULTIPLE_APPS = "LLM_SERVE_SERVE_MULTIPLE_APPS" + LLM_SERVE_JSON_MODE_MODELS = "LLM_SERVE_JSON_MODE_MODELS" + LLM_SERVE_JSON_MODE_NUM_REPLICAS = "LLM_SERVE_JSON_MODE_NUM_REPLICAS" + LLM_SERVE_LORA_BASE_MODELS = "LLM_SERVE_LORA_BASE_MODELS" + LLM_SERVE_INITIAL_NUM_LORA_ADAPTERS = "LLM_SERVE_INITIAL_NUM_LORA_ADAPTERS" + LLM_SERVE_AUTOSCALING_ENABLED_MODELS = "LLM_SERVE_AUTOSCALING_ENABLED_MODELS" + LLM_SERVE_AUTOSCALING_MIN_REPLICAS = "LLM_SERVE_AUTOSCALING_MIN_REPLICAS" + LLM_SERVE_AUTOSCALING_MAX_REPLICAS = "LLM_SERVE_AUTOSCALING_MAX_REPLICAS" + LLM_SERVE_TENSOR_PARALLEL_DEGREE = "LLM_SERVE_TENSOR_PARALLEL_DEGREE" + LLM_SERVE_NUM_REPLICAS = "LLM_SERVE_NUM_REPLICAS" + LLM_SERVE_MODELS = "LLM_SERVE_MODELS" + LLM_SERVE_GPU_TYPE = "LLM_SERVE_GPU_TYPE" + LLM_SERVE_NUM_GPUS = "LLM_SERVE_NUM_GPUS" + + +class TelemetryModel(BaseModelExtended): + """Telemetry model for LLM Serve.""" + + model_architecture: str + num_replicas: int + use_json_mode: bool + use_lora: bool + initial_num_lora_adapters: int + use_autoscaling: bool + min_replicas: int + max_replicas: int + tensor_parallel_degree: int + gpu_type: str + num_gpus: int + + +@ray.remote( + name=LLM_SERVE_TELEMETRY_ACTOR_NAME, + namespace=LLM_SERVE_TELEMETRY_NAMESPACE, + num_cpus=0, + lifetime="detached", +) +class TelemetryAgent: + """Named Actor to keep the state of all deployed models and record telemetry.""" + + def __init__(self): + self.models: List[TelemetryModel] = [] + self.record_tag_func = record_extra_usage_tag + + def _update_record_tag_func(self, record_tag_func: Callable) -> None: + """This method is only used in tests to record the telemetry tags to a different + object than Ray's default `record_extra_usage_tag` function.""" + self.record_tag_func = record_tag_func + + def _reset_models(self): + """This method is only used in tests to clean up the models list.""" + self.models = [] + + def _multiple_models(self) -> str: + unique_models = {model.model_architecture for model in self.models} + return "1" if len(unique_models) > 1 else "0" + + @staticmethod + def _multiple_apps() -> str: + try: + serve_status = serve.status() + except ray.exceptions.ActorDiedError: + # This only happens in a workspace and when multiple Serve sessions are + # used. Since telemetry agent is long running, it might be connecting to the + # previous Serve session, which is already dead. In this case, we need to + # call `serve.shutdown()` before the telemetry agent can re-connect to the + # existing Serve session. + serve.shutdown() + serve_status = serve.status() + return "1" if len(serve_status.applications) > 1 else "0" + + def _json_mode_models(self) -> str: + return ",".join( + [model.model_architecture for model in self.models if model.use_json_mode] + ) + + def _json_mode_num_deployments(self) -> str: + return ",".join( + [str(model.num_replicas) for model in self.models if model.use_json_mode] + ) + + def _lora_base_nodes(self) -> str: + return ",".join( + [model.model_architecture for model in self.models if model.use_lora] + ) + + def _lora_initial_num_adaptors(self) -> str: + return ",".join( + [ + str(model.initial_num_lora_adapters) + for model in self.models + if model.use_lora + ] + ) + + def _autoscaling_enabled_models(self) -> str: + return ",".join( + [model.model_architecture for model in self.models if model.use_autoscaling] + ) + + def _autoscaling_min_replicas(self) -> str: + return ",".join( + [str(model.min_replicas) for model in self.models if model.use_autoscaling] + ) + + def _autoscaling_max_replicas(self) -> str: + return ",".join( + [str(model.max_replicas) for model in self.models if model.use_autoscaling] + ) + + def _model_architectures(self) -> str: + return ",".join([model.model_architecture for model in self.models]) + + def _tensor_parallel_degree(self) -> str: + return ",".join([str(model.tensor_parallel_degree) for model in self.models]) + + def _num_replicas(self) -> str: + return ",".join([str(model.num_replicas) for model in self.models]) + + def _gpu_type(self) -> str: + return ",".join([model.gpu_type for model in self.models]) + + def _num_gpus(self) -> str: + return ",".join([str(model.num_gpus) for model in self.models]) + + def generate_report(self) -> Dict[str, str]: + return { + TelemetryTags.LLM_SERVE_SERVE_MULTIPLE_MODELS: self._multiple_models(), + TelemetryTags.LLM_SERVE_SERVE_MULTIPLE_APPS: self._multiple_apps(), + TelemetryTags.LLM_SERVE_JSON_MODE_MODELS: self._json_mode_models(), + TelemetryTags.LLM_SERVE_JSON_MODE_NUM_REPLICAS: self._json_mode_num_deployments(), + TelemetryTags.LLM_SERVE_LORA_BASE_MODELS: self._lora_base_nodes(), + TelemetryTags.LLM_SERVE_INITIAL_NUM_LORA_ADAPTERS: self._lora_initial_num_adaptors(), + TelemetryTags.LLM_SERVE_AUTOSCALING_ENABLED_MODELS: self._autoscaling_enabled_models(), + TelemetryTags.LLM_SERVE_AUTOSCALING_MIN_REPLICAS: self._autoscaling_min_replicas(), + TelemetryTags.LLM_SERVE_AUTOSCALING_MAX_REPLICAS: self._autoscaling_max_replicas(), + TelemetryTags.LLM_SERVE_MODELS: self._model_architectures(), + TelemetryTags.LLM_SERVE_TENSOR_PARALLEL_DEGREE: self._tensor_parallel_degree(), + TelemetryTags.LLM_SERVE_NUM_REPLICAS: self._num_replicas(), + TelemetryTags.LLM_SERVE_GPU_TYPE: self._gpu_type(), + TelemetryTags.LLM_SERVE_NUM_GPUS: self._num_gpus(), + } + + def record(self, model: Optional[TelemetryModel] = None) -> None: + """Record telemetry model.""" + from ray._common.usage.usage_lib import TagKey + + if model: + self.models.append(model) + + for key, value in self.generate_report().items(): + try: + self.record_tag_func(TagKey.Value(key), value) + except ValueError: + # If the key doesn't exist in the TagKey enum, skip it. + continue + + +def _get_or_create_telemetry_agent() -> TelemetryAgent: + """Helper to get or create the telemetry agent.""" + try: + telemetry_agent = ray.get_actor( + LLM_SERVE_TELEMETRY_ACTOR_NAME, namespace=LLM_SERVE_TELEMETRY_NAMESPACE + ) + except ValueError: + from ray._common.constants import HEAD_NODE_RESOURCE_NAME + from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy + + telemetry_agent = TelemetryAgent.options( + # Ensure the actor is created on the head node. + resources={HEAD_NODE_RESOURCE_NAME: 0.001}, + # Ensure the actor is not scheduled with the existing placement group. + scheduling_strategy=PlacementGroupSchedulingStrategy(placement_group=None), + ).remote() + + return telemetry_agent + + +def _retry_get_telemetry_agent( + max_retries: int = 5, base_delay: float = 0.1 +) -> TelemetryAgent: + max_retries = 5 + base_delay = 0.1 + + telemetry_agent = None + for attempt in range(max_retries): + try: + telemetry_agent = _get_or_create_telemetry_agent() + return telemetry_agent + except ValueError as e: + # Due to race conditions among multiple replicas, we may get: + # ValueError: Actor with name 'llm_serve_telemetry' already + # exists in the namespace llm_serve_telemetry + logger.info( + "Attempt %s/%s to get telemetry agent failed", attempt + 1, max_retries + ) + if attempt == max_retries - 1: + raise e + + # Exponential backoff with jitter + exponential_delay = base_delay * (2**attempt) + jitter = random.uniform(0, 0.5) + delay = exponential_delay + jitter + # Max total wait time is ~3.5 seconds for 5 attempts. + time.sleep(delay) + + +def _push_telemetry_report(model: Optional[TelemetryModel] = None) -> None: + """Push telemetry report for a model.""" + telemetry_agent = _retry_get_telemetry_agent() + assert telemetry_agent is not None + ray.get(telemetry_agent.record.remote(model)) + + +class HardwareUsage: + """Hardware usage class to report telemetry.""" + + def __init__(self, get_hardware_fn: Callable = get_hardware_usages_to_report): + self._get_hardware_fn = get_hardware_fn + + def infer_gpu_from_hardware(self) -> str: + """Infer the GPU type from the hardware when the accelerator type on llm config is + not specified. + + Iterate through all the hardware recorded on the cluster and return the first + ray-compatible accelerator as the GPU type used for the deployment. If not, return + `UNSPECIFIED` as the default GPU type. + """ + from ray.llm._internal.serve.configs.server_models import GPUType + + all_accelerator_types = [t.value for t in GPUType] + gcs_client = ray.experimental.internal_kv.internal_kv_get_gcs_client() + hardwares = self._get_hardware_fn(gcs_client) + for hardware in hardwares: + if hardware in all_accelerator_types: + return hardware + + return DEFAULT_GPU_TYPE + + +def push_telemetry_report_for_all_models( + all_models: Optional[Sequence["LLMConfig"]] = None, + get_lora_model_func: Callable = get_lora_model_ids, + get_hardware_fn: Callable = get_hardware_usages_to_report, +): + """Push telemetry report for all models.""" + if not all_models: + return + + for model in all_models: + use_lora = ( + model.lora_config is not None + and model.lora_config.dynamic_lora_loading_path is not None + ) + initial_num_lora_adapters = 0 + if use_lora: + lora_model_ids = get_lora_model_func( + dynamic_lora_loading_path=model.lora_config.dynamic_lora_loading_path, + base_model_id=model.model_id, + ) + initial_num_lora_adapters = len(lora_model_ids) + + use_autoscaling = model.deployment_config.get("autoscaling_config") is not None + num_replicas, min_replicas, max_replicas = 1, 1, 1 + if use_autoscaling: + from ray.serve.config import AutoscalingConfig + + autoscaling_config = AutoscalingConfig( + **model.deployment_config["autoscaling_config"] + ) + num_replicas = ( + autoscaling_config.initial_replicas or autoscaling_config.min_replicas + ) + min_replicas = autoscaling_config.min_replicas + max_replicas = autoscaling_config.max_replicas + + engine_config = model.get_engine_config() + hardware_usage = HardwareUsage(get_hardware_fn) + + telemetry_model = TelemetryModel( + model_architecture=model.model_architecture, + num_replicas=num_replicas, + use_json_mode=True, + use_lora=use_lora, + initial_num_lora_adapters=initial_num_lora_adapters, + use_autoscaling=use_autoscaling, + min_replicas=min_replicas, + max_replicas=max_replicas, + tensor_parallel_degree=engine_config.tensor_parallel_degree, + gpu_type=model.accelerator_type or hardware_usage.infer_gpu_from_hardware(), + num_gpus=engine_config.num_devices, + ) + _push_telemetry_report(telemetry_model) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/request_router/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/request_router/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/request_router/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/request_router/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1bb54569dbfb7e734c2bf341c9a7bb42153fb9ef Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/request_router/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/request_router/prefix_aware/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/request_router/prefix_aware/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/request_router/prefix_aware/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/request_router/prefix_aware/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3ff58b9d3f5c77dfefb00c58ae2c87897df956e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/request_router/prefix_aware/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/request_router/prefix_aware/__pycache__/prefix_aware_router.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/request_router/prefix_aware/__pycache__/prefix_aware_router.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74e423c5a5b4773ed0e4b07dc6db91292c9b4723 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/request_router/prefix_aware/__pycache__/prefix_aware_router.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/request_router/prefix_aware/__pycache__/prefix_tree.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/request_router/prefix_aware/__pycache__/prefix_tree.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94c6da4a10003c0fb8bdf74a470567352afba38c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/request_router/prefix_aware/__pycache__/prefix_tree.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/request_router/prefix_aware/prefix_aware_router.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/request_router/prefix_aware/prefix_aware_router.py new file mode 100644 index 0000000000000000000000000000000000000000..6d3027b0bef50b51ec24433b98388c6d6ddd9f35 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/request_router/prefix_aware/prefix_aware_router.py @@ -0,0 +1,397 @@ +# These imports are used for metrics tracking, will remove for PR +import logging +import time +from typing import ( + Any, + List, + Optional, +) + +import ray +from ray.actor import ActorHandle +from ray.llm._internal.serve.request_router.prefix_aware.prefix_tree import ( + PrefixTreeActor, +) +from ray.serve._private.common import ReplicaID +from ray.serve._private.constants import ( + SERVE_LOGGER_NAME, +) +from ray.serve._private.replica_result import ReplicaResult +from ray.serve._private.request_router import ( + PowerOfTwoChoicesRequestRouter, +) +from ray.serve._private.request_router.common import ( + PendingRequest, +) +from ray.serve._private.request_router.replica_wrapper import ( + RunningReplica, +) +from ray.serve._private.request_router.request_router import ( + LocalityMixin, + MultiplexMixin, + RequestRouter, +) + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +class PrefixCacheAffinityRouter(LocalityMixin, MultiplexMixin, RequestRouter): + """Extends the PowerOfTwoChoicesRequestRouter with prefix-matching capabilities. + + This request router optimizes replica selection by considering input text prefixes: + + 1. Mixes between three strategies to balance prefix cache hit rate and load balancing: + - When load is balanced (queue length difference < threshold), it selects replicas + with the highest prefix match rate for the input text + - When load is balanced but match rate is below 10%, it falls back to the smallest tenants + - When load is imbalanced, it uses the default Power of Two selection + + 2. Maintains a prefix tree to track which replicas have processed similar inputs: + - Inserts prompt text into the prefix tree after routing + - Uses this history to inform future routing decisions + + This approach improves performance by routing related requests to the same replicas, + increasing cache locality and reducing overhead for language model inference. + """ + + def initialize_state( + self, + imbalanced_threshold: Optional[int] = 10, + match_rate_threshold: Optional[float] = 0.1, + do_eviction: Optional[bool] = False, + eviction_threshold_chars: Optional[int] = 400_000, + eviction_target_chars: Optional[int] = 360_000, + eviction_interval_secs: Optional[int] = 10, + tree_actor: Optional[ActorHandle] = None, + ): + """Initialize the prefix-aware routing state and configuration. + + Args: + imbalanced_threshold: Threshold for queue length difference to consider + load balanced. When the difference between replica queue lengths is + less than this value, prefix-aware routing is used. + match_rate_threshold: Minimum prefix match rate (0.0-1.0) required to + use prefix-aware routing. If match rate is below this threshold, + falls back to smallest tenant selection. + do_eviction: Whether to enable automatic eviction of old prefix tree + entries to manage memory usage. + eviction_threshold_chars: Maximum number of characters in the prefix + tree before eviction is triggered. + eviction_target_chars: Target number of characters to reduce the + prefix tree to during eviction. + eviction_interval_secs: Interval in seconds between eviction checks + when eviction is enabled. + tree_actor: The actor to use for the prefix tree in a test environment. + If None, a detached actor will be created/retrieved. + """ + # === Prefix-aware routing logic hyperparameters === + self._imbalanced_threshold = imbalanced_threshold + self._match_rate_threshold = match_rate_threshold + + # === Eviction policy === + self._do_eviction = do_eviction + self._eviction_loop_running = False + self._eviction_threshold_chars = eviction_threshold_chars + # Default eviction_target_chars to eviction_threshold_chars if not specified + self._eviction_target_chars = ( + eviction_target_chars + if eviction_target_chars is not None + else eviction_threshold_chars + ) + self._eviction_interval_secs = eviction_interval_secs + + if tree_actor is None: + # Use a detached actor to avoid issues with actor lifetime since this is shared between routers + self._tree_actor = PrefixTreeActor.options( + name="LlmPrefixTreeActor", get_if_exists=True, lifetime="detached" + ).remote() + else: + self._tree_actor = tree_actor + + def _extract_text_from_request(self, pending_request: PendingRequest) -> str: + """Extracts the text content from a pending request for prefix matching. + + Searches through request arguments for either 'messages' or 'prompt' attributes, + then normalizes the content to a single string representation that can be used + for prefix tree operations. + + Args: + pending_request: The request to extract text from + + Returns: + A string containing the prompt text or concatenated message contents + + Raises: + ValueError: If no prompt or messages attribute is found in the request + """ + prompt = None + for arg in pending_request.args: + valid_input_types = ["messages", "prompt"] + for valid_input_type in valid_input_types: + if hasattr(arg, valid_input_type): + prompt = ( + arg.prompt if valid_input_type == "prompt" else arg.messages + ) + break + if prompt is not None: + break + if prompt is None: + raise ValueError( + "No request with message or prompt attribute found in pending_request.args" + ) + + return self._normalize_prompt_to_string(prompt) + + def _coerce_to_text(self, value: Any) -> str: + if value is None: + return "" + if isinstance(value, str): + return value + if isinstance(value, list): + return "".join(self._coerce_to_text(item) for item in value) + if isinstance(value, dict): + text_value = value.get("text") + if isinstance(text_value, str): + return text_value + if "content" in value: + return self._coerce_to_text(value["content"]) + + return "" + + def _normalize_prompt_to_string(self, prompt: Any) -> str: + """Normalize prompt/messages a single string of characters. + This is not exhaustive (e.g. thinking parts, multimodal are not supported). + TODO(seiji): find a more maintainable way to normalize the prompt/messages. + + Supported: + - string → return as-is + - list of strings → concat + - list of message dicts with 'content' as string → concat + - list of message dicts with 'content' as list of dicts → concat the 'text' fields from those parts + """ + if isinstance(prompt, str): + return prompt + + if isinstance(prompt, list): + return "".join( + self._coerce_to_text( + message.get("content") if isinstance(message, dict) else message + ) + for message in prompt + ) + + return "" + + async def _prefix_match_best_replicas( + self, + pending_request: Optional[PendingRequest], + candidate_replicas: List[RunningReplica], + ) -> List[RunningReplica]: + """ + Returns a set of candidate replicas, of which the one with the smallest replica queue will be chosen. + 0. Default: same as pow 2 request router, return 2 replicas at random. + 1. If load is balanced, choose replica(s) with highest prefix match rate. If highest hit rate is below 10% or no match found, use replicas with smallest KV cache usage. + 2. If load is imbalanced, use default. + """ + chosen_replica_id_strings = [] + if ( + pending_request is not None + and pending_request.args is not None + and len(pending_request.args) > 0 + ): + input_text = self._extract_text_from_request(pending_request) + if input_text is not None: + # Start Sphinx tag: __begin_load_balance_component__ + # Check for imbalanced load. + highest_queue_len = 0 + lowest_queue_len = float("inf") + not_in_cache: List[ReplicaID] = [] + if self._use_replica_queue_len_cache: + # Populate available queue lens from the cache. + for r in candidate_replicas: + queue_len = self._replica_queue_len_cache.get(r.replica_id) + if queue_len is None or queue_len >= r.max_ongoing_requests: + not_in_cache.append(r) + else: + highest_queue_len = max(highest_queue_len, queue_len) + lowest_queue_len = min(lowest_queue_len, queue_len) + else: + not_in_cache = candidate_replicas + if len(not_in_cache) > 0: + for r, queue_len in await self._probe_queue_lens( + not_in_cache, + 0, + ): + if queue_len is None: + continue + highest_queue_len = max(highest_queue_len, queue_len) + lowest_queue_len = min(lowest_queue_len, queue_len) + + is_imbalanced = ( + highest_queue_len - lowest_queue_len > self._imbalanced_threshold + ) + # End Sphinx tag: __end_load_balance_component__ + # Start Sphinx tag: __begin_prefix_match_component__ + if not is_imbalanced: + # Convert candidate replica IDs to strings for prefix matching. + candidate_replica_ids_strings = [ + r.replica_id.to_full_id_str() for r in candidate_replicas + ] + (matched_text, matched_tenant_id_strings,) = ray.get( + self._tree_actor.prefix_match.remote( + input_text, candidate_replica_ids_strings + ) + ) + match_rate = len(matched_text) / len(input_text) + if match_rate < self._match_rate_threshold: + smallest_tenants_id_strings = ray.get( + self._tree_actor.get_smallest_tenants.remote() + ) + if ( + smallest_tenants_id_strings is not None + and len(smallest_tenants_id_strings) > 0 + ): + chosen_replica_id_strings = smallest_tenants_id_strings + else: + if ( + matched_tenant_id_strings is not None + and len(matched_tenant_id_strings) > 0 + ): + chosen_replica_id_strings = matched_tenant_id_strings + # End Sphinx tag: __end_prefix_match_component__ + return [ + [ + self._replicas[ReplicaID.from_full_id_str(chosen_id_string)] + for chosen_id_string in chosen_replica_id_strings + ] + ] + + # Start Sphinx tag: __begin_on_replica_actor_died__ + def on_replica_actor_died(self, replica_id: ReplicaID): + """Drop replica from replica set so it's not considered for future requests.""" + super().on_replica_actor_died(replica_id) + ray.get(self._tree_actor.remove_tenants.remote([replica_id.to_full_id_str()])) + + # End Sphinx tag: __end_on_replica_actor_died__ + + def update_replicas(self, replicas: List[RunningReplica]): + """Update the set of available replicas to be considered for routing. + + When the set of replicas changes, we may spawn additional routing tasks + if there are pending requests. + """ + # 1) Record the old replica IDs + old_ids = set(self._replica_id_set) + + # 2) Run the default update_replicas logic + super().update_replicas(replicas) + + # 3) Figure out which replicas were added / removed + new_ids = set(self._replica_id_set) + added = new_ids - old_ids + removed = old_ids - new_ids + + # 4) Update the prefix tree with the changes + if added: + added_strings = [rid.to_full_id_str() for rid in added] + ray.get(self._tree_actor.add_tenants.remote(added_strings, time.time())) + + if removed: + removed_strings = [rid.to_full_id_str() for rid in removed] + ray.get(self._tree_actor.remove_tenants.remote(removed_strings)) + + # === Start tasks (if enabled and not already running) === + if self._do_eviction and not self._eviction_loop_running: + ray.get( + self._tree_actor.start_eviction_loop.remote( + self._eviction_threshold_chars, + self._eviction_target_chars, + self._eviction_interval_secs, + ) + ) + self._eviction_loop_running = True + + async def choose_replicas( + self, + candidate_replicas: List[RunningReplica], + pending_request: Optional[PendingRequest] = None, + ) -> List[RunningReplica]: + """One iteration of the power of two choices procedure that chooses + (at most) two random available replicas. + + For multiplexing, this will first attempt to choose replicas that have the + requested model ID for a configured timeout. If no replicas with the matching + model ID are available after that timeout, it will fall back to the regular + procedure. + """ + # Start Sphinx tag: __begin_pow2_router_base__ + # Get fallback replicas from PowerOfTwoChoicesRequestRouter + fallback_replicas = await PowerOfTwoChoicesRequestRouter.choose_replicas( + self, + candidate_replicas=candidate_replicas, + pending_request=pending_request, + ) + if pending_request is None or not fallback_replicas: + return fallback_replicas + # End Sphinx tag: __end_pow2_router_base__ + + if ( + pending_request is not None + and pending_request.metadata.multiplexed_model_id + ): + # Get candidates for multiplexed model ID. + candidate_replica_ids = self.apply_multiplex_routing( + pending_request=pending_request, + ) + else: + # Get candidates for locality preference. + candidate_replica_ids = self.apply_locality_routing( + pending_request=pending_request, + ) + if not candidate_replica_ids: + return fallback_replicas + + # Convert candidate replica IDs to RunningReplica objects. + replica_id_to_replica_map = { + replica.replica_id: replica for replica in candidate_replicas + } + candidate_replicas = [ + replica_id_to_replica_map[candidate_replica_id] + for candidate_replica_id in candidate_replica_ids + ] + chosen_replicas = await self._prefix_match_best_replicas( + pending_request, candidate_replicas + ) + if chosen_replicas[0]: + return chosen_replicas + + return fallback_replicas + + # Start Sphinx tag: __begin_on_request_routed__ + def on_request_routed( + self, + pending_request: PendingRequest, + replica_id: ReplicaID, + result: ReplicaResult, + ): + """Called when a request is routed to a replica. + + This is used as a callback to update the state of the request router + after a response is generated. + """ + # Right now this only inserts the prompt into the prefix tree, not the response (streaming response makes things complicated) + if ( + pending_request is not None + and pending_request.args is not None + and len(pending_request.args) > 0 + ): + input_text = self._extract_text_from_request(pending_request) + if input_text is not None: + # Insert into prefix tree + ray.get( + self._tree_actor.insert.remote( + input_text, replica_id.to_full_id_str(), time.time() + ) + ) + + # End Sphinx tag: __end_on_request_routed__ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/request_router/prefix_aware/prefix_tree.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/request_router/prefix_aware/prefix_tree.py new file mode 100644 index 0000000000000000000000000000000000000000..b3765e6e6813632feb9cb81e2711012ad491d58a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/request_router/prefix_aware/prefix_tree.py @@ -0,0 +1,620 @@ +from __future__ import annotations + +import logging +import os +import threading +from threading import RLock +from typing import Any, Dict, List, Optional, Tuple + +import ray +from ray.serve._private.constants import ( + SERVE_LOGGER_NAME, +) + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +class Node: + """ + Node in a prefix tree that represents a segment of text and can belong to multiple tenants. + Each node also tracks the last access time for each tenant. + Simple example of root node connected to two children Nodes: + root = Node(text="", parent=None, edge_label_to_child={"f": fooNode, "b": barNode}, tenant_to_last_access_time={"tenant_1": 2}) + fooNode = Node(text="foo", parent=root, edge_label_to_child={}, tenant_to_last_access_time={"tenant_1": 1}) + barNode = Node(text="bar", parent=root, edge_label_to_child={}, tenant_to_last_access_time={"tenant_1": 2}) + + In the above example, "foo" was inserted at time 1, and "bar" was inserted at time 2. + It follows that root was last accessed at time 2. + """ + + def __init__(self, text: str = "", parent: Optional[Node] = None) -> None: + """ + Initialize a node in the prefix tree. + + Args: + text: The text segment this node represents + parent: The parent node of this node + """ + self.text: str = text + self.parent: Optional[Node] = parent + + # Maps first character to child node + self.edge_label_to_child: Dict[str, Node] = {} + # For each tenant that has inserted text matching this node, track its last access timestamp (in seconds) + self.tenant_to_last_access_time: Dict[str, float] = {} + # Doubly linked list pointers for LRU tracking per tenant + # Points to the less recently used node (toward tail) + self.tenant_to_older_node: Dict[str, Optional[Node]] = {} + # Points to the more recently used node (toward head) + self.tenant_to_newer_node: Dict[str, Optional[Node]] = {} + + +class PrefixTree: + """ + Thread-safe multi-tenant prefix tree (approximate radix tree). + + Features: + 1. Stores data for multiple tenants in the same tree structure + 2. Thread-safe with node-level locking for concurrent access + 3. LRU eviction based on tenant access time + 4. Efficient prefix matching across multiple tenants + + + Example tree structure: + Representing the strings inserted in order: + - "helloworld" at time 1 by tenant_1 + - "hellothere" at time 2 by tenant_2 + - "hellothomas" at time 3 by tenant_2 + + root: [] {tenant_1: 1, tenant_2: 3} + (h) → [hello] {tenant_1: 1, tenant_2: 3} + (w) → [world] {tenant_1: 1} + (t) → [th] {tenant_2: 3} + (e) → [ere] {tenant_2: 2} + (o) → [omas] {tenant_2: 3} + + Legend for each node: + - [text] = Node.text + - {tenant, timestamp} = Node.tenant_to_last_access_time + - (x) = edge label (first character used as key for parent's children) + + PrefixTree instance variables: + self.tenant_to_char_count = {"tenant_1": 10, "tenant_2": 14} + self.tenant_to_lru_tail = {"tenant_1": Node("world"), "tenant_2": Node("ere")} + """ + + def __init__(self) -> None: + """Initialize an empty prefix tree.""" + self.lock: RLock = RLock() + + # Root is always the head of the LRU list for each tenant. + self.root: Node = Node() + + # Tracks total character count per tenant. Can be used by the replica request router to determine which tenant to evict, and by how much. + # Also uses the keys to track the active tenants in the tree. + self.tenant_to_char_count: Dict[str, int] = {} + + # LRU tracking - root is always the head, tail is the least recently used. + self.tenant_to_lru_tail: Dict[str, Optional[Node]] = {} + self._eviction_thread: Optional[threading.Thread] = None + self._eviction_stop_event: threading.Event = threading.Event() + + @staticmethod + def _shared_prefix_count(a: str, b: str) -> int: + """ + Count the number of shared characters at the beginning of two strings. + + Args: + a: First string + b: Second string + + Returns: + Number of matching characters at the beginning + """ + return len(os.path.commonprefix([a, b])) + + def _get_lru_chain(self, tenant: str) -> List[Node]: + """ + Get the LRU chain for a given tenant by traversing from the root to the oldest node. + Note: This method is intended to be used only in tests. + """ + with self.lock: + if tenant not in self.tenant_to_char_count: + return [] + nodes = [] + current_node = self.root + while current_node: + nodes.append(current_node) + current_node = current_node.tenant_to_older_node.get(tenant) + return nodes + + def _insert_node_into_linked_list( + self, + node: Node, + newer_neighbor: Optional[Node], + older_neighbor: Optional[Node], + tenant: str, + ) -> None: + """ + Insert a node into the LRU list between two neighbors. Updates the neighbors' pointers and the tail pointer, if that changes. + """ + with self.lock: + if tenant not in self.tenant_to_char_count: + logger.debug(f"Tenant '{tenant}' does not exist. No action taken.") + return + + # Skip if node is the root + if node == self.root: + return + + node.tenant_to_newer_node[tenant] = newer_neighbor + node.tenant_to_older_node[tenant] = older_neighbor + + if newer_neighbor: + newer_neighbor.tenant_to_older_node[tenant] = node + + if older_neighbor: + older_neighbor.tenant_to_newer_node[tenant] = node + + if self.tenant_to_lru_tail[tenant] == newer_neighbor: + self.tenant_to_lru_tail[tenant] = node + + def _remove_node_from_linked_list(self, node: Node, tenant: str) -> None: + """ + Remove a node from the LRU list. Updates the neighbors' pointers and the tail pointer, if that changes. + """ + with self.lock: + if tenant not in self.tenant_to_char_count: + logger.debug(f"Tenant '{tenant}' does not exist. No action taken.") + return + + # Skip if node is the root + if node == self.root: + return + + # Connect older and newer neighbors + older_neighbor = node.tenant_to_older_node.get(tenant) + newer_neighbor = node.tenant_to_newer_node.get(tenant) + + if older_neighbor: + older_neighbor.tenant_to_newer_node[tenant] = newer_neighbor + + if newer_neighbor: + newer_neighbor.tenant_to_older_node[tenant] = older_neighbor + + # Update tail pointer if necessary + if self.tenant_to_lru_tail[tenant] == node: + self.tenant_to_lru_tail[tenant] = newer_neighbor + + # Remove node from list + node.tenant_to_newer_node.pop(tenant, None) + node.tenant_to_older_node.pop(tenant, None) + + def _remove_tenant_single_node(self, tenant: str, node: Node) -> int: + """ + Remove a tenant from a single node. + + Args: + tenant: Tenant to remove + node: Node to remove tenant from + + Returns: + Number of characters removed (0 if preconditions not met) + """ + with self.lock: + if tenant not in self.tenant_to_char_count: + logger.debug(f"Tenant '{tenant}' does not exist. No action taken.") + return 0 + if tenant not in node.tenant_to_last_access_time: + logger.debug( + f"Tenant '{tenant}' does not have node '{node.text}'. No action taken." + ) + return 0 + + removed_chars_len: int = len(node.text) + self.tenant_to_char_count[tenant] -= removed_chars_len + node.tenant_to_last_access_time.pop(tenant, None) + + self._remove_node_from_linked_list(node, tenant) + + # Clean up empty nodes + if not node.tenant_to_last_access_time and node.parent: + if ( + node.text and node.text[0] in node.parent.edge_label_to_child + ): # Defensive check + node.parent.edge_label_to_child.pop(node.text[0], None) + + return removed_chars_len + + def add_tenants(self, tenants: List[str], time_s: float) -> None: + """ + Add multiple new tenants to the tree. Also inserts an empty string for each tenant into the tree. + + For each tenant that already exists, a warning is logged and that tenant is skipped. + + Args: + tenants: List of tenants to add + time_s: Current timestamp in seconds + """ + with self.lock: + for tenant in tenants: + if tenant in self.tenant_to_char_count: + logger.debug(f"Tenant '{tenant}' already exists. Skipping.") + continue + + self.tenant_to_char_count[tenant] = 0 + self.tenant_to_lru_tail[tenant] = self.root + + # Initialize the root node as the head of the LRU list for this tenant + self.root.tenant_to_newer_node[tenant] = None + self.root.tenant_to_older_node[tenant] = None + self.insert("", tenant, time_s) + + def insert(self, text: str, tenant: str, time_s: float) -> None: + """ + Insert text into tree for a specific tenant, but only if the tenant already exists. + + If the tenant doesn't exist in the tree, this will log a warning and return without + inserting anything. Use add_tenants() first to add a new tenant. + + Args: + text: Text to insert + tenant: Tenant + time_s: Current timestamp in seconds + + Loop structure: + 1. We update the current node at the start of each iteration of the while loop. + This includes updating tenant_to_char_count and tenant_to_last_access_time, and moving the node to the front of the LRU list. + 2. Each iteration then either: + a. Breaks (if we've processed the entire string). + b. Processes the next segment of text by: + 1. If no child exists for the first character, create a new leaf node that matches the current text. + 2. Then, match the current text with the child's text: + a. If they share a prefix (partial match), split the node and traverse into the new parent. + b. If they fully match, traverse into the child node. + """ + with self.lock: + if tenant not in self.tenant_to_char_count: + logger.debug( + f"Tenant '{tenant}' does not exist. Use add_tenants() first." + ) + return + + curr_node: Node = self.root + i: int = 0 + while i <= len(text): + # Invariant at beginning of each iteration: assume curr_node has not been visited by tenant yet. + # Update tenant info for current node. + if tenant not in curr_node.tenant_to_last_access_time: + self.tenant_to_char_count[tenant] += len(curr_node.text) + + curr_node.tenant_to_last_access_time[tenant] = time_s + if curr_node != self.root: + self._remove_node_from_linked_list(curr_node, tenant) + self._insert_node_into_linked_list( + curr_node, + self.root, + self.root.tenant_to_older_node.get(tenant), + tenant, + ) + if i == len(text): + break + + first_char: str = text[i] + curr_text: str = text[i:] + + if first_char not in curr_node.edge_label_to_child: + # No match, create new node. Don't update new node as "visited" by tenant yet; it will be done at the beginning of the next iteration. + # e.g. curr_node.edge_label_to_child = {}, curr_text = "hello" -> curr_node.edge_label_to_child = {"h": Node("hello")} + new_node: Node = Node(text=curr_text, parent=curr_node) + curr_node.edge_label_to_child[first_char] = new_node + # Add the node to the back of the LRU list; it will be moved to the front in the next iteration. + self._insert_node_into_linked_list( + new_node, self.tenant_to_lru_tail[tenant], None, tenant + ) + + # Match found, check if we need to split + matched_node: Node = curr_node.edge_label_to_child[first_char] + shared_count: int = self._shared_prefix_count( + matched_node.text, curr_text + ) + if shared_count < len(matched_node.text): + # Partial match, split node at matched point + # Example: + ## Before update: + ### curr_node.edge_label_to_child = {"h": Node("helloworld")}, curr_text = "hellothere" -> shared_count = 5 + ### matched_node = Node("helloworld") + + ## After update: + ### curr_node.edge_label_to_child = {"h": Node("hello", edge_label_to_child = {"w": Node("world")})} + ### parent_node = Node("hello"), matched_node = Node("world") + ### Copy matched_node.tenant_to_last_access_time to parent_node.tenant_to_last_access_time + ### Insert parent_node into the back of the LRU list; it will be moved to the front in the next iteration. (for the current tenant) + ### Insert parent_node between matched_node and matched_node's newer neighbor (for all other tenants) + ### (new) curr_text = "there", (new) curr_node = parent_node + ### Continue adding "there" to tree in next iteration + + matched_text: str = matched_node.text[:shared_count] + remaining_text: str = matched_node.text[shared_count:] + + # Create new intermediate node + # Note that we don't update new_parent.tenant_to_last_access_time yet; it will be done at the beginning of the next iteration. + new_parent: Node = Node(text=matched_text, parent=curr_node) + new_parent.tenant_to_last_access_time = ( + matched_node.tenant_to_last_access_time.copy() + ) + # Insert new_parent into the back of the LRU list; it will be moved to the front in the next iteration. (for the current tenant) + self._insert_node_into_linked_list( + new_parent, self.tenant_to_lru_tail[tenant], None, tenant + ) + # Insert new_parent between matched_node and matched_node's newer neighbor (for all other tenants) + for existing_tenant in new_parent.tenant_to_last_access_time: + if existing_tenant != tenant: + self._insert_node_into_linked_list( + new_parent, + matched_node.tenant_to_newer_node.get(existing_tenant), + matched_node, + existing_tenant, + ) + + # Update existing matched node + matched_node.text = remaining_text + matched_node.parent = new_parent + + # Connect nodes + new_parent.edge_label_to_child[remaining_text[0]] = matched_node + curr_node.edge_label_to_child[first_char] = new_parent + + # Continue traversal + curr_node = new_parent + i += shared_count + else: + # Full match, continue down the tree + curr_node = matched_node + i += shared_count + + def prefix_match( + self, text: str, available_tenants: Optional[List[str]] = None + ) -> Tuple[str, Optional[List[str]]]: + """ + Match text against tree and return matched text and matching tenants. + + Args: + text: Text to match + available_tenants: List of tenants to match against (or None for all) + + Returns: + Tuple of (matched_text, matched_tenants): + If the list of available tenants doesn't match any tenants in the tree: returns ("", None) + When no prefix match is found (does not traverse further than the root node): returns ("", list of available tenants) + When a prefix match is found: returns (matched_prefix, list of tenants that own the matched node) + """ + with self.lock: + if available_tenants: + # Filter available_tenants to only include those in the tree + available_tenants = [ + tenant + for tenant in available_tenants + if tenant in self.tenant_to_char_count + ] + if not available_tenants: + return "", None + else: + available_tenants = list(self.tenant_to_char_count.keys()) + + curr_node: Node = self.root + i: int = 0 + text_len: int = len(text) + + while i < text_len: + first_char: str = text[i] + curr_text: str = text[i:] + + if first_char in curr_node.edge_label_to_child: + matched_node: Node = curr_node.edge_label_to_child[first_char] + + # Check if any available tenants match this node + if not any( + tenant in matched_node.tenant_to_last_access_time + for tenant in available_tenants + ): + break + + shared_count: int = self._shared_prefix_count( + matched_node.text, curr_text + ) + i += shared_count + curr_node = matched_node + + if shared_count < len(matched_node.text): + # Partial match, stop here + break + else: + # No match found, stop here + break + + # Find tenants in current node that match available tenants + matched_tenants = [ + tenant + for tenant in available_tenants + if tenant in curr_node.tenant_to_last_access_time + ] or None + + matched_text: str = text[:i] + + return matched_text, matched_tenants + + def remove_tenants(self, tenants: List[str]) -> Dict[str, int]: + """ + Remove multiple tenants and all their nodes from the tree. + Time complexity: O(n) where n is the total number of nodes owned by all tenants. + + Args: + tenants: List of tenants to remove + + Returns: + Dictionary mapping each tenant to the number of characters removed + (0 if tenant doesn't exist) + """ + chars_removed: Dict[str, int] = {} + + with self.lock: + for tenant in tenants: + if tenant not in self.tenant_to_char_count: + logger.debug(f"Tenant '{tenant}' does not exist. Skipping.") + chars_removed[tenant] = 0 + continue + + tenant_chars_removed: int = 0 + + # Start from the tail and remove all nodes + current_tail = self.tenant_to_lru_tail.get(tenant) + while current_tail: + newer_neighbor = current_tail.tenant_to_newer_node.get(tenant) + tenant_chars_removed += self._remove_tenant_single_node( + tenant, current_tail + ) + current_tail = newer_neighbor + + # Clean up tenant references + self.tenant_to_char_count.pop(tenant, None) + self.tenant_to_lru_tail.pop(tenant, None) + + chars_removed[tenant] = tenant_chars_removed + + return chars_removed + + def evict_tenant_by_lru(self, tenant: str, min_remove_size: int) -> int: + """ + Evict least recently used nodes for a tenant until minimum size is freed. + Time complexity: O(m) where m is the number of nodes removed. + + Args: + tenant: The tenant to evict nodes from + min_remove_size: Minimum number of characters to remove + + Returns: + Actual number of characters removed (0 if tenant doesn't exist) + + Note: + - All nodes with the same oldest access time are removed together to maintain tree integrity, even if only removing a subset of them satisfies the min_remove_size. + - For more predictable eviction, use unique timestamps for each insertion. + - The root node is never evicted as it serves as the permanent head of the LRU list. + """ + with self.lock: + if tenant not in self.tenant_to_char_count: + logger.debug( + f"Cannot evict tenant '{tenant}': tenant does not exist. No action taken." + ) + return 0 + + if self.tenant_to_char_count[tenant] < min_remove_size: + logger.debug( + f"Cannot evict {min_remove_size} characters from tenant '{tenant}', which has only " + f"{self.tenant_to_char_count[tenant]} characters. Will remove all available characters." + ) + min_remove_size = self.tenant_to_char_count[tenant] + + total_chars_removed: int = 0 + + # Start removing from the tail (least recently used) + current_tail = self.tenant_to_lru_tail.get(tenant) + + # Continue until we've freed enough space or run out of nodes + while total_chars_removed < min_remove_size and current_tail: + # Stop if we've reached the root - the root is never evicted + if current_tail == self.root: + break + + # Get the current timestamp to remove all nodes with this timestamp + current_timestamp = current_tail.tenant_to_last_access_time[tenant] + + # Collect all nodes with the same timestamp (guaranteed to be contiguous in our LRU list) + while ( + current_tail != self.root # Never include the root + and current_tail.tenant_to_last_access_time[tenant] + == current_timestamp + ): + newer_neighbor = current_tail.tenant_to_newer_node.get(tenant) + total_chars_removed += self._remove_tenant_single_node( + tenant, current_tail + ) + current_tail = newer_neighbor + + return total_chars_removed + + def get_smallest_tenants(self) -> Optional[List[str]]: + """ + Get the tenants with the smallest total character count. + + Returns: + Tenants with smallest character count, or None if no tenants + """ + with self.lock: + if not self.tenant_to_char_count: + return None + + min_count = min(self.tenant_to_char_count.values()) + return [ + tenant + for tenant, count in self.tenant_to_char_count.items() + if count == min_count + ] + + def start_eviction_loop( + self, eviction_threshold: int, eviction_target: int, interval_secs: float + ) -> bool: + """Start a single eviction loop within the actor itself. + + Args: + eviction_threshold: Minimum number of characters a tenant must have to be evicted + eviction_target: The maximum number of characters a tenant should have after eviction + interval_secs: Number of seconds between eviction checks + + Returns: + True if the loop was started, False if it was already running + """ + self._eviction_stop_event.clear() + with self.lock: + if self._eviction_thread is None: + self._eviction_thread = threading.Thread( + target=self._run_eviction_loop, + args=(eviction_threshold, eviction_target, interval_secs), + daemon=True, + ) + self._eviction_thread.start() + return True + else: + logger.debug("Eviction loop already running") + return False + + def _run_eviction_loop(self, eviction_threshold, eviction_target, interval_secs): + while not self._eviction_stop_event.is_set(): + if self._eviction_stop_event.wait(interval_secs): + # Stop event was set, exit loop asap + break + + with self.lock: + for tenant, char_count in self.tenant_to_char_count.items(): + if char_count > eviction_threshold: + excess = char_count - eviction_target + self.evict_tenant_by_lru(tenant, excess) + + def stop_eviction_loop(self): + self._eviction_stop_event.set() + if self._eviction_thread: + self._eviction_thread.join() + self._eviction_thread = None + + +@ray.remote +class PrefixTreeActor(PrefixTree): + def getattr(self, attribute: str) -> Any: + """ + Get an attribute of the PrefixTree. + Note: This method is intended to be used only in tests. + """ + return getattr(self, attribute) + + def setattr(self, attribute: str, value: Any) -> None: + setattr(self, attribute, value) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/utils/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/utils/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1480d0763600f0f50f03e145af675ddba4378103 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/utils/__pycache__/lora_serve_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/utils/__pycache__/lora_serve_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5ab0e16de139d592f7f2c6395fe28abc56108d3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/utils/__pycache__/lora_serve_utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/utils/lora_serve_utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/utils/lora_serve_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8bddd40a9963af71ba411856a41716bd1eff98d3 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/_internal/serve/utils/lora_serve_utils.py @@ -0,0 +1,230 @@ +""" +Serve-specific LoRA utilities that use generic abstractions from lora_utils.py. + +This module provides serve-specific functionality while using the generic +LoRA abstractions from common/lora_utils.py. This ensures clean separation +between generic and serve-specific concerns. +""" + +import asyncio +import json +import os +from typing import Any, Dict, Optional + +from fastapi import HTTPException + +from ray.llm._internal.common.constants import LORA_ADAPTER_CONFIG_NAME +from ray.llm._internal.common.models import global_id_manager, make_async +from ray.llm._internal.common.utils.cloud_utils import ( + LoraMirrorConfig, +) +from ray.llm._internal.common.utils.lora_utils import ( + CLOUD_OBJECT_MISSING, + clean_model_id, + clear_directory, + get_base_model_id, + get_lora_id, + get_object_from_cloud, + retry_with_exponential_backoff, + sync_files_with_lock, +) +from ray.llm._internal.serve.configs.server_models import DiskMultiplexConfig, LLMConfig +from ray.llm._internal.serve.observability.logging import get_logger + +logger = get_logger(__name__) + + +async def get_lora_finetuned_context_length(bucket_uri: str) -> Optional[int]: + """Gets the sequence length used to tune the LoRA adapter. + + Return: Returns the max sequence length for the adapter, if it exists. + + Raises: HTTPException if the LoRA adapter config file isn't available + in the cloud storage repository. + """ + if bucket_uri.endswith("/"): + bucket_uri = bucket_uri.rstrip("/") + object_uri = f"{bucket_uri}/{LORA_ADAPTER_CONFIG_NAME}" + + object_str_or_missing_message = await get_object_from_cloud(object_uri) + + if object_str_or_missing_message is CLOUD_OBJECT_MISSING: + raise HTTPException( + 404, + f"Unable to find LoRA adapter config file " + f'"{LORA_ADAPTER_CONFIG_NAME}" in folder {bucket_uri}. ' + "Check that the file exists and that you have read permissions.", + ) + else: + adapter_config_str = object_str_or_missing_message + adapter_config = json.loads(adapter_config_str) + return adapter_config.get("max_length") + + +async def download_multiplex_config_info( + model_id: str, base_path: str +) -> tuple[str, Optional[int]]: + """Downloads info needed to create a multiplex config. + + Downloads objects using cloud storage provider APIs. + + Returns: 2-tuple containing + 1. A bucket_uri for the bucket containing LoRA weights and config. + 2. The maximum LoRA sequence length. + + Raises: HTTPException if the LoRA adapter config file isn't available + in the cloud storage repository. + """ + bucket_uri = f"{base_path}/{model_id}" + ft_context_length = await get_lora_finetuned_context_length(bucket_uri) + return bucket_uri, ft_context_length + + +async def get_lora_model_metadata( + model_id: str, llm_config: LLMConfig +) -> Dict[str, Any]: + """Get the lora model metadata for a given model id and llm config. + + This is used to get the metadata for the model with the given model id. + """ + # Note (genesu): `model_id` passed is a lora model id where it's in a form of + # base_model_id:suffix:id + base_model_id = get_base_model_id(model_id) + lora_id = get_lora_id(model_id) + base_path = llm_config.lora_config.dynamic_lora_loading_path + + # Examples of the variables: + # model_id: "meta-llama/Meta-Llama-3.1-8B-Instruct:my_suffix:aBc1234" + # base_path: "s3://ray-llama-weights" + # bucket_uri: "s3://ray-llama-weights/my_suffix:aBc1234" + ( + bucket_uri, + ft_context_length, + ) = await download_multiplex_config_info(lora_id, base_path) + + return { + "model_id": model_id, + "base_model_id": base_model_id, + "max_request_context_length": ft_context_length, + # Note (genesu): `bucket_uri` affects where the lora weights are downloaded + # from remote location. + "bucket_uri": bucket_uri, + } + + +async def get_lora_mirror_config( + model_id: str, + llm_config: LLMConfig, +) -> LoraMirrorConfig: + """Get LoRA mirror configuration for serve-specific LLM config.""" + metadata = await get_lora_model_metadata(model_id, llm_config) + + return LoraMirrorConfig( + lora_model_id=model_id, + bucket_uri=metadata["bucket_uri"], + max_total_tokens=metadata["max_request_context_length"], + sync_args=None, + ) + + +class LoraModelLoader: + """Download LoRA weights from remote storage and manage disk cache. + + This class is serve-specific as it depends on DiskMultiplexConfig and + other serve-specific concepts. + """ + + def __init__( + self, + lora_root: Optional[str] = None, + download_timeout_s: Optional[float] = None, + max_tries: int = 1, + ): + self.lora_root = lora_root or "/tmp/ray/llm/lora/cache" + self.disk_cache: Dict[str, DiskMultiplexConfig] = {} + self.active_syncing_tasks: Dict[str, asyncio.Task[DiskMultiplexConfig]] = {} + if download_timeout_s is not None and download_timeout_s <= 0: + raise ValueError( + f"download_timeout_s must be None or >0, got {download_timeout_s}" + ) + self.download_timeout_s = download_timeout_s + if max_tries < 1: + raise ValueError(f"max_tries must be >=1, got {max_tries}") + self.max_tries = max_tries + + async def load_model_from_config( + self, lora_model_id: str, llm_config + ) -> DiskMultiplexConfig: + """Load a LoRA model by first fetching its mirror config from S3.""" + lora_mirror_config = await get_lora_mirror_config(lora_model_id, llm_config) + return await self.load_model(lora_model_id, lora_mirror_config) + + async def load_model( + self, lora_model_id: str, lora_mirror_config: LoraMirrorConfig + ) -> DiskMultiplexConfig: + """Load a LoRA model.""" + if lora_model_id in self.disk_cache: + return self.disk_cache[lora_model_id] + + if lora_model_id not in self.active_syncing_tasks: + task = asyncio.create_task(self._load_model_async(lora_mirror_config)) + task.add_done_callback( + lambda result: self.active_syncing_tasks.pop(lora_model_id, None) + ) + self.active_syncing_tasks[lora_model_id] = task + else: + task = self.active_syncing_tasks[lora_model_id] + + disk_config = await asyncio.shield(task) + self.disk_cache[lora_model_id] = disk_config + return disk_config + + async def _load_model_async( + self, lora_mirror_config: LoraMirrorConfig + ) -> DiskMultiplexConfig: + return await self._load_model(lora_mirror_config) + + @make_async + def _load_model(self, lora_mirror_config: LoraMirrorConfig) -> DiskMultiplexConfig: + return self._load_model_sync(lora_mirror_config) + + @make_async + def clear_cache(self): + """Clear the disk cache.""" + clear_directory(self.lora_root) + + def _model_dir_path(self, model_id: str) -> str: + """Construct the path for the lora weight.""" + lora_id = get_lora_id(clean_model_id(model_id)) + path = os.path.join(self.lora_root, lora_id) + os.makedirs(path, exist_ok=True) + return path + + def _download_lora(self, lora_mirror_config: LoraMirrorConfig) -> str: + """Download LoRA weights using generic download primitives.""" + model_local_path = self._model_dir_path(lora_mirror_config.lora_model_id) + sync_files_with_lock( + lora_mirror_config.bucket_uri, + model_local_path, + timeout=self.download_timeout_s, + ) + return model_local_path + + def _load_model_sync( + self, lora_mirror_config: LoraMirrorConfig + ) -> DiskMultiplexConfig: + """Load a model from the given mirror configuration.""" + download_with_retries = retry_with_exponential_backoff( + max_tries=self.max_tries, + exception_to_check=Exception, + )(lambda config: self._download_lora(config)) + + local_path = download_with_retries(lora_mirror_config) + return DiskMultiplexConfig.model_validate( + { + "model_id": lora_mirror_config.lora_model_id, + "max_total_tokens": lora_mirror_config.max_total_tokens, + "local_path": local_path, + "lora_assigned_int_id": global_id_manager.next(), + } + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/utils/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/utils/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ea4ac77186712515cf575bd9651fb1febd7c496 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/utils/__pycache__/upload_model.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/utils/__pycache__/upload_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de9749c72d6f9e3235e9f43493bca53ac1f28a09 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/utils/__pycache__/upload_model.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/llm/utils/upload_model.py b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/utils/upload_model.py new file mode 100644 index 0000000000000000000000000000000000000000..0398f6f532ec4a2df325723f3592e2de2a522606 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/llm/utils/upload_model.py @@ -0,0 +1,23 @@ +"""Upload the model files to cloud storage (s3 or gcs). + +Example usage: +```bash +python -m ray.llm.utils.upload_model \ + --model-source facebook/opt-350m \ + --bucket-uri gs://my-bucket/path/to/facebook-opt-350m +``` +""" + +import typer + +from ray.llm._internal.common.utils.upload_utils import ( + upload_model_cli as _upload_model_cli, +) + + +def main(): + typer.run(_upload_model_cli) + + +if __name__ == "__main__": + main() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3bb47b1f79e058250932c9addc56efc86c22efb3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fdc21775e119d3c26aab374826be6a0518dcd2aa --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__init__.py @@ -0,0 +1,39 @@ +from ray.rllib.algorithms.algorithm import Algorithm +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig +from ray.rllib.algorithms.appo.appo import APPO, APPOConfig +from ray.rllib.algorithms.bc.bc import BC, BCConfig +from ray.rllib.algorithms.cql.cql import CQL, CQLConfig +from ray.rllib.algorithms.dqn.dqn import DQN, DQNConfig +from ray.rllib.algorithms.impala.impala import ( + IMPALA, + IMPALAConfig, + Impala, + ImpalaConfig, +) +from ray.rllib.algorithms.marwil.marwil import MARWIL, MARWILConfig +from ray.rllib.algorithms.ppo.ppo import PPO, PPOConfig +from ray.rllib.algorithms.sac.sac import SAC, SACConfig + + +__all__ = [ + "Algorithm", + "AlgorithmConfig", + "APPO", + "APPOConfig", + "BC", + "BCConfig", + "CQL", + "CQLConfig", + "DQN", + "DQNConfig", + "IMPALA", + "IMPALAConfig", + "Impala", + "ImpalaConfig", + "MARWIL", + "MARWILConfig", + "PPO", + "PPOConfig", + "SAC", + "SACConfig", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2eb68aa94116ddc05cedeee4d14fb387da9f8df3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/algorithm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/algorithm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5006b7044925e9d71d8ed630e7faa7ae4a00bc33 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/algorithm.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9951472fb86a9824db1fd9862b0450ccf7998b3b2b9ad124aea33a74ec131278 +size 169675 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/algorithm_config.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/algorithm_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f7f0d956f70b8c83672de85b0fc0c58190089c6 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/algorithm_config.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4a582efd2a54489676d25dbd7adb27de63a7fb3e30611bf1c3a069af6fd7e201 +size 260948 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/callbacks.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/callbacks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4906e65cff0d8bee5b84792c837f72606d88a8b6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/callbacks.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/mock.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/mock.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..060fa372320b91e053209d68ebf56f954aa0d6c4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/mock.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/registry.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/registry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c96519b4051cd973296befb36162b3e978551db Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/registry.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85257160eabf715b9e593d025e136f25441f4ae2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/algorithm.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..6d455da75c55c647967cef0fe6eaff1133c3a0d5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/algorithm.py @@ -0,0 +1,4581 @@ +from collections import defaultdict +import concurrent +import copy +from datetime import datetime +import functools +import gymnasium as gym +import importlib +import importlib.metadata +import json +import logging +import numpy as np +import os +from packaging import version +import pathlib +import pyarrow.fs +import re +import tempfile +import time +from typing import ( + Any, + Callable, + Collection, + DefaultDict, + Dict, + List, + Optional, + Set, + Tuple, + Type, + TYPE_CHECKING, + Union, +) + +import tree # pip install dm_tree + +import ray +from ray.tune.result import TRAINING_ITERATION +from ray._common.usage.usage_lib import TagKey, record_extra_usage_tag +from ray.actor import ActorHandle +from ray.tune import Checkpoint +import ray.cloudpickle as pickle +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig +from ray.rllib.algorithms.registry import ALGORITHMS_CLASS_TO_NAME as ALL_ALGORITHMS +from ray.rllib.algorithms.utils import ( + AggregatorActor, + _get_env_runner_bundles, + _get_offline_eval_runner_bundles, + _get_learner_bundles, + _get_main_process_bundle, +) +from ray.rllib.callbacks.utils import make_callback +from ray.rllib.connectors.agent.obs_preproc import ObsPreprocessorConnector +from ray.rllib.connectors.connector_pipeline_v2 import ConnectorPipelineV2 +from ray.rllib.core import ( + COMPONENT_ENV_RUNNER, + COMPONENT_ENV_TO_MODULE_CONNECTOR, + COMPONENT_EVAL_ENV_RUNNER, + COMPONENT_LEARNER, + COMPONENT_LEARNER_GROUP, + COMPONENT_METRICS_LOGGER, + COMPONENT_MODULE_TO_ENV_CONNECTOR, + COMPONENT_RL_MODULE, + DEFAULT_MODULE_ID, +) +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.multi_rl_module import ( + MultiRLModule, + MultiRLModuleSpec, +) +from ray.rllib.core.rl_module import validate_module_id +from ray.rllib.core.rl_module.rl_module import RLModule, RLModuleSpec +from ray.rllib.env import INPUT_ENV_SPACES +from ray.rllib.env.env_context import EnvContext +from ray.rllib.env.env_runner import EnvRunner +from ray.rllib.env.env_runner_group import EnvRunnerGroup +from ray.rllib.env.utils import _gym_env_creator +from ray.rllib.evaluation.metrics import ( + collect_episodes, + summarize_episodes, +) +from ray.rllib.execution.rollout_ops import synchronous_parallel_sample +from ray.rllib.offline import get_dataset_and_shards +from ray.rllib.offline.estimators import ( + OffPolicyEstimator, + ImportanceSampling, + WeightedImportanceSampling, + DirectMethod, + DoublyRobust, +) +from ray.rllib.offline.offline_evaluator import OfflineEvaluator +from ray.rllib.policy.policy import Policy, PolicySpec +from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID, SampleBatch +from ray.rllib.utils import deep_update, FilterManager, force_list +from ray.rllib.utils.actor_manager import FaultTolerantActorManager, RemoteCallResults +from ray.rllib.utils.annotations import ( + DeveloperAPI, + ExperimentalAPI, + OldAPIStack, + override, + OverrideToImplementCustomLogic, + OverrideToImplementCustomLogic_CallToSuperRecommended, + PublicAPI, +) +from ray.rllib.utils.checkpoints import ( + Checkpointable, + CHECKPOINT_VERSION, + CHECKPOINT_VERSION_LEARNER_AND_ENV_RUNNER, + get_checkpoint_info, + try_import_msgpack, +) +from ray.rllib.utils.debug import update_global_seed_if_necessary +from ray.rllib.utils.deprecation import ( + DEPRECATED_VALUE, + Deprecated, + deprecation_warning, +) +from ray.rllib.utils.error import ERR_MSG_INVALID_ENV_DESCRIPTOR, EnvError +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.from_config import from_config +from ray.rllib.utils.metrics import ( + AGGREGATOR_ACTOR_RESULTS, + ALL_MODULES, + DATASET_NUM_ITERS_EVALUATED, + ENV_RUNNER_RESULTS, + ENV_RUNNER_SAMPLING_TIMER, + EPISODE_LEN_MEAN, + EPISODE_RETURN_MEAN, + EVALUATION_ITERATION_TIMER, + EVALUATION_RESULTS, + FAULT_TOLERANCE_STATS, + LEARNER_RESULTS, + LEARNER_UPDATE_TIMER, + NUM_AGENT_STEPS_SAMPLED, + NUM_AGENT_STEPS_SAMPLED_LIFETIME, + NUM_AGENT_STEPS_SAMPLED_THIS_ITER, + NUM_AGENT_STEPS_TRAINED, + NUM_AGENT_STEPS_TRAINED_LIFETIME, + NUM_ENV_STEPS_SAMPLED, + NUM_ENV_STEPS_SAMPLED_LIFETIME, + NUM_ENV_STEPS_SAMPLED_THIS_ITER, + NUM_ENV_STEPS_SAMPLED_FOR_EVALUATION_THIS_ITER, + NUM_ENV_STEPS_TRAINED, + NUM_ENV_STEPS_TRAINED_LIFETIME, + NUM_EPISODES, + NUM_EPISODES_LIFETIME, + NUM_TRAINING_STEP_CALLS_PER_ITERATION, + OFFLINE_EVAL_RUNNER_RESULTS, + OFFLINE_EVALUATION_ITERATION_TIMER, + RESTORE_ENV_RUNNERS_TIMER, + RESTORE_EVAL_ENV_RUNNERS_TIMER, + RESTORE_OFFLINE_EVAL_RUNNERS_TIMER, + SYNCH_ENV_CONNECTOR_STATES_TIMER, + SYNCH_EVAL_ENV_CONNECTOR_STATES_TIMER, + SYNCH_WORKER_WEIGHTS_TIMER, + TIMERS, + TRAINING_ITERATION_TIMER, + TRAINING_STEP_TIMER, + STEPS_TRAINED_THIS_ITER_COUNTER, +) +from ray.rllib.utils.metrics.learner_info import LEARNER_INFO +from ray.rllib.utils.metrics.metrics_logger import MetricsLogger +from ray.rllib.utils.replay_buffers import MultiAgentReplayBuffer, ReplayBuffer +from ray.rllib.utils.runners.runner_group import RunnerGroup +from ray.rllib.utils.serialization import deserialize_type, NOT_SERIALIZABLE +from ray.rllib.utils.spaces import space_utils +from ray.rllib.utils.typing import ( + AgentConnectorDataType, + AgentID, + AgentToModuleMappingFn, + AlgorithmConfigDict, + EnvCreator, + EnvInfoDict, + EnvType, + EpisodeID, + ModuleID, + PartialAlgorithmConfigDict, + PolicyID, + PolicyState, + ResultDict, + SampleBatchType, + ShouldModuleBeUpdatedFn, + StateDict, + TensorStructType, + TensorType, +) +from ray.train.constants import DEFAULT_STORAGE_PATH +from ray.tune.execution.placement_groups import PlacementGroupFactory +from ray.tune.experiment.trial import ExportFormat +from ray.tune.logger import Logger, UnifiedLogger +from ray.tune.registry import ENV_CREATOR, _global_registry +from ray.tune.resources import Resources +from ray.tune.trainable import Trainable +from ray.util import log_once +from ray.util.timer import _Timer +from ray.tune.registry import get_trainable_cls + +if TYPE_CHECKING: + from ray.rllib.core.learner.learner_group import LearnerGroup + from ray.rllib.offline.offline_data import OfflineData + +tf1, tf, tfv = try_import_tf() + +logger = logging.getLogger(__name__) + + +@PublicAPI +class Algorithm(Checkpointable, Trainable): + """An RLlib algorithm responsible for training one or more neural network models. + + You can write your own Algorithm classes by sub-classing from `Algorithm` + or any of its built-in subclasses. + Override the `training_step` method to implement your own algorithm logic. + Find the various built-in `training_step()` methods for different algorithms in + their respective [algo name].py files, for example: + `ray.rllib.algorithms.dqn.dqn.py` or `ray.rllib.algorithms.impala.impala.py`. + + The most important API methods an Algorithm exposes are `train()` for running a + single training iteration, `evaluate()` for running a single round of evaluation, + `save_to_path()` for creating a checkpoint, and `restore_from_path()` for loading a + state from an existing checkpoint. + """ + + #: The AlgorithmConfig instance of the Algorithm. + config: Optional[AlgorithmConfig] = None + #: The MetricsLogger instance of the Algorithm. RLlib uses this to log + #: metrics from within the `training_step()` method. Users can use it to log + #: metrics from within their custom Algorithm-based callbacks. + metrics: Optional[MetricsLogger] = None + #: The `EnvRunnerGroup` of the Algorithm. An `EnvRunnerGroup` is + #: composed of a single local `EnvRunner` (see: `self.env_runner`), serving as + #: the reference copy of the models to be trained and optionally one or more + #: remote `EnvRunners` used to generate training samples from the RL + #: environment, in parallel. EnvRunnerGroup is fault-tolerant and elastic. It + #: tracks health states for all the managed remote EnvRunner actors. As a + #: result, Algorithm should never access the underlying actor handles directly. + #: Instead, always access them via all the foreach APIs with assigned IDs of + #: the underlying EnvRunners. + env_runner_group: Optional[EnvRunnerGroup] = None + #: A special EnvRunnerGroup only used for evaluation, not to + #: collect training samples. + eval_env_runner_group: Optional[EnvRunnerGroup] = None + #: The `LearnerGroup` instance of the Algorithm, managing either + #: one local `Learner` or one or more remote `Learner` actors. Responsible for + #: updating the models from RL environment (episode) data. + learner_group: Optional["LearnerGroup"] = None + #: An optional OfflineData instance, used for offline RL. + offline_data: Optional["OfflineData"] = None + + # Whether to allow unknown top-level config keys. + _allow_unknown_configs = False + + # List of top-level keys with value=dict, for which new sub-keys are + # allowed to be added to the value dict. + _allow_unknown_subkeys = [ + "tf_session_args", + "local_tf_session_args", + "env_config", + "model", + "optimizer", + "custom_resources_per_env_runner", + "custom_resources_per_worker", + "evaluation_config", + "exploration_config", + "replay_buffer_config", + "extra_python_environs_for_worker", + "input_config", + "output_config", + ] + + # List of top level keys with value=dict, for which we always override the + # entire value (dict), iff the "type" key in that value dict changes. + _override_all_subkeys_if_type_changes = [ + "exploration_config", + "replay_buffer_config", + ] + + # List of keys that are always fully overridden if present in any dict or sub-dict + _override_all_key_list = ["off_policy_estimation_methods", "policies"] + + _progress_metrics = ( + f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}", + f"{EVALUATION_RESULTS}/{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}", + f"{NUM_ENV_STEPS_SAMPLED_LIFETIME}", + f"{NUM_ENV_STEPS_TRAINED_LIFETIME}", + f"{NUM_EPISODES_LIFETIME}", + f"{ENV_RUNNER_RESULTS}/{EPISODE_LEN_MEAN}", + ) + + # Backward compatibility with old checkpoint system (now through the + # `Checkpointable` API). + METADATA_FILE_NAME = "rllib_checkpoint.json" + STATE_FILE_NAME = "algorithm_state" + + @classmethod + @override(Checkpointable) + def from_checkpoint( + cls, + path: Union[str, Checkpoint], + filesystem: Optional["pyarrow.fs.FileSystem"] = None, + *, + # @OldAPIStack + policy_ids: Optional[Collection[PolicyID]] = None, + policy_mapping_fn: Optional[Callable[[AgentID, EpisodeID], PolicyID]] = None, + policies_to_train: Optional[ + Union[ + Collection[PolicyID], + Callable[[PolicyID, Optional[SampleBatchType]], bool], + ] + ] = None, + # deprecated args + checkpoint=DEPRECATED_VALUE, + **kwargs, + ) -> "Algorithm": + """Creates a new algorithm instance from a given checkpoint. + + Args: + path: The path (str) to the checkpoint directory to use or a Ray Train + Checkpoint instance to restore from. + filesystem: PyArrow FileSystem to use to access data at the `path`. If not + specified, this is inferred from the URI scheme of `path`. + policy_ids: Optional list of PolicyIDs to recover. This allows users to + restore an Algorithm with only a subset of the originally present + Policies. + policy_mapping_fn: An optional (updated) policy mapping function to use from + here on. + policies_to_train: An optional list of policy IDs to be trained or a + callable taking PolicyID and SampleBatchType and returning a bool + (trainable or not?). If None, will keep the existing setup in place. + Policies, whose IDs are not in the list (or for which the callable + returns False) will not be updated. + + Returns: + The instantiated Algorithm. + """ + if checkpoint != DEPRECATED_VALUE: + deprecation_warning( + old="Algorithm.from_checkpoint(checkpoint=...)", + new="Algorithm.from_checkpoint(path=...)", + error=True, + ) + checkpoint_info = get_checkpoint_info(path) + + # New API stack -> Use Checkpointable's default implementation. + if checkpoint_info["checkpoint_version"] >= version.Version("2.0"): + # `path` is a Checkpoint instance: Translate to directory and continue. + if isinstance(path, Checkpoint): + path = path.to_directory() + return super().from_checkpoint(path, filesystem=filesystem, **kwargs) + + # Not possible for (v0.1) (algo class and config information missing + # or very hard to retrieve). + elif checkpoint_info["checkpoint_version"] == version.Version("0.1"): + raise ValueError( + "Cannot restore a v0 checkpoint using `Algorithm.from_checkpoint()`!" + "In this case, do the following:\n" + "1) Create a new Algorithm object using your original config.\n" + "2) Call the `restore()` method of this algo object passing it" + " your checkpoint dir or AIR Checkpoint object." + ) + elif checkpoint_info["checkpoint_version"] < version.Version("1.0"): + raise ValueError( + "`checkpoint_info['checkpoint_version']` in `Algorithm.from_checkpoint" + "()` must be 1.0 or later! You are using a checkpoint with " + f"version v{checkpoint_info['checkpoint_version']}." + ) + + # This is a msgpack checkpoint. + if checkpoint_info["format"] == "msgpack": + # User did not provide unserializable function with this call + # (`policy_mapping_fn`). Note that if `policies_to_train` is None, it + # defaults to training all policies (so it's ok to not provide this here). + if policy_mapping_fn is None: + # Only DEFAULT_POLICY_ID present in this algorithm, provide default + # implementations of these two functions. + if checkpoint_info["policy_ids"] == {DEFAULT_POLICY_ID}: + policy_mapping_fn = AlgorithmConfig.DEFAULT_POLICY_MAPPING_FN + # Provide meaningful error message. + else: + raise ValueError( + "You are trying to restore a multi-agent algorithm from a " + "`msgpack` formatted checkpoint, which do NOT store the " + "`policy_mapping_fn` or `policies_to_train` " + "functions! Make sure that when using the " + "`Algorithm.from_checkpoint()` utility, you also pass the " + "args: `policy_mapping_fn` and `policies_to_train` with your " + "call. You might leave `policies_to_train=None` in case " + "you would like to train all policies anyways." + ) + + state = Algorithm._checkpoint_info_to_algorithm_state( + checkpoint_info=checkpoint_info, + policy_ids=policy_ids, + policy_mapping_fn=policy_mapping_fn, + policies_to_train=policies_to_train, + ) + + return Algorithm.from_state(state) + + @PublicAPI + def __init__( + self, + config: Optional[AlgorithmConfig] = None, + env=None, # deprecated arg + logger_creator: Optional[Callable[[], Logger]] = None, + **kwargs, + ): + """Initializes an Algorithm instance. + + Args: + config: Algorithm-specific configuration object. + logger_creator: Callable that creates a ray.tune.Logger + object. If unspecified, a default logger is created. + **kwargs: Arguments passed to the Trainable base class. + """ + # Translate possible dict into an AlgorithmConfig object, as well as, + # resolving generic config objects into specific ones (e.g. passing + # an `AlgorithmConfig` super-class instance into a PPO constructor, + # which normally would expect a PPOConfig object). + if isinstance(config, dict): + default_config = self.get_default_config() + # `self.get_default_config()` also returned a dict -> + # Last resort: Create core AlgorithmConfig from merged dicts. + if isinstance(default_config, dict): + if "class" in config: + AlgorithmConfig.from_state(config) + else: + config = AlgorithmConfig.from_dict( + config_dict=self.merge_algorithm_configs( + default_config, config, True + ) + ) + + # Default config is an AlgorithmConfig -> update its properties + # from the given config dict. + else: + if isinstance(config, dict) and "class" in config: + config = default_config.from_state(config) + else: + config = default_config.update_from_dict(config) + else: + default_config = self.get_default_config() + # Given AlgorithmConfig is not of the same type as the default config: + # This could be the case e.g. if the user is building an algo from a + # generic AlgorithmConfig() object. + if not isinstance(config, type(default_config)): + config = default_config.update_from_dict(config.to_dict()) + else: + config = default_config.from_state(config.get_state()) + + # In case this algo is using a generic config (with no algo_class set), set it + # here. + if config.algo_class is None: + config.algo_class = type(self) + + if env is not None: + deprecation_warning( + old=f"algo = Algorithm(env='{env}', ...)", + new=f"algo = AlgorithmConfig().environment('{env}').build()", + error=False, + ) + config.environment(env) + + # Validate and freeze our AlgorithmConfig object (no more changes possible). + config.validate() + config.freeze() + + # Convert `env` provided in config into a concrete env creator callable, which + # takes an EnvContext (config dict) as arg and returning an RLlib supported Env + # type (e.g. a gym.Env). + self._env_id, self.env_creator = self._get_env_id_and_creator( + config.env, config + ) + env_descr = ( + self._env_id.__name__ if isinstance(self._env_id, type) else self._env_id + ) + + # Placeholder for a local replay buffer instance. + self.local_replay_buffer = None + + # Placeholder for our LearnerGroup responsible for updating the RLModule(s). + self.learner_group: Optional["LearnerGroup"] = None + + # The Algorithm's `MetricsLogger` object to collect stats from all its + # components (including timers, counters and other stats in its own + # `training_step()` and other methods) as well as custom callbacks. + self.metrics = MetricsLogger(root=True) + + # Create a default logger creator if no logger_creator is specified + if logger_creator is None: + # Default logdir prefix containing the agent's name and the + # env id. + timestr = datetime.today().strftime("%Y-%m-%d_%H-%M-%S") + env_descr_for_dir = re.sub("[/\\\\]", "-", str(env_descr)) + logdir_prefix = f"{type(self).__name__}_{env_descr_for_dir}_{timestr}" + + if not os.path.exists(DEFAULT_STORAGE_PATH): + # Possible race condition if dir is created several times on + # rollout workers + os.makedirs(DEFAULT_STORAGE_PATH, exist_ok=True) + logdir = tempfile.mkdtemp(prefix=logdir_prefix, dir=DEFAULT_STORAGE_PATH) + + # Allow users to more precisely configure the created logger + # via "logger_config.type". + if config.logger_config and "type" in config.logger_config: + + def default_logger_creator(config): + """Creates a custom logger with the default prefix.""" + cfg = config["logger_config"].copy() + cls = cfg.pop("type") + # Provide default for logdir, in case the user does + # not specify this in the "logger_config" dict. + logdir_ = cfg.pop("logdir", logdir) + return from_config(cls=cls, _args=[cfg], logdir=logdir_) + + # If no `type` given, use tune's UnifiedLogger as last resort. + else: + + def default_logger_creator(config): + """Creates a Unified logger with the default prefix.""" + return UnifiedLogger(config, logdir, loggers=None) + + logger_creator = default_logger_creator + + # Metrics-related properties. + self._timers = defaultdict(_Timer) + self._counters = defaultdict(int) + self._episode_history = [] + self._episodes_to_be_collected = [] + + # The fully qualified AlgorithmConfig used for evaluation + # (or None if evaluation not setup). + self.evaluation_config: Optional[AlgorithmConfig] = None + # Evaluation EnvRunnerGroup and metrics last returned by `self.evaluate()`. + self.eval_env_runner_group: Optional[EnvRunnerGroup] = None + + super().__init__( + config=config, + logger_creator=logger_creator, + **kwargs, + ) + + @OverrideToImplementCustomLogic + @classmethod + def get_default_config(cls) -> AlgorithmConfig: + return AlgorithmConfig() + + @OverrideToImplementCustomLogic + def _remote_worker_ids_for_metrics(self) -> List[int]: + """Returns a list of remote worker IDs to fetch metrics from. + + Specific Algorithm implementations can override this method to + use a subset of the workers for metrics collection. + + Returns: + List of remote worker IDs to fetch metrics from. + """ + return self.env_runner_group.healthy_worker_ids() + + @OverrideToImplementCustomLogic_CallToSuperRecommended + @override(Trainable) + def setup(self, config: AlgorithmConfig) -> None: + # Setup our config: Merge the user-supplied config dict (which could + # be a partial config dict) with the class' default. + if not isinstance(config, AlgorithmConfig): + assert isinstance(config, PartialAlgorithmConfigDict) + config_obj = self.get_default_config() + if not isinstance(config_obj, AlgorithmConfig): + assert isinstance(config, PartialAlgorithmConfigDict) + config_obj = AlgorithmConfig().from_dict(config_obj) + config_obj.update_from_dict(config) + config_obj.env = self._env_id + self.config = config_obj + + # Set Algorithm's seed after we have - if necessary - enabled + # tf eager-execution. + update_global_seed_if_necessary(self.config.framework_str, self.config.seed) + + self._record_usage(self.config) + + # Create the callbacks object. + if self.config.enable_env_runner_and_connector_v2: + self.callbacks = [cls() for cls in force_list(self.config.callbacks_class)] + else: + self.callbacks = self.config.callbacks_class() + + if self.config.log_level in ["WARN", "ERROR"]: + logger.info( + f"Current log_level is {self.config.log_level}. For more information, " + "set 'log_level': 'INFO' / 'DEBUG' or use the -v and " + "-vv flags." + ) + if self.config.log_level: + logging.getLogger("ray.rllib").setLevel(self.config.log_level) + + # Create local replay buffer if necessary. + self.local_replay_buffer = self._create_local_replay_buffer_if_necessary( + self.config + ) + + # Create a dict, mapping ActorHandles to sets of open remote + # requests (object refs). This way, we keep track, of which actors + # inside this Algorithm (e.g. a remote EnvRunner) have + # already been sent how many (e.g. `sample()`) requests. + self.remote_requests_in_flight: DefaultDict[ + ActorHandle, Set[ray.ObjectRef] + ] = defaultdict(set) + + self.env_runner_group: Optional[EnvRunnerGroup] = None + # In case there is no local EnvRunner anymore, we need to handle connector + # pipelines directly here. + self.spaces: Optional[Dict] = None + self.env_to_module_connector: Optional[ConnectorPipelineV2] = None + self.module_to_env_connector: Optional[ConnectorPipelineV2] = None + + # Offline RL settings. + input_evaluation = self.config.get("input_evaluation") + if input_evaluation is not None and input_evaluation is not DEPRECATED_VALUE: + ope_dict = {str(ope): {"type": ope} for ope in input_evaluation} + deprecation_warning( + old="config.input_evaluation={}".format(input_evaluation), + new="config.evaluation(evaluation_config=config.overrides(" + f"off_policy_estimation_methods={ope_dict}" + "))", + error=True, + help="Running OPE during training is not recommended.", + ) + self.config.off_policy_estimation_methods = ope_dict + + # If an input path is available and we are on the new API stack generate + # an `OfflineData` instance. + if self.config.is_offline: + from ray.rllib.offline.offline_data import OfflineData + + # Use either user-provided `OfflineData` class or RLlib's default. + offline_data_class = self.config.offline_data_class or OfflineData + # Build the `OfflineData` class. + self.offline_data = offline_data_class(self.config) + # Otherwise set the attribute to `None`. + else: + self.offline_data = None + + if self.config.is_online or not self.config.enable_env_runner_and_connector_v2: + # Create a set of env runner actors via a EnvRunnerGroup. + self.env_runner_group = EnvRunnerGroup( + env_creator=self.env_creator, + validate_env=self.validate_env, + default_policy_class=self.get_default_policy_class(self.config), + config=self.config, + # New API stack: User decides whether to create local env runner. + # Old API stack: Always create local EnvRunner. + local_env_runner=( + True + if not self.config.enable_env_runner_and_connector_v2 + else self.config.create_local_env_runner + ), + logdir=self.logdir, + tune_trial_id=self.trial_id, + ) + + # Compile, validate, and freeze an evaluation config. + self.evaluation_config = self.config.get_evaluation_config_object() + self.evaluation_config.validate() + self.evaluation_config.freeze() + + # Evaluation EnvRunnerGroup setup. + # User would like to setup a separate evaluation worker set. + # Note: We skip EnvRunnerGroup creation if we need to do offline evaluation. + if self._should_create_evaluation_env_runners(self.evaluation_config): + _, env_creator = self._get_env_id_and_creator( + self.evaluation_config.env, self.evaluation_config + ) + + # Create a separate evaluation worker set for evaluation. + # If evaluation_num_env_runners=0, use the evaluation set's local + # worker for evaluation, otherwise, use its remote workers + # (parallelized evaluation). + self.eval_env_runner_group: EnvRunnerGroup = EnvRunnerGroup( + env_creator=env_creator, + validate_env=None, + default_policy_class=self.get_default_policy_class(self.config), + config=self.evaluation_config, + logdir=self.logdir, + tune_trial_id=self.trial_id, + # New API stack: User decides whether to create local env runner. + # Old API stack: Always create local EnvRunner. + local_env_runner=( + True + if not self.evaluation_config.enable_env_runner_and_connector_v2 + else self.evaluation_config.create_local_env_runner + ), + pg_offset=self.config.num_env_runners, + ) + + if self.env_runner_group: + self.spaces = self.env_runner_group.get_spaces() + elif self.eval_env_runner_group: + self.spaces = self.eval_env_runner_group.get_spaces() + + if self.env_runner is None and self.spaces is not None: + self.env_to_module_connector = self.config.build_env_to_module_connector( + spaces=self.spaces + ) + self.module_to_env_connector = self.config.build_module_to_env_connector( + spaces=self.spaces + ) + + self.evaluation_dataset = None + if ( + self.evaluation_config.off_policy_estimation_methods + and not self.evaluation_config.ope_split_batch_by_episode + ): + # the num worker is set to 0 to avoid creating shards. The dataset will not + # be repartioned to num_workers blocks. + logger.info("Creating evaluation dataset ...") + self.evaluation_dataset, _ = get_dataset_and_shards( + self.evaluation_config, num_workers=0 + ) + logger.info("Evaluation dataset created") + + self.reward_estimators: Dict[str, OffPolicyEstimator] = {} + ope_types = { + "is": ImportanceSampling, + "wis": WeightedImportanceSampling, + "dm": DirectMethod, + "dr": DoublyRobust, + } + for name, method_config in self.config.off_policy_estimation_methods.items(): + method_type = method_config.pop("type") + if method_type in ope_types: + deprecation_warning( + old=method_type, + new=str(ope_types[method_type]), + error=True, + ) + method_type = ope_types[method_type] + elif isinstance(method_type, str): + logger.log(0, "Trying to import from string: " + method_type) + mod, obj = method_type.rsplit(".", 1) + mod = importlib.import_module(mod) + method_type = getattr(mod, obj) + if isinstance(method_type, type) and issubclass( + method_type, OfflineEvaluator + ): + # TODO(kourosh) : Add an integration test for all these + # offline evaluators. + policy = self.get_policy() + if issubclass(method_type, OffPolicyEstimator): + method_config["gamma"] = self.config.gamma + self.reward_estimators[name] = method_type(policy, **method_config) + else: + raise ValueError( + f"Unknown off_policy_estimation type: {method_type}! Must be " + "either a class path or a sub-class of ray.rllib." + "offline.offline_evaluator::OfflineEvaluator" + ) + # TODO (Rohan138): Refactor this and remove deprecated methods + # Need to add back method_type in case Algorithm is restored from checkpoint + method_config["type"] = method_type + + if self.config.enable_rl_module_and_learner: + spaces = { + INPUT_ENV_SPACES: ( + self.config.observation_space, + self.config.action_space, + ) + } + if self.env_runner_group: + spaces.update(self.spaces) + elif self.eval_env_runner_group: + spaces.update(self.eval_env_runner_group.get_spaces()) + else: + spaces.update( + { + DEFAULT_MODULE_ID: ( + self.config.observation_space, + self.config.action_space, + ), + } + ) + + module_spec: MultiRLModuleSpec = self.config.get_multi_rl_module_spec( + spaces=spaces, + inference_only=False, + ) + self.learner_group = self.config.build_learner_group( + rl_module_spec=module_spec + ) + + # Check if there are modules to load from the `module_spec`. + rl_module_ckpt_dirs = {} + multi_rl_module_ckpt_dir = module_spec.load_state_path + modules_to_load = module_spec.modules_to_load + for module_id, sub_module_spec in module_spec.rl_module_specs.items(): + if sub_module_spec.load_state_path: + rl_module_ckpt_dirs[module_id] = sub_module_spec.load_state_path + if multi_rl_module_ckpt_dir or rl_module_ckpt_dirs: + self.learner_group.load_module_state( + multi_rl_module_ckpt_dir=multi_rl_module_ckpt_dir, + modules_to_load=modules_to_load, + rl_module_ckpt_dirs=rl_module_ckpt_dirs, + ) + + # Sync the weights from the learner group to the EnvRunners. + rl_module_state = self.learner_group.get_state( + components=COMPONENT_LEARNER + "/" + COMPONENT_RL_MODULE, + inference_only=True, + )[COMPONENT_LEARNER] + if self.env_runner_group: + self.env_runner_group.sync_env_runner_states( + config=self.config, + env_steps_sampled=self.metrics.peek( + (ENV_RUNNER_RESULTS, NUM_ENV_STEPS_SAMPLED_LIFETIME), default=0 + ), + rl_module_state=rl_module_state, + env_to_module=self.env_to_module_connector, + module_to_env=self.module_to_env_connector, + ) + elif self.eval_env_runner_group: + self.eval_env_runner_group.sync_env_runner_states( + config=self.evaluation_config, + env_steps_sampled=self.metrics.peek( + (ENV_RUNNER_RESULTS, NUM_ENV_STEPS_SAMPLED_LIFETIME), default=0 + ), + rl_module_state=rl_module_state, + env_to_module=self.env_to_module_connector, + module_to_env=self.module_to_env_connector, + ) + # TODO (simon): Update modules in DataWorkers. + + if self.offline_data: + # If the learners are remote we need to provide specific + # information and the learner's actor handles. + if self.learner_group.is_remote: + # If learners run on different nodes, locality hints help + # to use the nearest learner in the workers that do the + # data preprocessing. + learner_node_ids = self.learner_group.foreach_learner( + lambda _: ray.get_runtime_context().get_node_id() + ) + self.offline_data.locality_hints = [ + node_id.get() for node_id in learner_node_ids + ] + # Provide the actor handles for the learners for module + # updating during preprocessing. + self.offline_data.learner_handles = self.learner_group._workers + # Otherwise we can simply pass in the local learner. + else: + self.offline_data.learner_handles = [self.learner_group._learner] + # TODO (simon, sven): Replace these set-some-object's-attributes- + # directly? We should find some solution for this in the future, an API, + # or setting these in the OfflineData constructor? + # Provide the module_spec. Note, in the remote case this is needed + # because the learner module cannot be copied, but must be built. + self.offline_data.module_spec = module_spec + # Provide the `OfflineData` instance with space information. It might + # need it for reading recorded experiences. + self.offline_data.spaces = spaces + + if self._should_create_offline_evaluation_runners(self.evaluation_config): + from ray.rllib.offline.offline_evaluation_runner_group import ( + OfflineEvaluationRunnerGroup, + ) + + # If no inference-only `RLModule` should be used in offline evaluation, + # get the complete learner module. + if not self.evaluation_config.offline_eval_rl_module_inference_only: + rl_module_state = self.learner_group.get_state( + components=COMPONENT_LEARNER + "/" + COMPONENT_RL_MODULE, + inference_only=False, + )[COMPONENT_LEARNER] + # Create the offline evaluation runner group. + self.offline_eval_runner_group: OfflineEvaluationRunnerGroup = OfflineEvaluationRunnerGroup( + config=self.evaluation_config, + # Do not create a local runner such that the dataset can be split. + local_runner=self.config.num_offline_eval_runners == 0, + # Provide the `RLModule`'s state for the `OfflinePreLearner`s. + module_state=rl_module_state[COMPONENT_RL_MODULE], + module_spec=module_spec, + # Note, even if no environment is run, the `MultiRLModule` needs + # spaces to construct the policy network. + spaces=spaces, + ) + + # Create an Aggregator actor set, if necessary. + self._aggregator_actor_manager = None + if self.config.enable_rl_module_and_learner and ( + self.config.num_aggregator_actors_per_learner > 0 + ): + rl_module_spec = self.config.get_multi_rl_module_spec( + spaces=self.spaces, + inference_only=False, + ) + agg_cls = ray.remote( + num_cpus=1, + max_restarts=-1, + )(AggregatorActor) + self._aggregator_actor_manager = FaultTolerantActorManager( + [ + agg_cls.remote(self.config, rl_module_spec) + for _ in range( + (self.config.num_learners or 1) + * self.config.num_aggregator_actors_per_learner + ) + ], + max_remote_requests_in_flight_per_actor=( + self.config.max_requests_in_flight_per_aggregator_actor + ), + ) + # Get the devices of each learner. + learner_locations = list( + enumerate( + self.learner_group.foreach_learner( + func=lambda _learner: (_learner.node, _learner.device), + ) + ) + ) + # Get the devices of each AggregatorActor. + aggregator_locations = list( + enumerate( + self._aggregator_actor_manager.foreach_actor( + func=lambda actor: (actor._node, actor._device) + ) + ) + ) + self._aggregator_actor_to_learner = {} + for agg_idx, aggregator_location in aggregator_locations: + aggregator_location = aggregator_location.get() + for learner_idx, learner_location in learner_locations: + # TODO (sven): Activate full comparison (including device) when Ray + # has figured out GPU pre-loading. + if learner_location.get()[0] == aggregator_location[0]: + # Round-robin, in case all Learners are on same device/node. + learner_locations = learner_locations[1:] + [ + learner_locations[0] + ] + self._aggregator_actor_to_learner[agg_idx] = learner_idx + break + if agg_idx not in self._aggregator_actor_to_learner: + raise RuntimeError( + "No Learner worker found that matches aggregation worker " + f"#{agg_idx}'s node ({aggregator_location[0]}) and device " + f"({aggregator_location[1]})! The Learner workers' locations " + f"are {learner_locations}." + ) + + # Make sure, each Learner index is mapped to from at least one + # AggregatorActor. + if not all( + learner_idx in self._aggregator_actor_to_learner.values() + for learner_idx in range(self.config.num_learners or 1) + ): + raise RuntimeError( + "Some Learner indices are not mapped to from any AggregatorActors! " + "Final AggregatorActor idx -> Learner idx mapping is: " + f"{self._aggregator_actor_to_learner}" + ) + + # Run `on_algorithm_init` callback after initialization is done. + make_callback( + "on_algorithm_init", + self.callbacks, + self.config.callbacks_on_algorithm_init, + kwargs=dict( + algorithm=self, + metrics_logger=self.metrics, + ), + ) + + @OverrideToImplementCustomLogic + @classmethod + def get_default_policy_class( + cls, + config: AlgorithmConfig, + ) -> Optional[Type[Policy]]: + """Returns a default Policy class to use, given a config. + + This class will be used by an Algorithm in case + the policy class is not provided by the user in any single- or + multi-agent PolicySpec. + + Note: This method is ignored when the RLModule API is enabled. + """ + return None + + @override(Trainable) + def step(self) -> ResultDict: + """Implements the main `Algorithm.train()` logic. + + Takes n attempts to perform a single training step. Thereby + catches RayErrors resulting from worker failures. After n attempts, + fails gracefully. + + Override this method in your Algorithm sub-classes if you would like to + handle worker failures yourself. + Otherwise, override only `training_step()` to implement the core + algorithm logic. + + Returns: + The results dict with stats/infos on sampling, training, + and - if required - evaluation. + """ + # Do we have to run `self.evaluate()` this iteration? + # `self.iteration` gets incremented after this function returns, + # meaning that e.g. the first time this function is called, + # self.iteration will be 0. + evaluate_this_iter = ( + self.config.evaluation_interval + and (self.iteration + 1) % self.config.evaluation_interval == 0 + ) + + evaluate_offline_this_iter = ( + self.config.offline_evaluation_interval + and (self.iteration + 1) % self.config.offline_evaluation_interval == 0 + ) + + # Results dict for training (and if appolicable: evaluation). + eval_results: ResultDict = {} + + # Parallel eval + training: Kick off evaluation-loop and parallel train() call. + if evaluate_this_iter and ( + self.config.evaluation_parallel_to_training + or self.config.offline_evaluation_parallel_to_training + ): + ( + train_results, + eval_results, + train_iter_ctx, + ) = self._run_one_training_iteration_and_evaluation_in_parallel() + + # - No evaluation necessary, just run the next training iteration. + # - We have to evaluate in this training iteration, but no parallelism -> + # evaluate after the training iteration is entirely done. + else: + if self.config.enable_env_runner_and_connector_v2: + train_results, train_iter_ctx = self._run_one_training_iteration() + else: + ( + train_results, + train_iter_ctx, + ) = self._run_one_training_iteration_old_api_stack() + + # Sequential: Train (already done above), then evaluate. + if evaluate_this_iter and not self.config.evaluation_parallel_to_training: + eval_results = self._run_one_evaluation(parallel_train_future=None) + + if evaluate_offline_this_iter: + offline_eval_results = self._run_one_offline_evaluation() + # If we already have online evaluation results merge the offline + # evaluation results. + if eval_results: + eval_results[EVALUATION_RESULTS].update( + offline_eval_results[EVALUATION_RESULTS] + ) + # Otherwise, just assign. + else: + eval_results = offline_eval_results + + # Sync EnvRunner workers. + # TODO (sven): For the new API stack, the common execution pattern for any algo + # should be: [sample + get_metrics + get_state] -> send all these in one remote + # call down to `training_step` (where episodes are sent as ray object + # references). Then distribute the episode refs to the learners, store metrics + # in special key in result dict and perform the connector merge/broadcast + # inside the `training_step` as well. See the new IMPALA for an example. + if self.config.enable_env_runner_and_connector_v2: + if ( + not self.config._dont_auto_sync_env_runner_states + and self.env_runner_group + ): + # Synchronize EnvToModule and ModuleToEnv connector states and broadcast + # new states back to all EnvRunners. + with self.metrics.log_time((TIMERS, SYNCH_ENV_CONNECTOR_STATES_TIMER)): + self.env_runner_group.sync_env_runner_states( + config=self.config, + env_to_module=self.env_to_module_connector, + module_to_env=self.module_to_env_connector, + ) + # Compile final ResultDict from `train_results` and `eval_results`. Note + # that, as opposed to the old API stack, EnvRunner stats should already be + # in `train_results` and `eval_results`. + results = self._compile_iteration_results( + train_results=train_results, + eval_results=eval_results, + ) + else: + self._sync_filters_if_needed( + central_worker=self.env_runner_group.local_env_runner, + workers=self.env_runner_group, + config=self.config, + ) + # Get EnvRunner metrics and compile them into results. + episodes_this_iter = collect_episodes( + self.env_runner_group, + self._remote_worker_ids_for_metrics(), + timeout_seconds=self.config.metrics_episode_collection_timeout_s, + ) + results = self._compile_iteration_results_old_api_stack( + episodes_this_iter=episodes_this_iter, + step_ctx=train_iter_ctx, + iteration_results={**train_results, **eval_results}, + ) + + return results + + @PublicAPI + def evaluate_offline(self): + """Evaluates current policy offline under `evaluation_config` settings. + + Returns: + A ResultDict only containing the offline evaluation results from the current + iteration. + """ + + # First synchronize weights. + self.offline_eval_runner_group.sync_weights( + from_worker_or_learner_group=self.learner_group, + inference_only=self.config.offline_eval_rl_module_inference_only, + ) + + # TODO (simon): Check, how we can sync without a local runner. Also, + # connectors are in the data pipeline not directly in the runner applied. + # if self.config.broadcast_offline_eval_runner_states: + # # TODO (simon): Create offline equivalent. + # with self.metrics.log_time(TIMERS, SYNCH_EVAL_ENV_CONNECTOR_STATES_TIMER): + # self.offline_eval_runner_group.sync_runner_states( + # from_runner= + # ) + + make_callback( + "on_evaluate_offline_start", + callbacks_objects=self.callbacks, + callbacks_functions=self.config.callbacks_on_evaluate_offline_start, + kwargs=dict(algorithm=self, metrics_logger=self.metrics), + ) + + # Evaluate with fixed duration. + if self.offline_eval_runner_group.num_healthy_remote_runners > 0: + self._evaluate_offline_with_fixed_duration() + else: + self._evaluate_offline_on_local_runner() + # Reduce the evaluation results. + eval_results = self.metrics.peek( + (EVALUATION_RESULTS, OFFLINE_EVAL_RUNNER_RESULTS), default={} + ) + + # Trigger `on_evaluate_offline_end` callback. + make_callback( + "on_evaluate_offline_end", + callbacks_objects=self.callbacks, + callbacks_functions=self.config.callbacks_on_evaluate_offline_end, + kwargs=dict( + algorithm=self, + metrics_logger=self.metrics, + evaluation_metrics=eval_results, + ), + ) + + # Also return the results here for convenience. + return {OFFLINE_EVAL_RUNNER_RESULTS: eval_results} + + @PublicAPI + def evaluate( + self, + parallel_train_future: Optional[concurrent.futures.ThreadPoolExecutor] = None, + ) -> ResultDict: + """Evaluates current policy under `evaluation_config` settings. + + Args: + parallel_train_future: In case, we are training and avaluating in parallel, + this arg carries the currently running ThreadPoolExecutor object that + runs the training iteration. Use `parallel_train_future.done()` to + check, whether the parallel training job has completed and + `parallel_train_future.result()` to get its return values. + + Returns: + A ResultDict only containing the evaluation results from the current + iteration. + """ + # Call the `_before_evaluate` hook. + self._before_evaluate() + + if self.evaluation_dataset is not None: + return self._run_offline_evaluation_old_api_stack() + + if self.config.enable_env_runner_and_connector_v2: + if ( + self.env_runner_group is not None + and self.env_runner_group.healthy_env_runner_ids() + ): + # TODO (sven): Replace this with a new ActorManager API: + # try_remote_request_till_success("get_state") -> tuple(int, + # remoteresult) + weights_src = self.env_runner_group._worker_manager._actors[ + self.env_runner_group.healthy_env_runner_ids()[0] + ] + else: + weights_src = self.learner_group + else: + weights_src = self.env_runner + + # Sync weights to the evaluation EnvRunners. + if self.eval_env_runner_group is not None: + self.eval_env_runner_group.sync_weights( + from_worker_or_learner_group=weights_src, + inference_only=True, + ) + + # Merge (eval) EnvRunner states and broadcast the merged state back + # to the remote (eval) EnvRunner actors. + if self.config.enable_env_runner_and_connector_v2: + if self.evaluation_config.broadcast_env_runner_states: + with self.metrics.log_time( + (TIMERS, SYNCH_EVAL_ENV_CONNECTOR_STATES_TIMER) + ): + self.eval_env_runner_group.sync_env_runner_states( + config=self.evaluation_config, + from_worker=self.env_runner, + env_to_module=self.env_to_module_connector, + module_to_env=self.module_to_env_connector, + ) + else: + self._sync_filters_if_needed( + central_worker=self.env_runner_group.local_env_runner, + workers=self.eval_env_runner_group, + config=self.evaluation_config, + ) + # Sync weights to the local EnvRunner (if no eval EnvRunnerGroup). + elif self.config.enable_env_runner_and_connector_v2: + self.env_runner_group.sync_weights( + from_worker_or_learner_group=weights_src, + inference_only=True, + ) + + make_callback( + "on_evaluate_start", + callbacks_objects=self.callbacks, + callbacks_functions=self.config.callbacks_on_evaluate_start, + kwargs=dict(algorithm=self, metrics_logger=self.metrics), + ) + + env_steps = agent_steps = 0 + batches = [] + + # We will use a user provided evaluation function. + if self.config.custom_evaluation_function: + if self.config.enable_env_runner_and_connector_v2: + ( + eval_results, + env_steps, + agent_steps, + ) = self._evaluate_with_custom_eval_function() + else: + eval_results = self.config.custom_evaluation_function() + # There is no eval EnvRunnerGroup -> Run on local EnvRunner. + elif self.eval_env_runner_group is None and self.env_runner: + ( + eval_results, + env_steps, + agent_steps, + batches, + ) = self._evaluate_on_local_env_runner(self.env_runner) + # There is only a local eval EnvRunner -> Run on that. + elif self.eval_env_runner_group.num_healthy_remote_workers() == 0: + ( + eval_results, + env_steps, + agent_steps, + batches, + ) = self._evaluate_on_local_env_runner(self.eval_env_runner) + # There are healthy remote evaluation workers -> Run on these. + elif self.eval_env_runner_group.num_healthy_remote_workers() > 0: + # Running in automatic duration mode (parallel with training step). + if self.config.evaluation_duration == "auto": + assert parallel_train_future is not None + ( + eval_results, + env_steps, + agent_steps, + batches, + ) = self._evaluate_with_auto_duration(parallel_train_future) + # Running with a fixed amount of data to sample. + else: + ( + eval_results, + env_steps, + agent_steps, + batches, + ) = self._evaluate_with_fixed_duration() + # Can't find a good way to run this evaluation -> Wait for next iteration. + else: + eval_results = {} + + if self.config.enable_env_runner_and_connector_v2: + eval_results = self.metrics.peek(key=EVALUATION_RESULTS, default={}) + if log_once("no_eval_results") and not eval_results: + logger.warning( + "No evaluation results found for this iteration. This can happen if the evaluation worker(s) is/are not healthy." + ) + else: + eval_results = {ENV_RUNNER_RESULTS: eval_results} + eval_results[NUM_AGENT_STEPS_SAMPLED_THIS_ITER] = agent_steps + eval_results[NUM_ENV_STEPS_SAMPLED_THIS_ITER] = env_steps + eval_results["timesteps_this_iter"] = env_steps + self._counters[NUM_ENV_STEPS_SAMPLED_FOR_EVALUATION_THIS_ITER] = env_steps + + # Compute off-policy estimates + if not self.config.custom_evaluation_function: + estimates = defaultdict(list) + # for each batch run the estimator's fwd pass + for name, estimator in self.reward_estimators.items(): + for batch in batches: + estimate_result = estimator.estimate( + batch, + split_batch_by_episode=self.config.ope_split_batch_by_episode, + ) + estimates[name].append(estimate_result) + + # collate estimates from all batches + if estimates: + eval_results["off_policy_estimator"] = {} + for name, estimate_list in estimates.items(): + avg_estimate = tree.map_structure( + lambda *x: np.mean(x, axis=0), *estimate_list + ) + eval_results["off_policy_estimator"][name] = avg_estimate + + # Trigger `on_evaluate_end` callback. + make_callback( + "on_evaluate_end", + callbacks_objects=self.callbacks, + callbacks_functions=self.config.callbacks_on_evaluate_end, + kwargs=dict( + algorithm=self, + metrics_logger=self.metrics, + evaluation_metrics=eval_results, + ), + ) + + # Also return the results here for convenience. + return eval_results + + def _evaluate_with_custom_eval_function(self) -> Tuple[ResultDict, int, int]: + logger.info( + f"Evaluating current state of {self} using the custom eval function " + f"{self.config.custom_evaluation_function}" + ) + if self.config.enable_env_runner_and_connector_v2: + ( + eval_results, + env_steps, + agent_steps, + ) = self.config.custom_evaluation_function(self, self.eval_env_runner_group) + if not env_steps or not agent_steps: + raise ValueError( + "Custom eval function must return " + "`Tuple[ResultDict, int, int]` with `int, int` being " + f"`env_steps` and `agent_steps`! Got {env_steps}, {agent_steps}." + ) + else: + eval_results = self.config.custom_evaluation_function() + if not eval_results or not isinstance(eval_results, dict): + raise ValueError( + "Custom eval function must return " + f"dict of metrics! Got {eval_results}." + ) + + return eval_results, env_steps, agent_steps + + def _evaluate_offline_on_local_runner(self): + # How many episodes/timesteps do we need to run? + unit = "batches" + duration = ( + self.config.offline_evaluation_duration + * self.config.dataset_num_iters_per_eval_runner + ) + + logger.info(f"Evaluating current state of {self} for {duration} {unit}.") + + results = self.offline_eval_runner_group.local_runner.run() + + self.metrics.aggregate( + [results], + key=(EVALUATION_RESULTS, OFFLINE_EVAL_RUNNER_RESULTS), + ) + + def _evaluate_on_local_env_runner(self, env_runner): + if hasattr(env_runner, "input_reader") and env_runner.input_reader is None: + raise ValueError( + "Can't evaluate on a local worker if this local worker does not have " + "an environment!\nTry one of the following:" + "\n1) Set `evaluation_interval` > 0 to force creating a separate " + "evaluation EnvRunnerGroup.\n2) Set `create_local_env_runner=True` to " + "force the local (non-eval) EnvRunner to have an environment to " + "evaluate on." + ) + elif self.config.evaluation_parallel_to_training: + raise ValueError( + "Cannot run on local evaluation worker parallel to training! Try " + "setting `evaluation_parallel_to_training=False`." + ) + + # How many episodes/timesteps do we need to run? + unit = self.config.evaluation_duration_unit + duration = self.config.evaluation_duration + eval_cfg = self.evaluation_config + + env_steps = agent_steps = 0 + + logger.info(f"Evaluating current state of {self} for {duration} {unit}.") + + all_batches = [] + if self.config.enable_env_runner_and_connector_v2: + episodes = env_runner.sample( + num_timesteps=duration if unit == "timesteps" else None, + num_episodes=duration if unit == "episodes" else None, + ) + agent_steps += sum(e.agent_steps() for e in episodes) + env_steps += sum(e.env_steps() for e in episodes) + elif unit == "episodes": + for _ in range(duration): + batch = env_runner.sample() + agent_steps += batch.agent_steps() + env_steps += batch.env_steps() + if self.reward_estimators: + all_batches.append(batch) + else: + batch = env_runner.sample() + agent_steps += batch.agent_steps() + env_steps += batch.env_steps() + if self.reward_estimators: + all_batches.append(batch) + + env_runner_results = env_runner.get_metrics() + + if not self.config.enable_env_runner_and_connector_v2: + env_runner_results = summarize_episodes( + env_runner_results, + env_runner_results, + keep_custom_metrics=eval_cfg.keep_per_episode_custom_metrics, + ) + else: + self.metrics.aggregate( + [env_runner_results], + key=(EVALUATION_RESULTS, ENV_RUNNER_RESULTS), + ) + env_runner_results = None + + return env_runner_results, env_steps, agent_steps, all_batches + + def _evaluate_with_auto_duration(self, parallel_train_future): + logger.info( + f"Evaluating current state of {self} for as long as the parallelly " + "running training step takes." + ) + + all_metrics = [] + all_batches = [] + + # How many episodes have we run (across all eval workers)? + num_healthy_workers = self.eval_env_runner_group.num_healthy_remote_workers() + # Do we have to force-reset the EnvRunners before the first round of `sample()` + # calls.? + force_reset = self.config.evaluation_force_reset_envs_before_iteration + + # Remote function used on healthy EnvRunners to sample, get metrics, and + # step counts. + def _env_runner_remote(worker, num, round, iter): + # Sample AND get_metrics, but only return metrics (and steps actually taken) + # to save time. + episodes = worker.sample( + num_timesteps=num, force_reset=force_reset and round == 0 + ) + metrics = worker.get_metrics() + env_steps = sum(e.env_steps() for e in episodes) + agent_steps = sum(e.agent_steps() for e in episodes) + return env_steps, agent_steps, metrics, iter + + env_steps = agent_steps = 0 + if self.config.enable_env_runner_and_connector_v2: + train_mean_time = self.metrics.peek( + (TIMERS, TRAINING_ITERATION_TIMER), default=0.0 + ) + else: + train_mean_time = self._timers[TRAINING_ITERATION_TIMER].mean + t0 = time.time() + algo_iteration = self.iteration + + _round = -1 + while ( + # In case all the remote evaluation workers die during a round of + # evaluation, we need to stop. + num_healthy_workers > 0 + # Run at least for one round AND at least for as long as the parallel + # training step takes. + and (_round == -1 or not parallel_train_future.done()) + ): + _round += 1 + # New API stack -> EnvRunners return Episodes. + if self.config.enable_env_runner_and_connector_v2: + # Compute rough number of timesteps it takes for a single EnvRunner + # to occupy the estimated (parallelly running) train step. + _num = min( + # Clamp number of steps to take between a max and a min. + self.config.evaluation_auto_duration_max_env_steps_per_sample, + max( + self.config.evaluation_auto_duration_min_env_steps_per_sample, + ( + # How much time do we have left? + (train_mean_time - (time.time() - t0)) + # Multiply by our own (eval) throughput to get the timesteps + # to do (per worker). + * self.metrics.peek( + ( + EVALUATION_RESULTS, + ENV_RUNNER_RESULTS, + NUM_ENV_STEPS_SAMPLED_LIFETIME, + ), + throughput=True, + default=0.0, + ) + / num_healthy_workers + ), + ), + ) + + results = self.eval_env_runner_group.fetch_ready_async_reqs( + return_obj_refs=False, timeout_seconds=0.0 + ) + self.eval_env_runner_group.foreach_env_runner_async( + func=functools.partial( + _env_runner_remote, num=_num, round=_round, iter=algo_iteration + ), + ) + for wid, (env_s, ag_s, metrics, iter) in results: + # Ignore eval results kicked off in an earlier iteration. + # (those results would be outdated and thus misleading). + if iter != self.iteration: + continue + env_steps += env_s + agent_steps += ag_s + all_metrics.append(metrics) + time.sleep(0.01) + + # Old API stack -> RolloutWorkers return batches. + else: + self.eval_env_runner_group.foreach_env_runner_async( + func=lambda w: (w.sample(), w.get_metrics(), algo_iteration), + ) + results = self.eval_env_runner_group.fetch_ready_async_reqs( + return_obj_refs=False, timeout_seconds=0.01 + ) + for wid, (batch, metrics, iter) in results: + if iter != self.iteration: + continue + env_steps += batch.env_steps() + agent_steps += batch.agent_steps() + all_metrics.extend(metrics) + if self.reward_estimators: + # TODO: (kourosh) This approach will cause an OOM issue when + # the dataset gets huge (should be ok for now). + all_batches.append(batch) + + # Update correct number of healthy remote workers. + num_healthy_workers = ( + self.eval_env_runner_group.num_healthy_remote_workers() + ) + + if num_healthy_workers == 0: + logger.warning( + "Calling `sample()` on your remote evaluation worker(s) " + "resulted in all workers crashing! Make sure a) your environment is not" + " too unstable, b) you have enough evaluation workers " + "(`config.evaluation(evaluation_num_env_runners=...)`) to cover for " + "occasional losses, and c) you use the `config.fault_tolerance(" + "restart_failed_env_runners=True)` setting." + ) + + if not self.config.enable_env_runner_and_connector_v2: + env_runner_results = summarize_episodes( + all_metrics, + all_metrics, + keep_custom_metrics=( + self.evaluation_config.keep_per_episode_custom_metrics + ), + ) + num_episodes = env_runner_results[NUM_EPISODES] + else: + self.metrics.aggregate( + all_metrics, + key=(EVALUATION_RESULTS, ENV_RUNNER_RESULTS), + ) + num_episodes = self.metrics.peek( + (EVALUATION_RESULTS, ENV_RUNNER_RESULTS, NUM_EPISODES), + default=0, + ) + env_runner_results = None + + # Warn if results are empty, it could be that this is because the auto-time is + # not enough to run through one full episode. + if ( + self.config.evaluation_force_reset_envs_before_iteration + and num_episodes == 0 + ): + logger.warning( + "This evaluation iteration resulted in an empty set of episode summary " + "results! It's possible that the auto-duration time (roughly the mean " + "time it takes for the training step to finish) is not enough to finish" + " even a single episode. Your current mean training iteration time is " + f"{train_mean_time}sec. Try setting the min iteration time to a higher " + "value via the `config.reporting(min_time_s_per_iteration=...)` OR you " + "can also set `config.evaluation_force_reset_envs_before_iteration` to " + "False. However, keep in mind that then the evaluation results may " + "contain some episode stats generated with earlier weights versions." + ) + + return env_runner_results, env_steps, agent_steps, all_batches + + def _evaluate_offline_with_fixed_duration(self) -> None: + # How many batches do we need to run? + num_workers = self.config.num_offline_eval_runners + time_out = self.config.offline_evaluation_timeout_s + + def _offline_eval_runner_remote(runner, iter): + + metrics = runner.run() + + return metrics, iter + + all_metrics = [] + num_units_done = [] + + # How many episodes have we run (across all eval workers)? + num_units_done = 0 + num_healthy_workers = self.offline_eval_runner_group.num_healthy_remote_runners + + # TODO (simon): Note, agent steps might not be available, but only + # module steps. + + t_last_result = time.time() + _round = -1 + algo_iteration = self.iteration + + # In case all the remote evaluation workers die during a round of + # evaluation, we need to stop. + while num_healthy_workers > 0: + units_left_to_do = ( + self.config.offline_evaluation_duration * num_workers - num_units_done + ) + if units_left_to_do <= 0: + break + + _round += 1 + + self.offline_eval_runner_group.foreach_runner_async( + func=functools.partial( + _offline_eval_runner_remote, + iter=algo_iteration, + ), + ) + results = self.offline_eval_runner_group.fetch_ready_async_reqs( + return_obj_refs=False, timeout_seconds=0.01 + ) + # Make sure we properly time out if we have not received any results + # for more than `time_out` seconds. + time_now = time.time() + if not results and time_now - t_last_result > time_out: + break + elif results: + t_last_result = time_now + for wid, (met, iter) in results: + if iter != self.iteration: + continue + all_metrics.append(met) + # Note, the `dataset_num_iters_per_eval_runner` must be smaller than + # `offline_evaluation_duration` // `num_offline_eval_runners`. + num_units_done += ( + met[ALL_MODULES][DATASET_NUM_ITERS_EVALUATED].peek() + if DATASET_NUM_ITERS_EVALUATED in met[ALL_MODULES] + else 0 + ) + + # Update correct number of healthy remote workers. + num_healthy_workers = ( + self.offline_eval_runner_group.num_healthy_remote_runners + ) + + if num_healthy_workers == 0: + logger.warning( + "Calling `run()` on your remote offline evaluation runner(s) " + "resulted in all runners crashing! Make sure a) your dataset is not" + " corrupted, b) you have enough offline evaluation runners " + "(`config.evaluation(num_offline_eval_runners=...)`) to cover for " + "occasional losses, and c) you use the `config.fault_tolerance(" + "restart_failed_offline_eval_runners=True)` setting." + ) + + self.metrics.aggregate( + all_metrics, + key=(EVALUATION_RESULTS, OFFLINE_EVAL_RUNNER_RESULTS), + ) + + def _evaluate_with_fixed_duration(self): + # How many episodes/timesteps do we need to run? + unit = self.config.evaluation_duration_unit + eval_cfg = self.evaluation_config + num_workers = self.config.evaluation_num_env_runners + force_reset = self.config.evaluation_force_reset_envs_before_iteration + time_out = self.config.evaluation_sample_timeout_s + + # Remote function used on healthy EnvRunners to sample, get metrics, and + # step counts. + def _env_runner_remote(worker, num, round, iter, _force_reset): + # Sample AND get_metrics, but only return metrics (and steps actually taken) + # to save time. Also return the iteration to check, whether we should + # discard and outdated result (from a slow worker). + episodes = worker.sample( + num_timesteps=( + num[worker.worker_index] if unit == "timesteps" else None + ), + num_episodes=(num[worker.worker_index] if unit == "episodes" else None), + force_reset=_force_reset and round == 0, + ) + metrics = worker.get_metrics() + env_steps = sum(e.env_steps() for e in episodes) + agent_steps = sum(e.agent_steps() for e in episodes) + return env_steps, agent_steps, metrics, iter + + all_metrics = [] + all_batches = [] + + # How many episodes have we run (across all eval workers)? + num_units_done = 0 + num_healthy_workers = self.eval_env_runner_group.num_healthy_remote_workers() + + env_steps = agent_steps = 0 + + t_last_result = time.time() + _round = -1 + algo_iteration = self.iteration + + # In case all the remote evaluation workers die during a round of + # evaluation, we need to stop. + while num_healthy_workers > 0: + units_left_to_do = self.config.evaluation_duration - num_units_done + if units_left_to_do <= 0: + break + + _round += 1 + + # New API stack -> EnvRunners return Episodes. + if self.config.enable_env_runner_and_connector_v2: + _num = [None] + [ # [None]: skip idx=0 (local worker) + (units_left_to_do // num_healthy_workers) + + bool(i <= (units_left_to_do % num_healthy_workers)) + for i in range(1, num_workers + 1) + ] + self.eval_env_runner_group.foreach_env_runner_async( + func=functools.partial( + _env_runner_remote, + num=_num, + round=_round, + iter=algo_iteration, + _force_reset=force_reset, + ), + ) + results = self.eval_env_runner_group.fetch_ready_async_reqs( + return_obj_refs=False, timeout_seconds=0.01 + ) + # Make sure we properly time out if we have not received any results + # for more than `time_out` seconds. + time_now = time.time() + if not results and time_now - t_last_result > time_out: + break + elif results: + t_last_result = time_now + for wid, (env_s, ag_s, met, iter) in results: + if iter != self.iteration: + continue + env_steps += env_s + agent_steps += ag_s + all_metrics.append(met) + num_units_done += ( + (met[NUM_EPISODES].peek() if NUM_EPISODES in met else 0) + if unit == "episodes" + else ( + env_s if self.config.count_steps_by == "env_steps" else ag_s + ) + ) + # Old API stack -> RolloutWorkers return batches. + else: + units_per_healthy_remote_worker = ( + 1 + if unit == "episodes" + else eval_cfg.rollout_fragment_length + * eval_cfg.num_envs_per_env_runner + ) + # Select proper number of evaluation workers for this round. + selected_eval_worker_ids = [ + worker_id + for i, worker_id in enumerate( + self.eval_env_runner_group.healthy_worker_ids() + ) + if i * units_per_healthy_remote_worker < units_left_to_do + ] + self.eval_env_runner_group.foreach_env_runner_async( + func=lambda w: (w.sample(), w.get_metrics(), algo_iteration), + remote_worker_ids=selected_eval_worker_ids, + ) + results = self.eval_env_runner_group.fetch_ready_async_reqs( + return_obj_refs=False, timeout_seconds=0.01 + ) + # Make sure we properly time out if we have not received any results + # for more than `time_out` seconds. + time_now = time.time() + if not results and time_now - t_last_result > time_out: + break + elif results: + t_last_result = time_now + for wid, (batch, metrics, iter) in results: + if iter != self.iteration: + continue + env_steps += batch.env_steps() + agent_steps += batch.agent_steps() + all_metrics.extend(metrics) + if self.reward_estimators: + # TODO: (kourosh) This approach will cause an OOM issue when + # the dataset gets huge (should be ok for now). + all_batches.append(batch) + + # 1 episode per returned batch. + if unit == "episodes": + num_units_done += len(results) + # n timesteps per returned batch. + else: + num_units_done = ( + env_steps + if self.config.count_steps_by == "env_steps" + else agent_steps + ) + + # Update correct number of healthy remote workers. + num_healthy_workers = ( + self.eval_env_runner_group.num_healthy_remote_workers() + ) + + if num_healthy_workers == 0: + logger.warning( + "Calling `sample()` on your remote evaluation worker(s) " + "resulted in all workers crashing! Make sure a) your environment is not" + " too unstable, b) you have enough evaluation workers " + "(`config.evaluation(evaluation_num_env_runners=...)`) to cover for " + "occasional losses, and c) you use the `config.fault_tolerance(" + "restart_failed_env_runners=True)` setting." + ) + + if not self.config.enable_env_runner_and_connector_v2: + env_runner_results = summarize_episodes( + all_metrics, + all_metrics, + keep_custom_metrics=( + self.evaluation_config.keep_per_episode_custom_metrics + ), + ) + num_episodes = env_runner_results[NUM_EPISODES] + else: + self.metrics.aggregate( + all_metrics, + key=(EVALUATION_RESULTS, ENV_RUNNER_RESULTS), + ) + num_episodes = self.metrics.peek( + (EVALUATION_RESULTS, ENV_RUNNER_RESULTS, NUM_EPISODES), default=0 + ) + env_runner_results = None + + # Warn if results are empty, it could be that this is because the eval timesteps + # are not enough to run through one full episode. + if num_episodes == 0: + logger.warning( + "This evaluation iteration resulted in an empty set of episode summary " + "results! It's possible that your configured duration timesteps are not" + " enough to finish even a single episode. You have configured " + f"{self.config.evaluation_duration} " + f"{self.config.evaluation_duration_unit}. For 'timesteps', try " + "increasing this value via the `config.evaluation(evaluation_duration=" + "...)` OR change the unit to 'episodes' via `config.evaluation(" + "evaluation_duration_unit='episodes')` OR try increasing the timeout " + "threshold via `config.evaluation(evaluation_sample_timeout_s=...)` OR " + "you can also set `config.evaluation_force_reset_envs_before_iteration`" + " to False. However, keep in mind that in the latter case, the " + "evaluation results may contain some episode stats generated with " + "earlier weights versions." + ) + + return env_runner_results, env_steps, agent_steps, all_batches + + @OverrideToImplementCustomLogic + def restore_env_runners(self, env_runner_group: EnvRunnerGroup) -> List[int]: + """Try bringing back unhealthy EnvRunners and - if successful - sync with local. + + Algorithms that use custom EnvRunners may override this method to + disable the default, and create custom restoration logics. Note that "restoring" + does not include the actual restarting process, but merely what should happen + after such a restart of a (previously failed) worker. + + Args: + env_runner_group: The EnvRunnerGroup to restore. This may be the training or + the evaluation EnvRunnerGroup. + + Returns: + A list of EnvRunner indices that have been restored during the call of + this method. + """ + # This is really cheap, since probe_unhealthy_env_runners() is a no-op + # if there are no unhealthy workers. + restored = None + if self.config.is_online: + restored = env_runner_group.probe_unhealthy_env_runners() + + if not restored: + return [] + + # Count the restored workers. + self._counters["total_num_restored_workers"] += len(restored) + + from_env_runner = env_runner_group.local_env_runner or self.env_runner + + # Sync from local EnvRunner, if it exists. + if from_env_runner is not None: + # Get the state of the EnvRunner. + state = from_env_runner.get_state() + state_ref = ray.put(state) + + # Take out (old) connector states from local worker's state. + if not self.config.enable_env_runner_and_connector_v2: + for pol_states in state["policy_states"].values(): + pol_states.pop("connector_configs", None) + + elif self.config.is_multi_agent: + + multi_rl_module_spec = MultiRLModuleSpec.from_module( + from_env_runner.module + ) + + # Otherwise, sync from another EnvRunner that's still healthy. + else: + multi_rl_module_spec = ( + self.learner_group.foreach_learner( + lambda learner: MultiRLModuleSpec.from_module(learner.module) + ) + .result_or_errors[0] + .get() + ) + + # Sync the weights from the learner group to the EnvRunners. + state = self.learner_group.get_state( + components=COMPONENT_LEARNER + "/" + COMPONENT_RL_MODULE, + inference_only=True, + )[COMPONENT_LEARNER] + state[ + COMPONENT_ENV_TO_MODULE_CONNECTOR + ] = self.env_to_module_connector.get_state() + state[ + COMPONENT_MODULE_TO_ENV_CONNECTOR + ] = self.module_to_env_connector.get_state() + state[NUM_ENV_STEPS_SAMPLED_LIFETIME] = self.metrics.peek( + (ENV_RUNNER_RESULTS, NUM_ENV_STEPS_SAMPLED_LIFETIME), default=0 + ) + state_ref = ray.put(state) + + def _sync_env_runner(er): # noqa + # Remove modules (new API stack only), if necessary. + if ( + er.config.enable_env_runner_and_connector_v2 + and er.config.is_multi_agent + ): + for module_id, module in er.module._rl_modules.copy().items(): + if module_id not in multi_rl_module_spec.rl_module_specs: + er.module.remove_module(module_id, raise_err_if_not_found=True) + # Add modules, if necessary. + for mid, mod_spec in multi_rl_module_spec.rl_module_specs.items(): + if mid not in er.module: + er.module.add_module(mid, mod_spec.build(), override=False) + # Now that the MultiRLModule is fixed, update the state. + er.set_state(ray.get(state_ref)) + + # By default, entire local EnvRunner state is synced after restoration + # to bring the previously failed EnvRunner up to date. + env_runner_group.foreach_env_runner( + func=_sync_env_runner, + remote_worker_ids=restored, + # Don't update the local EnvRunner, b/c it's the one we are synching + # from. + local_env_runner=False, + timeout_seconds=self.config.env_runner_restore_timeout_s, + ) + + return restored + + @OverrideToImplementCustomLogic + def restore_offline_eval_runners(self, runner_group: RunnerGroup) -> List[int]: + if not runner_group or not runner_group.local_runner: + return [] + + restored = runner_group.probe_unhealthy_runners() + + if restored: + # Count the restored workers. + self._counters["total_num_restored_workers"] += len(restored) + + # Get the state of the correct (reference) worker. + from_runner = runner_group.healthy_runner_ids()[0] + state = runner_group.foreach_runner( + "get_state", + local_runner=False, + remote_worker_ids=from_runner, + )[0] + state_ref = ray.put(state) + + def _sync_runner(r): + r.set_state(ray.get(state_ref)) + + # By default, entire `Runner`` state is synced after restoration + # to bring the previously failed `Runner` up to date. + runner_group.foreach_runner( + func=_sync_runner, + remote_worker_ids=restored, + # Don't update the local `Runner`. + local_runner=False, + timeout_seconds=self.evaluation_config.offline_eval_runner_restore_timeout_s, + ) + # Restore the correct data iterator split stream. + # TODO (simon): Define a `restore` method in the `RunnerGroup` + # such that we do not have to check here for the group. + # Also get a different streaming split if a runner fails and is not + # recreated. + runner_group.foreach_runner( + func="set_dataset_iterator", + remote_worker_ids=restored, + local_runner=False, + timeout_seconds=self.evaluation_config.offline_eval_runner_restore_timeout_s, + kwargs={"iterator": runner_group._offline_data_iterators[restored]}, + ) + + return restored + + @OverrideToImplementCustomLogic + def training_step(self) -> None: + """Default single iteration logic of an algorithm. + + - Collect on-policy samples (SampleBatches) in parallel using the + Algorithm's EnvRunners (@ray.remote). + - Concatenate collected SampleBatches into one train batch. + - Note that we may have more than one policy in the multi-agent case: + Call the different policies' `learn_on_batch` (simple optimizer) OR + `load_batch_into_buffer` + `learn_on_loaded_batch` (multi-GPU + optimizer) methods to calculate loss and update the model(s). + - Return all collected metrics for the iteration. + + Returns: + For the new API stack, returns None. Results are compiled and extracted + automatically through a single `self.metrics.reduce()` call at the very end + of an iteration (which might contain more than one call to + `training_step()`). This way, we make sure that we account for all + results generated by each individual `training_step()` call. + For the old API stack, returns the results dict from executing the training + step. + """ + if not self.config.enable_env_runner_and_connector_v2: + raise NotImplementedError( + "The `Algorithm.training_step()` default implementation no longer " + "supports the old API stack! If you would like to continue " + "using these " + "old APIs with this default `training_step`, simply subclass " + "`Algorithm` and override its `training_step` method (copy/paste the " + "code and delete this error message)." + ) + + # Collect a list of Episodes from EnvRunners until we reach the train batch + # size. + with self.metrics.log_time((TIMERS, ENV_RUNNER_SAMPLING_TIMER)): + if self.config.count_steps_by == "agent_steps": + episodes, env_runner_results = synchronous_parallel_sample( + worker_set=self.env_runner_group, + max_agent_steps=self.config.total_train_batch_size, + sample_timeout_s=self.config.sample_timeout_s, + _uses_new_env_runners=True, + _return_metrics=True, + ) + else: + episodes, env_runner_results = synchronous_parallel_sample( + worker_set=self.env_runner_group, + max_env_steps=self.config.total_train_batch_size, + sample_timeout_s=self.config.sample_timeout_s, + _uses_new_env_runners=True, + _return_metrics=True, + ) + # Reduce EnvRunner metrics over the n EnvRunners. + self.metrics.aggregate(env_runner_results, key=ENV_RUNNER_RESULTS) + + with self.metrics.log_time((TIMERS, LEARNER_UPDATE_TIMER)): + learner_results = self.learner_group.update( + episodes=episodes, + timesteps={ + NUM_ENV_STEPS_SAMPLED_LIFETIME: ( + self.metrics.peek(NUM_ENV_STEPS_SAMPLED_LIFETIME) + ), + }, + ) + self.metrics.log_dict(learner_results, key=LEARNER_RESULTS) + + # Update weights - after learning on the local worker - on all + # remote workers (only those RLModules that were actually trained). + with self.metrics.log_time((TIMERS, SYNCH_WORKER_WEIGHTS_TIMER)): + self.env_runner_group.sync_weights( + from_worker_or_learner_group=self.learner_group, + policies=list(set(learner_results.keys()) - {ALL_MODULES}), + inference_only=True, + ) + + @PublicAPI + def get_module(self, module_id: ModuleID = DEFAULT_MODULE_ID) -> Optional[RLModule]: + """Returns the (single-agent) RLModule with `model_id` (None if ID not found). + + Args: + module_id: ID of the (single-agent) RLModule to return from the MARLModule + used by the local EnvRunner. + + Returns: + The RLModule found under the ModuleID key inside the local EnvRunner's + MultiRLModule. None if `module_id` doesn't exist. + """ + if self.env_runner is not None: + module = self.env_runner.module + else: + module = self.env_runner_group.foreach_env_runner( + lambda er: er.module, + remote_worker_ids=[1], + local_env_runner=False, + )[0] + + if isinstance(module, MultiRLModule): + return module.get(module_id) + else: + return module + + @PublicAPI + def add_module( + self, + module_id: ModuleID, + module_spec: RLModuleSpec, + *, + config_overrides: Optional[Dict] = None, + new_agent_to_module_mapping_fn: Optional[AgentToModuleMappingFn] = None, + new_should_module_be_updated: Optional[ShouldModuleBeUpdatedFn] = None, + add_to_learners: bool = True, + add_to_env_runners: bool = True, + add_to_eval_env_runners: bool = True, + ) -> MultiRLModuleSpec: + """Adds a new (single-agent) RLModule to this Algorithm's MARLModule. + + Note that an Algorithm has up to 3 different components to which to add + the new module to: The LearnerGroup (with n Learners), the EnvRunnerGroup + (with m EnvRunners plus a local one) and - if applicable - the eval + EnvRunnerGroup (with o EnvRunners plus a local one). + + Args: + module_id: ID of the RLModule to add to the MARLModule. + IMPORTANT: Must not contain characters that + are also not allowed in Unix/Win filesystems, such as: `<>:"/|?*`, + or a dot, space or backslash at the end of the ID. + module_spec: The SingleAgentRLModuleSpec to use for constructing the new + RLModule. + config_overrides: The `AlgorithmConfig` overrides that should apply to + the new Module, if any. + new_agent_to_module_mapping_fn: An optional (updated) AgentID to ModuleID + mapping function to use from here on. Note that already ongoing + episodes will not change their mapping but will use the old mapping till + the end of the episode. + new_should_module_be_updated: An optional sequence of ModuleIDs or a + callable taking ModuleID and SampleBatchType and returning whether the + ModuleID should be updated (trained). + If None, will keep the existing setup in place. RLModules, + whose IDs are not in the list (or for which the callable + returns False) will not be updated. + add_to_learners: Whether to add the new RLModule to the LearnerGroup + (with its n Learners). + add_to_env_runners: Whether to add the new RLModule to the EnvRunnerGroup + (with its m EnvRunners plus the local one). + add_to_eval_env_runners: Whether to add the new RLModule to the eval + EnvRunnerGroup (with its o EnvRunners plus the local one). + + Returns: + The new MultiAgentRLModuleSpec (after the RLModule has been added). + """ + validate_module_id(module_id, error=True) + + # The to-be-returned new MultiAgentRLModuleSpec. + multi_rl_module_spec = None + + if not self.config.is_multi_agent: + raise RuntimeError( + "Can't add a new RLModule to a single-agent setup! Make sure that your " + "setup is already initially multi-agent by either defining >1 " + f"RLModules in your `rl_module_spec` or assigning a ModuleID other " + f"than {DEFAULT_MODULE_ID} to your (only) RLModule." + ) + + if not any([add_to_learners, add_to_env_runners, add_to_eval_env_runners]): + raise ValueError( + "At least one of `add_to_learners`, `add_to_env_runners`, or " + "`add_to_eval_env_runners` must be set to True!" + ) + + # Add to Learners and sync weights. + if add_to_learners: + multi_rl_module_spec = self.learner_group.add_module( + module_id=module_id, + module_spec=module_spec, + config_overrides=config_overrides, + new_should_module_be_updated=new_should_module_be_updated, + ) + + # Change our config (AlgorithmConfig) to contain the new Module. + # TODO (sven): This is a hack to manipulate the AlgorithmConfig directly, + # but we'll deprecate config.policies soon anyway. + self.config._is_frozen = False + self.config.policies[module_id] = PolicySpec() + if config_overrides is not None: + self.config.multi_agent( + algorithm_config_overrides_per_module={module_id: config_overrides} + ) + if new_agent_to_module_mapping_fn is not None: + self.config.multi_agent(policy_mapping_fn=new_agent_to_module_mapping_fn) + self.config.rl_module(rl_module_spec=multi_rl_module_spec) + if new_should_module_be_updated is not None: + self.config.multi_agent(policies_to_train=new_should_module_be_updated) + self.config.freeze() + + def _add(_env_runner, _module_spec=module_spec): + # Add the RLModule to the existing one on the EnvRunner. + _env_runner.module.add_module( + module_id=module_id, module=_module_spec.build() + ) + # Update the `agent_to_module_mapping_fn` on the EnvRunner. + if new_agent_to_module_mapping_fn is not None: + _env_runner.config.multi_agent( + policy_mapping_fn=new_agent_to_module_mapping_fn, + ) + # Update the `should_module_be_updated` on the EnvRunner. Note that + # even though this information is typically not needed by the EnvRunner, + # it's good practice to keep this setting updated everywhere either way. + if new_should_module_be_updated is not None: + _env_runner.config.multi_agent( + policies_to_train=new_should_module_be_updated, + ) + return MultiRLModuleSpec.from_module(_env_runner.module) + + # Add to (training) EnvRunners and sync weights. + if add_to_env_runners: + if multi_rl_module_spec is None: + multi_rl_module_spec = self.env_runner_group.foreach_env_runner(_add)[0] + else: + self.env_runner_group.foreach_env_runner(_add) + self.env_runner_group.sync_weights( + from_worker_or_learner_group=self.learner_group, + inference_only=True, + ) + # Add to eval EnvRunners and sync weights. + if add_to_eval_env_runners is True and self.eval_env_runner_group is not None: + if multi_rl_module_spec is None: + multi_rl_module_spec = self.eval_env_runner_group.foreach_env_runner( + _add + )[0] + else: + self.eval_env_runner_group.foreach_env_runner(_add) + self.eval_env_runner_group.sync_weights( + from_worker_or_learner_group=self.learner_group, + inference_only=True, + ) + + return multi_rl_module_spec + + @PublicAPI + def remove_module( + self, + module_id: ModuleID, + *, + new_agent_to_module_mapping_fn: Optional[AgentToModuleMappingFn] = None, + new_should_module_be_updated: Optional[ShouldModuleBeUpdatedFn] = None, + remove_from_learners: bool = True, + remove_from_env_runners: bool = True, + remove_from_eval_env_runners: bool = True, + ) -> Optional[Policy]: + """Removes a new (single-agent) RLModule from this Algorithm's MARLModule. + + Args: + module_id: ID of the RLModule to remove from the MARLModule. + IMPORTANT: Must not contain characters that + are also not allowed in Unix/Win filesystems, such as: `<>:"/|?*`, + or a dot, space or backslash at the end of the ID. + new_agent_to_module_mapping_fn: An optional (updated) AgentID to ModuleID + mapping function to use from here on. Note that already ongoing + episodes will not change their mapping but will use the old mapping till + the end of the episode. + new_should_module_be_updated: An optional sequence of ModuleIDs or a + callable taking ModuleID and SampleBatchType and returning whether the + ModuleID should be updated (trained). + If None, will keep the existing setup in place. RLModules, + whose IDs are not in the list (or for which the callable + returns False) will not be updated. + remove_from_learners: Whether to remove the RLModule from the LearnerGroup + (with its n Learners). + remove_from_env_runners: Whether to remove the RLModule from the + EnvRunnerGroup (with its m EnvRunners plus the local one). + remove_from_eval_env_runners: Whether to remove the RLModule from the eval + EnvRunnerGroup (with its o EnvRunners plus the local one). + + Returns: + The new MultiAgentRLModuleSpec (after the RLModule has been removed). + """ + # The to-be-returned new MultiAgentRLModuleSpec. + multi_rl_module_spec = None + + # Remove RLModule from the LearnerGroup. + if remove_from_learners: + multi_rl_module_spec = self.learner_group.remove_module( + module_id=module_id, + new_should_module_be_updated=new_should_module_be_updated, + ) + + # Change our config (AlgorithmConfig) with the Module removed. + # TODO (sven): This is a hack to manipulate the AlgorithmConfig directly, + # but we'll deprecate config.policies soon anyway. + self.config._is_frozen = False + del self.config.policies[module_id] + self.config.algorithm_config_overrides_per_module.pop(module_id, None) + if new_agent_to_module_mapping_fn is not None: + self.config.multi_agent(policy_mapping_fn=new_agent_to_module_mapping_fn) + self.config.rl_module(rl_module_spec=multi_rl_module_spec) + if new_should_module_be_updated is not None: + self.config.multi_agent(policies_to_train=new_should_module_be_updated) + self.config.freeze() + + def _remove(_env_runner): + # Remove the RLModule from the existing one on the EnvRunner. + _env_runner.module.remove_module(module_id=module_id) + # Update the `agent_to_module_mapping_fn` on the EnvRunner. + if new_agent_to_module_mapping_fn is not None: + _env_runner.config.multi_agent( + policy_mapping_fn=new_agent_to_module_mapping_fn + ) + # Force reset all ongoing episodes on the EnvRunner to avoid having + # different ModuleIDs compute actions for the same AgentID in the same + # episode. + # TODO (sven): Create an API for this. + _env_runner._needs_initial_reset = True + + return MultiRLModuleSpec.from_module(_env_runner.module) + + # Remove from (training) EnvRunners and sync weights. + if remove_from_env_runners: + if multi_rl_module_spec is None: + multi_rl_module_spec = self.env_runner_group.foreach_env_runner( + _remove + )[0] + else: + self.env_runner_group.foreach_env_runner(_remove) + self.env_runner_group.sync_weights( + from_worker_or_learner_group=self.learner_group, + inference_only=True, + ) + + # Remove from (eval) EnvRunners and sync weights. + if ( + remove_from_eval_env_runners is True + and self.eval_env_runner_group is not None + ): + if multi_rl_module_spec is None: + multi_rl_module_spec = self.eval_env_runner_group.foreach_env_runner( + _remove + )[0] + else: + self.eval_env_runner_group.foreach_env_runner(_remove) + self.eval_env_runner_group.sync_weights( + from_worker_or_learner_group=self.learner_group, + inference_only=True, + ) + + return multi_rl_module_spec + + @OldAPIStack + def get_policy(self, policy_id: PolicyID = DEFAULT_POLICY_ID) -> Policy: + """Return policy for the specified id, or None. + + Args: + policy_id: ID of the policy to return. + """ + return self.env_runner.get_policy(policy_id) + + @PublicAPI + def get_weights(self, policies: Optional[List[PolicyID]] = None) -> dict: + """Return a dict mapping Module/Policy IDs to weights. + + Args: + policies: Optional list of policies to return weights for, + or None for all policies. + """ + # New API stack (get weights from LearnerGroup). + if self.learner_group is not None: + return self.learner_group.get_weights(module_ids=policies) + return self.env_runner.get_weights(policies) + + @PublicAPI + def set_weights(self, weights: Dict[PolicyID, dict]): + """Set RLModule/Policy weights by Module/Policy ID. + + Args: + weights: Dict mapping ModuleID/PolicyID to weights. + """ + # New API stack -> Use `set_state` API and specify the LearnerGroup state in the + # call, which will automatically take care of weight synching to all EnvRunners. + if self.learner_group is not None: + self.set_state( + { + COMPONENT_LEARNER_GROUP: { + COMPONENT_LEARNER: { + COMPONENT_RL_MODULE: weights, + }, + }, + }, + ) + self.env_runner_group.local_env_runner.set_weights(weights) + + @OldAPIStack + def add_policy( + self, + policy_id: PolicyID, + policy_cls: Optional[Type[Policy]] = None, + policy: Optional[Policy] = None, + *, + observation_space: Optional[gym.spaces.Space] = None, + action_space: Optional[gym.spaces.Space] = None, + config: Optional[Union[AlgorithmConfig, PartialAlgorithmConfigDict]] = None, + policy_state: Optional[PolicyState] = None, + policy_mapping_fn: Optional[Callable[[AgentID, EpisodeID], PolicyID]] = None, + policies_to_train: Optional[ + Union[ + Collection[PolicyID], + Callable[[PolicyID, Optional[SampleBatchType]], bool], + ] + ] = None, + add_to_env_runners: bool = True, + add_to_eval_env_runners: bool = True, + module_spec: Optional[RLModuleSpec] = None, + # Deprecated arg. + evaluation_workers=DEPRECATED_VALUE, + add_to_learners=DEPRECATED_VALUE, + ) -> Optional[Policy]: + """Adds a new policy to this Algorithm. + + Args: + policy_id: ID of the policy to add. + IMPORTANT: Must not contain characters that + are also not allowed in Unix/Win filesystems, such as: `<>:"/|?*`, + or a dot, space or backslash at the end of the ID. + policy_cls: The Policy class to use for constructing the new Policy. + Note: Only one of `policy_cls` or `policy` must be provided. + policy: The Policy instance to add to this algorithm. If not None, the + given Policy object will be directly inserted into the Algorithm's + local worker and clones of that Policy will be created on all remote + workers as well as all evaluation workers. + Note: Only one of `policy_cls` or `policy` must be provided. + observation_space: The observation space of the policy to add. + If None, try to infer this space from the environment. + action_space: The action space of the policy to add. + If None, try to infer this space from the environment. + config: The config object or overrides for the policy to add. + policy_state: Optional state dict to apply to the new + policy instance, right after its construction. + policy_mapping_fn: An optional (updated) policy mapping function + to use from here on. Note that already ongoing episodes will + not change their mapping but will use the old mapping till + the end of the episode. + policies_to_train: An optional list of policy IDs to be trained + or a callable taking PolicyID and SampleBatchType and + returning a bool (trainable or not?). + If None, will keep the existing setup in place. Policies, + whose IDs are not in the list (or for which the callable + returns False) will not be updated. + add_to_env_runners: Whether to add the new RLModule to the EnvRunnerGroup + (with its m EnvRunners plus the local one). + add_to_eval_env_runners: Whether to add the new RLModule to the eval + EnvRunnerGroup (with its o EnvRunners plus the local one). + module_spec: In the new RLModule API we need to pass in the module_spec for + the new module that is supposed to be added. Knowing the policy spec is + not sufficient. + + Returns: + The newly added policy (the copy that got added to the local + worker). If `workers` was provided, None is returned. + """ + if self.config.enable_env_runner_and_connector_v2: + raise ValueError( + "`Algorithm.add_policy()` is not supported on the new API stack w/ " + "EnvRunners! Use `Algorithm.add_module()` instead. Also see " + "`rllib/examples/self_play_league_based_with_open_spiel.py` for an " + "example." + ) + + if evaluation_workers != DEPRECATED_VALUE: + deprecation_warning( + old="Algorithm.add_policy(evaluation_workers=...)", + new="Algorithm.add_policy(add_to_eval_env_runners=...)", + error=True, + ) + if add_to_learners != DEPRECATED_VALUE: + deprecation_warning( + old="Algorithm.add_policy(add_to_learners=..)", + help="Hybrid API stack no longer supported by RLlib!", + error=True, + ) + + validate_module_id(policy_id, error=True) + + if add_to_env_runners is True: + self.env_runner_group.add_policy( + policy_id, + policy_cls, + policy, + observation_space=observation_space, + action_space=action_space, + config=config, + policy_state=policy_state, + policy_mapping_fn=policy_mapping_fn, + policies_to_train=policies_to_train, + module_spec=module_spec, + ) + + # Add to evaluation workers, if necessary. + if add_to_eval_env_runners is True and self.eval_env_runner_group is not None: + self.eval_env_runner_group.add_policy( + policy_id, + policy_cls, + policy, + observation_space=observation_space, + action_space=action_space, + config=config, + policy_state=policy_state, + policy_mapping_fn=policy_mapping_fn, + policies_to_train=policies_to_train, + module_spec=module_spec, + ) + + # Return newly added policy (from the local EnvRunner). + if add_to_env_runners: + return self.get_policy(policy_id) + elif add_to_eval_env_runners and self.eval_env_runner_group: + return self.eval_env_runner.policy_map[policy_id] + + @OldAPIStack + def remove_policy( + self, + policy_id: PolicyID = DEFAULT_POLICY_ID, + *, + policy_mapping_fn: Optional[Callable[[AgentID], PolicyID]] = None, + policies_to_train: Optional[ + Union[ + Collection[PolicyID], + Callable[[PolicyID, Optional[SampleBatchType]], bool], + ] + ] = None, + remove_from_env_runners: bool = True, + remove_from_eval_env_runners: bool = True, + # Deprecated args. + evaluation_workers=DEPRECATED_VALUE, + remove_from_learners=DEPRECATED_VALUE, + ) -> None: + """Removes a policy from this Algorithm. + + Args: + policy_id: ID of the policy to be removed. + policy_mapping_fn: An optional (updated) policy mapping function + to use from here on. Note that already ongoing episodes will + not change their mapping but will use the old mapping till + the end of the episode. + policies_to_train: An optional list of policy IDs to be trained + or a callable taking PolicyID and SampleBatchType and + returning a bool (trainable or not?). + If None, will keep the existing setup in place. Policies, + whose IDs are not in the list (or for which the callable + returns False) will not be updated. + remove_from_env_runners: Whether to remove the Policy from the + EnvRunnerGroup (with its m EnvRunners plus the local one). + remove_from_eval_env_runners: Whether to remove the RLModule from the eval + EnvRunnerGroup (with its o EnvRunners plus the local one). + """ + if evaluation_workers != DEPRECATED_VALUE: + deprecation_warning( + old="Algorithm.remove_policy(evaluation_workers=...)", + new="Algorithm.remove_policy(remove_from_eval_env_runners=...)", + error=False, + ) + remove_from_eval_env_runners = evaluation_workers + if remove_from_learners != DEPRECATED_VALUE: + deprecation_warning( + old="Algorithm.remove_policy(remove_from_learners=..)", + help="Hybrid API stack no longer supported by RLlib!", + error=True, + ) + + def fn(worker): + worker.remove_policy( + policy_id=policy_id, + policy_mapping_fn=policy_mapping_fn, + policies_to_train=policies_to_train, + ) + + # Update all EnvRunner workers. + if remove_from_env_runners: + self.env_runner_group.foreach_env_runner(fn, local_env_runner=True) + + # Update the evaluation worker set's workers, if required. + if remove_from_eval_env_runners and self.eval_env_runner_group is not None: + self.eval_env_runner_group.foreach_env_runner(fn, local_env_runner=True) + + @OldAPIStack + @staticmethod + def from_state(state: Dict) -> "Algorithm": + """Recovers an Algorithm from a state object. + + The `state` of an instantiated Algorithm can be retrieved by calling its + `get_state` method. It contains all information necessary + to create the Algorithm from scratch. No access to the original code (e.g. + configs, knowledge of the Algorithm's class, etc..) is needed. + + Args: + state: The state to recover a new Algorithm instance from. + + Returns: + A new Algorithm instance. + """ + algorithm_class: Type[Algorithm] = state.get("algorithm_class") + if algorithm_class is None: + raise ValueError( + "No `algorithm_class` key was found in given `state`! " + "Cannot create new Algorithm." + ) + # algo_class = get_trainable_cls(algo_class_name) + # Create the new algo. + config = state.get("config") + if not config: + raise ValueError("No `config` found in given Algorithm state!") + new_algo = algorithm_class(config=config) + # Set the new algo's state. + new_algo.__setstate__(state) + + # Return the new algo. + return new_algo + + @OldAPIStack + def export_policy_model( + self, + export_dir: str, + policy_id: PolicyID = DEFAULT_POLICY_ID, + onnx: Optional[int] = None, + ) -> None: + """Exports policy model with given policy_id to a local directory. + + Args: + export_dir: Writable local directory. + policy_id: Optional policy id to export. + onnx: If given, will export model in ONNX format. The + value of this parameter set the ONNX OpSet version to use. + If None, the output format will be DL framework specific. + """ + self.get_policy(policy_id).export_model(export_dir, onnx) + + @OldAPIStack + def export_policy_checkpoint( + self, + export_dir: str, + policy_id: PolicyID = DEFAULT_POLICY_ID, + ) -> None: + """Exports Policy checkpoint to a local directory and returns an AIR Checkpoint. + + Args: + export_dir: Writable local directory to store the AIR Checkpoint + information into. + policy_id: Optional policy ID to export. If not provided, will export + "default_policy". If `policy_id` does not exist in this Algorithm, + will raise a KeyError. + + Raises: + KeyError: if `policy_id` cannot be found in this Algorithm. + """ + policy = self.get_policy(policy_id) + if policy is None: + raise KeyError(f"Policy with ID {policy_id} not found in Algorithm!") + policy.export_checkpoint(export_dir) + + @override(Trainable) + def save_checkpoint(self, checkpoint_dir: str) -> None: + """Exports checkpoint to a local directory. + + The structure of an Algorithm checkpoint dir will be as follows:: + + policies/ + pol_1/ + policy_state.pkl + pol_2/ + policy_state.pkl + learner/ + learner_state.json + module_state/ + module_1/ + ... + optimizer_state/ + optimizers_module_1/ + ... + rllib_checkpoint.json + algorithm_state.pkl + + Note: `rllib_checkpoint.json` contains a "version" key (e.g. with value 0.1) + helping RLlib to remain backward compatible wrt. restoring from checkpoints from + Ray 2.0 onwards. + + Args: + checkpoint_dir: The directory where the checkpoint files will be stored. + """ + # New API stack: Delegate to the `Checkpointable` implementation of + # `save_to_path()` and return. + if self.config.enable_rl_module_and_learner: + self.save_to_path( + checkpoint_dir, + use_msgpack=self.config._use_msgpack_checkpoints, + ) + return + + checkpoint_dir = pathlib.Path(checkpoint_dir) + + state = self.__getstate__() + + # Extract policy states from worker state (Policies get their own + # checkpoint sub-dirs). + policy_states = {} + if "worker" in state and "policy_states" in state["worker"]: + policy_states = state["worker"].pop("policy_states", {}) + + # Add RLlib checkpoint version. + if self.config.enable_rl_module_and_learner: + state["checkpoint_version"] = CHECKPOINT_VERSION_LEARNER_AND_ENV_RUNNER + else: + state["checkpoint_version"] = CHECKPOINT_VERSION + + # Write state (w/o policies) to disk. + state_file = checkpoint_dir / "algorithm_state.pkl" + with open(state_file, "wb") as f: + pickle.dump(state, f) + + # Write rllib_checkpoint.json. + with open(checkpoint_dir / "rllib_checkpoint.json", "w") as f: + json.dump( + { + "type": "Algorithm", + "checkpoint_version": str(state["checkpoint_version"]), + "format": "cloudpickle", + "state_file": str(state_file), + "policy_ids": list(policy_states.keys()), + "ray_version": ray.__version__, + "ray_commit": ray.__commit__, + }, + f, + ) + + # Old API stack: Write individual policies to disk, each in their own + # sub-directory. + for pid, policy_state in policy_states.items(): + # From here on, disallow policyIDs that would not work as directory names. + validate_module_id(pid, error=True) + policy_dir = checkpoint_dir / "policies" / pid + os.makedirs(policy_dir, exist_ok=True) + policy = self.get_policy(pid) + policy.export_checkpoint(policy_dir, policy_state=policy_state) + + # If we are using the learner API (hybrid API stack) -> Save the learner group's + # state inside a "learner" subdir. Note that this is not in line with the + # new Checkpointable API, but makes this case backward compatible. + # The new Checkpointable API is only strictly applied anyways to the + # new API stack. + if self.config.enable_rl_module_and_learner: + learner_state_dir = os.path.join(checkpoint_dir, "learner") + self.learner_group.save_to_path(learner_state_dir) + + @override(Trainable) + def load_checkpoint(self, checkpoint_dir: str) -> None: + # New API stack: Delegate to the `Checkpointable` implementation of + # `restore_from_path()`. + if self.config.enable_rl_module_and_learner: + self.restore_from_path(checkpoint_dir) + else: + # Checkpoint is provided as a local directory. + # Restore from the checkpoint file or dir. + checkpoint_info = get_checkpoint_info(checkpoint_dir) + checkpoint_data = Algorithm._checkpoint_info_to_algorithm_state( + checkpoint_info + ) + self.__setstate__(checkpoint_data) + + # Call the `on_checkpoint_loaded` callback. + make_callback( + "on_checkpoint_loaded", + callbacks_objects=self.callbacks, + callbacks_functions=self.config.callbacks_on_checkpoint_loaded, + kwargs=dict(algorithm=self), + ) + + @override(Checkpointable) + def get_state( + self, + components: Optional[Union[str, Collection[str]]] = None, + *, + not_components: Optional[Union[str, Collection[str]]] = None, + **kwargs, + ) -> StateDict: + if not self.config.enable_env_runner_and_connector_v2: + raise RuntimeError( + "Algorithm.get_state() not supported on the old API stack! " + "Use Algorithm.__getstate__() instead." + ) + + state = {} + + # Get (local) EnvRunner state (w/o RLModule). + if self.config.is_online: + if self.env_runner: + if self._check_component( + COMPONENT_ENV_RUNNER, components, not_components + ): + state[COMPONENT_ENV_RUNNER] = self.env_runner.get_state( + components=self._get_subcomponents( + COMPONENT_RL_MODULE, components + ), + not_components=force_list( + self._get_subcomponents(COMPONENT_RL_MODULE, not_components) + ) + # We don't want the RLModule state from the EnvRunners (it's + # `inference_only` anyway and already provided in full by the + # Learners). + + [COMPONENT_RL_MODULE], + **kwargs, + ) + else: + if self._check_component( + COMPONENT_ENV_TO_MODULE_CONNECTOR, components, not_components + ): + state[ + COMPONENT_ENV_TO_MODULE_CONNECTOR + ] = self.env_to_module_connector.get_state() + if self._check_component( + COMPONENT_MODULE_TO_ENV_CONNECTOR, components, not_components + ): + state[ + COMPONENT_MODULE_TO_ENV_CONNECTOR + ] = self.module_to_env_connector.get_state() + # Get (local) evaluation EnvRunner state (w/o RLModule). + if self.eval_env_runner and self._check_component( + COMPONENT_EVAL_ENV_RUNNER, components, not_components + ): + state[COMPONENT_EVAL_ENV_RUNNER] = self.eval_env_runner.get_state( + components=self._get_subcomponents(COMPONENT_RL_MODULE, components), + not_components=force_list( + self._get_subcomponents(COMPONENT_RL_MODULE, not_components) + ) + # We don't want the RLModule state from the EnvRunners (it's + # `inference_only` anyway and already provided in full by the Learners). + + [COMPONENT_RL_MODULE], + **kwargs, + ) + + # Get LearnerGroup state (w/ RLModule). + if self._check_component(COMPONENT_LEARNER_GROUP, components, not_components): + state[COMPONENT_LEARNER_GROUP] = self.learner_group.get_state( + components=self._get_subcomponents(COMPONENT_LEARNER_GROUP, components), + not_components=self._get_subcomponents( + COMPONENT_LEARNER_GROUP, not_components + ), + **kwargs, + ) + + # Get entire MetricsLogger state. + # TODO (sven): Make `MetricsLogger` a Checkpointable. + state[COMPONENT_METRICS_LOGGER] = self.metrics.get_state() + + # Save current `training_iteration`. + state[TRAINING_ITERATION] = self.training_iteration + + return state + + @override(Checkpointable) + def set_state(self, state: StateDict) -> None: + # Set the (training) EnvRunners' states. + if COMPONENT_ENV_RUNNER in state: + if self.env_runner: + self.env_runner.set_state(state[COMPONENT_ENV_RUNNER]) + else: + self.env_to_module_connector.set_state( + state[COMPONENT_ENV_RUNNER][COMPONENT_ENV_TO_MODULE_CONNECTOR] + ) + self.module_to_env_connector.set_state( + state[COMPONENT_ENV_RUNNER][COMPONENT_MODULE_TO_ENV_CONNECTOR] + ) + self.env_runner_group.sync_env_runner_states( + config=self.config, + from_worker=self.env_runner, + env_to_module=self.env_to_module_connector, + module_to_env=self.module_to_env_connector, + ) + + # Set the (eval) EnvRunners' states. + if self.eval_env_runner_group and COMPONENT_EVAL_ENV_RUNNER in state: + if self.eval_env_runner: + self.eval_env_runner.set_state(state[COMPONENT_ENV_RUNNER]) + self.eval_env_runner_group.sync_env_runner_states( + config=self.evaluation_config, + from_worker=self.env_runner, + env_to_module=self.env_to_module_connector, + module_to_env=self.module_to_env_connector, + ) + + # Set the LearnerGroup's state. + if COMPONENT_LEARNER_GROUP in state: + self.learner_group.set_state(state[COMPONENT_LEARNER_GROUP]) + # Sync new weights to all EnvRunners. + self.env_runner_group.sync_weights( + from_worker_or_learner_group=self.learner_group, + inference_only=True, + ) + if self.eval_env_runner_group: + self.eval_env_runner_group.sync_weights( + from_worker_or_learner_group=self.learner_group, + inference_only=True, + ) + + # TODO (sven): Make `MetricsLogger` a Checkpointable. + if COMPONENT_METRICS_LOGGER in state: + self.metrics.set_state(state[COMPONENT_METRICS_LOGGER]) + + if TRAINING_ITERATION in state: + self._iteration = state[TRAINING_ITERATION] + + @override(Checkpointable) + def get_checkpointable_components(self) -> List[Tuple[str, "Checkpointable"]]: + components = [ + (COMPONENT_LEARNER_GROUP, self.learner_group), + ] + if self.config.is_online and self.env_runner: + components.append( + (COMPONENT_ENV_RUNNER, self.env_runner), + ) + elif self.config.is_online and not self.env_runner: + if self.env_to_module_connector: + components.append( + (COMPONENT_ENV_TO_MODULE_CONNECTOR, self.env_to_module_connector), + ) + if self.module_to_env_connector: + components.append( + (COMPONENT_MODULE_TO_ENV_CONNECTOR, self.module_to_env_connector), + ) + if self.eval_env_runner: + components.append( + ( + COMPONENT_EVAL_ENV_RUNNER, + self.eval_env_runner, + ) + ) + return components + + @override(Checkpointable) + def get_ctor_args_and_kwargs(self) -> Tuple[Tuple, Dict[str, Any]]: + return ( + (self.config.get_state(),), # *args, + {}, # **kwargs + ) + + @override(Checkpointable) + def restore_from_path(self, path, *args, **kwargs): + # Override from parent method, b/c we might have to sync the EnvRunner weights + # after having restored/loaded the LearnerGroup state. + super().restore_from_path(path, *args, **kwargs) + + # Sync EnvRunners, if LearnerGroup's checkpoint can be found in path + # or user loaded a subcomponent within the LearnerGroup (for example a module). + path = pathlib.Path(path) + if (path / COMPONENT_LEARNER_GROUP).is_dir() or ( + "component" in kwargs and COMPONENT_LEARNER_GROUP in kwargs["component"] + ): + # Make also sure, all (training) EnvRunners get the just loaded weights, but + # only the inference-only ones. + self.env_runner_group.sync_weights( + from_worker_or_learner_group=self.learner_group, + inference_only=True, + ) + + # If we have remote `EnvRunner`s but no local `EnvRunner` we have to restore states + # from path. + if self.env_runner_group.num_remote_env_runners() > 0 and not self.env_runner: + if (path / COMPONENT_ENV_TO_MODULE_CONNECTOR).is_dir(): + self.env_to_module_connector.restore_from_path( + path / COMPONENT_ENV_TO_MODULE_CONNECTOR, *args, **kwargs + ) + + if (path / COMPONENT_MODULE_TO_ENV_CONNECTOR).is_dir(): + self.module_to_env_connector.restore_from_path( + path / COMPONENT_MODULE_TO_ENV_CONNECTOR, *args, **kwargs + ) + + self.env_runner_group.sync_env_runner_states( + config=self.config, + from_worker=None, + env_steps_sampled=self.metrics.peek( + (ENV_RUNNER_RESULTS, NUM_ENV_STEPS_SAMPLED) + ), + # connector_states=connector_states, + env_to_module=self.env_to_module_connector, + module_to_env=self.module_to_env_connector, + ) + # Otherwise get the connector states from the local `EnvRunner`. + elif self.env_runner_group.num_remote_env_runners() > 0 and self.env_runner: + self.env_runner_group.sync_env_runner_states( + config=self.config, + from_worker=self.env_runner, + ) + + @override(Trainable) + def log_result(self, result: ResultDict) -> None: + # Log after the callback is invoked, so that the user has a chance + # to mutate the result. + # TODO (sven): It might not make sense to pass in the MetricsLogger at this late + # point in time. In here, the result dict has already been "compiled" (reduced) + # by the MetricsLogger and there is probably no point in adding more Stats + # here. + make_callback( + "on_train_result", + callbacks_objects=self.callbacks, + callbacks_functions=self.config.callbacks_on_train_result, + kwargs=dict( + algorithm=self, + metrics_logger=self.metrics, + result=result, + ), + ) + # Then log according to Trainable's logging logic. + Trainable.log_result(self, result) + + @override(Trainable) + def cleanup(self) -> None: + # Stop all Learners. + if hasattr(self, "learner_group") and self.learner_group is not None: + self.learner_group.shutdown() + + # Stop all aggregation actors. + if hasattr(self, "_aggregator_actor_manager") and ( + self._aggregator_actor_manager is not None + ): + self._aggregator_actor_manager.clear() + + # Stop all EnvRunners. + if hasattr(self, "env_runner_group") and self.env_runner_group is not None: + self.env_runner_group.stop() + if ( + hasattr(self, "eval_env_runner_group") + and self.eval_env_runner_group is not None + ): + self.eval_env_runner_group.stop() + + @OverrideToImplementCustomLogic + @classmethod + @override(Trainable) + def default_resource_request( + cls, config: Union[AlgorithmConfig, PartialAlgorithmConfigDict] + ) -> Union[Resources, PlacementGroupFactory]: + config = cls.get_default_config().update_from_dict(config) + config.validate() + config.freeze() + eval_config = config.get_evaluation_config_object() + eval_config.validate() + eval_config.freeze() + + if config.enable_rl_module_and_learner: + main_process = _get_main_process_bundle(config) + else: + main_process = { + "CPU": config.num_cpus_for_main_process, + "GPU": ( + 0 + if config._fake_gpus + else config.num_gpus + if not config.enable_rl_module_and_learner + else 0 + ), + } + + env_runner_bundles = _get_env_runner_bundles(config) + + if cls._should_create_evaluation_env_runners(eval_config): + eval_env_runner_bundles = _get_env_runner_bundles(eval_config) + else: + eval_env_runner_bundles = [] + + if cls._should_create_offline_evaluation_runners(eval_config): + offline_eval_runner_bundles = _get_offline_eval_runner_bundles(eval_config) + else: + offline_eval_runner_bundles = [] + + learner_bundles = [] + if config.enable_rl_module_and_learner: + learner_bundles = _get_learner_bundles(config) + + bundles = ( + [main_process] + + env_runner_bundles + + eval_env_runner_bundles + + offline_eval_runner_bundles + + learner_bundles + ) + + return PlacementGroupFactory( + bundles=bundles, + strategy=config.placement_strategy, + ) + + @DeveloperAPI + def _before_evaluate(self): + """Pre-evaluation callback.""" + pass + + @staticmethod + def _get_env_id_and_creator( + env_specifier: Union[str, EnvType, None], config: AlgorithmConfig + ) -> Tuple[Optional[str], EnvCreator]: + """Returns env_id and creator callable given original env id from config. + + Args: + env_specifier: An env class, an already tune registered env ID, a known + gym env name, or None (if no env is used). + config: The AlgorithmConfig object. + + Returns: + Tuple consisting of a) env ID string and b) env creator callable. + """ + # Environment is specified via a string. + if isinstance(env_specifier, str): + # An already registered env. + if _global_registry.contains(ENV_CREATOR, env_specifier): + return env_specifier, _global_registry.get(ENV_CREATOR, env_specifier) + + # A class path specifier. + elif "." in env_specifier: + + def env_creator_from_classpath(env_context): + try: + env_obj = from_config(env_specifier, env_context) + except ValueError: + raise EnvError( + ERR_MSG_INVALID_ENV_DESCRIPTOR.format(env_specifier) + ) + return env_obj + + return env_specifier, env_creator_from_classpath + # Try gym/PyBullet. + else: + return env_specifier, functools.partial( + _gym_env_creator, env_descriptor=env_specifier + ) + + elif isinstance(env_specifier, type): + env_id = env_specifier # .__name__ + + if config["remote_worker_envs"]: + # Check gym version (0.22 or higher?). + # If > 0.21, can't perform auto-wrapping of the given class as this + # would lead to a pickle error. + gym_version = importlib.metadata.version("gym") + if version.parse(gym_version) >= version.parse("0.22"): + raise ValueError( + "Cannot specify a gym.Env class via `config.env` while setting " + "`config.remote_worker_env=True` AND your gym version is >= " + "0.22! Try installing an older version of gym or set `config." + "remote_worker_env=False`." + ) + + @ray.remote(num_cpus=1) + class _wrapper(env_specifier): + # Add convenience `_get_spaces` and `_is_multi_agent` + # methods: + def _get_spaces(self): + return self.observation_space, self.action_space + + def _is_multi_agent(self): + from ray.rllib.env.multi_agent_env import MultiAgentEnv + + return isinstance(self, MultiAgentEnv) + + return env_id, lambda cfg: _wrapper.remote(cfg) + # gym.Env-subclass: Also go through our RLlib gym-creator. + elif issubclass(env_specifier, gym.Env): + return env_id, functools.partial( + _gym_env_creator, + env_descriptor=env_specifier, + ) + # All other env classes: Call c'tor directly. + else: + return env_id, lambda cfg: env_specifier(cfg) + + # No env -> Env creator always returns None. + elif env_specifier is None: + return None, lambda env_config: None + + else: + raise ValueError( + "{} is an invalid env specifier. ".format(env_specifier) + + "You can specify a custom env as either a class " + '(e.g., YourEnvCls) or a registered env id (e.g., "your_env").' + ) + + def _sync_filters_if_needed( + self, + *, + central_worker: EnvRunner, + workers: EnvRunnerGroup, + config: AlgorithmConfig, + ) -> None: + """Synchronizes the filter stats from `workers` to `central_worker`. + + .. and broadcasts the central_worker's filter stats back to all `workers` + (if configured). + + Args: + central_worker: The worker to sync/aggregate all `workers`' filter stats to + and from which to (possibly) broadcast the updated filter stats back to + `workers`. + workers: The EnvRunnerGroup, whose EnvRunners' filter stats should be used + for aggregation on `central_worker` and which (possibly) get updated + from `central_worker` after the sync. + config: The algorithm config instance. This is used to determine, whether + syncing from `workers` should happen at all and whether broadcasting + back to `workers` (after possible syncing) should happen. + """ + if central_worker and config.observation_filter != "NoFilter": + FilterManager.synchronize( + central_worker.filters, + workers, + update_remote=config.update_worker_filter_stats, + timeout_seconds=config.sync_filters_on_rollout_workers_timeout_s, + use_remote_data_for_update=config.use_worker_filter_stats, + ) + + @classmethod + @override(Trainable) + def resource_help(cls, config: Union[AlgorithmConfig, AlgorithmConfigDict]) -> str: + return ( + "\n\nYou can adjust the resource requests of RLlib Algorithms by calling " + "`AlgorithmConfig.env_runners(" + "num_env_runners=.., num_cpus_per_env_runner=.., " + "num_gpus_per_env_runner=.., ..)` and " + "`AgorithmConfig.learners(num_learners=.., num_gpus_per_learner=..)`. See " + "the `ray.rllib.algorithms.algorithm_config.AlgorithmConfig` classes " + "(each Algorithm has its own subclass of this class) for more info.\n\n" + f"The config of this Algorithm is: {config}" + ) + + @override(Trainable) + def get_auto_filled_metrics( + self, + now: Optional[datetime] = None, + time_this_iter: Optional[float] = None, + timestamp: Optional[int] = None, + debug_metrics_only: bool = False, + ) -> dict: + # Override this method to make sure, the `config` key of the returned results + # contains the proper Tune config dict (instead of an AlgorithmConfig object). + auto_filled = super().get_auto_filled_metrics( + now, time_this_iter, timestamp, debug_metrics_only + ) + if "config" not in auto_filled: + raise KeyError("`config` key not found in auto-filled results dict!") + + # If `config` key is no dict (but AlgorithmConfig object) -> + # make sure, it's a dict to not break Tune APIs. + if not isinstance(auto_filled["config"], dict): + assert isinstance(auto_filled["config"], AlgorithmConfig) + auto_filled["config"] = auto_filled["config"].to_dict() + return auto_filled + + @classmethod + def merge_algorithm_configs( + cls, + config1: AlgorithmConfigDict, + config2: PartialAlgorithmConfigDict, + _allow_unknown_configs: Optional[bool] = None, + ) -> AlgorithmConfigDict: + """Merges a complete Algorithm config dict with a partial override dict. + + Respects nested structures within the config dicts. The values in the + partial override dict take priority. + + Args: + config1: The complete Algorithm's dict to be merged (overridden) + with `config2`. + config2: The partial override config dict to merge on top of + `config1`. + _allow_unknown_configs: If True, keys in `config2` that don't exist + in `config1` are allowed and will be added to the final config. + + Returns: + The merged full algorithm config dict. + """ + config1 = copy.deepcopy(config1) + if "callbacks" in config2 and type(config2["callbacks"]) is dict: + deprecation_warning( + "callbacks dict interface", + "a class extending rllib.callbacks.callbacks.RLlibCallback; " + "see `rllib/examples/metrics/custom_metrics_and_callbacks.py` for an " + "example.", + error=True, + ) + + if _allow_unknown_configs is None: + _allow_unknown_configs = cls._allow_unknown_configs + return deep_update( + config1, + config2, + _allow_unknown_configs, + cls._allow_unknown_subkeys, + cls._override_all_subkeys_if_type_changes, + cls._override_all_key_list, + ) + + @staticmethod + @ExperimentalAPI + def validate_env(env: EnvType, env_context: EnvContext) -> None: + """Env validator function for this Algorithm class. + + Override this in child classes to define custom validation + behavior. + + Args: + env: The (sub-)environment to validate. This is normally a + single sub-environment (e.g. a gym.Env) within a vectorized + setup. + env_context: The EnvContext to configure the environment. + + Raises: + Exception: in case something is wrong with the given environment. + """ + pass + + def _run_one_training_iteration(self) -> Tuple[ResultDict, "TrainIterCtx"]: + """Runs one training iteration (`self.iteration` will be +1 after this). + + Calls `self.training_step()` repeatedly until the configured minimum time (sec), + minimum sample- or minimum training steps have been reached. + + Returns: + The ResultDict from the last call to `training_step()`. Note that even + though we only return the last ResultDict, the user still has full control + over the history and reduce behavior of individual metrics at the time these + metrics are logged with `self.metrics.log_...()`. + """ + with self.metrics.log_time((TIMERS, TRAINING_ITERATION_TIMER)): + # In case we are training (in a thread) parallel to evaluation, + # we may have to re-enable eager mode here (gets disabled in the + # thread). + if self.config.get("framework") == "tf2" and not tf.executing_eagerly(): + tf1.enable_eager_execution() + + has_run_once = False + # Create a step context ... + with TrainIterCtx(algo=self) as train_iter_ctx: + # .. so we can query it whether we should stop the iteration loop (e.g. + # when we have reached `min_time_s_per_iteration`). + while not train_iter_ctx.should_stop(has_run_once): + # Before training step, try to bring failed workers back. + with self.metrics.log_time((TIMERS, RESTORE_ENV_RUNNERS_TIMER)): + restored = self.restore_env_runners(self.env_runner_group) + # Fire the callback for re-created EnvRunners. + if restored: + self._make_on_env_runners_recreated_callbacks( + config=self.config, + env_runner_group=self.env_runner_group, + restored_env_runner_indices=restored, + ) + + # Try to train one step. + with self.metrics.log_time((TIMERS, TRAINING_STEP_TIMER)): + training_step_return_value = self.training_step() + has_run_once = True + + # On the new API stack, results should NOT be returned anymore as + # a dict, but purely logged through the `MetricsLogger` API. This + # way, we make sure to never miss a single stats/counter/timer + # when calling `self.training_step()` more than once within the same + # iteration. + if training_step_return_value is not None: + raise ValueError( + "`Algorithm.training_step()` should NOT return a result " + "dict anymore on the new API stack! Instead, log all " + "results, timers, counters through the `self.metrics` " + "(MetricsLogger) instance of the Algorithm and return " + "None. The logged results are compiled automatically into " + "one single result dict per training iteration." + ) + + # TODO (sven): Resolve this metric through log_time's future + # ability to compute throughput. + self.metrics.log_value( + NUM_TRAINING_STEP_CALLS_PER_ITERATION, + 1, + reduce="sum", + clear_on_reduce=True, + ) + + if self.config.num_aggregator_actors_per_learner: + remote_aggregator_metrics: RemoteCallResults = ( + self._aggregator_actor_manager.fetch_ready_async_reqs( + timeout_seconds=0.0, + return_obj_refs=False, + tags="metrics", + ) + ) + self._aggregator_actor_manager.foreach_actor_async( + func=lambda actor: actor.get_metrics(), + tag="metrics", + ) + + FaultTolerantActorManager.handle_remote_call_result_errors( + remote_aggregator_metrics, + ignore_ray_errors=False, + ) + self.metrics.aggregate( + [res.get() for res in remote_aggregator_metrics.result_or_errors], + key=AGGREGATOR_ACTOR_RESULTS, + ) + + # Only here (at the end of the iteration), compile the results into a single result dict. + # Calling compile here reduces the metrics into single values and adds throughputs to the results where applicable. + return self.metrics.compile(), train_iter_ctx + + def _run_one_offline_evaluation(self): + """Runs offline evaluation step via `self.offline_evaluate()` and handling runner + failures. + + Returns: + The results dict from the offline evaluation call. + """ + # Restore crashed offline evaluation runners. + if self.offline_eval_runner_group is not None: + with self.metrics.log_time((TIMERS, RESTORE_OFFLINE_EVAL_RUNNERS_TIMER)): + restored = self.restore_offline_eval_runners( + self.offline_eval_runner_group + ) + if restored: + # Fire the callback for re-created workers. + make_callback( + "on_offline_eval_runners_recreated", + callbacks_objects=self.callbacks, + callbacks_functions=( + self.config.callbacks_on_offline_eval_runners_recreated + ), + kwargs=dict( + algorithm=self, + env_runner_group=self.offline_eval_runner_group, + env_runner_indices=restored, + ), + ) + + # Run one offline evaluation and time it. + with self.metrics.log_time((TIMERS, OFFLINE_EVALUATION_ITERATION_TIMER)): + eval_results = self.evaluate_offline() + + # After evaluation, do a round of health check on remote eval runners to see if + # any of the failed runners are back. + if self.offline_eval_runner_group is not None: + # Add number of healthy evaluation runners after this iteration. + eval_results[ + "num_healthy_offline_eval_runners" + ] = self.offline_eval_runner_group.num_healthy_remote_runners + eval_results[ + "offline_runners_actor_manager_num_outstanding_async_reqs" + ] = self.offline_eval_runner_group.num_in_flight_async_reqs + eval_results[ + "num_remote_offline_eval_runners_restarts" + ] = self.offline_eval_runner_group.num_remote_runner_restarts + + return {EVALUATION_RESULTS: eval_results} + + def _run_one_evaluation( + self, + parallel_train_future: Optional[concurrent.futures.ThreadPoolExecutor] = None, + ) -> ResultDict: + """Runs evaluation step via `self.evaluate()` and handling worker failures. + + Args: + parallel_train_future: In case, we are training and avaluating in parallel, + this arg carries the currently running ThreadPoolExecutor object that + runs the training iteration. Use `parallel_train_future.done()` to + check, whether the parallel training job has completed and + `parallel_train_future.result()` to get its return values. + + Returns: + The results dict from the evaluation call. + """ + if self.eval_env_runner_group is not None: + if self.config.enable_env_runner_and_connector_v2: + with self.metrics.log_time((TIMERS, RESTORE_EVAL_ENV_RUNNERS_TIMER)): + restored = self.restore_env_runners(self.eval_env_runner_group) + else: + with self._timers["restore_eval_workers"]: + restored = self.restore_env_runners(self.eval_env_runner_group) + # Fire the callback for re-created EnvRunners. + if restored: + self._make_on_env_runners_recreated_callbacks( + config=self.evaluation_config, + env_runner_group=self.eval_env_runner_group, + restored_env_runner_indices=restored, + ) + + # Run `self.evaluate()` only once per training iteration. + if self.config.enable_env_runner_and_connector_v2: + with self.metrics.log_time((TIMERS, EVALUATION_ITERATION_TIMER)): + eval_results = self.evaluate( + parallel_train_future=parallel_train_future + ) + else: + with self._timers[EVALUATION_ITERATION_TIMER]: + eval_results = self.evaluate( + parallel_train_future=parallel_train_future + ) + self._timers[EVALUATION_ITERATION_TIMER].push_units_processed( + self._counters[NUM_ENV_STEPS_SAMPLED_FOR_EVALUATION_THIS_ITER] + ) + + # After evaluation, do a round of health check on remote eval workers to see if + # any of the failed workers are back. + if self.eval_env_runner_group is not None: + # Add number of healthy evaluation workers after this iteration. + eval_results[ + "num_healthy_workers" + ] = self.eval_env_runner_group.num_healthy_remote_workers() + eval_results[ + "actor_manager_num_outstanding_async_reqs" + ] = self.eval_env_runner_group.num_in_flight_async_reqs() + eval_results[ + "num_remote_worker_restarts" + ] = self.eval_env_runner_group.num_remote_worker_restarts() + + return {EVALUATION_RESULTS: eval_results} + + def _run_one_training_iteration_and_evaluation_in_parallel( + self, + ) -> Tuple[ResultDict, ResultDict, "TrainIterCtx"]: + """Runs one training iteration and one evaluation step in parallel. + + First starts the training iteration (via `self._run_one_training_iteration()`) + within a ThreadPoolExecutor, then runs the evaluation step in parallel. + In auto-duration mode (config.evaluation_duration=auto), makes sure the + evaluation step takes roughly the same time as the training iteration. + + Returns: + A tuple containing the training results, the evaluation results, and + the `TrainIterCtx` object returned by the training call. + """ + with concurrent.futures.ThreadPoolExecutor() as executor: + + if self.config.enable_env_runner_and_connector_v2: + parallel_train_future = executor.submit( + lambda: self._run_one_training_iteration() + ) + else: + parallel_train_future = executor.submit( + lambda: self._run_one_training_iteration_old_api_stack() + ) + + # Pass the train_future into `self._run_one_evaluation()` to allow it + # to run exactly as long as the training iteration takes in case + # evaluation_duration=auto. + evaluation_results = self._run_one_evaluation( + parallel_train_future=parallel_train_future + ) + # Collect the training results from the future. + train_results, train_iter_ctx = parallel_train_future.result() + + return train_results, evaluation_results, train_iter_ctx + + def _run_offline_evaluation_old_api_stack(self): + """Runs offline evaluation via `OfflineEvaluator.estimate_on_dataset()` API. + + This method will be used when `evaluation_dataset` is provided. + Note: This will only work if the policy is a single agent policy. + + Returns: + The results dict from the offline evaluation call. + """ + assert len(self.env_runner_group.local_env_runner.policy_map) == 1 + + parallelism = self.evaluation_config.evaluation_num_env_runners or 1 + offline_eval_results = {"off_policy_estimator": {}} + for evaluator_name, offline_evaluator in self.reward_estimators.items(): + offline_eval_results["off_policy_estimator"][ + evaluator_name + ] = offline_evaluator.estimate_on_dataset( + self.evaluation_dataset, + n_parallelism=parallelism, + ) + return offline_eval_results + + @classmethod + def _should_create_evaluation_env_runners(cls, eval_config: "AlgorithmConfig"): + """Determines whether we need to create evaluation workers. + + Returns False if we need to run offline evaluation + (with ope.estimate_on_dastaset API) or when local worker is to be used for + evaluation. Note: We only use estimate_on_dataset API with bandits for now. + That is when ope_split_batch_by_episode is False. + TODO: In future we will do the same for episodic RL OPE. + """ + run_offline_evaluation = ( + eval_config.off_policy_estimation_methods + and not eval_config.ope_split_batch_by_episode + ) + return not run_offline_evaluation and ( + eval_config.evaluation_num_env_runners > 0 + or eval_config.evaluation_interval + ) + + # TODO (simon, sven): Flexibilize the different env/offline components and move + # away from the currently hard-coded: (1) eval `EnvRunnerGroup`, (2) OfflineData + # and (3) `OfflineEvaluationRunnerGroup`. + @classmethod + def _should_create_offline_evaluation_runners(cls, eval_config: "AlgorithmConfig"): + """Determines whether we need to create offline evaluation workers.""" + + return ( + eval_config.offline_evaluation_interval is not None + or eval_config.num_offline_eval_runners > 0 + ) + + def _compile_iteration_results(self, *, train_results, eval_results): + # Error if users still use `self._timers`. + if self._timers: + raise ValueError( + "`Algorithm._timers` is no longer supported on the new API stack! " + "Instead, use `Algorithm.metrics.log_time(" + "[some key (str) or nested key sequence (tuple)])`, e.g. inside your " + "custom `training_step()` method, do: " + "`with self.metrics.log_time(('timers', 'my_block_to_be_timed')): ...`" + ) + + # Return dict (shallow copy of `train_results`). + results: ResultDict = train_results.copy() + # Backward compatibility `NUM_ENV_STEPS_SAMPLED_LIFETIME` is now: + # `ENV_RUNNER_RESULTS/NUM_ENV_STEPS_SAMPLED_LIFETIME`. + results[NUM_ENV_STEPS_SAMPLED_LIFETIME] = results.get( + ENV_RUNNER_RESULTS, {} + ).get(NUM_ENV_STEPS_SAMPLED_LIFETIME, 0) + + # Evaluation results. + if eval_results: + assert ( + isinstance(eval_results, dict) + and len(eval_results) == 1 + and EVALUATION_RESULTS in eval_results + ) + results.update(eval_results) + + # EnvRunner actors fault tolerance stats. + if self.env_runner_group: + results[FAULT_TOLERANCE_STATS] = { + "num_healthy_workers": ( + self.env_runner_group.num_healthy_remote_workers() + ), + "num_remote_worker_restarts": ( + self.env_runner_group.num_remote_worker_restarts() + ), + } + results["env_runner_group"] = { + "actor_manager_num_outstanding_async_reqs": ( + self.env_runner_group.num_in_flight_async_reqs() + ), + } + + return results + + def _make_on_env_runners_recreated_callbacks( + self, + *, + config, + env_runner_group, + restored_env_runner_indices, + ): + make_callback( + "on_env_runners_recreated", + callbacks_objects=self.callbacks, + callbacks_functions=(config.callbacks_on_env_runners_recreated), + kwargs=dict( + algorithm=self, + env_runner_group=env_runner_group, + env_runner_indices=restored_env_runner_indices, + is_evaluation=config.in_evaluation, + ), + ) + # TODO (sven): Deprecate this call. + make_callback( + "on_workers_recreated", + callbacks_objects=self.callbacks, + kwargs=dict( + algorithm=self, + worker_set=env_runner_group, + worker_ids=restored_env_runner_indices, + is_evaluation=config.in_evaluation, + ), + ) + + def __repr__(self): + if self.config.enable_rl_module_and_learner: + return ( + f"{type(self).__name__}(" + f"env={self.config.env}; env-runners={self.config.num_env_runners}; " + f"learners={self.config.num_learners}; " + f"multi-agent={self.config.is_multi_agent}" + f")" + ) + else: + return type(self).__name__ + + @property + def env_runner(self): + """The local EnvRunner instance within the algo's EnvRunnerGroup.""" + if self.env_runner_group: + return self.env_runner_group.local_env_runner + return None + + @property + def eval_env_runner(self): + """The local EnvRunner instance within the algo's evaluation EnvRunnerGroup.""" + if self.eval_env_runner_group: + return self.eval_env_runner_group.local_env_runner + return None + + def _record_usage(self, config): + """Record the framework and algorithm used. + + Args: + config: Algorithm config dict. + """ + record_extra_usage_tag(TagKey.RLLIB_FRAMEWORK, config["framework"]) + record_extra_usage_tag(TagKey.RLLIB_NUM_WORKERS, str(config["num_env_runners"])) + alg = self.__class__.__name__ + # We do not want to collect user defined algorithm names. + if alg not in ALL_ALGORITHMS: + alg = "USER_DEFINED" + record_extra_usage_tag(TagKey.RLLIB_ALGORITHM, alg) + + @OldAPIStack + def _export_model( + self, export_formats: List[str], export_dir: str + ) -> Dict[str, str]: + ExportFormat.validate(export_formats) + exported = {} + if ExportFormat.CHECKPOINT in export_formats: + path = os.path.join(export_dir, ExportFormat.CHECKPOINT) + self.export_policy_checkpoint(path) + exported[ExportFormat.CHECKPOINT] = path + if ExportFormat.MODEL in export_formats: + path = os.path.join(export_dir, ExportFormat.MODEL) + self.export_policy_model(path) + exported[ExportFormat.MODEL] = path + if ExportFormat.ONNX in export_formats: + path = os.path.join(export_dir, ExportFormat.ONNX) + self.export_policy_model(path, onnx=int(os.getenv("ONNX_OPSET", "11"))) + exported[ExportFormat.ONNX] = path + return exported + + @OldAPIStack + def __getstate__(self) -> Dict: + """Returns current state of Algorithm, sufficient to restore it from scratch. + + Returns: + The current state dict of this Algorithm, which can be used to sufficiently + restore the algorithm from scratch without any other information. + """ + if self.config.enable_env_runner_and_connector_v2: + raise RuntimeError( + "Algorithm.__getstate__() not supported anymore on the new API stack! " + "Use Algorithm.get_state() instead." + ) + + # Add config to state so complete Algorithm can be reproduced w/o it. + state = { + "algorithm_class": type(self), + "config": self.config.get_state(), + } + + if hasattr(self, "env_runner_group"): + state["worker"] = self.env_runner_group.local_env_runner.get_state() + + # Also store eval `policy_mapping_fn` (in case it's different from main + # one). Note, the new `EnvRunner API` has no policy mapping function. + if ( + hasattr(self, "eval_env_runner_group") + and self.eval_env_runner_group is not None + ): + state["eval_policy_mapping_fn"] = self.eval_env_runner.policy_mapping_fn + + # Save counters. + state["counters"] = self._counters + + # TODO: Experimental functionality: Store contents of replay buffer + # to checkpoint, only if user has configured this. + if self.local_replay_buffer is not None and self.config.get( + "store_buffer_in_checkpoints" + ): + state["local_replay_buffer"] = self.local_replay_buffer.get_state() + + # Save current `training_iteration`. + state[TRAINING_ITERATION] = self.training_iteration + + return state + + @OldAPIStack + def __setstate__(self, state) -> None: + """Sets the algorithm to the provided state. + + Args: + state: The state dict to restore this Algorithm instance to. `state` may + have been returned by a call to an Algorithm's `__getstate__()` method. + """ + if self.config.enable_env_runner_and_connector_v2: + raise RuntimeError( + "Algorithm.__setstate__() not supported anymore on the new API stack! " + "Use Algorithm.set_state() instead." + ) + + # Old API stack: The local worker stores its state (together with all the + # Module information) in state['worker']. + if hasattr(self, "env_runner_group") and "worker" in state and state["worker"]: + self.env_runner.set_state(state["worker"]) + remote_state_ref = ray.put(state["worker"]) + self.env_runner_group.foreach_env_runner( + lambda w: w.set_state(ray.get(remote_state_ref)), + local_env_runner=False, + ) + if self.eval_env_runner_group: + # Avoid `state` being pickled into the remote function below. + _eval_policy_mapping_fn = state.get("eval_policy_mapping_fn") + + def _setup_eval_worker(w): + w.set_state(ray.get(remote_state_ref)) + # Override `policy_mapping_fn` as it might be different for eval + # workers. + w.set_policy_mapping_fn(_eval_policy_mapping_fn) + + # If evaluation workers are used, also restore the policies + # there in case they are used for evaluation purpose. + self.eval_env_runner_group.foreach_env_runner(_setup_eval_worker) + + # Restore replay buffer data. + if self.local_replay_buffer is not None: + # TODO: Experimental functionality: Restore contents of replay + # buffer from checkpoint, only if user has configured this. + if self.config.store_buffer_in_checkpoints: + if "local_replay_buffer" in state: + self.local_replay_buffer.set_state(state["local_replay_buffer"]) + else: + logger.warning( + "`store_buffer_in_checkpoints` is True, but no replay " + "data found in state!" + ) + elif "local_replay_buffer" in state and log_once( + "no_store_buffer_in_checkpoints_but_data_found" + ): + logger.warning( + "`store_buffer_in_checkpoints` is False, but some replay " + "data found in state!" + ) + + if "counters" in state: + self._counters = state["counters"] + + if TRAINING_ITERATION in state: + self._iteration = state[TRAINING_ITERATION] + + @OldAPIStack + @staticmethod + def _checkpoint_info_to_algorithm_state( + checkpoint_info: dict, + *, + policy_ids: Optional[Collection[PolicyID]] = None, + policy_mapping_fn: Optional[Callable[[AgentID, EpisodeID], PolicyID]] = None, + policies_to_train: Optional[ + Union[ + Collection[PolicyID], + Callable[[PolicyID, Optional[SampleBatchType]], bool], + ] + ] = None, + ) -> Dict: + """Converts a checkpoint info or object to a proper Algorithm state dict. + + The returned state dict can be used inside self.__setstate__(). + + Args: + checkpoint_info: A checkpoint info dict as returned by + `ray.rllib.utils.checkpoints.get_checkpoint_info( + [checkpoint dir or AIR Checkpoint])`. + policy_ids: Optional list/set of PolicyIDs. If not None, only those policies + listed here will be included in the returned state. Note that + state items such as filters, the `is_policy_to_train` function, as + well as the multi-agent `policy_ids` dict will be adjusted as well, + based on this arg. + policy_mapping_fn: An optional (updated) policy mapping function + to include in the returned state. + policies_to_train: An optional list of policy IDs to be trained + or a callable taking PolicyID and SampleBatchType and + returning a bool (trainable or not?) to include in the returned state. + + Returns: + The state dict usable within the `self.__setstate__()` method. + """ + if checkpoint_info["type"] != "Algorithm": + raise ValueError( + "`checkpoint` arg passed to " + "`Algorithm._checkpoint_info_to_algorithm_state()` must be an " + f"Algorithm checkpoint (but is {checkpoint_info['type']})!" + ) + + msgpack = None + if checkpoint_info.get("format") == "msgpack": + msgpack = try_import_msgpack(error=True) + + with open(checkpoint_info["state_file"], "rb") as f: + if msgpack is not None: + data = f.read() + state = msgpack.unpackb(data, raw=False) + else: + state = pickle.load(f) + + # Old API stack: Policies are in separate sub-dirs. + if ( + checkpoint_info["checkpoint_version"] > version.Version("0.1") + and state.get("worker") is not None + and state.get("worker") + ): + worker_state = state["worker"] + + # Retrieve the set of all required policy IDs. + policy_ids = set( + policy_ids if policy_ids is not None else worker_state["policy_ids"] + ) + + # Remove those policies entirely from filters that are not in + # `policy_ids`. + worker_state["filters"] = { + pid: filter + for pid, filter in worker_state["filters"].items() + if pid in policy_ids + } + + # Get Algorithm class. + if isinstance(state["algorithm_class"], str): + # Try deserializing from a full classpath. + # Or as a last resort: Tune registered algorithm name. + state["algorithm_class"] = deserialize_type( + state["algorithm_class"] + ) or get_trainable_cls(state["algorithm_class"]) + # Compile actual config object. + default_config = state["algorithm_class"].get_default_config() + if isinstance(default_config, AlgorithmConfig): + new_config = default_config.update_from_dict(state["config"]) + else: + new_config = Algorithm.merge_algorithm_configs( + default_config, state["config"] + ) + + # Remove policies from multiagent dict that are not in `policy_ids`. + new_policies = new_config.policies + if isinstance(new_policies, (set, list, tuple)): + new_policies = {pid for pid in new_policies if pid in policy_ids} + else: + new_policies = { + pid: spec for pid, spec in new_policies.items() if pid in policy_ids + } + new_config.multi_agent( + policies=new_policies, + policies_to_train=policies_to_train, + **( + {"policy_mapping_fn": policy_mapping_fn} + if policy_mapping_fn is not None + else {} + ), + ) + state["config"] = new_config + + # Prepare local `worker` state to add policies' states into it, + # read from separate policy checkpoint files. + worker_state["policy_states"] = {} + for pid in policy_ids: + policy_state_file = os.path.join( + checkpoint_info["checkpoint_dir"], + "policies", + pid, + "policy_state." + + ("msgpck" if checkpoint_info["format"] == "msgpack" else "pkl"), + ) + if not os.path.isfile(policy_state_file): + raise ValueError( + "Given checkpoint does not seem to be valid! No policy " + f"state file found for PID={pid}. " + f"The file not found is: {policy_state_file}." + ) + + with open(policy_state_file, "rb") as f: + if msgpack is not None: + worker_state["policy_states"][pid] = msgpack.load(f) + else: + worker_state["policy_states"][pid] = pickle.load(f) + + # These two functions are never serialized in a msgpack checkpoint (which + # does not store code, unlike a cloudpickle checkpoint). Hence the user has + # to provide them with the `Algorithm.from_checkpoint()` call. + if policy_mapping_fn is not None: + worker_state["policy_mapping_fn"] = policy_mapping_fn + if ( + policies_to_train is not None + # `policies_to_train` might be left None in case all policies should be + # trained. + or worker_state["is_policy_to_train"] == NOT_SERIALIZABLE + ): + worker_state["is_policy_to_train"] = policies_to_train + + if state["config"].enable_rl_module_and_learner: + state["learner_state_dir"] = os.path.join( + checkpoint_info["checkpoint_dir"], "learner" + ) + + return state + + @OldAPIStack + def _create_local_replay_buffer_if_necessary( + self, config: PartialAlgorithmConfigDict + ) -> Optional[MultiAgentReplayBuffer]: + """Create a MultiAgentReplayBuffer instance if necessary. + + Args: + config: Algorithm-specific configuration data. + + Returns: + MultiAgentReplayBuffer instance based on algorithm config. + None, if local replay buffer is not needed. + """ + if not config.get("replay_buffer_config") or config["replay_buffer_config"].get( + "no_local_replay_buffer" + ): + return + + # Add parameters, if necessary. + if "EpisodeReplayBuffer" in config["replay_buffer_config"]["type"]: + # TODO (simon): Subclassing needs a proper class and therefore + # we need at this moment the string checking. Because we add + # this keyword argument the old stack ReplayBuffer constructors + # will exit with an error b/c tje keyword argument is unknown to them. + config["replay_buffer_config"][ + "metrics_num_episodes_for_smoothing" + ] = self.config.metrics_num_episodes_for_smoothing + + return from_config(ReplayBuffer, config["replay_buffer_config"]) + + @OldAPIStack + def _run_one_training_iteration_old_api_stack(self): + with self._timers[TRAINING_ITERATION_TIMER]: + if self.config.get("framework") == "tf2" and not tf.executing_eagerly(): + tf1.enable_eager_execution() + + results = {} + training_step_results = None + with TrainIterCtx(algo=self) as train_iter_ctx: + while not train_iter_ctx.should_stop(training_step_results): + with self._timers["restore_workers"]: + restored = self.restore_env_runners(self.env_runner_group) + # Fire the callback for re-created EnvRunners. + if restored: + self._make_on_env_runners_recreated_callbacks( + config=self.config, + env_runner_group=self.env_runner_group, + restored_env_runner_indices=restored, + ) + + with self._timers[TRAINING_STEP_TIMER]: + training_step_results = self.training_step() + + if training_step_results: + results = training_step_results + + return results, train_iter_ctx + + @OldAPIStack + def _compile_iteration_results_old_api_stack( + self, *, episodes_this_iter, step_ctx, iteration_results + ): + # Results to be returned. + results: ResultDict = {} + + # Evaluation results. + if "evaluation" in iteration_results: + eval_results = iteration_results.pop("evaluation") + iteration_results.pop(EVALUATION_RESULTS, None) + results["evaluation"] = results[EVALUATION_RESULTS] = eval_results + + # Custom metrics and episode media. + results["custom_metrics"] = iteration_results.pop("custom_metrics", {}) + results["episode_media"] = iteration_results.pop("episode_media", {}) + + # Learner info. + results["info"] = {LEARNER_INFO: iteration_results} + + # Calculate how many (if any) of older, historical episodes we have to add to + # `episodes_this_iter` in order to reach the required smoothing window. + episodes_for_metrics = episodes_this_iter[:] + missing = self.config.metrics_num_episodes_for_smoothing - len( + episodes_this_iter + ) + # We have to add some older episodes to reach the smoothing window size. + if missing > 0: + episodes_for_metrics = self._episode_history[-missing:] + episodes_this_iter + assert ( + len(episodes_for_metrics) + <= self.config.metrics_num_episodes_for_smoothing + ) + # Note that when there are more than `metrics_num_episodes_for_smoothing` + # episodes in `episodes_for_metrics`, leave them as-is. In this case, we'll + # compute the stats over that larger number. + + # Add new episodes to our history and make sure it doesn't grow larger than + # needed. + self._episode_history.extend(episodes_this_iter) + self._episode_history = self._episode_history[ + -self.config.metrics_num_episodes_for_smoothing : + ] + results[ENV_RUNNER_RESULTS] = summarize_episodes( + episodes_for_metrics, + episodes_this_iter, + self.config.keep_per_episode_custom_metrics, + ) + + results[ + "num_healthy_workers" + ] = self.env_runner_group.num_healthy_remote_workers() + results[ + "actor_manager_num_outstanding_async_reqs" + ] = self.env_runner_group.num_in_flight_async_reqs() + results[ + "num_remote_worker_restarts" + ] = self.env_runner_group.num_remote_worker_restarts() + + # Train-steps- and env/agent-steps this iteration. + for c in [ + NUM_AGENT_STEPS_SAMPLED, + NUM_AGENT_STEPS_TRAINED, + NUM_ENV_STEPS_SAMPLED, + NUM_ENV_STEPS_TRAINED, + ]: + results[c] = self._counters[c] + time_taken_sec = step_ctx.get_time_taken_sec() + if self.config.count_steps_by == "agent_steps": + results[NUM_AGENT_STEPS_SAMPLED + "_this_iter"] = step_ctx.sampled + results[NUM_AGENT_STEPS_TRAINED + "_this_iter"] = step_ctx.trained + results[NUM_AGENT_STEPS_SAMPLED + "_throughput_per_sec"] = ( + step_ctx.sampled / time_taken_sec + ) + results[NUM_AGENT_STEPS_TRAINED + "_throughput_per_sec"] = ( + step_ctx.trained / time_taken_sec + ) + # TODO: For CQL and other algos, count by trained steps. + results["timesteps_total"] = self._counters[NUM_AGENT_STEPS_SAMPLED] + else: + results[NUM_ENV_STEPS_SAMPLED + "_this_iter"] = step_ctx.sampled + results[NUM_ENV_STEPS_TRAINED + "_this_iter"] = step_ctx.trained + results[NUM_ENV_STEPS_SAMPLED + "_throughput_per_sec"] = ( + step_ctx.sampled / time_taken_sec + ) + results[NUM_ENV_STEPS_TRAINED + "_throughput_per_sec"] = ( + step_ctx.trained / time_taken_sec + ) + # TODO: For CQL and other algos, count by trained steps. + results["timesteps_total"] = self._counters[NUM_ENV_STEPS_SAMPLED] + + # Forward compatibility with new API stack. + results[NUM_ENV_STEPS_SAMPLED_LIFETIME] = results["timesteps_total"] + results[NUM_AGENT_STEPS_SAMPLED_LIFETIME] = self._counters[ + NUM_AGENT_STEPS_SAMPLED + ] + + # TODO: Backward compatibility. + results[STEPS_TRAINED_THIS_ITER_COUNTER] = step_ctx.trained + results["agent_timesteps_total"] = self._counters[NUM_AGENT_STEPS_SAMPLED] + + # Process timer results. + timers = {} + for k, timer in self._timers.items(): + timers["{}_time_ms".format(k)] = round(timer.mean * 1000, 3) + if timer.has_units_processed(): + timers["{}_throughput".format(k)] = round(timer.mean_throughput, 3) + results["timers"] = timers + + # Process counter results. + counters = {} + for k, counter in self._counters.items(): + counters[k] = counter + results["counters"] = counters + # TODO: Backward compatibility. + results["info"].update(counters) + + return results + + @OldAPIStack + @Deprecated( + help="`Algorithm.compute_single_action` should no longer be used. Get the " + "RLModule instance through `Algorithm.get_module([module ID])`, then compute " + "actions through `RLModule.forward_inference({'obs': [obs batch]})`.", + error=False, + ) + def compute_single_action( + self, + observation: Optional[TensorStructType] = None, + state: Optional[List[TensorStructType]] = None, + *, + prev_action: Optional[TensorStructType] = None, + prev_reward: Optional[float] = None, + info: Optional[EnvInfoDict] = None, + input_dict: Optional[SampleBatch] = None, + policy_id: PolicyID = DEFAULT_POLICY_ID, + full_fetch: bool = False, + explore: Optional[bool] = None, + timestep: Optional[int] = None, + episode=None, + unsquash_action: Optional[bool] = None, + clip_action: Optional[bool] = None, + ) -> Union[ + TensorStructType, + Tuple[TensorStructType, List[TensorType], Dict[str, TensorType]], + ]: + if unsquash_action is None: + unsquash_action = self.config.normalize_actions + elif clip_action is None: + clip_action = self.config.clip_actions + + err_msg = ( + "Provide either `input_dict` OR [`observation`, ...] as " + "args to `Algorithm.compute_single_action()`!" + ) + if input_dict is not None: + assert ( + observation is None + and prev_action is None + and prev_reward is None + and state is None + ), err_msg + observation = input_dict[Columns.OBS] + else: + assert observation is not None, err_msg + + policy = self.get_policy(policy_id) + if policy is None: + raise KeyError( + f"PolicyID '{policy_id}' not found in PolicyMap of the " + f"Algorithm's local worker!" + ) + pp = policy.agent_connectors[ObsPreprocessorConnector] + + if not isinstance(observation, (np.ndarray, dict, tuple)): + try: + observation = np.asarray(observation) + except Exception: + raise ValueError( + f"Observation type {type(observation)} cannot be converted to " + f"np.ndarray." + ) + if pp: + assert len(pp) == 1, "Only one preprocessor should be in the pipeline" + pp = pp[0] + + if not pp.is_identity(): + pp.in_eval() + if observation is not None: + _input_dict = {Columns.OBS: observation} + elif input_dict is not None: + _input_dict = {Columns.OBS: input_dict[Columns.OBS]} + else: + raise ValueError( + "Either observation or input_dict must be provided." + ) + + acd = AgentConnectorDataType("0", "0", _input_dict) + pp.reset(env_id="0") + ac_o = pp([acd])[0] + observation = ac_o.data[Columns.OBS] + + if input_dict is not None: + input_dict[Columns.OBS] = observation + action, state, extra = policy.compute_single_action( + input_dict=input_dict, + explore=explore, + timestep=timestep, + episode=episode, + ) + else: + action, state, extra = policy.compute_single_action( + obs=observation, + state=state, + prev_action=prev_action, + prev_reward=prev_reward, + info=info, + explore=explore, + timestep=timestep, + episode=episode, + ) + + if unsquash_action: + action = space_utils.unsquash_action(action, policy.action_space_struct) + elif clip_action: + action = space_utils.clip_action(action, policy.action_space_struct) + + if state or full_fetch: + return action, state, extra + else: + return action + + @OldAPIStack + @Deprecated( + help="`Algorithm.compute_actions` should no longer be used. Get the RLModule " + "instance through `Algorithm.get_module([module ID])`, then compute actions " + "through `RLModule.forward_inference({'obs': [obs batch]})`.", + error=False, + ) + def compute_actions( + self, + observations: TensorStructType, + state: Optional[List[TensorStructType]] = None, + *, + prev_action: Optional[TensorStructType] = None, + prev_reward: Optional[TensorStructType] = None, + info: Optional[EnvInfoDict] = None, + policy_id: PolicyID = DEFAULT_POLICY_ID, + full_fetch: bool = False, + explore: Optional[bool] = None, + timestep: Optional[int] = None, + episodes=None, + unsquash_actions: Optional[bool] = None, + clip_actions: Optional[bool] = None, + ): + if unsquash_actions is None: + unsquash_actions = self.config.normalize_actions + elif clip_actions is None: + clip_actions = self.config.clip_actions + + state_defined = state is not None + policy = self.get_policy(policy_id) + filtered_obs, filtered_state = [], [] + for agent_id, ob in observations.items(): + worker = self.env_runner_group.local_env_runner + if worker.preprocessors.get(policy_id) is not None: + preprocessed = worker.preprocessors[policy_id].transform(ob) + else: + preprocessed = ob + filtered = worker.filters[policy_id](preprocessed, update=False) + filtered_obs.append(filtered) + if state is None: + continue + elif agent_id in state: + filtered_state.append(state[agent_id]) + else: + filtered_state.append(policy.get_initial_state()) + + obs_batch = np.stack(filtered_obs) + if state is None: + state = [] + else: + state = list(zip(*filtered_state)) + state = [np.stack(s) for s in state] + + input_dict = {Columns.OBS: obs_batch} + + if prev_action is not None: + input_dict[SampleBatch.PREV_ACTIONS] = prev_action + if prev_reward is not None: + input_dict[SampleBatch.PREV_REWARDS] = prev_reward + if info: + input_dict[Columns.INFOS] = info + for i, s in enumerate(state): + input_dict[f"state_in_{i}"] = s + + actions, states, infos = policy.compute_actions_from_input_dict( + input_dict=input_dict, + explore=explore, + timestep=timestep, + episodes=episodes, + ) + + single_actions = space_utils.unbatch(actions) + actions = {} + for key, a in zip(observations, single_actions): + if unsquash_actions: + a = space_utils.unsquash_action(a, policy.action_space_struct) + elif clip_actions: + a = space_utils.clip_action(a, policy.action_space_struct) + actions[key] = a + + unbatched_states = {} + for idx, agent_id in enumerate(observations): + unbatched_states[agent_id] = [s[idx] for s in states] + + if state_defined or full_fetch: + return actions, unbatched_states, infos + else: + return actions + + @Deprecated(new="Algorithm.restore_env_runners", error=True) + def restore_workers(self, *args, **kwargs): + pass + + @Deprecated( + new="Algorithm.env_runner_group", + error=True, + ) + @property + def workers(self): + return self.env_runner_group + + @Deprecated( + new="Algorithm.eval_env_runner_group", + error=True, + ) + @property + def evaluation_workers(self): + return self.eval_env_runner_group + + +class TrainIterCtx: + def __init__(self, algo: Algorithm): + self.algo = algo + self.time_start = None + self.time_stop = None + + def __enter__(self): + # Before first call to `step()`, `results` is expected to be None -> + # Start with self.failures=-1 -> set to 0 before the very first call + # to `self.step()`. + self.failures = -1 + + self.time_start = time.time() + self.sampled = 0 + self.trained = 0 + if self.algo.config.enable_env_runner_and_connector_v2: + self.init_env_steps_sampled = self.algo.metrics.peek( + (ENV_RUNNER_RESULTS, NUM_ENV_STEPS_SAMPLED_LIFETIME), default=0 + ) + self.init_env_steps_trained = self.algo.metrics.peek( + (LEARNER_RESULTS, ALL_MODULES, NUM_ENV_STEPS_TRAINED_LIFETIME), + default=0, + ) + self.init_agent_steps_sampled = sum( + self.algo.metrics.peek( + (ENV_RUNNER_RESULTS, NUM_AGENT_STEPS_SAMPLED_LIFETIME), default={} + ).values() + ) + self.init_agent_steps_trained = sum( + self.algo.metrics.peek( + (LEARNER_RESULTS, NUM_AGENT_STEPS_TRAINED_LIFETIME), default={} + ).values() + ) + else: + self.init_env_steps_sampled = self.algo._counters[NUM_ENV_STEPS_SAMPLED] + self.init_env_steps_trained = self.algo._counters[NUM_ENV_STEPS_TRAINED] + self.init_agent_steps_sampled = self.algo._counters[NUM_AGENT_STEPS_SAMPLED] + self.init_agent_steps_trained = self.algo._counters[NUM_AGENT_STEPS_TRAINED] + self.failure_tolerance = ( + self.algo.config.num_consecutive_env_runner_failures_tolerance + ) + return self + + def __exit__(self, *args): + self.time_stop = time.time() + + def get_time_taken_sec(self) -> float: + """Returns the time we spent in the context in seconds.""" + return self.time_stop - self.time_start + + def should_stop(self, results): + # Before first call to `step()`. + if results in [None, False]: + # Fail after n retries. + self.failures += 1 + if self.failures > self.failure_tolerance: + raise RuntimeError( + "More than `num_consecutive_env_runner_failures_tolerance=" + f"{self.failure_tolerance}` consecutive worker failures! " + "Exiting." + ) + # Continue to very first `step()` call or retry `step()` after + # a (tolerable) failure. + return False + + # Stopping criteria. + if self.algo.config.enable_env_runner_and_connector_v2: + if self.algo.config.count_steps_by == "agent_steps": + self.sampled = ( + sum( + self.algo.metrics.peek( + (ENV_RUNNER_RESULTS, NUM_AGENT_STEPS_SAMPLED_LIFETIME), + default={}, + ).values() + ) + - self.init_agent_steps_sampled + ) + self.trained = ( + sum( + self.algo.metrics.peek( + (LEARNER_RESULTS, NUM_AGENT_STEPS_TRAINED_LIFETIME), + default={}, + ).values() + ) + - self.init_agent_steps_trained + ) + else: + self.sampled = ( + self.algo.metrics.peek( + (ENV_RUNNER_RESULTS, NUM_ENV_STEPS_SAMPLED_LIFETIME), default=0 + ) + - self.init_env_steps_sampled + ) + self.trained = ( + self.algo.metrics.peek( + (LEARNER_RESULTS, ALL_MODULES, NUM_ENV_STEPS_TRAINED_LIFETIME), + default=0, + ) + - self.init_env_steps_trained + ) + else: + if self.algo.config.count_steps_by == "agent_steps": + self.sampled = ( + self.algo._counters[NUM_AGENT_STEPS_SAMPLED] + - self.init_agent_steps_sampled + ) + self.trained = ( + self.algo._counters[NUM_AGENT_STEPS_TRAINED] + - self.init_agent_steps_trained + ) + else: + self.sampled = ( + self.algo._counters[NUM_ENV_STEPS_SAMPLED] + - self.init_env_steps_sampled + ) + self.trained = ( + self.algo._counters[NUM_ENV_STEPS_TRAINED] + - self.init_env_steps_trained + ) + + min_t = self.algo.config.min_time_s_per_iteration + min_sample_ts = self.algo.config.min_sample_timesteps_per_iteration + min_train_ts = self.algo.config.min_train_timesteps_per_iteration + + # Repeat if not enough time has passed or if not enough + # env|train timesteps have been processed (or these min + # values are not provided by the user). + if ( + (not min_t or time.time() - self.time_start >= min_t) + and (not min_sample_ts or self.sampled >= min_sample_ts) + and (not min_train_ts or self.trained >= min_train_ts) + ): + return True + else: + return False diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/algorithm_config.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/algorithm_config.py new file mode 100644 index 0000000000000000000000000000000000000000..19e8801319af57431e9a3ef55af72e060c5bd55f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/algorithm_config.py @@ -0,0 +1,6312 @@ +import copy +import dataclasses +from enum import Enum +import logging +import math +import sys +from typing import ( + Any, + Callable, + Collection, + Dict, + List, + Optional, + Tuple, + Type, + TYPE_CHECKING, + Union, +) + +import gymnasium as gym +import tree +from packaging import version + +import ray +from ray.rllib.callbacks.callbacks import RLlibCallback +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core import DEFAULT_MODULE_ID +from ray.rllib.core.columns import Columns +from ray.rllib.core.learner.differentiable_learner_config import ( + DifferentiableLearnerConfig, +) +from ray.rllib.core.rl_module import validate_module_id +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.env import INPUT_ENV_SPACES, INPUT_ENV_SINGLE_SPACES +from ray.rllib.env.multi_agent_env import MultiAgentEnv +from ray.rllib.env.wrappers.atari_wrappers import is_atari +from ray.rllib.evaluation.collectors.sample_collector import SampleCollector +from ray.rllib.evaluation.collectors.simple_list_collector import SimpleListCollector +from ray.rllib.models import MODEL_DEFAULTS +from ray.rllib.offline.input_reader import InputReader +from ray.rllib.offline.io_context import IOContext +from ray.rllib.policy.policy import Policy, PolicySpec +from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID +from ray.rllib.utils import deep_update, force_list, merge_dicts +from ray.rllib.utils.annotations import ( + OldAPIStack, + OverrideToImplementCustomLogic_CallToSuperRecommended, +) +from ray.rllib.utils.deprecation import ( + DEPRECATED_VALUE, + Deprecated, + deprecation_warning, +) +from ray.rllib.utils.framework import try_import_tf, try_import_torch +from ray.rllib.utils.from_config import NotProvided, from_config +from ray.rllib.utils.schedules.scheduler import Scheduler +from ray.rllib.utils.serialization import ( + NOT_SERIALIZABLE, + deserialize_type, + serialize_type, +) +from ray.rllib.utils.test_utils import check +from ray.rllib.utils.torch_utils import TORCH_COMPILE_REQUIRED_VERSION +from ray.rllib.utils.typing import ( + AgentID, + AlgorithmConfigDict, + EnvConfigDict, + EnvType, + LearningRateOrSchedule, + ModuleID, + MultiAgentPolicyConfigDict, + PartialAlgorithmConfigDict, + PolicyID, + RLModuleSpecType, + SampleBatchType, +) +from ray.tune.logger import Logger +from ray.tune.registry import get_trainable_cls +from ray.tune.result import TRIAL_INFO +from ray.tune.tune import _Config +from ray.util import log_once +from ray.util.placement_group import PlacementGroup + + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm import Algorithm + from ray.rllib.core.learner import Learner + from ray.rllib.core.learner.differentiable_learner import DifferentiableLearner + from ray.rllib.core.learner.learner_group import LearnerGroup + from ray.rllib.core.learner.torch.torch_meta_learner import TorchMetaLearner + from ray.rllib.core.rl_module.rl_module import RLModule + from ray.rllib.utils.typing import EpisodeType + +logger = logging.getLogger(__name__) + + +def _check_rl_module_spec(module_spec: RLModuleSpecType) -> None: + if not isinstance(module_spec, (RLModuleSpec, MultiRLModuleSpec)): + raise ValueError( + "rl_module_spec must be an instance of " + "RLModuleSpec or MultiRLModuleSpec." + f"Got {type(module_spec)} instead." + ) + + +class AlgorithmConfig(_Config): + """A RLlib AlgorithmConfig builds an RLlib Algorithm from a given configuration. + + .. testcode:: + + from ray.rllib.algorithms.ppo import PPOConfig + from ray.rllib.algorithms.callbacks import MemoryTrackingCallbacks + # Construct a generic config object, specifying values within different + # sub-categories, e.g. "training". + config = ( + PPOConfig() + .training(gamma=0.9, lr=0.01) + .environment(env="CartPole-v1") + .env_runners(num_env_runners=0) + .callbacks(MemoryTrackingCallbacks) + ) + # A config object can be used to construct the respective Algorithm. + rllib_algo = config.build() + + .. testcode:: + + from ray.rllib.algorithms.ppo import PPOConfig + from ray import tune + # In combination with a tune.grid_search: + config = PPOConfig() + config.training(lr=tune.grid_search([0.01, 0.001])) + # Use `to_dict()` method to get the legacy plain python config dict + # for usage with `tune.Tuner().fit()`. + tune.Tuner("PPO", param_space=config.to_dict()) + """ + + @staticmethod + def DEFAULT_AGENT_TO_MODULE_MAPPING_FN(agent_id, episode): + # The default agent ID to module ID mapping function to use in the multi-agent + # case if None is provided. + # Map any agent ID to "default_policy". + return DEFAULT_MODULE_ID + + # TODO (sven): Deprecate in new API stack. + @staticmethod + def DEFAULT_POLICY_MAPPING_FN(aid, episode, worker, **kwargs): + # The default policy mapping function to use if None provided. + # Map any agent ID to "default_policy". + return DEFAULT_POLICY_ID + + @classmethod + def from_dict(cls, config_dict: dict) -> "AlgorithmConfig": + """Creates an AlgorithmConfig from a legacy python config dict. + + .. testcode:: + + from ray.rllib.algorithms.ppo.ppo import PPOConfig + # pass a RLlib config dict + ppo_config = PPOConfig.from_dict({}) + ppo = ppo_config.build(env="Pendulum-v1") + + Args: + config_dict: The legacy formatted python config dict for some algorithm. + + Returns: + A new AlgorithmConfig object that matches the given python config dict. + """ + # Create a default config object of this class. + config_obj = cls() + # Remove `_is_frozen` flag from config dict in case the AlgorithmConfig that + # the dict was derived from was already frozen (we don't want to copy the + # frozenness). + config_dict.pop("_is_frozen", None) + config_obj.update_from_dict(config_dict) + return config_obj + + @classmethod + def overrides(cls, **kwargs): + """Generates and validates a set of config key/value pairs (passed via kwargs). + + Validation whether given config keys are valid is done immediately upon + construction (by comparing against the properties of a default AlgorithmConfig + object of this class). + Allows combination with a full AlgorithmConfig object to yield a new + AlgorithmConfig object. + + Used anywhere, we would like to enable the user to only define a few config + settings that would change with respect to some main config, e.g. in multi-agent + setups and evaluation configs. + + .. testcode:: + + from ray.rllib.algorithms.ppo import PPOConfig + from ray.rllib.policy.policy import PolicySpec + config = ( + PPOConfig() + .multi_agent( + policies={ + "pol0": PolicySpec(config=PPOConfig.overrides(lambda_=0.95)) + }, + ) + ) + + + .. testcode:: + + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + from ray.rllib.algorithms.ppo import PPOConfig + config = ( + PPOConfig() + .evaluation( + evaluation_num_env_runners=1, + evaluation_interval=1, + evaluation_config=AlgorithmConfig.overrides(explore=False), + ) + ) + + Returns: + A dict mapping valid config property-names to values. + + Raises: + KeyError: In case a non-existing property name (kwargs key) is being + passed in. Valid property names are taken from a default + AlgorithmConfig object of `cls`. + """ + default_config = cls() + config_overrides = {} + for key, value in kwargs.items(): + if not hasattr(default_config, key): + raise KeyError( + f"Invalid property name {key} for config class {cls.__name__}!" + ) + # Allow things like "lambda" as well. + key = cls._translate_special_keys(key, warn_deprecated=True) + config_overrides[key] = value + + return config_overrides + + def __init__(self, algo_class: Optional[type] = None): + """Initializes an AlgorithmConfig instance. + + Args: + algo_class: An optional Algorithm class that this config class belongs to. + Used (if provided) to build a respective Algorithm instance from this + config. + """ + # Define all settings and their default values. + + # Define the default RLlib Algorithm class that this AlgorithmConfig is applied + # to. + self.algo_class = algo_class + + # `self.python_environment()` + self.extra_python_environs_for_driver = {} + self.extra_python_environs_for_worker = {} + + # `self.resources()` + self.placement_strategy = "PACK" + self.num_gpus = 0 # @OldAPIStack + self._fake_gpus = False # @OldAPIStack + self.num_cpus_for_main_process = 1 + + # `self.framework()` + self.framework_str = "torch" + self.eager_tracing = True + self.eager_max_retraces = 20 + self.tf_session_args = { + # note: overridden by `local_tf_session_args` + "intra_op_parallelism_threads": 2, + "inter_op_parallelism_threads": 2, + "gpu_options": { + "allow_growth": True, + }, + "log_device_placement": False, + "device_count": {"CPU": 1}, + # Required by multi-GPU (num_gpus > 1). + "allow_soft_placement": True, + } + self.local_tf_session_args = { + # Allow a higher level of parallelism by default, but not unlimited + # since that can cause crashes with many concurrent drivers. + "intra_op_parallelism_threads": 8, + "inter_op_parallelism_threads": 8, + } + # Torch compile settings + self.torch_compile_learner = False + self.torch_compile_learner_what_to_compile = ( + TorchCompileWhatToCompile.FORWARD_TRAIN + ) + # AOT Eager is a dummy backend and doesn't result in speedups. + self.torch_compile_learner_dynamo_backend = ( + "aot_eager" if sys.platform == "darwin" else "inductor" + ) + self.torch_compile_learner_dynamo_mode = None + self.torch_compile_worker = False + # AOT Eager is a dummy backend and doesn't result in speedups. + self.torch_compile_worker_dynamo_backend = ( + "aot_eager" if sys.platform == "darwin" else "onnxrt" + ) + self.torch_compile_worker_dynamo_mode = None + # Default kwargs for `torch.nn.parallel.DistributedDataParallel`. + self.torch_ddp_kwargs = {} + # Default setting for skipping `nan` gradient updates. + self.torch_skip_nan_gradients = False + + # `self.environment()` + self.env = None + self.env_config = {} + self.observation_space = None + self.action_space = None + self.clip_rewards = None + self.normalize_actions = True + self.clip_actions = False + self._is_atari = None + self.disable_env_checking = False + # Deprecated settings: + self.render_env = False + self.action_mask_key = "action_mask" + + # `self.env_runners()` + self.env_runner_cls = None + self.num_env_runners = 0 + self.create_local_env_runner = True + self.num_envs_per_env_runner = 1 + # TODO (sven): Once new ormsgpack system in place, replace the string + # with proper `gym.envs.registration.VectorizeMode.SYNC`. + self.gym_env_vectorize_mode = "SYNC" + self.num_cpus_per_env_runner = 1 + self.num_gpus_per_env_runner = 0 + self.custom_resources_per_env_runner = {} + self.validate_env_runners_after_construction = True + self.episodes_to_numpy = True + self.max_requests_in_flight_per_env_runner = 1 + self.sample_timeout_s = 60.0 + self.create_env_on_local_worker = False + self._env_to_module_connector = None + self.add_default_connectors_to_env_to_module_pipeline = True + self._module_to_env_connector = None + self.add_default_connectors_to_module_to_env_pipeline = True + self.merge_env_runner_states = "training_only" + self.broadcast_env_runner_states = True + self.episode_lookback_horizon = 1 + # TODO (sven): Rename into `sample_timesteps` (or `sample_duration` + # and `sample_duration_unit` (replacing batch_mode), like we do it + # in the evaluation config). + self.rollout_fragment_length = 200 + # TODO (sven): Rename into `sample_mode`. + self.batch_mode = "truncate_episodes" + self.compress_observations = False + # @OldAPIStack + self.remote_worker_envs = False + self.remote_env_batch_wait_ms = 0 + self.enable_tf1_exec_eagerly = False + self.sample_collector = SimpleListCollector + self.preprocessor_pref = "deepmind" + self.observation_filter = "NoFilter" + self.update_worker_filter_stats = True + self.use_worker_filter_stats = True + self.sampler_perf_stats_ema_coef = None + self._is_online = True + + # `self.learners()` + self.num_learners = 0 + self.num_gpus_per_learner = 0 + self.num_cpus_per_learner = "auto" + self.num_aggregator_actors_per_learner = 0 + self.max_requests_in_flight_per_aggregator_actor = 3 + self.local_gpu_idx = 0 + # TODO (sven): This probably works even without any restriction + # (allowing for any arbitrary number of requests in-flight). Test with + # 3 first, then with unlimited, and if both show the same behavior on + # an async algo, remove this restriction entirely. + self.max_requests_in_flight_per_learner = 3 + + # `self.training()` + self.gamma = 0.99 + self.lr = 0.001 + self.grad_clip = None + self.grad_clip_by = "global_norm" + # Simple logic for now: If None, use `train_batch_size`. + self._train_batch_size_per_learner = None + self.train_batch_size = 32 # @OldAPIStack + + # These setting have been adopted from the original PPO batch settings: + # num_sgd_iter, minibatch_size, and shuffle_sequences. + self.num_epochs = 1 + self.minibatch_size = None + self.shuffle_batch_per_epoch = False + + # TODO (sven): Unsolved problem with RLModules sometimes requiring settings from + # the main AlgorithmConfig. We should not require the user to provide those + # settings in both, the AlgorithmConfig (as property) AND the model config + # dict. We should generally move to a world, in which there exists an + # AlgorithmConfig that a) has-a user provided model config object and b) + # is given a chance to compile a final model config (dict or object) that is + # then passed into the RLModule/Catalog. This design would then match our + # "compilation" pattern, where we compile automatically those settings that + # should NOT be touched by the user. + # In case, an Algorithm already uses the above described pattern (and has + # `self.model` as a @property, ignore AttributeError (for trying to set this + # property). + try: + self.model = copy.deepcopy(MODEL_DEFAULTS) + except AttributeError: + pass + + self._learner_connector = None + self.add_default_connectors_to_learner_pipeline = True + self.learner_config_dict = {} + self.optimizer = {} # @OldAPIStack + self._learner_class = None + + # `self.callbacks()` + # TODO (sven): Set this default to None, once the old API stack has been + # deprecated. + self.callbacks_class = RLlibCallback + self.callbacks_on_algorithm_init = None + self.callbacks_on_env_runners_recreated = None + self.callbacks_on_offline_eval_runners_recreated = None + self.callbacks_on_checkpoint_loaded = None + self.callbacks_on_environment_created = None + self.callbacks_on_episode_created = None + self.callbacks_on_episode_start = None + self.callbacks_on_episode_step = None + self.callbacks_on_episode_end = None + self.callbacks_on_evaluate_start = None + self.callbacks_on_evaluate_end = None + self.callbacks_on_evaluate_offline_start = None + self.callbacks_on_evaluate_offline_end = None + self.callbacks_on_sample_end = None + self.callbacks_on_train_result = None + + # `self.explore()` + self.explore = True + # This is not compatible with RLModules, which have a method + # `forward_exploration` to specify custom exploration behavior. + if not hasattr(self, "exploration_config"): + # Helper to keep track of the original exploration config when dis-/enabling + # rl modules. + self._prior_exploration_config = None + self.exploration_config = {} + + # `self.api_stack()` + self.enable_rl_module_and_learner = True + self.enable_env_runner_and_connector_v2 = True + self.api_stack( + enable_rl_module_and_learner=True, + enable_env_runner_and_connector_v2=True, + ) + + # `self.multi_agent()` + # TODO (sven): Prepare multi-agent setup for logging each agent's and each + # RLModule's steps taken thus far (and passing this information into the + # EnvRunner metrics and the RLModule's forward pass). Thereby, deprecate the + # `count_steps_by` config setting AND - at the same time - allow users to + # specify the batch size unit instead (agent- vs env steps). + self.count_steps_by = "env_steps" + # self.agent_to_module_mapping_fn = self.DEFAULT_AGENT_TO_MODULE_MAPPING_FN + # Soon to be Deprecated. + self.policies = {DEFAULT_POLICY_ID: PolicySpec()} + self.policy_map_capacity = 100 + self.policy_mapping_fn = self.DEFAULT_POLICY_MAPPING_FN + self.policies_to_train = None + self.policy_states_are_swappable = False + self.observation_fn = None + + # `self.offline_data()` + self.input_ = "sampler" + self.offline_data_class = None + self.offline_data_class = None + self.input_read_method = "read_parquet" + self.input_read_method_kwargs = {} + self.input_read_schema = {} + self.input_read_episodes = False + self.input_read_sample_batches = False + self.input_read_batch_size = None + self.input_filesystem = None + self.input_filesystem_kwargs = {} + self.input_compress_columns = [Columns.OBS, Columns.NEXT_OBS] + self.input_spaces_jsonable = True + self.materialize_data = False + self.materialize_mapped_data = True + self.map_batches_kwargs = {} + self.iter_batches_kwargs = {} + # Use always the final observation until the user explicitly ask + # to ignore it. + self.ignore_final_observation = False + self.prelearner_class = None + self.prelearner_buffer_class = None + self.prelearner_buffer_kwargs = {} + self.prelearner_module_synch_period = 10 + self.dataset_num_iters_per_learner = None + self.input_config = {} + self.actions_in_input_normalized = False + self.postprocess_inputs = False + self.shuffle_buffer_size = 0 + self.output = None + self.output_config = {} + self.output_compress_columns = [Columns.OBS, Columns.NEXT_OBS] + self.output_max_file_size = 64 * 1024 * 1024 + self.output_max_rows_per_file = None + self.output_write_remaining_data = False + self.output_write_method = "write_parquet" + self.output_write_method_kwargs = {} + self.output_filesystem = None + self.output_filesystem_kwargs = {} + self.output_write_episodes = True + self.offline_sampling = False + + # `self.evaluation()` + self.evaluation_interval = None + self.evaluation_duration = 10 + self.evaluation_duration_unit = "episodes" + self.evaluation_sample_timeout_s = 120.0 + self.evaluation_auto_duration_min_env_steps_per_sample = 100 + self.evaluation_auto_duration_max_env_steps_per_sample = 2000 + self.evaluation_parallel_to_training = False + self.evaluation_force_reset_envs_before_iteration = True + self.evaluation_config = None + self.off_policy_estimation_methods = {} + self.ope_split_batch_by_episode = True + self.evaluation_num_env_runners = 0 + self.custom_evaluation_function = None + # TODO: Set this flag still in the config or - much better - in the + # RolloutWorker as a property. + self.in_evaluation = False + # TODO (sven): Deprecate this setting (it's not user-accessible right now any + # way). Replace by logic within `training_step` to merge and broadcast the + # EnvRunner (connector) states. + self.sync_filters_on_rollout_workers_timeout_s = 10.0 + # Offline evaluation. + self.offline_evaluation_interval = None + self.num_offline_eval_runners = 0 + self.offline_evaluation_type: str = None + self.offline_eval_runner_class = None + # TODO (simon): Only `_offline_evaluate_with_fixed_duration` works. Also, + # decide, if we use `offline_evaluation_duration` or + # `dataset_num_iters_per_offline_eval_runner`. Should the user decide here? + # The latter will be much faster, but runs per runner call all evaluation. + self.offline_loss_for_module_fn = None + self.offline_evaluation_duration = 1 + self.offline_evaluation_parallel_to_training = False + self.offline_evaluation_timeout_s = 120.0 + self.num_cpus_per_offline_eval_runner = 1 + self.num_gpus_per_offline_eval_runner = 0 + self.custom_resources_per_offline_eval_runner = {} + self.restart_failed_offline_eval_runners = True + self.ignore_offline_eval_runner_failures = False + self.max_num_offline_eval_runner_restarts = 1000 + self.offline_eval_runner_restore_timeout_s = 1800.0 + self.max_requests_in_flight_per_offline_eval_runner = 1 + self.validate_offline_eval_runners_after_construction = True + self.offline_eval_runner_health_probe_timeout_s = 30.0 + self.offline_eval_rl_module_inference_only = False + self.broadcast_offline_eval_runner_states = False + self.offline_eval_batch_size_per_runner = 256 + self.dataset_num_iters_per_eval_runner = 1 + + # `self.reporting()` + self.keep_per_episode_custom_metrics = False + self.metrics_episode_collection_timeout_s = 60.0 + self.metrics_num_episodes_for_smoothing = 100 + self.min_time_s_per_iteration = None + self.min_train_timesteps_per_iteration = 0 + self.min_sample_timesteps_per_iteration = 0 + self.log_gradients = True + + # `self.checkpointing()` + self.export_native_model_files = False + self.checkpoint_trainable_policies_only = False + + # `self.debugging()` + self.logger_creator = None + self.logger_config = None + self.log_level = "WARN" + self.log_sys_usage = True + self.fake_sampler = False + self.seed = None + + # `self.fault_tolerance()` + self.restart_failed_env_runners = True + self.ignore_env_runner_failures = False + # By default, restart failed worker a thousand times. + # This should be enough to handle normal transient failures. + # This also prevents infinite number of restarts in case the worker or env has + # a bug. + self.max_num_env_runner_restarts = 1000 + # Small delay between worker restarts. In case EnvRunners or eval EnvRunners + # have remote dependencies, this delay can be adjusted to make sure we don't + # flood them with re-connection requests, and allow them enough time to recover. + # This delay also gives Ray time to stream back error logging and exceptions. + self.delay_between_env_runner_restarts_s = 60.0 + self.restart_failed_sub_environments = False + self.num_consecutive_env_runner_failures_tolerance = 100 + self.env_runner_health_probe_timeout_s = 30.0 + self.env_runner_restore_timeout_s = 1800.0 + + # `self.rl_module()` + self._model_config = {} + self._rl_module_spec = None + # Module ID specific config overrides. + self.algorithm_config_overrides_per_module = {} + # Cached, actual AlgorithmConfig objects derived from + # `self.algorithm_config_overrides_per_module`. + self._per_module_overrides: Dict[ModuleID, "AlgorithmConfig"] = {} + + # `self.experimental()` + self._validate_config = True + self._use_msgpack_checkpoints = False + self._torch_grad_scaler_class = None + self._torch_lr_scheduler_classes = None + self._tf_policy_handles_more_than_one_loss = False + self._disable_preprocessor_api = False + self._disable_action_flattening = False + self._disable_initialize_loss_from_dummy_batch = False + self._dont_auto_sync_env_runner_states = False + + # Has this config object been frozen (cannot alter its attributes anymore). + self._is_frozen = False + + # TODO: Remove, once all deprecation_warning calls upon using these keys + # have been removed. + # === Deprecated keys === + self.env_task_fn = DEPRECATED_VALUE + self.enable_connectors = DEPRECATED_VALUE + self.simple_optimizer = DEPRECATED_VALUE + self.monitor = DEPRECATED_VALUE + self.evaluation_num_episodes = DEPRECATED_VALUE + self.metrics_smoothing_episodes = DEPRECATED_VALUE + self.timesteps_per_iteration = DEPRECATED_VALUE + self.min_iter_time_s = DEPRECATED_VALUE + self.collect_metrics_timeout = DEPRECATED_VALUE + self.min_time_s_per_reporting = DEPRECATED_VALUE + self.min_train_timesteps_per_reporting = DEPRECATED_VALUE + self.min_sample_timesteps_per_reporting = DEPRECATED_VALUE + self.input_evaluation = DEPRECATED_VALUE + self.policy_map_cache = DEPRECATED_VALUE + self.worker_cls = DEPRECATED_VALUE + self.synchronize_filters = DEPRECATED_VALUE + self.enable_async_evaluation = DEPRECATED_VALUE + self.custom_async_evaluation_function = DEPRECATED_VALUE + self._enable_rl_module_api = DEPRECATED_VALUE + self.auto_wrap_old_gym_envs = DEPRECATED_VALUE + self.always_attach_evaluation_results = DEPRECATED_VALUE + + # The following values have moved because of the new ReplayBuffer API + self.buffer_size = DEPRECATED_VALUE + self.prioritized_replay = DEPRECATED_VALUE + self.learning_starts = DEPRECATED_VALUE + self.replay_batch_size = DEPRECATED_VALUE + # -1 = DEPRECATED_VALUE is a valid value for replay_sequence_length + self.replay_sequence_length = None + self.replay_mode = DEPRECATED_VALUE + self.prioritized_replay_alpha = DEPRECATED_VALUE + self.prioritized_replay_beta = DEPRECATED_VALUE + self.prioritized_replay_eps = DEPRECATED_VALUE + self.min_time_s_per_reporting = DEPRECATED_VALUE + self.min_train_timesteps_per_reporting = DEPRECATED_VALUE + self.min_sample_timesteps_per_reporting = DEPRECATED_VALUE + self._disable_execution_plan_api = DEPRECATED_VALUE + + def to_dict(self) -> AlgorithmConfigDict: + """Converts all settings into a legacy config dict for backward compatibility. + + Returns: + A complete AlgorithmConfigDict, usable in backward-compatible Tune/RLlib + use cases. + """ + config = copy.deepcopy(vars(self)) + config.pop("algo_class") + config.pop("_is_frozen") + + # Worst naming convention ever: NEVER EVER use reserved key-words... + if "lambda_" in config: + assert hasattr(self, "lambda_") + config["lambda"] = self.lambda_ + config.pop("lambda_") + if "input_" in config: + assert hasattr(self, "input_") + config["input"] = self.input_ + config.pop("input_") + + # Convert `policies` (PolicySpecs?) into dict. + # Convert policies dict such that each policy ID maps to a old-style. + # 4-tuple: class, obs-, and action space, config. + if "policies" in config and isinstance(config["policies"], dict): + policies_dict = {} + for policy_id, policy_spec in config.pop("policies").items(): + if isinstance(policy_spec, PolicySpec): + policies_dict[policy_id] = policy_spec.get_state() + else: + policies_dict[policy_id] = policy_spec + config["policies"] = policies_dict + + # Switch out deprecated vs new config keys. + config["callbacks"] = config.pop("callbacks_class", None) + config["create_env_on_driver"] = config.pop("create_env_on_local_worker", 1) + config["custom_eval_function"] = config.pop("custom_evaluation_function", None) + config["framework"] = config.pop("framework_str", None) + + # Simplify: Remove all deprecated keys that have as value `DEPRECATED_VALUE`. + # These would be useless in the returned dict anyways. + for dep_k in [ + "monitor", + "evaluation_num_episodes", + "metrics_smoothing_episodes", + "timesteps_per_iteration", + "min_iter_time_s", + "collect_metrics_timeout", + "buffer_size", + "prioritized_replay", + "learning_starts", + "replay_batch_size", + "replay_mode", + "prioritized_replay_alpha", + "prioritized_replay_beta", + "prioritized_replay_eps", + "min_time_s_per_reporting", + "min_train_timesteps_per_reporting", + "min_sample_timesteps_per_reporting", + "input_evaluation", + "_enable_new_api_stack", + ]: + if config.get(dep_k) == DEPRECATED_VALUE: + config.pop(dep_k, None) + + return config + + def update_from_dict( + self, + config_dict: PartialAlgorithmConfigDict, + ) -> "AlgorithmConfig": + """Modifies this AlgorithmConfig via the provided python config dict. + + Warns if `config_dict` contains deprecated keys. + Silently sets even properties of `self` that do NOT exist. This way, this method + may be used to configure custom Policies which do not have their own specific + AlgorithmConfig classes, e.g. + `ray.rllib.examples.policy.random_policy::RandomPolicy`. + + Args: + config_dict: The old-style python config dict (PartialAlgorithmConfigDict) + to use for overriding some properties defined in there. + + Returns: + This updated AlgorithmConfig object. + """ + eval_call = {} + + # We deal with this special key before all others because it may influence + # stuff like "exploration_config". + # Namely, we want to re-instantiate the exploration config this config had + # inside `self.experimental()` before potentially overwriting it in the + # following. + enable_new_api_stack = config_dict.get( + "enable_rl_module_and_learner", + config_dict.get("enable_env_runner_and_connector_v2"), + ) + if enable_new_api_stack is not None: + self.api_stack( + enable_rl_module_and_learner=enable_new_api_stack, + enable_env_runner_and_connector_v2=enable_new_api_stack, + ) + + # Modify our properties one by one. + for key, value in config_dict.items(): + key = self._translate_special_keys(key, warn_deprecated=False) + + # Ray Tune saves additional data under this magic keyword. + # This should not get treated as AlgorithmConfig field. + if key == TRIAL_INFO: + continue + + if key in ["_enable_new_api_stack"]: + # We've dealt with this above. + continue + # Set our multi-agent settings. + elif key == "multiagent": + kwargs = { + k: value[k] + for k in [ + "policies", + "policy_map_capacity", + "policy_mapping_fn", + "policies_to_train", + "policy_states_are_swappable", + "observation_fn", + "count_steps_by", + ] + if k in value + } + self.multi_agent(**kwargs) + # Some keys specify config sub-dicts and therefore should go through the + # correct methods to properly `.update()` those from given config dict + # (to not lose any sub-keys). + elif key == "callbacks_class" and value != NOT_SERIALIZABLE: + # For backward compatibility reasons, only resolve possible + # classpath if value is a str type. + if isinstance(value, str): + value = deserialize_type(value, error=True) + self.callbacks(callbacks_class=value) + elif key == "env_config": + self.environment(env_config=value) + elif key.startswith("evaluation_"): + eval_call[key] = value + elif key == "exploration_config": + if enable_new_api_stack: + self.exploration_config = value + continue + if isinstance(value, dict) and "type" in value: + value["type"] = deserialize_type(value["type"]) + self.env_runners(exploration_config=value) + elif key == "model": + # Resolve possible classpath. + if isinstance(value, dict) and value.get("custom_model"): + value["custom_model"] = deserialize_type(value["custom_model"]) + self.training(**{key: value}) + elif key == "optimizer": + self.training(**{key: value}) + elif key == "replay_buffer_config": + if isinstance(value, dict) and "type" in value: + value["type"] = deserialize_type(value["type"]) + self.training(**{key: value}) + elif key == "sample_collector": + # Resolve possible classpath. + value = deserialize_type(value) + self.env_runners(sample_collector=value) + # Set the property named `key` to `value`. + else: + setattr(self, key, value) + + self.evaluation(**eval_call) + + return self + + def get_state(self) -> Dict[str, Any]: + """Returns a dict state that can be pickled. + + Returns: + A dictionary containing all attributes of the instance. + """ + + state = self.__dict__.copy() + state["class"] = type(self) + state.pop("algo_class") + state.pop("_is_frozen") + state = {k: v for k, v in state.items() if v != DEPRECATED_VALUE} + + # Convert `policies` (PolicySpecs?) into dict. + # Convert policies dict such that each policy ID maps to a old-style. + # 4-tuple: class, obs-, and action space, config. + # TODO (simon, sven): Remove when deprecating old stack. + if "policies" in state and isinstance(state["policies"], dict): + policies_dict = {} + for policy_id, policy_spec in state.pop("policies").items(): + if isinstance(policy_spec, PolicySpec): + policies_dict[policy_id] = policy_spec.get_state() + else: + policies_dict[policy_id] = policy_spec + state["policies"] = policies_dict + + # state = self._serialize_dict(state) + + return state + + @classmethod + def from_state(cls, state: Dict[str, Any]) -> "AlgorithmConfig": + """Returns an instance constructed from the state. + + Args: + cls: An `AlgorithmConfig` class. + state: A dictionary containing the state of an `AlgorithmConfig`. + See `AlgorithmConfig.get_state` for creating a state. + + Returns: + An `AlgorithmConfig` instance with attributes from the `state`. + """ + + ctor = state["class"] + config = ctor() + + config.__dict__.update(state) + + return config + + # TODO(sven): We might want to have a `deserialize` method as well. Right now, + # simply using the from_dict() API works in this same (deserializing) manner, + # whether the dict used is actually code-free (already serialized) or not + # (i.e. a classic RLlib config dict with e.g. "callbacks" key still pointing to + # a class). + def serialize(self) -> Dict[str, Any]: + """Returns a mapping from str to JSON'able values representing this config. + + The resulting values don't have any code in them. + Classes (such as `callbacks_class`) are converted to their full + classpath, e.g. `ray.rllib.callbacks.callbacks.RLlibCallback`. + Actual code such as lambda functions ware written as their source + code (str) plus any closure information for properly restoring the + code inside the AlgorithmConfig object made from the returned dict data. + Dataclass objects get converted to dicts. + + Returns: + A dict mapping from str to JSON'able values. + """ + config = self.to_dict() + return self._serialize_dict(config) + + def copy(self, copy_frozen: Optional[bool] = None) -> "AlgorithmConfig": + """Creates a deep copy of this config and (un)freezes if necessary. + + Args: + copy_frozen: Whether the created deep copy is frozen or not. If None, + keep the same frozen status that `self` currently has. + + Returns: + A deep copy of `self` that is (un)frozen. + """ + cp = copy.deepcopy(self) + if copy_frozen is True: + cp.freeze() + elif copy_frozen is False: + cp._is_frozen = False + if isinstance(cp.evaluation_config, AlgorithmConfig): + cp.evaluation_config._is_frozen = False + return cp + + def freeze(self) -> None: + """Freezes this config object, such that no attributes can be set anymore. + + Algorithms should use this method to make sure that their config objects + remain read-only after this. + """ + if self._is_frozen: + return + self._is_frozen = True + + # Also freeze underlying eval config, if applicable. + if isinstance(self.evaluation_config, AlgorithmConfig): + self.evaluation_config.freeze() + + # TODO: Flip out all set/dict/list values into frozen versions + # of themselves? This way, users won't even be able to alter those values + # directly anymore. + + @OverrideToImplementCustomLogic_CallToSuperRecommended + def validate(self) -> None: + """Validates all values in this config.""" + + # Validation is blocked. + if not self._validate_config: + return + + self._validate_env_runner_settings() + self._validate_callbacks_settings() + self._validate_framework_settings() + self._validate_resources_settings() + self._validate_multi_agent_settings() + self._validate_input_settings() + self._validate_evaluation_settings() + self._validate_offline_settings() + self._validate_new_api_stack_settings() + self._validate_to_be_deprecated_settings() + + def build_algo( + self, + env: Optional[Union[str, EnvType]] = None, + logger_creator: Optional[Callable[[], Logger]] = None, + use_copy: bool = True, + ) -> "Algorithm": + """Builds an Algorithm from this AlgorithmConfig (or a copy thereof). + + Args: + env: Name of the environment to use (e.g. a gym-registered str), + a full class path (e.g. + "ray.rllib.examples.envs.classes.random_env.RandomEnv"), or an Env + class directly. Note that this arg can also be specified via + the "env" key in `config`. + logger_creator: Callable that creates a ray.tune.Logger + object. If unspecified, a default logger is created. + use_copy: Whether to deepcopy `self` and pass the copy to the Algorithm + (instead of `self`) as config. This is useful in case you would like to + recycle the same AlgorithmConfig over and over, e.g. in a test case, in + which we loop over different DL-frameworks. + + Returns: + A ray.rllib.algorithms.algorithm.Algorithm object. + """ + if env is not None: + self.env = env + if self.evaluation_config is not None: + self.evaluation_config["env"] = env + if logger_creator is not None: + self.logger_creator = logger_creator + + algo_class = self.algo_class + if isinstance(self.algo_class, str): + algo_class = get_trainable_cls(self.algo_class) + + return algo_class( + config=self if not use_copy else copy.deepcopy(self), + logger_creator=self.logger_creator, + ) + + def build_env_to_module_connector( + self, + env=None, + spaces=None, + device=None, + ) -> ConnectorV2: + from ray.rllib.connectors.env_to_module import ( + AddObservationsFromEpisodesToBatch, + AddStatesFromEpisodesToBatch, + AddTimeDimToBatchAndZeroPad, + AgentToModuleMapping, + BatchIndividualItems, + EnvToModulePipeline, + NumpyToTensor, + ) + + custom_connectors = [] + # Create an env-to-module connector pipeline (including RLlib's default + # env->module connector piece) and return it. + if self._env_to_module_connector is not None: + try: + val_ = self._env_to_module_connector(env, spaces, device) + # Try deprecated signature, if necessary. + except TypeError as e: + if "positional argument" in e.args[0]: + if log_once("env-to-module-wrong-signature"): + logger.error( + "Your `config.env_to_module_connector` function seems to " + "have a wrong or outdated signature! It should be: " + "`def myfunc(env, spaces, device): ...`, where any of " + "these arguments are optional and may be None.\n" + "`env` is the (vectorized) gym env.\n" + "`spaces` is a dict of structure `{'__env__': ([" + "vectorized env obs. space, vectorized env act. space])," + "'__env_single__': ([env obs. space, env act. space])}`.\n" + "`device` is a (torch) device.\n" + ) + val_ = self._env_to_module_connector(env) + + # ConnectorV2 (piece or pipeline). + if isinstance(val_, ConnectorV2): + custom_connectors = [val_] + # Sequence of individual ConnectorV2 pieces. + elif isinstance(val_, (list, tuple)): + custom_connectors = list(val_) + # Unsupported return value. + else: + raise ValueError( + "`AlgorithmConfig.env_runners(env_to_module_connector=..)` must " + "return a ConnectorV2 object or a list thereof to be added to a " + f"connector pipeline! Your function returned {val_}." + ) + + if env is not None: + obs_space = getattr(env, "single_observation_space", env.observation_space) + elif spaces is not None and INPUT_ENV_SINGLE_SPACES in spaces: + obs_space = spaces[INPUT_ENV_SINGLE_SPACES][0] + else: + obs_space = self.observation_space + if obs_space is None and self.is_multi_agent: + obs_space = gym.spaces.Dict( + { + aid: env.envs[0].unwrapped.get_observation_space(aid) + for aid in env.envs[0].unwrapped.possible_agents + } + ) + if env is not None: + act_space = getattr(env, "single_action_space", env.action_space) + elif spaces is not None and INPUT_ENV_SINGLE_SPACES in spaces: + act_space = spaces[INPUT_ENV_SINGLE_SPACES][1] + else: + act_space = self.action_space + if act_space is None and self.is_multi_agent: + act_space = gym.spaces.Dict( + { + aid: env.envs[0].unwrapped.get_action_space(aid) + for aid in env.envs[0].unwrapped.possible_agents + } + ) + pipeline = EnvToModulePipeline( + input_observation_space=obs_space, + input_action_space=act_space, + connectors=custom_connectors, + ) + + if self.add_default_connectors_to_env_to_module_pipeline: + # Append OBS handling. + pipeline.append(AddObservationsFromEpisodesToBatch()) + # Append time-rank handler. + pipeline.append(AddTimeDimToBatchAndZeroPad()) + # Append STATE_IN/STATE_OUT handler. + pipeline.append(AddStatesFromEpisodesToBatch()) + # If multi-agent -> Map from AgentID-based data to ModuleID based data. + if self.is_multi_agent: + pipeline.append( + AgentToModuleMapping( + rl_module_specs=( + self.rl_module_spec.rl_module_specs + if isinstance(self.rl_module_spec, MultiRLModuleSpec) + else set(self.policies) + ), + agent_to_module_mapping_fn=self.policy_mapping_fn, + ) + ) + # Batch all data. + pipeline.append(BatchIndividualItems(multi_agent=self.is_multi_agent)) + # Convert to Tensors. + pipeline.append(NumpyToTensor(device=device)) + + return pipeline + + def build_module_to_env_connector(self, env=None, spaces=None) -> ConnectorV2: + from ray.rllib.connectors.module_to_env import ( + GetActions, + ListifyDataForVectorEnv, + ModuleToAgentUnmapping, + ModuleToEnvPipeline, + NormalizeAndClipActions, + RemoveSingleTsTimeRankFromBatch, + TensorToNumpy, + UnBatchToIndividualItems, + ) + + custom_connectors = [] + # Create a module-to-env connector pipeline (including RLlib's default + # module->env connector piece) and return it. + if self._module_to_env_connector is not None: + try: + val_ = self._module_to_env_connector(env, spaces) + # Try deprecated signature, if necessary. + except TypeError as e: + if "positional argument" in e.args[0]: + if log_once("module-to-env-wrong-signature"): + logger.error( + "Your `config.module_to_env_connector` function seems to " + "have a wrong or outdated signature! It should be: " + "`def myfunc(env, spaces): ...`, where any of " + "these arguments are optional and may be None.\n" + "`env` is the (vectorized) gym env.\n" + "`spaces` is a dict of structure `{'__env__': ([" + "vectorized env obs. space, vectorized env act. space])," + "'__env_single__': ([env obs. space, env act. space])}`.\n" + ) + val_ = self._module_to_env_connector(env) + + # ConnectorV2 (piece or pipeline). + if isinstance(val_, ConnectorV2): + custom_connectors = [val_] + # Sequence of individual ConnectorV2 pieces. + elif isinstance(val_, (list, tuple)): + custom_connectors = list(val_) + # Unsupported return value. + else: + raise ValueError( + "`AlgorithmConfig.env_runners(module_to_env_connector=..)` must " + "return a ConnectorV2 object or a list thereof to be added to a " + f"connector pipeline! Your function returned {val_}." + ) + + if env is not None: + obs_space = getattr(env, "single_observation_space", env.observation_space) + elif spaces is not None and INPUT_ENV_SINGLE_SPACES in spaces: + obs_space = spaces[INPUT_ENV_SINGLE_SPACES][0] + else: + obs_space = self.observation_space + if obs_space is None and self.is_multi_agent: + obs_space = gym.spaces.Dict( + { + aid: env.envs[0].unwrapped.get_observation_space(aid) + for aid in env.envs[0].unwrapped.possible_agents + } + ) + if env is not None: + act_space = getattr(env, "single_action_space", env.action_space) + elif spaces is not None and INPUT_ENV_SINGLE_SPACES in spaces: + act_space = spaces[INPUT_ENV_SINGLE_SPACES][1] + else: + act_space = self.action_space + if act_space is None and self.is_multi_agent: + act_space = gym.spaces.Dict( + { + aid: env.envs[0].unwrapped.get_action_space(aid) + for aid in env.envs[0].unwrapped.possible_agents + } + ) + pipeline = ModuleToEnvPipeline( + input_observation_space=obs_space, + input_action_space=act_space, + connectors=custom_connectors, + ) + + if self.add_default_connectors_to_module_to_env_pipeline: + # Prepend: Anything that has to do with plain data processing (not + # particularly with the actions). + + # Remove extra time-rank, if applicable. + pipeline.prepend(RemoveSingleTsTimeRankFromBatch()) + + # If multi-agent -> Map from ModuleID-based data to AgentID based data. + if self.is_multi_agent: + pipeline.prepend(ModuleToAgentUnmapping()) + + # Unbatch all data. + pipeline.prepend(UnBatchToIndividualItems()) + + # Convert to numpy. + pipeline.prepend(TensorToNumpy()) + + # Sample actions from ACTION_DIST_INPUTS (if ACTIONS not present). + pipeline.prepend(GetActions()) + + # Append: Anything that has to do with action sampling. + # Unsquash/clip actions based on config and action space. + pipeline.append( + NormalizeAndClipActions( + normalize_actions=self.normalize_actions, + clip_actions=self.clip_actions, + ) + ) + # Listify data from ConnectorV2-data format to normal lists that we can + # index into by env vector index. These lists contain individual items + # for single-agent and multi-agent dicts for multi-agent. + pipeline.append(ListifyDataForVectorEnv()) + + return pipeline + + def build_learner_connector( + self, + input_observation_space, + input_action_space, + device=None, + ) -> ConnectorV2: + from ray.rllib.connectors.learner import ( + AddColumnsFromEpisodesToTrainBatch, + AddObservationsFromEpisodesToBatch, + AddStatesFromEpisodesToBatch, + AddTimeDimToBatchAndZeroPad, + AgentToModuleMapping, + BatchIndividualItems, + LearnerConnectorPipeline, + NumpyToTensor, + ) + + custom_connectors = [] + # Create a learner connector pipeline (including RLlib's default + # learner connector piece) and return it. + if self._learner_connector is not None: + val_ = self._learner_connector( + input_observation_space, + input_action_space, + # device, # TODO (sven): Also pass device into custom builder. + ) + + # ConnectorV2 (piece or pipeline). + if isinstance(val_, ConnectorV2): + custom_connectors = [val_] + # Sequence of individual ConnectorV2 pieces. + elif isinstance(val_, (list, tuple)): + custom_connectors = list(val_) + # Unsupported return value. + else: + raise ValueError( + "`AlgorithmConfig.learners(learner_connector=..)` must return " + "a ConnectorV2 object or a list thereof to be added to a connector " + f"pipeline! Your function returned {val_}." + ) + + pipeline = LearnerConnectorPipeline( + connectors=custom_connectors, + input_observation_space=input_observation_space, + input_action_space=input_action_space, + ) + if self.add_default_connectors_to_learner_pipeline: + # Append OBS handling. + pipeline.append( + AddObservationsFromEpisodesToBatch(as_learner_connector=True) + ) + # Append all other columns handling. + pipeline.append(AddColumnsFromEpisodesToTrainBatch()) + # Append time-rank handler. + pipeline.append(AddTimeDimToBatchAndZeroPad(as_learner_connector=True)) + # Append STATE_IN/STATE_OUT handler. + pipeline.append(AddStatesFromEpisodesToBatch(as_learner_connector=True)) + # If multi-agent -> Map from AgentID-based data to ModuleID based data. + if self.is_multi_agent: + pipeline.append( + AgentToModuleMapping( + rl_module_specs=( + self.rl_module_spec.rl_module_specs + if isinstance(self.rl_module_spec, MultiRLModuleSpec) + else set(self.policies) + ), + agent_to_module_mapping_fn=self.policy_mapping_fn, + ) + ) + # Batch all data. + pipeline.append(BatchIndividualItems(multi_agent=self.is_multi_agent)) + # Convert to Tensors. + pipeline.append(NumpyToTensor(as_learner_connector=True, device=device)) + return pipeline + + def build_learner_group( + self, + *, + env: Optional[EnvType] = None, + spaces: Optional[Dict[ModuleID, Tuple[gym.Space, gym.Space]]] = None, + rl_module_spec: Optional[RLModuleSpecType] = None, + placement_group: Optional["PlacementGroup"] = None, + ) -> "LearnerGroup": + """Builds and returns a new LearnerGroup object based on settings in `self`. + + Args: + env: An optional EnvType object (e.g. a gym.Env) useful for extracting space + information for the to-be-constructed RLModule inside the LearnerGroup's + Learner workers. Note that if RLlib cannot infer any space information + either from this `env` arg, from the optional `spaces` arg or from + `self`, the LearnerGroup cannot be created. + spaces: An optional dict mapping ModuleIDs to + (observation-space, action-space)-tuples for the to-be-constructed + RLModule inside the LearnerGroup's Learner workers. Note that if RLlib + cannot infer any space information either from this `spces` arg, + from the optional `env` arg or from `self`, the LearnerGroup cannot + be created. + rl_module_spec: An optional (single-agent or multi-agent) RLModuleSpec to + use for the constructed LearnerGroup. If None, RLlib tries to infer + the RLModuleSpec using the other information given and stored in this + `AlgorithmConfig` object. + + Returns: + The newly created `LearnerGroup` object. + """ + from ray.rllib.core.learner.learner_group import LearnerGroup + + # If `spaces` or `env` provided -> Create a MultiRLModuleSpec first to be + # passed into the LearnerGroup constructor. + if rl_module_spec is None: + rl_module_spec = self.get_multi_rl_module_spec(env=env, spaces=spaces) + + # Construct the actual LearnerGroup. + learner_group = LearnerGroup( + config=self.copy(), + module_spec=rl_module_spec, + placement_group=placement_group, + ) + + return learner_group + + def build_learner( + self, + *, + env: Optional[EnvType] = None, + spaces: Optional[Dict[PolicyID, Tuple[gym.Space, gym.Space]]] = None, + ) -> "Learner": + """Builds and returns a new Learner object based on settings in `self`. + + This Learner object already has its `build()` method called, meaning + its RLModule is already constructed. + + Args: + env: An optional EnvType object (e.g. a gym.Env) useful for extracting space + information for the to-be-constructed RLModule inside the Learner. + Note that if RLlib cannot infer any space information + either from this `env` arg, from the optional `spaces` arg or from + `self`, the Learner cannot be created. + spaces: An optional dict mapping ModuleIDs to + (observation-space, action-space)-tuples for the to-be-constructed + RLModule inside the Learner. Note that if RLlib cannot infer any + space information either from this `spces` arg, from the optional + `env` arg or from `self`, the Learner cannot be created. + + Returns: + The newly created (and already built) Learner object. + """ + # If `spaces` or `env` provided -> Create a MultiRLModuleSpec first to be + # passed into the LearnerGroup constructor. + rl_module_spec = None + if env is not None or spaces is not None: + rl_module_spec = self.get_multi_rl_module_spec(env=env, spaces=spaces) + # Construct the actual Learner object. + learner = self.learner_class(config=self, module_spec=rl_module_spec) + # `build()` the Learner (internal structures such as RLModule, etc..). + learner.build() + + return learner + + def get_config_for_module(self, module_id: ModuleID) -> "AlgorithmConfig": + """Returns an AlgorithmConfig object, specific to the given module ID. + + In a multi-agent setup, individual modules might override one or more + AlgorithmConfig properties (e.g. `train_batch_size`, `lr`) using the + `overrides()` method. + + In order to retrieve a full AlgorithmConfig instance (with all these overrides + already translated and built-in), users can call this method with the respective + module ID. + + Args: + module_id: The module ID for which to get the final AlgorithmConfig object. + + Returns: + A new AlgorithmConfig object for the specific module ID. + """ + # ModuleID NOT found in cached ModuleID, but in overrides dict. + # Create new algo config object and cache it. + if ( + module_id not in self._per_module_overrides + and module_id in self.algorithm_config_overrides_per_module + ): + self._per_module_overrides[module_id] = self.copy().update_from_dict( + self.algorithm_config_overrides_per_module[module_id] + ) + + # Return the module specific algo config object. + if module_id in self._per_module_overrides: + return self._per_module_overrides[module_id] + # No overrides for ModuleID -> return self. + else: + return self + + def python_environment( + self, + *, + extra_python_environs_for_driver: Optional[dict] = NotProvided, + extra_python_environs_for_worker: Optional[dict] = NotProvided, + ) -> "AlgorithmConfig": + """Sets the config's python environment settings. + + Args: + extra_python_environs_for_driver: Any extra python env vars to set in the + algorithm's process, e.g., {"OMP_NUM_THREADS": "16"}. + extra_python_environs_for_worker: The extra python environments need to set + for worker processes. + + Returns: + This updated AlgorithmConfig object. + """ + if extra_python_environs_for_driver is not NotProvided: + self.extra_python_environs_for_driver = extra_python_environs_for_driver + if extra_python_environs_for_worker is not NotProvided: + self.extra_python_environs_for_worker = extra_python_environs_for_worker + return self + + def resources( + self, + *, + num_cpus_for_main_process: Optional[int] = NotProvided, + num_gpus: Optional[Union[float, int]] = NotProvided, # @OldAPIStack + _fake_gpus: Optional[bool] = NotProvided, # @OldAPIStack + placement_strategy: Optional[str] = NotProvided, + # Deprecated args. + num_cpus_per_worker=DEPRECATED_VALUE, # moved to `env_runners` + num_gpus_per_worker=DEPRECATED_VALUE, # moved to `env_runners` + custom_resources_per_worker=DEPRECATED_VALUE, # moved to `env_runners` + num_learner_workers=DEPRECATED_VALUE, # moved to `learners` + num_cpus_per_learner_worker=DEPRECATED_VALUE, # moved to `learners` + num_gpus_per_learner_worker=DEPRECATED_VALUE, # moved to `learners` + local_gpu_idx=DEPRECATED_VALUE, # moved to `learners` + num_cpus_for_local_worker=DEPRECATED_VALUE, + ) -> "AlgorithmConfig": + """Specifies resources allocated for an Algorithm and its ray actors/workers. + + Args: + num_cpus_for_main_process: Number of CPUs to allocate for the main algorithm + process that runs `Algorithm.training_step()`. + Note: This is only relevant when running RLlib through Tune. Otherwise, + `Algorithm.training_step()` runs in the main program (driver). + num_gpus: Number of GPUs to allocate to the algorithm process. + Note that not all algorithms can take advantage of GPUs. + Support for multi-GPU is currently only available for + tf-[PPO/IMPALA/DQN/PG]. This can be fractional (e.g., 0.3 GPUs). + _fake_gpus: Set to True for debugging (multi-)?GPU funcitonality on a + CPU machine. GPU towers are simulated by graphs located on + CPUs in this case. Use `num_gpus` to test for different numbers of + fake GPUs. + placement_strategy: The strategy for the placement group factory returned by + `Algorithm.default_resource_request()`. A PlacementGroup defines, which + devices (resources) should always be co-located on the same node. + For example, an Algorithm with 2 EnvRunners and 1 Learner (with + 1 GPU) requests a placement group with the bundles: + [{"cpu": 1}, {"gpu": 1, "cpu": 1}, {"cpu": 1}, {"cpu": 1}], where the + first bundle is for the local (main Algorithm) process, the second one + for the 1 Learner worker and the last 2 bundles are for the two + EnvRunners. These bundles can now be "placed" on the same or different + nodes depending on the value of `placement_strategy`: + "PACK": Packs bundles into as few nodes as possible. + "SPREAD": Places bundles across distinct nodes as even as possible. + "STRICT_PACK": Packs bundles into one node. The group is not allowed + to span multiple nodes. + "STRICT_SPREAD": Packs bundles across distinct nodes. + + Returns: + This updated AlgorithmConfig object. + """ + if num_cpus_per_worker != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.resources(num_cpus_per_worker)", + new="AlgorithmConfig.env_runners(num_cpus_per_env_runner)", + error=False, + ) + self.num_cpus_per_env_runner = num_cpus_per_worker + + if num_gpus_per_worker != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.resources(num_gpus_per_worker)", + new="AlgorithmConfig.env_runners(num_gpus_per_env_runner)", + error=False, + ) + self.num_gpus_per_env_runner = num_gpus_per_worker + + if custom_resources_per_worker != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.resources(custom_resources_per_worker)", + new="AlgorithmConfig.env_runners(custom_resources_per_env_runner)", + error=False, + ) + self.custom_resources_per_env_runner = custom_resources_per_worker + + if num_learner_workers != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.resources(num_learner_workers)", + new="AlgorithmConfig.learners(num_learner)", + error=False, + ) + self.num_learners = num_learner_workers + + if num_cpus_per_learner_worker != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.resources(num_cpus_per_learner_worker)", + new="AlgorithmConfig.learners(num_cpus_per_learner)", + error=False, + ) + self.num_cpus_per_learner = num_cpus_per_learner_worker + + if num_gpus_per_learner_worker != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.resources(num_gpus_per_learner_worker)", + new="AlgorithmConfig.learners(num_gpus_per_learner)", + error=False, + ) + self.num_gpus_per_learner = num_gpus_per_learner_worker + + if local_gpu_idx != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.resources(local_gpu_idx)", + new="AlgorithmConfig.learners(local_gpu_idx)", + error=False, + ) + self.local_gpu_idx = local_gpu_idx + + if num_cpus_for_local_worker != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.resources(num_cpus_for_local_worker)", + new="AlgorithmConfig.resources(num_cpus_for_main_process)", + error=False, + ) + self.num_cpus_for_main_process = num_cpus_for_local_worker + + if num_cpus_for_main_process is not NotProvided: + self.num_cpus_for_main_process = num_cpus_for_main_process + if num_gpus is not NotProvided: + self.num_gpus = num_gpus + if _fake_gpus is not NotProvided: + self._fake_gpus = _fake_gpus + if placement_strategy is not NotProvided: + self.placement_strategy = placement_strategy + + return self + + def framework( + self, + framework: Optional[str] = NotProvided, + *, + eager_tracing: Optional[bool] = NotProvided, + eager_max_retraces: Optional[int] = NotProvided, + tf_session_args: Optional[Dict[str, Any]] = NotProvided, + local_tf_session_args: Optional[Dict[str, Any]] = NotProvided, + torch_compile_learner: Optional[bool] = NotProvided, + torch_compile_learner_what_to_compile: Optional[str] = NotProvided, + torch_compile_learner_dynamo_mode: Optional[str] = NotProvided, + torch_compile_learner_dynamo_backend: Optional[str] = NotProvided, + torch_compile_worker: Optional[bool] = NotProvided, + torch_compile_worker_dynamo_backend: Optional[str] = NotProvided, + torch_compile_worker_dynamo_mode: Optional[str] = NotProvided, + torch_ddp_kwargs: Optional[Dict[str, Any]] = NotProvided, + torch_skip_nan_gradients: Optional[bool] = NotProvided, + ) -> "AlgorithmConfig": + """Sets the config's DL framework settings. + + Args: + framework: torch: PyTorch; tf2: TensorFlow 2.x (eager execution or traced + if eager_tracing=True); tf: TensorFlow (static-graph); + eager_tracing: Enable tracing in eager mode. This greatly improves + performance (speedup ~2x), but makes it slightly harder to debug + since Python code won't be evaluated after the initial eager pass. + Only possible if framework=tf2. + eager_max_retraces: Maximum number of tf.function re-traces before a + runtime error is raised. This is to prevent unnoticed retraces of + methods inside the `..._eager_traced` Policy, which could slow down + execution by a factor of 4, without the user noticing what the root + cause for this slowdown could be. + Only necessary for framework=tf2. + Set to None to ignore the re-trace count and never throw an error. + tf_session_args: Configures TF for single-process operation by default. + local_tf_session_args: Override the following tf session args on the local + worker + torch_compile_learner: If True, forward_train methods on TorchRLModules + on the learner are compiled. If not specified, the default is to compile + forward train on the learner. + torch_compile_learner_what_to_compile: A TorchCompileWhatToCompile + mode specifying what to compile on the learner side if + torch_compile_learner is True. See TorchCompileWhatToCompile for + details and advice on its usage. + torch_compile_learner_dynamo_backend: The torch dynamo backend to use on + the learner. + torch_compile_learner_dynamo_mode: The torch dynamo mode to use on the + learner. + torch_compile_worker: If True, forward exploration and inference methods on + TorchRLModules on the workers are compiled. If not specified, + the default is to not compile forward methods on the workers because + retracing can be expensive. + torch_compile_worker_dynamo_backend: The torch dynamo backend to use on + the workers. + torch_compile_worker_dynamo_mode: The torch dynamo mode to use on the + workers. + torch_ddp_kwargs: The kwargs to pass into + `torch.nn.parallel.DistributedDataParallel` when using `num_learners + > 1`. This is specifically helpful when searching for unused parameters + that are not used in the backward pass. This can give hints for errors + in custom models where some parameters do not get touched in the + backward pass although they should. + torch_skip_nan_gradients: If updates with `nan` gradients should be entirely + skipped. This skips updates in the optimizer entirely if they contain + any `nan` gradient. This can help to avoid biasing moving-average based + optimizers - like Adam. This can help in training phases where policy + updates can be highly unstable such as during the early stages of + training or with highly exploratory policies. In such phases many + gradients might turn `nan` and setting them to zero could corrupt the + optimizer's internal state. The default is `False` and turns `nan` + gradients to zero. If many `nan` gradients are encountered consider (a) + monitoring gradients by setting `log_gradients` in `AlgorithmConfig` to + `True`, (b) use proper weight initialization (e.g. Xavier, Kaiming) via + the `model_config_dict` in `AlgorithmConfig.rl_module` and/or (c) + gradient clipping via `grad_clip` in `AlgorithmConfig.training`. + + Returns: + This updated AlgorithmConfig object. + """ + if framework is not NotProvided: + if framework == "tfe": + deprecation_warning( + old="AlgorithmConfig.framework('tfe')", + new="AlgorithmConfig.framework('tf2')", + error=True, + ) + self.framework_str = framework + if eager_tracing is not NotProvided: + self.eager_tracing = eager_tracing + if eager_max_retraces is not NotProvided: + self.eager_max_retraces = eager_max_retraces + if tf_session_args is not NotProvided: + self.tf_session_args = tf_session_args + if local_tf_session_args is not NotProvided: + self.local_tf_session_args = local_tf_session_args + + if torch_compile_learner is not NotProvided: + self.torch_compile_learner = torch_compile_learner + if torch_compile_learner_dynamo_backend is not NotProvided: + self.torch_compile_learner_dynamo_backend = ( + torch_compile_learner_dynamo_backend + ) + if torch_compile_learner_dynamo_mode is not NotProvided: + self.torch_compile_learner_dynamo_mode = torch_compile_learner_dynamo_mode + if torch_compile_learner_what_to_compile is not NotProvided: + self.torch_compile_learner_what_to_compile = ( + torch_compile_learner_what_to_compile + ) + if torch_compile_worker is not NotProvided: + self.torch_compile_worker = torch_compile_worker + if torch_compile_worker_dynamo_backend is not NotProvided: + self.torch_compile_worker_dynamo_backend = ( + torch_compile_worker_dynamo_backend + ) + if torch_compile_worker_dynamo_mode is not NotProvided: + self.torch_compile_worker_dynamo_mode = torch_compile_worker_dynamo_mode + if torch_ddp_kwargs is not NotProvided: + self.torch_ddp_kwargs = torch_ddp_kwargs + if torch_skip_nan_gradients is not NotProvided: + self.torch_skip_nan_gradients = torch_skip_nan_gradients + + return self + + def api_stack( + self, + enable_rl_module_and_learner: Optional[bool] = NotProvided, + enable_env_runner_and_connector_v2: Optional[bool] = NotProvided, + ) -> "AlgorithmConfig": + """Sets the config's API stack settings. + + Args: + enable_rl_module_and_learner: Enables the usage of `RLModule` (instead of + `ModelV2`) and Learner (instead of the training-related parts of + `Policy`). Must be used with `enable_env_runner_and_connector_v2=True`. + Together, these two settings activate the "new API stack" of RLlib. + enable_env_runner_and_connector_v2: Enables the usage of EnvRunners + (SingleAgentEnvRunner and MultiAgentEnvRunner) and ConnectorV2. + When setting this to True, `enable_rl_module_and_learner` must be True + as well. Together, these two settings activate the "new API stack" of + RLlib. + + Returns: + This updated AlgorithmConfig object. + """ + if enable_rl_module_and_learner is not NotProvided: + self.enable_rl_module_and_learner = enable_rl_module_and_learner + + if enable_rl_module_and_learner is True and self.exploration_config: + self._prior_exploration_config = self.exploration_config + self.exploration_config = {} + + elif enable_rl_module_and_learner is False and not self.exploration_config: + if self._prior_exploration_config is not None: + self.exploration_config = self._prior_exploration_config + self._prior_exploration_config = None + else: + logger.warning( + "config.enable_rl_module_and_learner was set to False, but no " + "prior exploration config was found to be restored." + ) + + if enable_env_runner_and_connector_v2 is not NotProvided: + self.enable_env_runner_and_connector_v2 = enable_env_runner_and_connector_v2 + + return self + + def environment( + self, + env: Optional[Union[str, EnvType]] = NotProvided, + *, + env_config: Optional[EnvConfigDict] = NotProvided, + observation_space: Optional[gym.Space] = NotProvided, + action_space: Optional[gym.Space] = NotProvided, + render_env: Optional[bool] = NotProvided, + clip_rewards: Optional[Union[bool, float]] = NotProvided, + normalize_actions: Optional[bool] = NotProvided, + clip_actions: Optional[bool] = NotProvided, + disable_env_checking: Optional[bool] = NotProvided, + is_atari: Optional[bool] = NotProvided, + action_mask_key: Optional[str] = NotProvided, + # Deprecated args. + env_task_fn=DEPRECATED_VALUE, + ) -> "AlgorithmConfig": + """Sets the config's RL-environment settings. + + Args: + env: The environment specifier. This can either be a tune-registered env, + via `tune.register_env([name], lambda env_ctx: [env object])`, + or a string specifier of an RLlib supported type. In the latter case, + RLlib tries to interpret the specifier as either an Farama-Foundation + gymnasium env, a PyBullet env, or a fully qualified classpath to an Env + class, e.g. "ray.rllib.examples.envs.classes.random_env.RandomEnv". + env_config: Arguments dict passed to the env creator as an EnvContext + object (which is a dict plus the properties: `num_env_runners`, + `worker_index`, `vector_index`, and `remote`). + observation_space: The observation space for the Policies of this Algorithm. + action_space: The action space for the Policies of this Algorithm. + render_env: If True, try to render the environment on the local worker or on + worker 1 (if num_env_runners > 0). For vectorized envs, this usually + means that only the first sub-environment is rendered. + In order for this to work, your env has to implement the + `render()` method which either: + a) handles window generation and rendering itself (returning True) or + b) returns a numpy uint8 image of shape [height x width x 3 (RGB)]. + clip_rewards: Whether to clip rewards during Policy's postprocessing. + None (default): Clip for Atari only (r=sign(r)). + True: r=sign(r): Fixed rewards -1.0, 1.0, or 0.0. + False: Never clip. + [float value]: Clip at -value and + value. + Tuple[value1, value2]: Clip at value1 and value2. + normalize_actions: If True, RLlib learns entirely inside a normalized + action space (0.0 centered with small stddev; only affecting Box + components). RLlib unsquashes actions (and clip, just in case) to the + bounds of the env's action space before sending actions back to the env. + clip_actions: If True, the RLlib default ModuleToEnv connector clips + actions according to the env's bounds (before sending them into the + `env.step()` call). + disable_env_checking: Disable RLlib's env checks after a gymnasium.Env + instance has been constructed in an EnvRunner. Note that the checks + include an `env.reset()` and `env.step()` (with a random action), which + might tinker with your env's logic and behavior and thus negatively + influence sample collection- and/or learning behavior. + is_atari: This config can be used to explicitly specify whether the env is + an Atari env or not. If not specified, RLlib tries to auto-detect + this. + action_mask_key: If observation is a dictionary, expect the value by + the key `action_mask_key` to contain a valid actions mask (`numpy.int8` + array of zeros and ones). Defaults to "action_mask". + + Returns: + This updated AlgorithmConfig object. + """ + if env_task_fn != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.environment(env_task_fn=..)", + error=True, + ) + if env is not NotProvided: + self.env = env + if env_config is not NotProvided: + deep_update(self.env_config, env_config, True) + if observation_space is not NotProvided: + self.observation_space = observation_space + if action_space is not NotProvided: + self.action_space = action_space + if render_env is not NotProvided: + self.render_env = render_env + if clip_rewards is not NotProvided: + self.clip_rewards = clip_rewards + if normalize_actions is not NotProvided: + self.normalize_actions = normalize_actions + if clip_actions is not NotProvided: + self.clip_actions = clip_actions + if disable_env_checking is not NotProvided: + self.disable_env_checking = disable_env_checking + if is_atari is not NotProvided: + self._is_atari = is_atari + if action_mask_key is not NotProvided: + self.action_mask_key = action_mask_key + + return self + + def env_runners( + self, + *, + env_runner_cls: Optional[type] = NotProvided, + num_env_runners: Optional[int] = NotProvided, + create_local_env_runner: Optional[bool] = NotProvided, + create_env_on_local_worker: Optional[bool] = NotProvided, + num_envs_per_env_runner: Optional[int] = NotProvided, + gym_env_vectorize_mode: Optional[str] = NotProvided, + num_cpus_per_env_runner: Optional[int] = NotProvided, + num_gpus_per_env_runner: Optional[Union[float, int]] = NotProvided, + custom_resources_per_env_runner: Optional[dict] = NotProvided, + validate_env_runners_after_construction: Optional[bool] = NotProvided, + sample_timeout_s: Optional[float] = NotProvided, + max_requests_in_flight_per_env_runner: Optional[int] = NotProvided, + env_to_module_connector: Optional[ + Callable[[EnvType], Union["ConnectorV2", List["ConnectorV2"]]] + ] = NotProvided, + module_to_env_connector: Optional[ + Callable[[EnvType, "RLModule"], Union["ConnectorV2", List["ConnectorV2"]]] + ] = NotProvided, + add_default_connectors_to_env_to_module_pipeline: Optional[bool] = NotProvided, + add_default_connectors_to_module_to_env_pipeline: Optional[bool] = NotProvided, + episode_lookback_horizon: Optional[int] = NotProvided, + merge_env_runner_states: Optional[Union[str, bool]] = NotProvided, + broadcast_env_runner_states: Optional[bool] = NotProvided, + compress_observations: Optional[bool] = NotProvided, + rollout_fragment_length: Optional[Union[int, str]] = NotProvided, + batch_mode: Optional[str] = NotProvided, + explore: Optional[bool] = NotProvided, + episodes_to_numpy: Optional[bool] = NotProvided, + # @OldAPIStack settings. + use_worker_filter_stats: Optional[bool] = NotProvided, + update_worker_filter_stats: Optional[bool] = NotProvided, + exploration_config: Optional[dict] = NotProvided, # @OldAPIStack + sample_collector: Optional[Type[SampleCollector]] = NotProvided, # @OldAPIStack + remote_worker_envs: Optional[bool] = NotProvided, # @OldAPIStack + remote_env_batch_wait_ms: Optional[float] = NotProvided, # @OldAPIStack + preprocessor_pref: Optional[str] = NotProvided, # @OldAPIStack + observation_filter: Optional[str] = NotProvided, # @OldAPIStack + enable_tf1_exec_eagerly: Optional[bool] = NotProvided, # @OldAPIStack + sampler_perf_stats_ema_coef: Optional[float] = NotProvided, # @OldAPIStack + # Deprecated args. + num_rollout_workers=DEPRECATED_VALUE, + num_envs_per_worker=DEPRECATED_VALUE, + validate_workers_after_construction=DEPRECATED_VALUE, + ignore_worker_failures=DEPRECATED_VALUE, + recreate_failed_workers=DEPRECATED_VALUE, + restart_failed_sub_environments=DEPRECATED_VALUE, + num_consecutive_worker_failures_tolerance=DEPRECATED_VALUE, + worker_health_probe_timeout_s=DEPRECATED_VALUE, + worker_restore_timeout_s=DEPRECATED_VALUE, + synchronize_filter=DEPRECATED_VALUE, + enable_connectors=DEPRECATED_VALUE, + ) -> "AlgorithmConfig": + """Sets the rollout worker configuration. + + Args: + env_runner_cls: The EnvRunner class to use for environment rollouts (data + collection). + num_env_runners: Number of EnvRunner actors to create for parallel sampling. + Setting this to 0 forces sampling to be done in the local + EnvRunner (main process or the Algorithm's actor when using Tune). + num_envs_per_env_runner: Number of environments to step through + (vector-wise) per EnvRunner. This enables batching when computing + actions through RLModule inference, which can improve performance + for inference-bottlenecked workloads. + gym_env_vectorize_mode: The gymnasium vectorization mode for vector envs. + Must be a `gymnasium.envs.registration.VectorizeMode` (enum) value. + Default is SYNC. Set this to ASYNC to parallelize the individual sub + environments within the vector. This can speed up your EnvRunners + significantly when using heavier environments. + num_cpus_per_env_runner: Number of CPUs to allocate per EnvRunner. + num_gpus_per_env_runner: Number of GPUs to allocate per EnvRunner. This can + be fractional. This is usually needed only if your env itself requires a + GPU (i.e., it is a GPU-intensive video game), or model inference is + unusually expensive. + custom_resources_per_env_runner: Any custom Ray resources to allocate per + EnvRunner. + sample_timeout_s: The timeout in seconds for calling `sample()` on remote + EnvRunner workers. Results (episode list) from workers that take longer + than this time are discarded. Only used by algorithms that sample + synchronously in turn with their update step (e.g., PPO or DQN). Not + relevant for any algos that sample asynchronously, such as APPO or + IMPALA. + max_requests_in_flight_per_env_runner: Max number of in-flight requests + to each EnvRunner (actor)). See the + `ray.rllib.utils.actor_manager.FaultTolerantActorManager` class for more + details. + Tuning these values is important when running experiments with + large sample batches, where there is the risk that the object store may + fill up, causing spilling of objects to disk. This can cause any + asynchronous requests to become very slow, making your experiment run + slowly as well. You can inspect the object store during your experiment + through a call to `ray memory` on your head node, and by using the Ray + dashboard. If you're seeing that the object store is filling up, + turn down the number of remote requests in flight or enable compression + or increase the object store memory through, for example: + `ray.init(object_store_memory=10 * 1024 * 1024 * 1024) # =10 GB` + sample_collector: For the old API stack only. The SampleCollector class to + be used to collect and retrieve environment-, model-, and sampler data. + Override the SampleCollector base class to implement your own + collection/buffering/retrieval logic. + create_local_env_runner: If True, create a local EnvRunner instance, besides + the `num_env_runners` remote EnvRunner actors. If `num_env_runners` is + 0, this setting is ignored and one local EnvRunner is created + regardless. + create_env_on_local_worker: When `num_env_runners` > 0, the driver + (local_worker; worker-idx=0) does not need an environment. This is + because it doesn't have to sample (done by remote_workers; + worker_indices > 0) nor evaluate (done by evaluation workers; + see below). + env_to_module_connector: A callable taking an Env as input arg and returning + an env-to-module ConnectorV2 (might be a pipeline) object. + module_to_env_connector: A callable taking an Env and an RLModule as input + args and returning a module-to-env ConnectorV2 (might be a pipeline) + object. + add_default_connectors_to_env_to_module_pipeline: If True (default), RLlib's + EnvRunners automatically add the default env-to-module ConnectorV2 + pieces to the EnvToModulePipeline. These automatically perform adding + observations and states (in case of stateful Module(s)), agent-to-module + mapping, batching, and conversion to tensor data. Only if you know + exactly what you are doing, you should set this setting to False. + Note that this setting is only relevant if the new API stack is used + (including the new EnvRunner classes). + add_default_connectors_to_module_to_env_pipeline: If True (default), RLlib's + EnvRunners automatically add the default module-to-env ConnectorV2 + pieces to the ModuleToEnvPipeline. These automatically perform removing + the additional time-rank (if applicable, in case of stateful + Module(s)), module-to-agent unmapping, un-batching (to lists), and + conversion from tensor data to numpy. Only if you know exactly what you + are doing, you should set this setting to False. + Note that this setting is only relevant if the new API stack is used + (including the new EnvRunner classes). + episode_lookback_horizon: The amount of data (in timesteps) to keep from the + preceeding episode chunk when a new chunk (for the same episode) is + generated to continue sampling at a later time. The larger this value, + the more an env-to-module connector can look back in time + and compile RLModule input data from this information. For example, if + your custom env-to-module connector (and your custom RLModule) requires + the previous 10 rewards as inputs, you must set this to at least 10. + merge_env_runner_states: True, if remote EnvRunner actor states should be + merged into central connector pipelines. Use "training_only" (default) + for only doing this for the training EnvRunners, NOT for the evaluation + EnvRunners. + broadcast_env_runner_states: True, if merged EnvRunner states (from the + central connector pipelines) should be broadcast back to all remote + EnvRunner actors. + use_worker_filter_stats: Whether to use the workers in the EnvRunnerGroup to + update the central filters (held by the local worker). If False, stats + from the workers aren't used and are discarded. + update_worker_filter_stats: Whether to push filter updates from the central + filters (held by the local worker) to the remote workers' filters. + Setting this to True might be useful within the evaluation config in + order to disable the usage of evaluation trajectories for synching + the central filter (used for training). + rollout_fragment_length: Divide episodes into fragments of this many steps + each during sampling. Trajectories of this size are collected from + EnvRunners and combined into a larger batch of `train_batch_size` + for learning. + For example, given rollout_fragment_length=100 and + train_batch_size=1000: + 1. RLlib collects 10 fragments of 100 steps each from rollout workers. + 2. These fragments are concatenated and we perform an epoch of SGD. + When using multiple envs per worker, the fragment size is multiplied by + `num_envs_per_env_runner`. This is since we are collecting steps from + multiple envs in parallel. For example, if num_envs_per_env_runner=5, + then EnvRunners return experiences in chunks of 5*100 = 500 steps. + The dataflow here can vary per algorithm. For example, PPO further + divides the train batch into minibatches for multi-epoch SGD. + Set `rollout_fragment_length` to "auto" to have RLlib compute an exact + value to match the given batch size. + batch_mode: How to build individual batches with the EnvRunner(s). Batches + coming from distributed EnvRunners are usually concat'd to form the + train batch. Note that "steps" below can mean different things (either + env- or agent-steps) and depends on the `count_steps_by` setting, + adjustable via `AlgorithmConfig.multi_agent(count_steps_by=..)`: + 1) "truncate_episodes": Each call to `EnvRunner.sample()` returns a + batch of at most `rollout_fragment_length * num_envs_per_env_runner` in + size. The batch is exactly `rollout_fragment_length * num_envs` + in size if postprocessing does not change batch sizes. Episodes + may be truncated in order to meet this size requirement. + This mode guarantees evenly sized batches, but increases + variance as the future return must now be estimated at truncation + boundaries. + 2) "complete_episodes": Each call to `EnvRunner.sample()` returns a + batch of at least `rollout_fragment_length * num_envs_per_env_runner` in + size. Episodes aren't truncated, but multiple episodes + may be packed within one batch to meet the (minimum) batch size. + Note that when `num_envs_per_env_runner > 1`, episode steps are + buffered until the episode completes, and hence batches may contain + significant amounts of off-policy data. + explore: Default exploration behavior, iff `explore=None` is passed into + compute_action(s). Set to False for no exploration behavior (e.g., + for evaluation). + episodes_to_numpy: Whether to numpy'ize episodes before + returning them from an EnvRunner. False by default. If True, EnvRunners + call `to_numpy()` on those episode (chunks) to be returned by + `EnvRunners.sample()`. + exploration_config: A dict specifying the Exploration object's config. + remote_worker_envs: If using num_envs_per_env_runner > 1, whether to create + those new envs in remote processes instead of in the same worker. + This adds overheads, but can make sense if your envs can take much + time to step / reset (e.g., for StarCraft). Use this cautiously; + overheads are significant. + remote_env_batch_wait_ms: Timeout that remote workers are waiting when + polling environments. 0 (continue when at least one env is ready) is + a reasonable default, but optimal value could be obtained by measuring + your environment step / reset and model inference perf. + validate_env_runners_after_construction: Whether to validate that each + created remote EnvRunner is healthy after its construction process. + preprocessor_pref: Whether to use "rllib" or "deepmind" preprocessors by + default. Set to None for using no preprocessor. In this case, the + model has to handle possibly complex observations from the + environment. + observation_filter: Element-wise observation filter, either "NoFilter" + or "MeanStdFilter". + compress_observations: Whether to LZ4 compress individual observations + in the SampleBatches collected during rollouts. + enable_tf1_exec_eagerly: Explicitly tells the rollout worker to enable + TF eager execution. This is useful for example when framework is + "torch", but a TF2 policy needs to be restored for evaluation or + league-based purposes. + sampler_perf_stats_ema_coef: If specified, perf stats are in EMAs. This + is the coeff of how much new data points contribute to the averages. + Default is None, which uses simple global average instead. + The EMA update rule is: updated = (1 - ema_coef) * old + ema_coef * new + + Returns: + This updated AlgorithmConfig object. + """ + if enable_connectors != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.env_runners(enable_connectors=...)", + error=False, + ) + if num_rollout_workers != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.env_runners(num_rollout_workers)", + new="AlgorithmConfig.env_runners(num_env_runners)", + error=True, + ) + if num_envs_per_worker != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.env_runners(num_envs_per_worker)", + new="AlgorithmConfig.env_runners(num_envs_per_env_runner)", + error=True, + ) + if validate_workers_after_construction != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.env_runners(validate_workers_after_construction)", + new="AlgorithmConfig.env_runners(validate_env_runners_after_" + "construction)", + error=True, + ) + + if env_runner_cls is not NotProvided: + self.env_runner_cls = env_runner_cls + if num_env_runners is not NotProvided: + self.num_env_runners = num_env_runners + if num_envs_per_env_runner is not NotProvided: + if num_envs_per_env_runner <= 0: + raise ValueError( + f"`num_envs_per_env_runner` ({num_envs_per_env_runner}) must be " + "larger 0!" + ) + self.num_envs_per_env_runner = num_envs_per_env_runner + if gym_env_vectorize_mode is not NotProvided: + self.gym_env_vectorize_mode = gym_env_vectorize_mode + if num_cpus_per_env_runner is not NotProvided: + self.num_cpus_per_env_runner = num_cpus_per_env_runner + if num_gpus_per_env_runner is not NotProvided: + self.num_gpus_per_env_runner = num_gpus_per_env_runner + if custom_resources_per_env_runner is not NotProvided: + self.custom_resources_per_env_runner = custom_resources_per_env_runner + + if sample_timeout_s is not NotProvided: + self.sample_timeout_s = sample_timeout_s + if max_requests_in_flight_per_env_runner is not NotProvided: + self.max_requests_in_flight_per_env_runner = ( + max_requests_in_flight_per_env_runner + ) + if sample_collector is not NotProvided: + self.sample_collector = sample_collector + if create_local_env_runner is not NotProvided: + self.create_local_env_runner = create_local_env_runner + if create_env_on_local_worker is not NotProvided: + self.create_env_on_local_worker = create_env_on_local_worker + if env_to_module_connector is not NotProvided: + self._env_to_module_connector = env_to_module_connector + if module_to_env_connector is not NotProvided: + self._module_to_env_connector = module_to_env_connector + if add_default_connectors_to_env_to_module_pipeline is not NotProvided: + self.add_default_connectors_to_env_to_module_pipeline = ( + add_default_connectors_to_env_to_module_pipeline + ) + if add_default_connectors_to_module_to_env_pipeline is not NotProvided: + self.add_default_connectors_to_module_to_env_pipeline = ( + add_default_connectors_to_module_to_env_pipeline + ) + if episode_lookback_horizon is not NotProvided: + self.episode_lookback_horizon = episode_lookback_horizon + if merge_env_runner_states is not NotProvided: + self.merge_env_runner_states = merge_env_runner_states + if broadcast_env_runner_states is not NotProvided: + self.broadcast_env_runner_states = broadcast_env_runner_states + if use_worker_filter_stats is not NotProvided: + self.use_worker_filter_stats = use_worker_filter_stats + if update_worker_filter_stats is not NotProvided: + self.update_worker_filter_stats = update_worker_filter_stats + if rollout_fragment_length is not NotProvided: + if not ( + ( + isinstance(rollout_fragment_length, int) + and rollout_fragment_length > 0 + ) + or rollout_fragment_length == "auto" + ): + raise ValueError("`rollout_fragment_length` must be int >0 or 'auto'!") + self.rollout_fragment_length = rollout_fragment_length + if batch_mode is not NotProvided: + if batch_mode not in ["truncate_episodes", "complete_episodes"]: + raise ValueError( + f"`batch_mode` ({batch_mode}) must be one of [truncate_episodes|" + "complete_episodes]!" + ) + self.batch_mode = batch_mode + if explore is not NotProvided: + self.explore = explore + if episodes_to_numpy is not NotProvided: + self.episodes_to_numpy = episodes_to_numpy + + # @OldAPIStack + if exploration_config is not NotProvided: + # Override entire `exploration_config` if `type` key changes. + # Update, if `type` key remains the same or is not specified. + new_exploration_config = deep_update( + {"exploration_config": self.exploration_config}, + {"exploration_config": exploration_config}, + False, + ["exploration_config"], + ["exploration_config"], + ) + self.exploration_config = new_exploration_config["exploration_config"] + if remote_worker_envs is not NotProvided: + self.remote_worker_envs = remote_worker_envs + if remote_env_batch_wait_ms is not NotProvided: + self.remote_env_batch_wait_ms = remote_env_batch_wait_ms + if validate_env_runners_after_construction is not NotProvided: + self.validate_env_runners_after_construction = ( + validate_env_runners_after_construction + ) + if preprocessor_pref is not NotProvided: + self.preprocessor_pref = preprocessor_pref + if observation_filter is not NotProvided: + self.observation_filter = observation_filter + if synchronize_filter is not NotProvided: + self.synchronize_filters = synchronize_filter + if compress_observations is not NotProvided: + self.compress_observations = compress_observations + if enable_tf1_exec_eagerly is not NotProvided: + self.enable_tf1_exec_eagerly = enable_tf1_exec_eagerly + if sampler_perf_stats_ema_coef is not NotProvided: + self.sampler_perf_stats_ema_coef = sampler_perf_stats_ema_coef + + # Deprecated settings. + if synchronize_filter != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.env_runners(synchronize_filter=..)", + new="AlgorithmConfig.env_runners(update_worker_filter_stats=..)", + error=True, + ) + if ignore_worker_failures != DEPRECATED_VALUE: + deprecation_warning( + old="ignore_worker_failures is deprecated, and will soon be a no-op", + error=True, + ) + if recreate_failed_workers != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.env_runners(recreate_failed_workers=..)", + new="AlgorithmConfig.fault_tolerance(recreate_failed_workers=..)", + error=True, + ) + if restart_failed_sub_environments != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.env_runners(restart_failed_sub_environments=..)", + new=( + "AlgorithmConfig.fault_tolerance(" + "restart_failed_sub_environments=..)" + ), + error=True, + ) + if num_consecutive_worker_failures_tolerance != DEPRECATED_VALUE: + deprecation_warning( + old=( + "AlgorithmConfig.env_runners(" + "num_consecutive_worker_failures_tolerance=..)" + ), + new=( + "AlgorithmConfig.fault_tolerance(" + "num_consecutive_worker_failures_tolerance=..)" + ), + error=True, + ) + if worker_health_probe_timeout_s != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.env_runners(worker_health_probe_timeout_s=..)", + new="AlgorithmConfig.fault_tolerance(worker_health_probe_timeout_s=..)", + error=True, + ) + if worker_restore_timeout_s != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.env_runners(worker_restore_timeout_s=..)", + new="AlgorithmConfig.fault_tolerance(worker_restore_timeout_s=..)", + error=True, + ) + + return self + + def learners( + self, + *, + num_learners: Optional[int] = NotProvided, + num_cpus_per_learner: Optional[Union[str, float, int]] = NotProvided, + num_gpus_per_learner: Optional[Union[float, int]] = NotProvided, + num_aggregator_actors_per_learner: Optional[int] = NotProvided, + max_requests_in_flight_per_aggregator_actor: Optional[float] = NotProvided, + local_gpu_idx: Optional[int] = NotProvided, + max_requests_in_flight_per_learner: Optional[int] = NotProvided, + ): + """Sets LearnerGroup and Learner worker related configurations. + + Args: + num_learners: Number of Learner workers used for updating the RLModule. + A value of 0 means training takes place on a local Learner on main + process CPUs or 1 GPU (determined by `num_gpus_per_learner`). + For multi-gpu training, you have to set `num_learners` to > 1 and set + `num_gpus_per_learner` accordingly (e.g., 4 GPUs total and model fits on + 1 GPU: `num_learners=4; num_gpus_per_learner=1` OR 4 GPUs total and + model requires 2 GPUs: `num_learners=2; num_gpus_per_learner=2`). + num_cpus_per_learner: Number of CPUs allocated per Learner worker. + If "auto" (default), use 1 if `num_gpus_per_learner=0`, otherwise 0. + Only necessary for custom processing pipeline inside each Learner + requiring multiple CPU cores. + If `num_learners=0`, RLlib creates only one local Learner instance and + the number of CPUs on the main process is + `max(num_cpus_per_learner, num_cpus_for_main_process)`. + num_gpus_per_learner: Number of GPUs allocated per Learner worker. If + `num_learners=0`, any value greater than 0 runs the + training on a single GPU on the main process, while a value of 0 runs + the training on main process CPUs. + num_aggregator_actors_per_learner: The number of aggregator actors per + Learner (if num_learners=0, one local learner is created). Must be at + least 1. Aggregator actors perform the task of a) converting episodes + into a train batch and b) move that train batch to the same GPU that + the corresponding learner is located on. Good values are 1 or 2, but + this strongly depends on your setup and `EnvRunner` throughput. + max_requests_in_flight_per_aggregator_actor: How many in-flight requests + are allowed per aggregator actor before new requests are dropped? + local_gpu_idx: If `num_gpus_per_learner` > 0, and + `num_learners` < 2, then RLlib uses this GPU index for training. This is + an index into the available + CUDA devices. For example if `os.environ["CUDA_VISIBLE_DEVICES"] = "1"` + and `local_gpu_idx=0`, RLlib uses the GPU with ID=1 on the node. + max_requests_in_flight_per_learner: Max number of in-flight requests + to each Learner (actor). You normally do not have to tune this setting + (default is 3), however, for asynchronous algorithms, this determines + the "queue" size for incoming batches (or lists of episodes) into each + Learner worker, thus also determining, how much off-policy'ness would be + acceptable. The off-policy'ness is the difference between the numbers of + updates a policy has undergone on the Learner vs the EnvRunners. + See the `ray.rllib.utils.actor_manager.FaultTolerantActorManager` class + for more details. + + Returns: + This updated AlgorithmConfig object. + """ + if num_learners is not NotProvided: + self.num_learners = num_learners + if num_cpus_per_learner is not NotProvided: + self.num_cpus_per_learner = num_cpus_per_learner + if num_gpus_per_learner is not NotProvided: + self.num_gpus_per_learner = num_gpus_per_learner + if num_aggregator_actors_per_learner is not NotProvided: + self.num_aggregator_actors_per_learner = num_aggregator_actors_per_learner + if max_requests_in_flight_per_aggregator_actor is not NotProvided: + self.max_requests_in_flight_per_aggregator_actor = ( + max_requests_in_flight_per_aggregator_actor + ) + if local_gpu_idx is not NotProvided: + self.local_gpu_idx = local_gpu_idx + if max_requests_in_flight_per_learner is not NotProvided: + self.max_requests_in_flight_per_learner = max_requests_in_flight_per_learner + + return self + + def training( + self, + *, + gamma: Optional[float] = NotProvided, + lr: Optional[LearningRateOrSchedule] = NotProvided, + grad_clip: Optional[float] = NotProvided, + grad_clip_by: Optional[str] = NotProvided, + train_batch_size: Optional[int] = NotProvided, + train_batch_size_per_learner: Optional[int] = NotProvided, + num_epochs: Optional[int] = NotProvided, + minibatch_size: Optional[int] = NotProvided, + shuffle_batch_per_epoch: Optional[bool] = NotProvided, + model: Optional[dict] = NotProvided, + optimizer: Optional[dict] = NotProvided, + # Deprecated args. + num_aggregator_actors_per_learner=DEPRECATED_VALUE, + max_requests_in_flight_per_aggregator_actor=DEPRECATED_VALUE, + num_sgd_iter=DEPRECATED_VALUE, + max_requests_in_flight_per_sampler_worker=DEPRECATED_VALUE, + # Moved to `learners()` method. + learner_class: Optional[Type["Learner"]] = NotProvided, + learner_connector: Optional[ + Callable[["RLModule"], Union["ConnectorV2", List["ConnectorV2"]]] + ] = NotProvided, + add_default_connectors_to_learner_pipeline: Optional[bool] = NotProvided, + learner_config_dict: Optional[Dict[str, Any]] = NotProvided, + ) -> "AlgorithmConfig": + """Sets the training related configuration. + + Args: + gamma: Float specifying the discount factor of the Markov Decision process. + lr: The learning rate (float) or learning rate schedule in the format of + [[timestep, lr-value], [timestep, lr-value], ...] + In case of a schedule, intermediary timesteps are assigned to + linearly interpolated learning rate values. A schedule config's first + entry must start with timestep 0, i.e.: [[0, initial_value], [...]]. + Note: If you require a) more than one optimizer (per RLModule), + b) optimizer types that are not Adam, c) a learning rate schedule that + is not a linearly interpolated, piecewise schedule as described above, + or d) specifying c'tor arguments of the optimizer that are not the + learning rate (e.g. Adam's epsilon), then you must override your + Learner's `configure_optimizer_for_module()` method and handle + lr-scheduling yourself. + grad_clip: If None, no gradient clipping is applied. Otherwise, + depending on the setting of `grad_clip_by`, the (float) value of + `grad_clip` has the following effect: + If `grad_clip_by=value`: Clips all computed gradients individually + inside the interval [-`grad_clip`, +`grad_clip`]. + If `grad_clip_by=norm`, computes the L2-norm of each weight/bias + gradient tensor individually and then clip all gradients such that these + L2-norms do not exceed `grad_clip`. The L2-norm of a tensor is computed + via: `sqrt(SUM(w0^2, w1^2, ..., wn^2))` where w[i] are the elements of + the tensor (no matter what the shape of this tensor is). + If `grad_clip_by=global_norm`, computes the square of the L2-norm of + each weight/bias gradient tensor individually, sum up all these squared + L2-norms across all given gradient tensors (e.g. the entire module to + be updated), square root that overall sum, and then clip all gradients + such that this global L2-norm does not exceed the given value. + The global L2-norm over a list of tensors (e.g. W and V) is computed + via: + `sqrt[SUM(w0^2, w1^2, ..., wn^2) + SUM(v0^2, v1^2, ..., vm^2)]`, where + w[i] and v[j] are the elements of the tensors W and V (no matter what + the shapes of these tensors are). + grad_clip_by: See `grad_clip` for the effect of this setting on gradient + clipping. Allowed values are `value`, `norm`, and `global_norm`. + train_batch_size_per_learner: Train batch size per individual Learner + worker. This setting only applies to the new API stack. The number + of Learner workers can be set via `config.resources( + num_learners=...)`. The total effective batch size is then + `num_learners` x `train_batch_size_per_learner` and you can + access it with the property `AlgorithmConfig.total_train_batch_size`. + train_batch_size: Training batch size, if applicable. When on the new API + stack, this setting should no longer be used. Instead, use + `train_batch_size_per_learner` (in combination with + `num_learners`). + num_epochs: The number of complete passes over the entire train batch (per + Learner). Each pass might be further split into n minibatches (if + `minibatch_size` provided). + minibatch_size: The size of minibatches to use to further split the train + batch into. + shuffle_batch_per_epoch: Whether to shuffle the train batch once per epoch. + If the train batch has a time rank (axis=1), shuffling only takes + place along the batch axis to not disturb any intact (episode) + trajectories. + model: Arguments passed into the policy model. See models/catalog.py for a + full list of the available model options. + TODO: Provide ModelConfig objects instead of dicts. + optimizer: Arguments to pass to the policy optimizer. This setting is not + used when `enable_rl_module_and_learner=True`. + + Returns: + This updated AlgorithmConfig object. + """ + if learner_class is not NotProvided: + deprecation_warning( + old="config.training(learner_class=..)", + new="config.learners(learner_class=..)", + error=False, + ) + self._learner_class = learner_class + if learner_connector is not NotProvided: + deprecation_warning( + old="config.training(learner_connector=..)", + new="config.learners(learner_connector=..)", + error=False, + ) + self._learner_connector = learner_connector + if add_default_connectors_to_learner_pipeline is not NotProvided: + deprecation_warning( + old="config.training(add_default_connectors_to_learner_pipeline=..)", + new="config.learners(add_default_connectors_to_learner_pipeline=..)", + error=False, + ) + self.add_default_connectors_to_learner_pipeline = ( + add_default_connectors_to_learner_pipeline + ) + if learner_config_dict is not NotProvided: + deprecation_warning( + old="config.training(learner_config_dict=..)", + new="config.learners(learner_config_dict=..)", + error=False, + ) + self.learner_config_dict.update(learner_config_dict) + + if num_aggregator_actors_per_learner != DEPRECATED_VALUE: + deprecation_warning( + old="config.training(num_aggregator_actors_per_learner=..)", + new="config.learners(num_aggregator_actors_per_learner=..)", + error=False, + ) + self.num_aggregator_actors_per_learner = num_aggregator_actors_per_learner + if max_requests_in_flight_per_aggregator_actor != DEPRECATED_VALUE: + deprecation_warning( + old="config.training(max_requests_in_flight_per_aggregator_actor=..)", + new="config.learners(max_requests_in_flight_per_aggregator_actor=..)", + error=False, + ) + self.max_requests_in_flight_per_aggregator_actor = ( + max_requests_in_flight_per_aggregator_actor + ) + + if num_sgd_iter != DEPRECATED_VALUE: + deprecation_warning( + old="config.training(num_sgd_iter=..)", + new="config.training(num_epochs=..)", + error=False, + ) + num_epochs = num_sgd_iter + if max_requests_in_flight_per_sampler_worker != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.training(" + "max_requests_in_flight_per_sampler_worker=...)", + new="AlgorithmConfig.env_runners(" + "max_requests_in_flight_per_env_runner=...)", + error=False, + ) + self.env_runners( + max_requests_in_flight_per_env_runner=( + max_requests_in_flight_per_sampler_worker + ), + ) + + if gamma is not NotProvided: + self.gamma = gamma + if lr is not NotProvided: + self.lr = lr + if grad_clip is not NotProvided: + self.grad_clip = grad_clip + if grad_clip_by is not NotProvided: + if grad_clip_by not in ["value", "norm", "global_norm"]: + raise ValueError( + f"`grad_clip_by` ({grad_clip_by}) must be one of: 'value', 'norm', " + "or 'global_norm'!" + ) + self.grad_clip_by = grad_clip_by + if train_batch_size_per_learner is not NotProvided: + self._train_batch_size_per_learner = train_batch_size_per_learner + if train_batch_size is not NotProvided: + self.train_batch_size = train_batch_size + if num_epochs is not NotProvided: + self.num_epochs = num_epochs + if minibatch_size is not NotProvided: + self.minibatch_size = minibatch_size + if shuffle_batch_per_epoch is not NotProvided: + self.shuffle_batch_per_epoch = shuffle_batch_per_epoch + + if model is not NotProvided: + self.model.update(model) + if ( + model.get("_use_default_native_models", DEPRECATED_VALUE) + != DEPRECATED_VALUE + ): + deprecation_warning( + old="AlgorithmConfig.training(_use_default_native_models=True)", + help="_use_default_native_models is not supported " + "anymore. To get rid of this error, set `config.api_stack(" + "enable_rl_module_and_learner=True)`. Native models will " + "be better supported by the upcoming RLModule API.", + # Error out if user tries to enable this. + error=model["_use_default_native_models"], + ) + if optimizer is not NotProvided: + self.optimizer = merge_dicts(self.optimizer, optimizer) + + return self + + def callbacks( + self, + callbacks_class: Optional[ + Union[Type[RLlibCallback], List[Type[RLlibCallback]]] + ] = NotProvided, + *, + on_algorithm_init: Optional[Union[Callable, List[Callable]]] = NotProvided, + on_train_result: Optional[Union[Callable, List[Callable]]] = NotProvided, + on_evaluate_start: Optional[Union[Callable, List[Callable]]] = NotProvided, + on_evaluate_end: Optional[Union[Callable, List[Callable]]] = NotProvided, + on_evaluate_offline_start: Optional[ + Union[Callable, List[Callable]] + ] = NotProvided, + on_evaluate_offline_end: Optional[ + Union[Callable, List[Callable]] + ] = NotProvided, + on_env_runners_recreated: Optional[ + Union[Callable, List[Callable]] + ] = NotProvided, + on_offline_eval_runners_recreated: Optional[ + Union[Callable, List[Callable]] + ] = NotProvided, + on_checkpoint_loaded: Optional[Union[Callable, List[Callable]]] = NotProvided, + on_environment_created: Optional[Union[Callable, List[Callable]]] = NotProvided, + on_episode_created: Optional[Union[Callable, List[Callable]]] = NotProvided, + on_episode_start: Optional[Union[Callable, List[Callable]]] = NotProvided, + on_episode_step: Optional[Union[Callable, List[Callable]]] = NotProvided, + on_episode_end: Optional[Union[Callable, List[Callable]]] = NotProvided, + on_sample_end: Optional[Union[Callable, List[Callable]]] = NotProvided, + ) -> "AlgorithmConfig": + """Sets the callbacks configuration. + + Args: + callbacks_class: RLlibCallback class, whose methods are called during + various phases of training and RL environment sample collection. + TODO (sven): Change the link to new rst callbacks page. + See the `RLlibCallback` class and + `examples/metrics/custom_metrics_and_callbacks.py` for more information. + on_algorithm_init: A callable or a list of callables. If a list, RLlib calls + the items in the same sequence. `on_algorithm_init` methods overridden + in `callbacks_class` take precedence and are called first. + See + :py:meth:`~ray.rllib.callbacks.callbacks.RLlibCallback.on_algorithm_init` # noqa + for more information. + on_evaluate_start: A callable or a list of callables. If a list, RLlib calls + the items in the same sequence. `on_evaluate_start` methods overridden + in `callbacks_class` take precedence and are called first. + See :py:meth:`~ray.rllib.callbacks.callbacks.RLlibCallback.on_evaluate_start` # noqa + for more information. + on_evaluate_end: A callable or a list of callables. If a list, RLlib calls + the items in the same sequence. `on_evaluate_end` methods overridden + in `callbacks_class` take precedence and are called first. + See :py:meth:`~ray.rllib.callbacks.callbacks.RLlibCallback.on_evaluate_end` # noqa + for more information. + on_env_runners_recreated: A callable or a list of callables. If a list, + RLlib calls the items in the same sequence. `on_env_runners_recreated` + methods overridden in `callbacks_class` take precedence and are called + first. + See :py:meth:`~ray.rllib.callbacks.callbacks.RLlibCallback.on_env_runners_recreated` # noqa + for more information. + on_checkpoint_loaded: A callable or a list of callables. If a list, + RLlib calls the items in the same sequence. `on_checkpoint_loaded` + methods overridden in `callbacks_class` take precedence and are called + first. + See :py:meth:`~ray.rllib.callbacks.callbacks.RLlibCallback.on_checkpoint_loaded` # noqa + for more information. + on_environment_created: A callable or a list of callables. If a list, + RLlib calls the items in the same sequence. `on_environment_created` + methods overridden in `callbacks_class` take precedence and are called + first. + See :py:meth:`~ray.rllib.callbacks.callbacks.RLlibCallback.on_environment_created` # noqa + for more information. + on_episode_created: A callable or a list of callables. If a list, + RLlib calls the items in the same sequence. `on_episode_created` methods + overridden in `callbacks_class` take precedence and are called first. + See :py:meth:`~ray.rllib.callbacks.callbacks.RLlibCallback.on_episode_created` # noqa + for more information. + on_episode_start: A callable or a list of callables. If a list, + RLlib calls the items in the same sequence. `on_episode_start` methods + overridden in `callbacks_class` take precedence and are called first. + See :py:meth:`~ray.rllib.callbacks.callbacks.RLlibCallback.on_episode_start` # noqa + for more information. + on_episode_step: A callable or a list of callables. If a list, + RLlib calls the items in the same sequence. `on_episode_step` methods + overridden in `callbacks_class` take precedence and are called first. + See :py:meth:`~ray.rllib.callbacks.callbacks.RLlibCallback.on_episode_step` # noqa + for more information. + on_episode_end: A callable or a list of callables. If a list, + RLlib calls the items in the same sequence. `on_episode_end` methods + overridden in `callbacks_class` take precedence and are called first. + See :py:meth:`~ray.rllib.callbacks.callbacks.RLlibCallback.on_episode_end` # noqa + for more information. + on_sample_end: A callable or a list of callables. If a list, + RLlib calls the items in the same sequence. `on_sample_end` methods + overridden in `callbacks_class` take precedence and are called first. + See :py:meth:`~ray.rllib.callbacks.callbacks.RLlibCallback.on_sample_end` # noqa + for more information. + + Returns: + This updated AlgorithmConfig object. + """ + if callbacks_class is None: + callbacks_class = RLlibCallback + + if callbacks_class is not NotProvided: + # Check, whether given `callbacks` is a callable. + # TODO (sven): Once the old API stack is deprecated, this can also be None + # (which should then become the default value for this attribute). + to_check = force_list(callbacks_class) + if not all(callable(c) for c in to_check): + raise ValueError( + "`config.callbacks_class` must be a callable or list of callables that " + "returns a subclass of DefaultCallbacks, got " + f"{callbacks_class}!" + ) + self.callbacks_class = callbacks_class + if on_algorithm_init is not NotProvided: + self.callbacks_on_algorithm_init = on_algorithm_init + if on_train_result is not NotProvided: + self.callbacks_on_train_result = on_train_result + if on_evaluate_start is not NotProvided: + self.callbacks_on_evaluate_start = on_evaluate_start + if on_evaluate_end is not NotProvided: + self.callbacks_on_evaluate_end = on_evaluate_end + if on_evaluate_offline_start is not NotProvided: + self.callbacks_on_evaluate_offline_start = on_evaluate_offline_start + if on_evaluate_offline_end is not NotProvided: + self.callbacks_on_evaluate_offline_end = on_evaluate_offline_end + if on_env_runners_recreated is not NotProvided: + self.callbacks_on_env_runners_recreated = on_env_runners_recreated + if on_offline_eval_runners_recreated is not NotProvided: + self.callbacks_on_offline_eval_runners_recreated = ( + on_offline_eval_runners_recreated + ) + if on_checkpoint_loaded is not NotProvided: + self.callbacks_on_checkpoint_loaded = on_checkpoint_loaded + if on_environment_created is not NotProvided: + self.callbacks_on_environment_created = on_environment_created + if on_episode_created is not NotProvided: + self.callbacks_on_episode_created = on_episode_created + if on_episode_start is not NotProvided: + self.callbacks_on_episode_start = on_episode_start + if on_episode_step is not NotProvided: + self.callbacks_on_episode_step = on_episode_step + if on_episode_end is not NotProvided: + self.callbacks_on_episode_end = on_episode_end + if on_sample_end is not NotProvided: + self.callbacks_on_sample_end = on_sample_end + + return self + + def evaluation( + self, + *, + evaluation_interval: Optional[int] = NotProvided, + evaluation_duration: Optional[Union[int, str]] = NotProvided, + evaluation_duration_unit: Optional[str] = NotProvided, + evaluation_auto_duration_min_env_steps_per_sample: Optional[int] = NotProvided, + evaluation_auto_duration_max_env_steps_per_sample: Optional[int] = NotProvided, + evaluation_sample_timeout_s: Optional[float] = NotProvided, + evaluation_parallel_to_training: Optional[bool] = NotProvided, + evaluation_force_reset_envs_before_iteration: Optional[bool] = NotProvided, + evaluation_config: Optional[ + Union["AlgorithmConfig", PartialAlgorithmConfigDict] + ] = NotProvided, + off_policy_estimation_methods: Optional[Dict] = NotProvided, + ope_split_batch_by_episode: Optional[bool] = NotProvided, + evaluation_num_env_runners: Optional[int] = NotProvided, + custom_evaluation_function: Optional[Callable] = NotProvided, + # Offline evaluation. + offline_evaluation_interval: Optional[int] = NotProvided, + num_offline_eval_runners: Optional[int] = NotProvided, + offline_evaluation_type: Optional[Callable] = NotProvided, + offline_eval_runner_class: Optional[Callable] = NotProvided, + offline_loss_for_module_fn: Optional[Callable] = NotProvided, + offline_eval_batch_size_per_runner: Optional[int] = NotProvided, + dataset_num_iters_per_offline_eval_runner: Optional[int] = NotProvided, + offline_eval_rl_module_inference_only: Optional[bool] = NotProvided, + num_cpus_per_offline_eval_runner: Optional[int] = NotProvided, + num_gpus_per_offline_eval_runner: Optional[int] = NotProvided, + custom_resources_per_offline_eval_runner: Optional[ + Dict[str, Any] + ] = NotProvided, + offline_evaluation_timeout_s: Optional[float] = NotProvided, + max_requests_in_flight_per_offline_eval_runner: Optional[int] = NotProvided, + broadcast_offline_eval_runner_states: Optional[bool] = NotProvided, + validate_offline_eval_runners_after_construction: Optional[bool] = NotProvided, + restart_failed_offline_eval_runners: Optional[bool] = NotProvided, + ignore_offline_eval_runner_failures: Optional[bool] = NotProvided, + max_num_offline_eval_runner_restarts: Optional[int] = NotProvided, + offline_eval_runner_health_probe_timeout_s: Optional[float] = NotProvided, + offline_eval_runner_restore_timeout_s: Optional[float] = NotProvided, + # Deprecated args. + always_attach_evaluation_results=DEPRECATED_VALUE, + evaluation_num_workers=DEPRECATED_VALUE, + ) -> "AlgorithmConfig": + """Sets the config's evaluation settings. + + Args: + evaluation_interval: Evaluate with every `evaluation_interval` training + iterations. The evaluation stats are reported under the "evaluation" + metric key. Set to None (or 0) for no evaluation. + evaluation_duration: Duration for which to run evaluation each + `evaluation_interval`. The unit for the duration can be set via + `evaluation_duration_unit` to either "episodes" (default) or + "timesteps". If using multiple evaluation workers (EnvRunners) in the + `evaluation_num_env_runners > 1` setting, the amount of + episodes/timesteps to run are split amongst these. + A special value of "auto" can be used in case + `evaluation_parallel_to_training=True`. This is the recommended way when + trying to save as much time on evaluation as possible. The Algorithm + then runs as many timesteps via the evaluation workers as possible, + while not taking longer than the parallely running training step and + thus, never wasting any idle time on either training- or evaluation + workers. When using this setting (`evaluation_duration="auto"`), it is + strongly advised to set `evaluation_interval=1` and + `evaluation_force_reset_envs_before_iteration=True` at the same time. + evaluation_duration_unit: The unit, with which to count the evaluation + duration. Either "episodes" (default) or "timesteps". Note that this + setting is ignored if `evaluation_duration="auto"`. + evaluation_auto_duration_min_env_steps_per_sample: If `evaluation_duration` + is "auto" (in which case `evaluation_duration_unit` is always + "timesteps"), at least how many timesteps should be done per remote + `sample()` call. + evaluation_auto_duration_max_env_steps_per_sample: If `evaluation_duration` + is "auto" (in which case `evaluation_duration_unit` is always + "timesteps"), at most how many timesteps should be done per remote + `sample()` call. + evaluation_sample_timeout_s: The timeout (in seconds) for evaluation workers + to sample a complete episode in the case your config settings are: + `evaluation_duration != auto` and `evaluation_duration_unit=episode`. + After this time, the user receives a warning and instructions on how + to fix the issue. + evaluation_parallel_to_training: Whether to run evaluation in parallel to + the `Algorithm.training_step()` call, using threading. Default=False. + E.g. for evaluation_interval=1 -> In every call to `Algorithm.train()`, + the `Algorithm.training_step()` and `Algorithm.evaluate()` calls + run in parallel. Note that this setting - albeit extremely efficient b/c + it wastes no extra time for evaluation - causes the evaluation results + to lag one iteration behind the rest of the training results. This is + important when picking a good checkpoint. For example, if iteration 42 + reports a good evaluation `episode_return_mean`, be aware that these + results were achieved on the weights trained in iteration 41, so you + should probably pick the iteration 41 checkpoint instead. + evaluation_force_reset_envs_before_iteration: Whether all environments + should be force-reset (even if they are not done yet) right before + the evaluation step of the iteration begins. Setting this to True + (default) makes sure that the evaluation results aren't polluted with + episode statistics that were actually (at least partially) achieved with + an earlier set of weights. Note that this setting is only + supported on the new API stack w/ EnvRunners and ConnectorV2 + (`config.enable_rl_module_and_learner=True` AND + `config.enable_env_runner_and_connector_v2=True`). + evaluation_config: Typical usage is to pass extra args to evaluation env + creator and to disable exploration by computing deterministic actions. + IMPORTANT NOTE: Policy gradient algorithms are able to find the optimal + policy, even if this is a stochastic one. Setting "explore=False" here + results in the evaluation workers not using this optimal policy! + off_policy_estimation_methods: Specify how to evaluate the current policy, + along with any optional config parameters. This only has an effect when + reading offline experiences ("input" is not "sampler"). + Available keys: + {ope_method_name: {"type": ope_type, ...}} where `ope_method_name` + is a user-defined string to save the OPE results under, and + `ope_type` can be any subclass of OffPolicyEstimator, e.g. + ray.rllib.offline.estimators.is::ImportanceSampling + or your own custom subclass, or the full class path to the subclass. + You can also add additional config arguments to be passed to the + OffPolicyEstimator in the dict, e.g. + {"qreg_dr": {"type": DoublyRobust, "q_model_type": "qreg", "k": 5}} + ope_split_batch_by_episode: Whether to use SampleBatch.split_by_episode() to + split the input batch to episodes before estimating the ope metrics. In + case of bandits you should make this False to see improvements in ope + evaluation speed. In case of bandits, it is ok to not split by episode, + since each record is one timestep already. The default is True. + evaluation_num_env_runners: Number of parallel EnvRunners to use for + evaluation. Note that this is set to zero by default, which means + evaluation is run in the algorithm process (only if + `evaluation_interval` is not 0 or None). If you increase this, also + increases the Ray resource usage of the algorithm since evaluation + workers are created separately from those EnvRunners used to sample data + for training. + custom_evaluation_function: Customize the evaluation method. This must be a + function of signature (algo: Algorithm, eval_workers: EnvRunnerGroup) -> + (metrics: dict, env_steps: int, agent_steps: int) (metrics: dict if + `enable_env_runner_and_connector_v2=True`), where `env_steps` and + `agent_steps` define the number of sampled steps during the evaluation + iteration. See the Algorithm.evaluate() method to see the default + implementation. The Algorithm guarantees all eval workers have the + latest policy state before this function is called. + offline_evaluation_interval: Evaluate offline with every + `offline_evaluation_interval` training iterations. The offline evaluation + stats are reported under the "evaluation/offline_evaluation" metric key. Set + to None (or 0) for no offline evaluation. + num_offline_eval_runners: Number of OfflineEvaluationRunner actors to create + for parallel evaluation. Setting this to 0 forces sampling to be done in the + local OfflineEvaluationRunner (main process or the Algorithm's actor when + using Tune). + offline_evaluation_type: Type of offline evaluation to run. Either `"eval_loss"` + for evaluating the validation loss of the policy, `"is"` for importance + sampling, or `"pdis"` for per-decision importance sampling. If you want to + implement your own offline evaluation method write an `OfflineEvaluationRunner` + and use the `AlgorithmConfig.offline_eval_runner_class`. + offline_eval_runner_class: An `OfflineEvaluationRunner` class that implements + custom offline evaluation logic. + offline_loss_for_module_fn: A callable to compute the loss per `RLModule` in + offline evaluation. If not provided the training loss function ( + `Learner.compute_loss_for_module`) is used. The signature must be ( + runner: OfflineEvaluationRunner, module_id: ModuleID, config: AlgorithmConfig, + batch: Dict[str, Any], fwd_out: Dict[str, TensorType]). + offline_eval_batch_size_per_runner: Evaluation batch size per individual + OfflineEvaluationRunner worker. This setting only applies to the new API + stack. The number of OfflineEvaluationRunner workers can be set via + `config.evaluation(num_offline_eval_runners=...)`. The total effective batch + size is then `num_offline_eval_runners` x + `offline_eval_batch_size_per_runner`. + dataset_num_iters_per_offline_eval_runner: Number of batches to evaluate in each + OfflineEvaluationRunner during a single evaluation. If None, each learner runs a + complete epoch over its data block (the dataset is partitioned into + at least as many blocks as there are runners). The default is `1`. + offline_eval_rl_module_inference_only: If `True`, the module spec is used in an + inference-only setting (no-loss) and the RLModule can thus be built in + its light version (if available). For example, the `inference_only` + version of an RLModule might only contain the networks required for + computing actions, but misses additional target- or critic networks. + Also, if `True`, the module does NOT contain those (sub) RLModules that have + their `learner_only` flag set to True. + num_cpus_per_offline_eval_runner: Number of CPUs to allocate per + OfflineEvaluationRunner. + num_gpus_per_offline_eval_runner: Number of GPUs to allocate per + OfflineEvaluationRunner. This can be fractional. This is usually needed only if + your (custom) loss function itself requires a GPU (i.e., it contains GPU- + intensive computations), or model inference is unusually expensive. + custom_resources_per_eval_runner: Any custom Ray resources to allocate per + OfflineEvaluationRunner. + offline_evaluation_timeout_s: The timeout in seconds for calling `run()` on remote + OfflineEvaluationRunner workers. Results (episode list) from workers that take + longer than this time are discarded. + max_requests_in_flight_per_offline_eval_runner: Max number of in-flight requests + to each OfflineEvaluationRunner (actor)). See the + `ray.rllib.utils.actor_manager.FaultTolerantActorManager` class for more + details. + Tuning these values is important when running experiments with + large evaluation batches, where there is the risk that the object store may + fill up, causing spilling of objects to disk. This can cause any + asynchronous requests to become very slow, making your experiment run + slowly as well. You can inspect the object store during your experiment + through a call to `ray memory` on your head node, and by using the Ray + dashboard. If you're seeing that the object store is filling up, + turn down the number of remote requests in flight or enable compression + or increase the object store memory through, for example: + `ray.init(object_store_memory=10 * 1024 * 1024 * 1024) # =10 GB`. + broadcast_offline_eval_runner_states: True, if merged OfflineEvaluationRunner + states (from the central connector pipelines) should be broadcast back to + all remote OfflineEvaluationRunner actors. + validate_offline_eval_runners_after_construction: Whether to validate that each + created remote OfflineEvaluationRunner is healthy after its construction process. + restart_failed_offline_eval_runners: Whether - upon an OfflineEvaluationRunner + failure - RLlib tries to restart the lost OfflineEvaluationRunner(s) as an + identical copy of the failed one(s). You should set this to True when training + on SPOT instances that may preempt any time and/or if you need to evaluate always a + complete dataset b/c OfflineEvaluationRunner(s) evaluate through streaming split + iterators on disjoint batches. The new, recreated OfflineEvaluationRunner(s) only + differ from the failed one in their `self.recreated_worker=True` property value + and have the same `worker_index` as the original(s). If this setting is True, the + value of the `ignore_offline_eval_runner_failures` setting is ignored. + ignore_offline_eval_runner_failures: Whether to ignore any OfflineEvalautionRunner + failures and continue running with the remaining OfflineEvaluationRunners. This + setting is ignored, if `restart_failed_offline_eval_runners=True`. + max_num_offline_eval_runner_restarts: The maximum number of times any + OfflineEvaluationRunner is allowed to be restarted (if + `restart_failed_offline_eval_runners` is True). + offline_eval_runner_health_probe_timeout_s: Max amount of time in seconds, we should + spend waiting for OfflineEvaluationRunner health probe calls + (`OfflineEvaluationRunner.ping.remote()`) to respond. Health pings are very cheap, + however, we perform the health check via a blocking `ray.get()`, so the + default value should not be too large. + offline_eval_runner_restore_timeout_s: Max amount of time we should wait to restore + states on recovered OfflineEvaluationRunner actors. Default is 30 mins. + + Returns: + This updated AlgorithmConfig object. + """ + if always_attach_evaluation_results != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.evaluation(always_attach_evaluation_results=..)", + help="This setting is no longer needed, b/c Tune does not error " + "anymore (only warns) when a metrics key can't be found in the " + "results.", + error=True, + ) + if evaluation_num_workers != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.evaluation(evaluation_num_workers=..)", + new="AlgorithmConfig.evaluation(evaluation_num_env_runners=..)", + error=False, + ) + self.evaluation_num_env_runners = evaluation_num_workers + + if evaluation_interval is not NotProvided: + self.evaluation_interval = evaluation_interval + if evaluation_duration is not NotProvided: + self.evaluation_duration = evaluation_duration + if evaluation_duration_unit is not NotProvided: + self.evaluation_duration_unit = evaluation_duration_unit + if evaluation_auto_duration_min_env_steps_per_sample is not NotProvided: + self.evaluation_auto_duration_min_env_steps_per_sample = ( + evaluation_auto_duration_min_env_steps_per_sample + ) + if evaluation_auto_duration_max_env_steps_per_sample is not NotProvided: + self.evaluation_auto_duration_max_env_steps_per_sample = ( + evaluation_auto_duration_max_env_steps_per_sample + ) + if evaluation_sample_timeout_s is not NotProvided: + self.evaluation_sample_timeout_s = evaluation_sample_timeout_s + if evaluation_parallel_to_training is not NotProvided: + self.evaluation_parallel_to_training = evaluation_parallel_to_training + if evaluation_force_reset_envs_before_iteration is not NotProvided: + self.evaluation_force_reset_envs_before_iteration = ( + evaluation_force_reset_envs_before_iteration + ) + if evaluation_config is not NotProvided: + # If user really wants to set this to None, we should allow this here, + # instead of creating an empty dict. + if evaluation_config is None: + self.evaluation_config = None + # Update (don't replace) the existing overrides with the provided ones. + else: + from ray.rllib.algorithms.algorithm import Algorithm + + self.evaluation_config = deep_update( + self.evaluation_config or {}, + evaluation_config, + True, + Algorithm._allow_unknown_subkeys, + Algorithm._override_all_subkeys_if_type_changes, + Algorithm._override_all_key_list, + ) + if off_policy_estimation_methods is not NotProvided: + self.off_policy_estimation_methods = off_policy_estimation_methods + if evaluation_num_env_runners is not NotProvided: + self.evaluation_num_env_runners = evaluation_num_env_runners + if custom_evaluation_function is not NotProvided: + self.custom_evaluation_function = custom_evaluation_function + if ope_split_batch_by_episode is not NotProvided: + self.ope_split_batch_by_episode = ope_split_batch_by_episode + # Offline evaluation. + if offline_evaluation_interval is not NotProvided: + self.offline_evaluation_interval = offline_evaluation_interval + if num_offline_eval_runners is not NotProvided: + self.num_offline_eval_runners = num_offline_eval_runners + if offline_evaluation_type is not NotProvided: + self.offline_evaluation_type = offline_evaluation_type + if offline_eval_runner_class is not NotProvided: + self.offline_eval_runner_class = offline_eval_runner_class + if offline_loss_for_module_fn is not NotProvided: + self.offline_loss_for_module_fn = offline_loss_for_module_fn + if offline_eval_batch_size_per_runner is not NotProvided: + self.offline_eval_batch_size_per_runner = offline_eval_batch_size_per_runner + if dataset_num_iters_per_offline_eval_runner is not NotProvided: + self.dataset_num_iters_per_eval_runner = ( + dataset_num_iters_per_offline_eval_runner + ) + if offline_eval_rl_module_inference_only is not NotProvided: + self.offline_eval_rl_module_inference_only = ( + offline_eval_rl_module_inference_only + ) + if num_cpus_per_offline_eval_runner is not NotProvided: + self.num_cpus_per_offline_eval_runner = num_cpus_per_offline_eval_runner + if num_gpus_per_offline_eval_runner is not NotProvided: + self.num_gpus_per_offline_eval_runner = num_gpus_per_offline_eval_runner + if custom_resources_per_offline_eval_runner is not NotProvided: + self.custom_resources_per_offline_eval_runner = ( + custom_resources_per_offline_eval_runner + ) + if offline_evaluation_timeout_s is not NotProvided: + self.offline_evaluation_timeout_s = offline_evaluation_timeout_s + if max_requests_in_flight_per_offline_eval_runner is not NotProvided: + self.max_requests_in_flight_per_offline_eval_runner = ( + max_requests_in_flight_per_offline_eval_runner + ) + if broadcast_offline_eval_runner_states is not NotProvided: + self.broadcast_offline_eval_runner_states = ( + broadcast_offline_eval_runner_states + ) + if validate_offline_eval_runners_after_construction is not NotProvided: + self.validate_offline_eval_runners_after_construction = ( + validate_offline_eval_runners_after_construction + ) + if restart_failed_offline_eval_runners is not NotProvided: + self.restart_failed_offline_eval_runners = ( + restart_failed_offline_eval_runners + ) + if ignore_offline_eval_runner_failures is not NotProvided: + self.ignore_offline_eval_runner_failures = ( + ignore_offline_eval_runner_failures + ) + if max_num_offline_eval_runner_restarts is not NotProvided: + self.max_num_offline_eval_runner_restarts = ( + max_num_offline_eval_runner_restarts + ) + if offline_eval_runner_health_probe_timeout_s is not NotProvided: + self.offline_eval_runner_health_probe_timeout_s = ( + offline_eval_runner_health_probe_timeout_s + ) + if offline_eval_runner_restore_timeout_s is not NotProvided: + self.offline_eval_runner_restore_timeout_s = ( + offline_eval_runner_restore_timeout_s + ) + + return self + + def offline_data( + self, + *, + input_: Optional[Union[str, Callable[[IOContext], InputReader]]] = NotProvided, + offline_data_class: Optional[Type] = NotProvided, + input_read_method: Optional[Union[str, Callable]] = NotProvided, + input_read_method_kwargs: Optional[Dict] = NotProvided, + input_read_schema: Optional[Dict[str, str]] = NotProvided, + input_read_episodes: Optional[bool] = NotProvided, + input_read_sample_batches: Optional[bool] = NotProvided, + input_read_batch_size: Optional[int] = NotProvided, + input_filesystem: Optional[str] = NotProvided, + input_filesystem_kwargs: Optional[Dict] = NotProvided, + input_compress_columns: Optional[List[str]] = NotProvided, + materialize_data: Optional[bool] = NotProvided, + materialize_mapped_data: Optional[bool] = NotProvided, + map_batches_kwargs: Optional[Dict] = NotProvided, + iter_batches_kwargs: Optional[Dict] = NotProvided, + ignore_final_observation: Optional[bool] = NotProvided, + prelearner_class: Optional[Type] = NotProvided, + prelearner_buffer_class: Optional[Type] = NotProvided, + prelearner_buffer_kwargs: Optional[Dict] = NotProvided, + prelearner_module_synch_period: Optional[int] = NotProvided, + dataset_num_iters_per_learner: Optional[int] = NotProvided, + input_config: Optional[Dict] = NotProvided, + actions_in_input_normalized: Optional[bool] = NotProvided, + postprocess_inputs: Optional[bool] = NotProvided, + shuffle_buffer_size: Optional[int] = NotProvided, + output: Optional[str] = NotProvided, + output_config: Optional[Dict] = NotProvided, + output_compress_columns: Optional[List[str]] = NotProvided, + output_max_file_size: Optional[float] = NotProvided, + output_max_rows_per_file: Optional[int] = NotProvided, + output_write_remaining_data: Optional[bool] = NotProvided, + output_write_method: Optional[str] = NotProvided, + output_write_method_kwargs: Optional[Dict] = NotProvided, + output_filesystem: Optional[str] = NotProvided, + output_filesystem_kwargs: Optional[Dict] = NotProvided, + output_write_episodes: Optional[bool] = NotProvided, + offline_sampling: Optional[str] = NotProvided, + ) -> "AlgorithmConfig": + """Sets the config's offline data settings. + + Args: + input_: Specify how to generate experiences: + - "sampler": Generate experiences via online (env) simulation (default). + - A local directory or file glob expression (e.g., "/tmp/*.json"). + - A list of individual file paths/URIs (e.g., ["/tmp/1.json", + "s3://bucket/2.json"]). + - A dict with string keys and sampling probabilities as values (e.g., + {"sampler": 0.4, "/tmp/*.json": 0.4, "s3://bucket/expert.json": 0.2}). + - A callable that takes an `IOContext` object as only arg and returns a + `ray.rllib.offline.InputReader`. + - A string key that indexes a callable with + `tune.registry.register_input` + offline_data_class: An optional `OfflineData` class that is used to define + the offline data pipeline, including the dataset and the sampling + methodology. Override the `OfflineData` class and pass your derived + class here, if you need some primer transformations specific to your + data or your loss. Usually overriding the `OfflinePreLearner` and using + the resulting customization via `prelearner_class` suffices for most + cases. The default is `None` which uses the base `OfflineData` defined + in `ray.rllib.offline.offline_data.OfflineData`. + input_read_method: Read method for the `ray.data.Dataset` to read in the + offline data from `input_`. The default is `read_parquet` for Parquet + files. See https://docs.ray.io/en/latest/data/api/input_output.html for + more info about available read methods in `ray.data`. + input_read_method_kwargs: Keyword args for `input_read_method`. These + are passed by RLlib into the read method without checking. Use these + keyword args together with `map_batches_kwargs` and + `iter_batches_kwargs` to tune the performance of the data pipeline. + It is strongly recommended to rely on Ray Data's automatic read + performance tuning. + input_read_schema: Table schema for converting offline data to episodes. + This schema maps the offline data columns to + ray.rllib.core.columns.Columns: + `{Columns.OBS: 'o_t', Columns.ACTIONS: 'a_t', ...}`. Columns in + the data set that are not mapped via this schema are sorted into + episodes' `extra_model_outputs`. If no schema is passed in the default + schema used is `ray.rllib.offline.offline_data.SCHEMA`. If your data set + contains already the names in this schema, no `input_read_schema` is + needed. The same applies if the data is in RLlib's `EpisodeType` or its + old `SampleBatch` format. + input_read_episodes: Whether offline data is already stored in RLlib's + `EpisodeType` format, i.e. `ray.rllib.env.SingleAgentEpisode` (multi + -agent is planned but not supported, yet). Reading episodes directly + avoids additional transform steps and is usually faster and + therefore the recommended format when your application remains fully + inside of RLlib's schema. The other format is a columnar format and is + agnostic to the RL framework used. Use the latter format, if you are + unsure when to use the data or in which RL framework. The default is + to read column data, for example, `False`. `input_read_episodes`, and + `input_read_sample_batches` can't be `True` at the same time. See + also `output_write_episodes` to define the output data format when + recording. + input_read_sample_batches: Whether offline data is stored in RLlib's old + stack `SampleBatch` type. This is usually the case for older data + recorded with RLlib in JSON line format. Reading in `SampleBatch` + data needs extra transforms and might not concatenate episode chunks + contained in different `SampleBatch`es in the data. If possible avoid + to read `SampleBatch`es and convert them in a controlled form into + RLlib's `EpisodeType` (i.e. `SingleAgentEpisode`). The default is + `False`. `input_read_episodes`, and `input_read_sample_batches` can't + be `True` at the same time. + input_read_batch_size: Batch size to pull from the data set. This could + differ from the `train_batch_size_per_learner`, if a dataset holds + `EpisodeType` (i.e., `SingleAgentEpisode`) or `SampleBatch`, or any + other data type that contains multiple timesteps in a single row of + the dataset. In such cases a single batch of size + `train_batch_size_per_learner` will potentially pull a multiple of + `train_batch_size_per_learner` timesteps from the offline dataset. The + default is `None` in which the `train_batch_size_per_learner` is pulled. + input_filesystem: A cloud filesystem to handle access to cloud storage when + reading experiences. Can be either "gcs" for Google Cloud Storage, + "s3" for AWS S3 buckets, "abs" for Azure Blob Storage, or any + filesystem supported by PyArrow. In general the file path is sufficient + for accessing data from public or local storage systems. See + https://arrow.apache.org/docs/python/filesystems.html for details. + input_filesystem_kwargs: A dictionary holding the kwargs for the filesystem + given by `input_filesystem`. See `gcsfs.GCSFilesystem` for GCS, + `pyarrow.fs.S3FileSystem`, for S3, and `ablfs.AzureBlobFilesystem` for + ABS filesystem arguments. + input_compress_columns: What input columns are compressed with LZ4 in the + input data. If data is stored in RLlib's `SingleAgentEpisode` ( + `MultiAgentEpisode` not supported, yet). Note the providing + `rllib.core.columns.Columns.OBS` also tries to decompress + `rllib.core.columns.Columns.NEXT_OBS`. + materialize_data: Whether the raw data should be materialized in memory. + This boosts performance, but requires enough memory to avoid an OOM, so + make sure that your cluster has the resources available. For very large + data you might want to switch to streaming mode by setting this to + `False` (default). If your algorithm does not need the RLModule in the + Learner connector pipeline or all (learner) connectors are stateless + you should consider setting `materialize_mapped_data` to `True` + instead (and set `materialize_data` to `False`). If your data does not + fit into memory and your Learner connector pipeline requires an RLModule + or is stateful, set both `materialize_data` and + `materialize_mapped_data` to `False`. + materialize_mapped_data: Whether the data should be materialized after + running it through the Learner connector pipeline (i.e. after running + the `OfflinePreLearner`). This improves performance, but should only be + used in case the (learner) connector pipeline does not require an + RLModule and the (learner) connector pipeline is stateless. For example, + MARWIL's Learner connector pipeline requires the RLModule for value + function predictions and training batches would become stale after some + iterations causing learning degradation or divergence. Also ensure that + your cluster has enough memory available to avoid an OOM. If set to + `True` (True), make sure that `materialize_data` is set to `False` to + avoid materialization of two datasets. If your data does not fit into + memory and your Learner connector pipeline requires an RLModule or is + stateful, set both `materialize_data` and `materialize_mapped_data` to + `False`. + map_batches_kwargs: Keyword args for the `map_batches` method. These are + passed into the `ray.data.Dataset.map_batches` method when sampling + without checking. If no arguments passed in the default arguments + `{'concurrency': max(2, num_learners), 'zero_copy_batch': True}` is + used. Use these keyword args together with `input_read_method_kwargs` + and `iter_batches_kwargs` to tune the performance of the data pipeline. + iter_batches_kwargs: Keyword args for the `iter_batches` method. These are + passed into the `ray.data.Dataset.iter_batches` method when sampling + without checking. If no arguments are passed in, the default argument + `{'prefetch_batches': 2}` is used. Use these keyword args + together with `input_read_method_kwargs` and `map_batches_kwargs` to + tune the performance of the data pipeline. + ignore_final_observation: If the final observation in an episode chunk should + be ignored. This concerns mainly column-based data and instead of using a + user-provided `NEXT_OBS` sets final observations to zero. This should be + used with BC only, as in true Offline RL algorithms the final observation + is important. + prelearner_class: An optional `OfflinePreLearner` class that is used to + transform data batches in `ray.data.map_batches` used in the + `OfflineData` class to transform data from columns to batches that can + be used in the `Learner.update...()` methods. Override the + `OfflinePreLearner` class and pass your derived class in here, if you + need to make some further transformations specific for your data or + loss. The default is None which uses the base `OfflinePreLearner` + defined in `ray.rllib.offline.offline_prelearner`. + prelearner_buffer_class: An optional `EpisodeReplayBuffer` class that RLlib + uses to buffer experiences when data is in `EpisodeType` or + RLlib's previous `SampleBatch` type format. In this case, a single + data row may contain multiple timesteps and the buffer serves two + purposes: (a) to store intermediate data in memory, and (b) to ensure + that RLlib samples exactly `train_batch_size_per_learner` experiences + per batch. The default is RLlib's `EpisodeReplayBuffer`. + prelearner_buffer_kwargs: Optional keyword arguments for initializing the + `EpisodeReplayBuffer`. In most cases this value is simply the `capacity` + for the default buffer that RLlib uses (`EpisodeReplayBuffer`), but it + may differ if the `prelearner_buffer_class` uses a custom buffer. + prelearner_module_synch_period: The period (number of batches converted) + after which the `RLModule` held by the `PreLearner` should sync weights. + The `PreLearner` is used to preprocess batches for the learners. The + higher this value, the more off-policy the `PreLearner`'s module is. + Values too small force the `PreLearner` to sync more frequently + and thus might slow down the data pipeline. The default value chosen + by the `OfflinePreLearner` is 10. + dataset_num_iters_per_learner: Number of updates to run in each learner + during a single training iteration. If None, each learner runs a + complete epoch over its data block (the dataset is partitioned into + at least as many blocks as there are learners). The default is `None`. + This value must be set to `1`, if RLlib uses a single (local) learner. + input_config: Arguments that describe the settings for reading the input. + If input is "sample", this is the environment configuration, e.g. + `env_name` and `env_config`, etc. See `EnvContext` for more info. + If the input is "dataset", this contains e.g. `format`, `path`. + actions_in_input_normalized: True, if the actions in a given offline "input" + are already normalized (between -1.0 and 1.0). This is usually the case + when the offline file has been generated by another RLlib algorithm + (e.g. PPO or SAC), while "normalize_actions" was set to True. + postprocess_inputs: Whether to run postprocess_trajectory() on the + trajectory fragments from offline inputs. Note that postprocessing is + done using the *current* policy, not the *behavior* policy, which + is typically undesirable for on-policy algorithms. + shuffle_buffer_size: If positive, input batches are shuffled via a + sliding window buffer of this number of batches. Use this if the input + data is not in random enough order. Input is delayed until the shuffle + buffer is filled. + output: Specify where experiences should be saved: + - None: don't save any experiences + - "logdir" to save to the agent log dir + - a path/URI to save to a custom output directory (e.g., "s3://bckt/") + - a function that returns a rllib.offline.OutputWriter + output_config: Arguments accessible from the IOContext for configuring + custom output. + output_compress_columns: What sample batch columns to LZ4 compress in the + output data. Note that providing `rllib.core.columns.Columns.OBS` also + compresses `rllib.core.columns.Columns.NEXT_OBS`. + output_max_file_size: Max output file size (in bytes) before rolling over + to a new file. + output_max_rows_per_file: Max output row numbers before rolling over to a + new file. + output_write_remaining_data: Determines whether any remaining data in the + recording buffers should be stored to disk. It is only applicable if + `output_max_rows_per_file` is defined. When sampling data, it is + buffered until the threshold specified by `output_max_rows_per_file` + is reached. Only complete multiples of `output_max_rows_per_file` are + written to disk, while any leftover data remains in the buffers. If a + recording session is stopped, residual data may still reside in these + buffers. Setting `output_write_remaining_data` to `True` ensures this + data is flushed to disk. By default, this attribute is set to `False`. + output_write_method: Write method for the `ray.data.Dataset` to write the + offline data to `output`. The default is `read_parquet` for Parquet + files. See https://docs.ray.io/en/latest/data/api/input_output.html for + more info about available read methods in `ray.data`. + output_write_method_kwargs: `kwargs` for the `output_write_method`. These + are passed into the write method without checking. + output_filesystem: A cloud filesystem to handle access to cloud storage when + writing experiences. Should be either "gcs" for Google Cloud Storage, + "s3" for AWS S3 buckets, or "abs" for Azure Blob Storage. + output_filesystem_kwargs: A dictionary holding the kwargs for the filesystem + given by `output_filesystem`. See `gcsfs.GCSFilesystem` for GCS, + `pyarrow.fs.S3FileSystem`, for S3, and `ablfs.AzureBlobFilesystem` for + ABS filesystem arguments. + output_write_episodes: If RLlib should record data in its RLlib's + `EpisodeType` format (that is, `SingleAgentEpisode` objects). Use this + format, if you need RLlib to order data in time and directly group by + episodes for example to train stateful modules or if you plan to use + recordings exclusively in RLlib. Otherwise RLlib records data in tabular + (columnar) format. Default is `True`. + offline_sampling: Whether sampling for the Algorithm happens via + reading from offline data. If True, EnvRunners don't limit the number + of collected batches within the same `sample()` call based on + the number of sub-environments within the worker (no sub-environments + present). + + Returns: + This updated AlgorithmConfig object. + """ + if input_ is not NotProvided: + self.input_ = input_ + if offline_data_class is not NotProvided: + self.offline_data_class = offline_data_class + if input_read_method is not NotProvided: + self.input_read_method = input_read_method + if input_read_method_kwargs is not NotProvided: + self.input_read_method_kwargs = input_read_method_kwargs + if input_read_schema is not NotProvided: + self.input_read_schema = input_read_schema + if input_read_episodes is not NotProvided: + self.input_read_episodes = input_read_episodes + if input_read_sample_batches is not NotProvided: + self.input_read_sample_batches = input_read_sample_batches + if input_read_batch_size is not NotProvided: + self.input_read_batch_size = input_read_batch_size + if input_filesystem is not NotProvided: + self.input_filesystem = input_filesystem + if input_filesystem_kwargs is not NotProvided: + self.input_filesystem_kwargs = input_filesystem_kwargs + if input_compress_columns is not NotProvided: + self.input_compress_columns = input_compress_columns + if materialize_data is not NotProvided: + self.materialize_data = materialize_data + if materialize_mapped_data is not NotProvided: + self.materialize_mapped_data = materialize_mapped_data + if map_batches_kwargs is not NotProvided: + self.map_batches_kwargs = map_batches_kwargs + if iter_batches_kwargs is not NotProvided: + self.iter_batches_kwargs = iter_batches_kwargs + if ignore_final_observation is not NotProvided: + self.ignore_final_observation = ignore_final_observation + if prelearner_class is not NotProvided: + self.prelearner_class = prelearner_class + if prelearner_buffer_class is not NotProvided: + self.prelearner_buffer_class = prelearner_buffer_class + if prelearner_buffer_kwargs is not NotProvided: + self.prelearner_buffer_kwargs = prelearner_buffer_kwargs + if prelearner_module_synch_period is not NotProvided: + self.prelearner_module_synch_period = prelearner_module_synch_period + if dataset_num_iters_per_learner is not NotProvided: + self.dataset_num_iters_per_learner = dataset_num_iters_per_learner + if input_config is not NotProvided: + if not isinstance(input_config, dict): + raise ValueError( + f"input_config must be a dict, got {type(input_config)}." + ) + # TODO (Kourosh) Once we use a complete separation between rollout worker + # and input dataset reader we can remove this. + # For now Error out if user attempts to set these parameters. + msg = "{} should not be set in the input_config. RLlib uses {} instead." + if input_config.get("num_cpus_per_read_task") is not None: + raise ValueError( + msg.format( + "num_cpus_per_read_task", + "config.env_runners(num_cpus_per_env_runner=..)", + ) + ) + if input_config.get("parallelism") is not None: + if self.in_evaluation: + raise ValueError( + msg.format( + "parallelism", + "config.evaluation(evaluation_num_env_runners=..)", + ) + ) + else: + raise ValueError( + msg.format( + "parallelism", "config.env_runners(num_env_runners=..)" + ) + ) + self.input_config = input_config + if actions_in_input_normalized is not NotProvided: + self.actions_in_input_normalized = actions_in_input_normalized + if postprocess_inputs is not NotProvided: + self.postprocess_inputs = postprocess_inputs + if shuffle_buffer_size is not NotProvided: + self.shuffle_buffer_size = shuffle_buffer_size + # TODO (simon): Enable storing to general log-directory. + if output is not NotProvided: + self.output = output + if output_config is not NotProvided: + self.output_config = output_config + if output_compress_columns is not NotProvided: + self.output_compress_columns = output_compress_columns + if output_max_file_size is not NotProvided: + self.output_max_file_size = output_max_file_size + if output_max_rows_per_file is not NotProvided: + self.output_max_rows_per_file = output_max_rows_per_file + if output_write_remaining_data is not NotProvided: + self.output_write_remaining_data = output_write_remaining_data + if output_write_method is not NotProvided: + self.output_write_method = output_write_method + if output_write_method_kwargs is not NotProvided: + self.output_write_method_kwargs = output_write_method_kwargs + if output_filesystem is not NotProvided: + self.output_filesystem = output_filesystem + if output_filesystem_kwargs is not NotProvided: + self.output_filesystem_kwargs = output_filesystem_kwargs + if output_write_episodes is not NotProvided: + self.output_write_episodes = output_write_episodes + if offline_sampling is not NotProvided: + self.offline_sampling = offline_sampling + + return self + + def multi_agent( + self, + *, + policies: Optional[ + Union[MultiAgentPolicyConfigDict, Collection[PolicyID]] + ] = NotProvided, + policy_map_capacity: Optional[int] = NotProvided, + policy_mapping_fn: Optional[ + Callable[[AgentID, "EpisodeType"], PolicyID] + ] = NotProvided, + policies_to_train: Optional[ + Union[Collection[PolicyID], Callable[[PolicyID, SampleBatchType], bool]] + ] = NotProvided, + policy_states_are_swappable: Optional[bool] = NotProvided, + observation_fn: Optional[Callable] = NotProvided, + count_steps_by: Optional[str] = NotProvided, + # Deprecated args: + algorithm_config_overrides_per_module=DEPRECATED_VALUE, + replay_mode=DEPRECATED_VALUE, + # Now done via Ray object store, which has its own cloud-supported + # spillover mechanism. + policy_map_cache=DEPRECATED_VALUE, + ) -> "AlgorithmConfig": + """Sets the config's multi-agent settings. + + Validates the new multi-agent settings and translates everything into + a unified multi-agent setup format. For example a `policies` list or set + of IDs is properly converted into a dict mapping these IDs to PolicySpecs. + + Args: + policies: Map of type MultiAgentPolicyConfigDict from policy ids to either + 4-tuples of (policy_cls, obs_space, act_space, config) or PolicySpecs. + These tuples or PolicySpecs define the class of the policy, the + observation- and action spaces of the policies, and any extra config. + policy_map_capacity: Keep this many policies in the "policy_map" (before + writing least-recently used ones to disk/S3). + policy_mapping_fn: Function mapping agent ids to policy ids. The signature + is: `(agent_id, episode, worker, **kwargs) -> PolicyID`. + policies_to_train: Determines those policies that should be updated. + Options are: + - None, for training all policies. + - An iterable of PolicyIDs that should be trained. + - A callable, taking a PolicyID and a SampleBatch or MultiAgentBatch + and returning a bool (indicating whether the given policy is trainable + or not, given the particular batch). This allows you to have a policy + trained only on certain data (e.g. when playing against a certain + opponent). + policy_states_are_swappable: Whether all Policy objects in this map can be + "swapped out" via a simple `state = A.get_state(); B.set_state(state)`, + where `A` and `B` are policy instances in this map. You should set + this to True for significantly speeding up the PolicyMap's cache lookup + times, iff your policies all share the same neural network + architecture and optimizer types. If True, the PolicyMap doesn't + have to garbage collect old, least recently used policies, but instead + keeps them in memory and simply override their state with the state of + the most recently accessed one. + For example, in a league-based training setup, you might have 100s of + the same policies in your map (playing against each other in various + combinations), but all of them share the same state structure + (are "swappable"). + observation_fn: Optional function that can be used to enhance the local + agent observations to include more state. See + rllib/evaluation/observation_function.py for more info. + count_steps_by: Which metric to use as the "batch size" when building a + MultiAgentBatch. The two supported values are: + "env_steps": Count each time the env is "stepped" (no matter how many + multi-agent actions are passed/how many multi-agent observations + have been returned in the previous step). + "agent_steps": Count each individual agent step as one step. + + Returns: + This updated AlgorithmConfig object. + """ + if policies is not NotProvided: + # Make sure our Policy IDs are ok (this should work whether `policies` + # is a dict or just any Sequence). + for pid in policies: + validate_module_id(pid, error=True) + + # Collection: Convert to dict. + if isinstance(policies, (set, tuple, list)): + policies = {p: PolicySpec() for p in policies} + # Validate each policy spec in a given dict. + if isinstance(policies, dict): + for pid, spec in policies.items(): + # If not a PolicySpec object, values must be lists/tuples of len 4. + if not isinstance(spec, PolicySpec): + if not isinstance(spec, (list, tuple)) or len(spec) != 4: + raise ValueError( + "Policy specs must be tuples/lists of " + "(cls or None, obs_space, action_space, config), " + f"got {spec} for PolicyID={pid}" + ) + # TODO: Switch from dict to AlgorithmConfigOverride, once available. + # Config not a dict. + elif ( + not isinstance(spec.config, (AlgorithmConfig, dict)) + and spec.config is not None + ): + raise ValueError( + f"Multi-agent policy config for {pid} must be a dict or " + f"AlgorithmConfig object, but got {type(spec.config)}!" + ) + self.policies = policies + else: + raise ValueError( + "`policies` must be dict mapping PolicyID to PolicySpec OR a " + "set/tuple/list of PolicyIDs!" + ) + + if algorithm_config_overrides_per_module != DEPRECATED_VALUE: + deprecation_warning(old="", error=False) + self.rl_module( + algorithm_config_overrides_per_module=( + algorithm_config_overrides_per_module + ) + ) + + if policy_map_capacity is not NotProvided: + self.policy_map_capacity = policy_map_capacity + + if policy_mapping_fn is not NotProvided: + # Create `policy_mapping_fn` from a config dict. + # Helpful if users would like to specify custom callable classes in + # yaml files. + if isinstance(policy_mapping_fn, dict): + policy_mapping_fn = from_config(policy_mapping_fn) + self.policy_mapping_fn = policy_mapping_fn + + if observation_fn is not NotProvided: + self.observation_fn = observation_fn + + if policy_map_cache != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.multi_agent(policy_map_cache=..)", + error=True, + ) + + if replay_mode != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.multi_agent(replay_mode=..)", + new="AlgorithmConfig.training(" + "replay_buffer_config={'replay_mode': ..})", + error=True, + ) + + if count_steps_by is not NotProvided: + if count_steps_by not in ["env_steps", "agent_steps"]: + raise ValueError( + "config.multi_agent(count_steps_by=..) must be one of " + f"[env_steps|agent_steps], not {count_steps_by}!" + ) + self.count_steps_by = count_steps_by + + if policies_to_train is not NotProvided: + assert ( + isinstance(policies_to_train, (list, set, tuple)) + or callable(policies_to_train) + or policies_to_train is None + ), ( + "ERROR: `policies_to_train` must be a [list|set|tuple] or a " + "callable taking PolicyID and SampleBatch and returning " + "True|False (trainable or not?) or None (for always training all " + "policies)." + ) + # Check `policies_to_train` for invalid entries. + if isinstance(policies_to_train, (list, set, tuple)): + if len(policies_to_train) == 0: + logger.warning( + "`config.multi_agent(policies_to_train=..)` is empty! " + "Make sure - if you would like to learn at least one policy - " + "to add its ID to that list." + ) + self.policies_to_train = policies_to_train + + if policy_states_are_swappable is not NotProvided: + self.policy_states_are_swappable = policy_states_are_swappable + + return self + + def reporting( + self, + *, + keep_per_episode_custom_metrics: Optional[bool] = NotProvided, + metrics_episode_collection_timeout_s: Optional[float] = NotProvided, + metrics_num_episodes_for_smoothing: Optional[int] = NotProvided, + min_time_s_per_iteration: Optional[float] = NotProvided, + min_train_timesteps_per_iteration: Optional[int] = NotProvided, + min_sample_timesteps_per_iteration: Optional[int] = NotProvided, + log_gradients: Optional[bool] = NotProvided, + ) -> "AlgorithmConfig": + """Sets the config's reporting settings. + + Args: + keep_per_episode_custom_metrics: Store raw custom metrics without + calculating max, min, mean + metrics_episode_collection_timeout_s: Wait for metric batches for at most + this many seconds. Those that have not returned in time are collected + in the next train iteration. + metrics_num_episodes_for_smoothing: Smooth rollout metrics over this many + episodes, if possible. + In case rollouts (sample collection) just started, there may be fewer + than this many episodes in the buffer and we'll compute metrics + over this smaller number of available episodes. + In case there are more than this many episodes collected in a single + training iteration, use all of these episodes for metrics computation, + meaning don't ever cut any "excess" episodes. + Set this to 1 to disable smoothing and to always report only the most + recently collected episode's return. + min_time_s_per_iteration: Minimum time (in sec) to accumulate within a + single `Algorithm.train()` call. This value does not affect learning, + only the number of times `Algorithm.training_step()` is called by + `Algorithm.train()`. If - after one such step attempt, the time taken + has not reached `min_time_s_per_iteration`, performs n more + `Algorithm.training_step()` calls until the minimum time has been + consumed. Set to 0 or None for no minimum time. + min_train_timesteps_per_iteration: Minimum training timesteps to accumulate + within a single `train()` call. This value does not affect learning, + only the number of times `Algorithm.training_step()` is called by + `Algorithm.train()`. If - after one such step attempt, the training + timestep count has not been reached, performs n more + `training_step()` calls until the minimum timesteps have been + executed. Set to 0 or None for no minimum timesteps. + min_sample_timesteps_per_iteration: Minimum env sampling timesteps to + accumulate within a single `train()` call. This value does not affect + learning, only the number of times `Algorithm.training_step()` is + called by `Algorithm.train()`. If - after one such step attempt, the env + sampling timestep count has not been reached, performs n more + `training_step()` calls until the minimum timesteps have been + executed. Set to 0 or None for no minimum timesteps. + log_gradients: Log gradients to results. If this is `True` the global norm + of the gradients dictionariy for each optimizer is logged to results. + The default is `True`. + + Returns: + This updated AlgorithmConfig object. + """ + if keep_per_episode_custom_metrics is not NotProvided: + self.keep_per_episode_custom_metrics = keep_per_episode_custom_metrics + if metrics_episode_collection_timeout_s is not NotProvided: + self.metrics_episode_collection_timeout_s = ( + metrics_episode_collection_timeout_s + ) + if metrics_num_episodes_for_smoothing is not NotProvided: + self.metrics_num_episodes_for_smoothing = metrics_num_episodes_for_smoothing + if min_time_s_per_iteration is not NotProvided: + self.min_time_s_per_iteration = min_time_s_per_iteration + if min_train_timesteps_per_iteration is not NotProvided: + self.min_train_timesteps_per_iteration = min_train_timesteps_per_iteration + if min_sample_timesteps_per_iteration is not NotProvided: + self.min_sample_timesteps_per_iteration = min_sample_timesteps_per_iteration + if log_gradients is not NotProvided: + self.log_gradients = log_gradients + + return self + + def checkpointing( + self, + export_native_model_files: Optional[bool] = NotProvided, + checkpoint_trainable_policies_only: Optional[bool] = NotProvided, + ) -> "AlgorithmConfig": + """Sets the config's checkpointing settings. + + Args: + export_native_model_files: Whether an individual Policy- + or the Algorithm's checkpoints also contain (tf or torch) native + model files. These could be used to restore just the NN models + from these files w/o requiring RLlib. These files are generated + by calling the tf- or torch- built-in saving utility methods on + the actual models. + checkpoint_trainable_policies_only: Whether to only add Policies to the + Algorithm checkpoint (in sub-directory "policies/") that are trainable + according to the `is_trainable_policy` callable of the local worker. + + Returns: + This updated AlgorithmConfig object. + """ + + if export_native_model_files is not NotProvided: + self.export_native_model_files = export_native_model_files + if checkpoint_trainable_policies_only is not NotProvided: + self.checkpoint_trainable_policies_only = checkpoint_trainable_policies_only + + return self + + def debugging( + self, + *, + logger_creator: Optional[Callable[[], Logger]] = NotProvided, + logger_config: Optional[dict] = NotProvided, + log_level: Optional[str] = NotProvided, + log_sys_usage: Optional[bool] = NotProvided, + fake_sampler: Optional[bool] = NotProvided, + seed: Optional[int] = NotProvided, + ) -> "AlgorithmConfig": + """Sets the config's debugging settings. + + Args: + logger_creator: Callable that creates a ray.tune.Logger + object. If unspecified, a default logger is created. + logger_config: Define logger-specific configuration to be used inside Logger + Default value None allows overwriting with nested dicts. + log_level: Set the ray.rllib.* log level for the agent process and its + workers. Should be one of DEBUG, INFO, WARN, or ERROR. The DEBUG level + also periodically prints out summaries of relevant internal dataflow + (this is also printed out once at startup at the INFO level). + log_sys_usage: Log system resource metrics to results. This requires + `psutil` to be installed for sys stats, and `gputil` for GPU metrics. + fake_sampler: Use fake (infinite speed) sampler. For testing only. + seed: This argument, in conjunction with worker_index, sets the random + seed of each worker, so that identically configured trials have + identical results. This makes experiments reproducible. + + Returns: + This updated AlgorithmConfig object. + """ + if logger_creator is not NotProvided: + self.logger_creator = logger_creator + if logger_config is not NotProvided: + self.logger_config = logger_config + if log_level is not NotProvided: + self.log_level = log_level + if log_sys_usage is not NotProvided: + self.log_sys_usage = log_sys_usage + if fake_sampler is not NotProvided: + self.fake_sampler = fake_sampler + if seed is not NotProvided: + self.seed = seed + + return self + + def fault_tolerance( + self, + *, + restart_failed_env_runners: Optional[bool] = NotProvided, + ignore_env_runner_failures: Optional[bool] = NotProvided, + max_num_env_runner_restarts: Optional[int] = NotProvided, + delay_between_env_runner_restarts_s: Optional[float] = NotProvided, + restart_failed_sub_environments: Optional[bool] = NotProvided, + num_consecutive_env_runner_failures_tolerance: Optional[int] = NotProvided, + env_runner_health_probe_timeout_s: Optional[float] = NotProvided, + env_runner_restore_timeout_s: Optional[float] = NotProvided, + # Deprecated args. + recreate_failed_env_runners=DEPRECATED_VALUE, + ignore_worker_failures=DEPRECATED_VALUE, + recreate_failed_workers=DEPRECATED_VALUE, + max_num_worker_restarts=DEPRECATED_VALUE, + delay_between_worker_restarts_s=DEPRECATED_VALUE, + num_consecutive_worker_failures_tolerance=DEPRECATED_VALUE, + worker_health_probe_timeout_s=DEPRECATED_VALUE, + worker_restore_timeout_s=DEPRECATED_VALUE, + ): + """Sets the config's fault tolerance settings. + + Args: + restart_failed_env_runners: Whether - upon an EnvRunner failure - RLlib + tries to restart the lost EnvRunner(s) as an identical copy of the + failed one(s). You should set this to True when training on SPOT + instances that may preempt any time. The new, recreated EnvRunner(s) + only differ from the failed one in their `self.recreated_worker=True` + property value and have the same `worker_index` as the original(s). + If this setting is True, the value of the `ignore_env_runner_failures` + setting is ignored. + ignore_env_runner_failures: Whether to ignore any EnvRunner failures + and continue running with the remaining EnvRunners. This setting is + ignored, if `restart_failed_env_runners=True`. + max_num_env_runner_restarts: The maximum number of times any EnvRunner + is allowed to be restarted (if `restart_failed_env_runners` is True). + delay_between_env_runner_restarts_s: The delay (in seconds) between two + consecutive EnvRunner restarts (if `restart_failed_env_runners` is + True). + restart_failed_sub_environments: If True and any sub-environment (within + a vectorized env) throws any error during env stepping, the + Sampler tries to restart the faulty sub-environment. This is done + without disturbing the other (still intact) sub-environment and without + the EnvRunner crashing. + num_consecutive_env_runner_failures_tolerance: The number of consecutive + times an EnvRunner failure (also for evaluation) is tolerated before + finally crashing the Algorithm. Only useful if either + `ignore_env_runner_failures` or `restart_failed_env_runners` is True. + Note that for `restart_failed_sub_environments` and sub-environment + failures, the EnvRunner itself is NOT affected and won't throw any + errors as the flawed sub-environment is silently restarted under the + hood. + env_runner_health_probe_timeout_s: Max amount of time in seconds, we should + spend waiting for EnvRunner health probe calls + (`EnvRunner.ping.remote()`) to respond. Health pings are very cheap, + however, we perform the health check via a blocking `ray.get()`, so the + default value should not be too large. + env_runner_restore_timeout_s: Max amount of time we should wait to restore + states on recovered EnvRunner actors. Default is 30 mins. + + Returns: + This updated AlgorithmConfig object. + """ + if recreate_failed_env_runners != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.fault_tolerance(recreate_failed_env_runners)", + new="AlgorithmConfig.fault_tolerance(restart_failed_env_runners)", + error=True, + ) + if ignore_worker_failures != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.fault_tolerance(ignore_worker_failures)", + new="AlgorithmConfig.fault_tolerance(ignore_env_runner_failures)", + error=True, + ) + if recreate_failed_workers != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.fault_tolerance(recreate_failed_workers)", + new="AlgorithmConfig.fault_tolerance(restart_failed_env_runners)", + error=True, + ) + if max_num_worker_restarts != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.fault_tolerance(max_num_worker_restarts)", + new="AlgorithmConfig.fault_tolerance(max_num_env_runner_restarts)", + error=True, + ) + if delay_between_worker_restarts_s != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.fault_tolerance(delay_between_worker_restarts_s)", + new="AlgorithmConfig.fault_tolerance(delay_between_env_runner_" + "restarts_s)", + error=True, + ) + if num_consecutive_worker_failures_tolerance != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.fault_tolerance(num_consecutive_worker_" + "failures_tolerance)", + new="AlgorithmConfig.fault_tolerance(num_consecutive_env_runner_" + "failures_tolerance)", + error=True, + ) + if worker_health_probe_timeout_s != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.fault_tolerance(worker_health_probe_timeout_s)", + new="AlgorithmConfig.fault_tolerance(" + "env_runner_health_probe_timeout_s)", + error=True, + ) + if worker_restore_timeout_s != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.fault_tolerance(worker_restore_timeout_s)", + new="AlgorithmConfig.fault_tolerance(env_runner_restore_timeout_s)", + error=True, + ) + + if ignore_env_runner_failures is not NotProvided: + self.ignore_env_runner_failures = ignore_env_runner_failures + if restart_failed_env_runners is not NotProvided: + self.restart_failed_env_runners = restart_failed_env_runners + if max_num_env_runner_restarts is not NotProvided: + self.max_num_env_runner_restarts = max_num_env_runner_restarts + if delay_between_env_runner_restarts_s is not NotProvided: + self.delay_between_env_runner_restarts_s = ( + delay_between_env_runner_restarts_s + ) + if restart_failed_sub_environments is not NotProvided: + self.restart_failed_sub_environments = restart_failed_sub_environments + if num_consecutive_env_runner_failures_tolerance is not NotProvided: + self.num_consecutive_env_runner_failures_tolerance = ( + num_consecutive_env_runner_failures_tolerance + ) + if env_runner_health_probe_timeout_s is not NotProvided: + self.env_runner_health_probe_timeout_s = env_runner_health_probe_timeout_s + if env_runner_restore_timeout_s is not NotProvided: + self.env_runner_restore_timeout_s = env_runner_restore_timeout_s + + return self + + def rl_module( + self, + *, + model_config: Optional[Union[Dict[str, Any], DefaultModelConfig]] = NotProvided, + rl_module_spec: Optional[RLModuleSpecType] = NotProvided, + algorithm_config_overrides_per_module: Optional[ + Dict[ModuleID, PartialAlgorithmConfigDict] + ] = NotProvided, + # Deprecated arg. + model_config_dict=DEPRECATED_VALUE, + _enable_rl_module_api=DEPRECATED_VALUE, + ) -> "AlgorithmConfig": + """Sets the config's RLModule settings. + + Args: + model_config: The DefaultModelConfig object (or a config dictionary) passed + as `model_config` arg into each RLModule's constructor. This is used + for all RLModules, if not otherwise specified through `rl_module_spec`. + rl_module_spec: The RLModule spec to use for this config. It can be either + a RLModuleSpec or a MultiRLModuleSpec. If the + observation_space, action_space, catalog_class, or the model config is + not specified it is inferred from the env and other parts of the + algorithm config object. + algorithm_config_overrides_per_module: Only used if + `enable_rl_module_and_learner=True`. + A mapping from ModuleIDs to per-module AlgorithmConfig override dicts, + which apply certain settings, + e.g. the learning rate, from the main AlgorithmConfig only to this + particular module (within a MultiRLModule). + You can create override dicts by using the `AlgorithmConfig.overrides` + utility. For example, to override your learning rate and (PPO) lambda + setting just for a single RLModule with your MultiRLModule, do: + config.multi_agent(algorithm_config_overrides_per_module={ + "module_1": PPOConfig.overrides(lr=0.0002, lambda_=0.75), + }) + + Returns: + This updated AlgorithmConfig object. + """ + if _enable_rl_module_api != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.rl_module(_enable_rl_module_api=..)", + new="AlgorithmConfig.api_stack(enable_rl_module_and_learner=..)", + error=True, + ) + if model_config_dict != DEPRECATED_VALUE: + deprecation_warning( + old="AlgorithmConfig.rl_module(model_config_dict=..)", + new="AlgorithmConfig.rl_module(model_config=..)", + error=False, + ) + model_config = model_config_dict + + if model_config is not NotProvided: + self._model_config = model_config + if rl_module_spec is not NotProvided: + self._rl_module_spec = rl_module_spec + if algorithm_config_overrides_per_module is not NotProvided: + if not isinstance(algorithm_config_overrides_per_module, dict): + raise ValueError( + "`algorithm_config_overrides_per_module` must be a dict mapping " + "module IDs to config override dicts! You provided " + f"{algorithm_config_overrides_per_module}." + ) + self.algorithm_config_overrides_per_module.update( + algorithm_config_overrides_per_module + ) + + return self + + def experimental( + self, + *, + _validate_config: Optional[bool] = True, + _use_msgpack_checkpoints: Optional[bool] = NotProvided, + _torch_grad_scaler_class: Optional[Type] = NotProvided, + _torch_lr_scheduler_classes: Optional[ + Union[List[Type], Dict[ModuleID, List[Type]]] + ] = NotProvided, + _tf_policy_handles_more_than_one_loss: Optional[bool] = NotProvided, + _disable_preprocessor_api: Optional[bool] = NotProvided, + _disable_action_flattening: Optional[bool] = NotProvided, + _disable_initialize_loss_from_dummy_batch: Optional[bool] = NotProvided, + ) -> "AlgorithmConfig": + """Sets the config's experimental settings. + + Args: + _validate_config: Whether to run `validate()` on this config. True by + default. If False, ignores any calls to `self.validate()`. + _use_msgpack_checkpoints: Create state files in all checkpoints through + msgpack rather than pickle. + _torch_grad_scaler_class: Class to use for torch loss scaling (and gradient + unscaling). The class must implement the following methods to be + compatible with a `TorchLearner`. These methods/APIs match exactly those + of torch's own `torch.amp.GradScaler` (see here for more details + https://pytorch.org/docs/stable/amp.html#gradient-scaling): + `scale([loss])` to scale the loss by some factor. + `get_scale()` to get the current scale factor value. + `step([optimizer])` to unscale the grads (divide by the scale factor) + and step the given optimizer. + `update()` to update the scaler after an optimizer step (for example to + adjust the scale factor). + _torch_lr_scheduler_classes: A list of `torch.lr_scheduler.LRScheduler` + (see here for more details + https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate) + classes or a dictionary mapping module IDs to such a list of respective + scheduler classes. Multiple scheduler classes can be applied in sequence + and are stepped in the same sequence as defined here. Note, most + learning rate schedulers need arguments to be configured, that is, you + might have to partially initialize the schedulers in the list(s) using + `functools.partial`. + _tf_policy_handles_more_than_one_loss: Experimental flag. + If True, TFPolicy handles more than one loss or optimizer. + Set this to True, if you would like to return more than + one loss term from your `loss_fn` and an equal number of optimizers + from your `optimizer_fn`. + _disable_preprocessor_api: Experimental flag. + If True, no (observation) preprocessor is created and + observations arrive in model as they are returned by the env. + _disable_action_flattening: Experimental flag. + If True, RLlib doesn't flatten the policy-computed actions into + a single tensor (for storage in SampleCollectors/output files/etc..), + but leave (possibly nested) actions as-is. Disabling flattening affects: + - SampleCollectors: Have to store possibly nested action structs. + - Models that have the previous action(s) as part of their input. + - Algorithms reading from offline files (incl. action information). + + Returns: + This updated AlgorithmConfig object. + """ + if _validate_config is not NotProvided: + self._validate_config = _validate_config + if _use_msgpack_checkpoints is not NotProvided: + self._use_msgpack_checkpoints = _use_msgpack_checkpoints + if _tf_policy_handles_more_than_one_loss is not NotProvided: + self._tf_policy_handles_more_than_one_loss = ( + _tf_policy_handles_more_than_one_loss + ) + if _disable_preprocessor_api is not NotProvided: + self._disable_preprocessor_api = _disable_preprocessor_api + if _disable_action_flattening is not NotProvided: + self._disable_action_flattening = _disable_action_flattening + if _disable_initialize_loss_from_dummy_batch is not NotProvided: + self._disable_initialize_loss_from_dummy_batch = ( + _disable_initialize_loss_from_dummy_batch + ) + if _torch_grad_scaler_class is not NotProvided: + self._torch_grad_scaler_class = _torch_grad_scaler_class + if _torch_lr_scheduler_classes is not NotProvided: + self._torch_lr_scheduler_classes = _torch_lr_scheduler_classes + + return self + + @property + def is_atari(self) -> bool: + """True if if specified env is an Atari env.""" + + # Not yet determined, try to figure this out. + if self._is_atari is None: + # Atari envs are usually specified via a string like "PongNoFrameskip-v4" + # or "ale_py:ALE/Breakout-v5". + # We do NOT attempt to auto-detect Atari env for other specified types like + # a callable, to avoid running heavy logics in validate(). + # For these cases, users can explicitly set `environment(atari=True)`. + if type(self.env) is not str: + return False + try: + env = gym.make(self.env) + # Any gymnasium error -> Cannot be an Atari env. + except gym.error.Error: + return False + + self._is_atari = is_atari(env) + # Clean up env's resources, if any. + env.close() + + return self._is_atari + + @property + def is_multi_agent(self) -> bool: + """Returns whether this config specifies a multi-agent setup. + + Returns: + True, if a) >1 policies defined OR b) 1 policy defined, but its ID is NOT + DEFAULT_POLICY_ID. + """ + return len(self.policies) > 1 or DEFAULT_POLICY_ID not in self.policies + + @property + def learner_class(self) -> Type["Learner"]: + """Returns the Learner sub-class to use by this Algorithm. + + Either + a) User sets a specific learner class via calling `.training(learner_class=...)` + b) User leaves learner class unset (None) and the AlgorithmConfig itself + figures out the actual learner class by calling its own + `.get_default_learner_class()` method. + """ + return self._learner_class or self.get_default_learner_class() + + @property + def model_config(self): + """Defines the model configuration used. + + This method combines the auto configuration `self _model_config_auto_includes` + defined by an algorithm with the user-defined configuration in + `self._model_config`.This configuration dictionary is used to + configure the `RLModule` in the new stack and the `ModelV2` in the old + stack. + + Returns: + A dictionary with the model configuration. + """ + return self._model_config_auto_includes | ( + self._model_config + if isinstance(self._model_config, dict) + else dataclasses.asdict(self._model_config) + ) + + @property + def rl_module_spec(self): + default_rl_module_spec = self.get_default_rl_module_spec() + _check_rl_module_spec(default_rl_module_spec) + + # `self._rl_module_spec` has been user defined (via call to `self.rl_module()`). + if self._rl_module_spec is not None: + # Merge provided RL Module spec class with defaults. + _check_rl_module_spec(self._rl_module_spec) + # Merge given spec with default one (in case items are missing, such as + # spaces, module class, etc.) + if isinstance(self._rl_module_spec, RLModuleSpec): + if isinstance(default_rl_module_spec, RLModuleSpec): + default_rl_module_spec.update(self._rl_module_spec) + return default_rl_module_spec + elif isinstance(default_rl_module_spec, MultiRLModuleSpec): + raise ValueError( + "Cannot merge MultiRLModuleSpec with RLModuleSpec!" + ) + else: + multi_rl_module_spec = copy.deepcopy(self._rl_module_spec) + multi_rl_module_spec.update(default_rl_module_spec) + return multi_rl_module_spec + + # `self._rl_module_spec` has not been user defined -> return default one. + else: + return default_rl_module_spec + + @property + def train_batch_size_per_learner(self) -> int: + # If not set explicitly, try to infer the value. + if self._train_batch_size_per_learner is None: + return self.train_batch_size // (self.num_learners or 1) + return self._train_batch_size_per_learner + + @train_batch_size_per_learner.setter + def train_batch_size_per_learner(self, value: int) -> None: + self._train_batch_size_per_learner = value + + @property + def total_train_batch_size(self) -> int: + """Returns the effective total train batch size. + + New API stack: `train_batch_size_per_learner` * [effective num Learners]. + + @OldAPIStack: User never touches `train_batch_size_per_learner` or + `num_learners`) -> `train_batch_size`. + """ + return self.train_batch_size_per_learner * (self.num_learners or 1) + + # TODO: Make rollout_fragment_length as read-only property and replace the current + # self.rollout_fragment_length a private variable. + def get_rollout_fragment_length(self, worker_index: int = 0) -> int: + """Automatically infers a proper rollout_fragment_length setting if "auto". + + Uses the simple formula: + `rollout_fragment_length` = `total_train_batch_size` / + (`num_envs_per_env_runner` * `num_env_runners`) + + If result is a fraction AND `worker_index` is provided, makes + those workers add additional timesteps, such that the overall batch size (across + the workers) adds up to exactly the `total_train_batch_size`. + + Returns: + The user-provided `rollout_fragment_length` or a computed one (if user + provided value is "auto"), making sure `total_train_batch_size` is reached + exactly in each iteration. + """ + if self.rollout_fragment_length == "auto": + # Example: + # 2 workers, 2 envs per worker, 2000 train batch size: + # -> 2000 / 4 -> 500 + # 4 workers, 3 envs per worker, 2500 train batch size: + # -> 2500 / 12 -> 208.333 -> diff=4 (208 * 12 = 2496) + # -> worker 1, 2: 209, workers 3, 4: 208 + # 2 workers, 20 envs per worker, 512 train batch size: + # -> 512 / 40 -> 12.8 -> diff=32 (12 * 40 = 480) + # -> worker 1: 13, workers 2: 12 + rollout_fragment_length = self.total_train_batch_size / ( + self.num_envs_per_env_runner * (self.num_env_runners or 1) + ) + if int(rollout_fragment_length) != rollout_fragment_length: + diff = self.total_train_batch_size - int( + rollout_fragment_length + ) * self.num_envs_per_env_runner * (self.num_env_runners or 1) + if ((worker_index - 1) * self.num_envs_per_env_runner) >= diff: + return int(rollout_fragment_length) + else: + return int(rollout_fragment_length) + 1 + return int(rollout_fragment_length) + else: + return self.rollout_fragment_length + + # TODO: Make evaluation_config as read-only property and replace the current + # self.evaluation_config a private variable. + def get_evaluation_config_object( + self, + ) -> Optional["AlgorithmConfig"]: + """Creates a full AlgorithmConfig object from `self.evaluation_config`. + + Returns: + A fully valid AlgorithmConfig object that can be used for the evaluation + EnvRunnerGroup. If `self` is already an evaluation config object, return + None. + """ + if self.in_evaluation: + assert self.evaluation_config is None + return None + + evaluation_config = self.evaluation_config + # Already an AlgorithmConfig -> copy and use as-is. + if isinstance(evaluation_config, AlgorithmConfig): + eval_config_obj = evaluation_config.copy(copy_frozen=False) + # Create unfrozen copy of self to be used as the to-be-returned eval + # AlgorithmConfig. + else: + eval_config_obj = self.copy(copy_frozen=False) + # Update with evaluation override settings: + eval_config_obj.update_from_dict(evaluation_config or {}) + + # Switch on the `in_evaluation` flag and remove `evaluation_config` + # (set to None). + eval_config_obj.in_evaluation = True + eval_config_obj.evaluation_config = None + + # Force-set the `num_env_runners` setting to `self.evaluation_num_env_runners`. + # Actually, the `self.evaluation_num_env_runners` is merely a convenience + # attribute and might be set instead through: + # `config.evaluation(evaluation_config={"num_env_runners": ...})` + eval_config_obj.num_env_runners = self.evaluation_num_env_runners + + # NOTE: The following if-block is only relevant for the old API stack. + # For the new API stack (EnvRunners), the evaluation methods of Algorithm + # explicitly tell each EnvRunner on each sample call, how many timesteps + # of episodes to collect. + # Evaluation duration unit: episodes. + # Switch on `complete_episode` rollouts. Also, make sure + # rollout fragments are short so we never have more than one + # episode in one rollout. + if self.evaluation_duration_unit == "episodes": + eval_config_obj.batch_mode = "complete_episodes" + eval_config_obj.rollout_fragment_length = 1 + # Evaluation duration unit: timesteps. + # - Set `batch_mode=truncate_episodes` so we don't perform rollouts + # strictly along episode borders. + # Set `rollout_fragment_length` such that desired steps are divided + # equally amongst workers or - in "auto" duration mode - set it + # to a reasonably small number (10), such that a single `sample()` + # call doesn't take too much time and we can stop evaluation as soon + # as possible after the train step is completed. + else: + eval_config_obj.batch_mode = "truncate_episodes" + eval_config_obj.rollout_fragment_length = ( + # Set to a moderately small (but not too small) value in order + # to a) not overshoot too much the parallelly running `training_step` + # but also to b) avoid too many `sample()` remote calls. + # 100 seems like a good middle ground. + 100 + if self.evaluation_duration == "auto" + else int( + math.ceil( + self.evaluation_duration + / (self.evaluation_num_env_runners or 1) + ) + ) + ) + + return eval_config_obj + + def validate_train_batch_size_vs_rollout_fragment_length(self) -> None: + """Detects mismatches for `train_batch_size` vs `rollout_fragment_length`. + + Only applicable for algorithms, whose train_batch_size should be directly + dependent on rollout_fragment_length (synchronous sampling, on-policy PG algos). + + If rollout_fragment_length != "auto", makes sure that the product of + `rollout_fragment_length` x `num_env_runners` x `num_envs_per_env_runner` + roughly (10%) matches the provided `train_batch_size`. Otherwise, errors with + asking the user to set rollout_fragment_length to `auto` or to a matching + value. + + Raises: + ValueError: If there is a mismatch between user provided + `rollout_fragment_length` and `total_train_batch_size`. + """ + if self.rollout_fragment_length != "auto" and not self.in_evaluation: + min_batch_size = ( + max(self.num_env_runners, 1) + * self.num_envs_per_env_runner + * self.rollout_fragment_length + ) + batch_size = min_batch_size + while batch_size < self.total_train_batch_size: + batch_size += min_batch_size + if batch_size - self.total_train_batch_size > ( + 0.1 * self.total_train_batch_size + ) or batch_size - min_batch_size - self.total_train_batch_size > ( + 0.1 * self.total_train_batch_size + ): + suggested_rollout_fragment_length = self.total_train_batch_size // ( + self.num_envs_per_env_runner * (self.num_env_runners or 1) + ) + self._value_error( + "Your desired `total_train_batch_size` " + f"({self.total_train_batch_size}={self.num_learners} " + f"learners x {self.train_batch_size_per_learner}) " + "or a value 10% off of that cannot be achieved with your other " + f"settings (num_env_runners={self.num_env_runners}; " + f"num_envs_per_env_runner={self.num_envs_per_env_runner}; " + f"rollout_fragment_length={self.rollout_fragment_length})! " + "Try setting `rollout_fragment_length` to 'auto' OR to a value of " + f"{suggested_rollout_fragment_length}." + ) + + def get_torch_compile_worker_config(self): + """Returns the TorchCompileConfig to use on workers.""" + + from ray.rllib.core.rl_module.torch.torch_compile_config import ( + TorchCompileConfig, + ) + + return TorchCompileConfig( + torch_dynamo_backend=self.torch_compile_worker_dynamo_backend, + torch_dynamo_mode=self.torch_compile_worker_dynamo_mode, + ) + + def get_default_rl_module_spec(self) -> RLModuleSpecType: + """Returns the RLModule spec to use for this algorithm. + + Override this method in the subclass to return the RLModule spec, given + the input framework. + + Returns: + The RLModuleSpec (or MultiRLModuleSpec) to + use for this algorithm's RLModule. + """ + raise NotImplementedError + + def get_default_learner_class(self) -> Union[Type["Learner"], str]: + """Returns the Learner class to use for this algorithm. + + Override this method in the sub-class to return the Learner class type given + the input framework. + + Returns: + The Learner class to use for this algorithm either as a class type or as + a string (e.g. "ray.rllib.algorithms.ppo.ppo_learner.PPOLearner"). + """ + raise NotImplementedError + + def get_rl_module_spec( + self, + env: Optional[EnvType] = None, + spaces: Optional[Dict[str, Tuple[gym.Space, gym.Space]]] = None, + inference_only: Optional[bool] = None, + ) -> RLModuleSpec: + """Returns the RLModuleSpec based on the given env/spaces and this config. + + Args: + env: An optional environment instance, from which to infer the observation- + and action spaces for the RLModule. If not provided, tries to infer + from `spaces`, otherwise from `self.observation_space` and + `self.action_space`. Raises an error, if no information on spaces can be + inferred. + spaces: Optional dict mapping ModuleIDs to 2-tuples of observation- and + action space that should be used for the respective RLModule. + These spaces are usually provided by an already instantiated remote + EnvRunner (call `EnvRunner.get_spaces()` to receive this dict). If not + provided, RLlib tries to infer this from `env`, if provided, otherwise + from `self.observation_space` and `self.action_space`. Raises an error, + if no information on spaces can be inferred. + inference_only: If `True`, the returned module spec is used in an + inference-only setting (sampling) and the RLModule can thus be built in + its light version (if available). For example, the `inference_only` + version of an RLModule might only contain the networks required for + computing actions, but misses additional target- or critic networks. + + Returns: + A new RLModuleSpec instance that can be used to build an RLModule. + """ + rl_module_spec = copy.deepcopy(self.rl_module_spec) + + # If a MultiRLModuleSpec -> Reduce to single-agent (and assert that + # all non DEFAULT_MODULE_IDs are `learner_only` (so they are not built on + # EnvRunner). + if isinstance(rl_module_spec, MultiRLModuleSpec): + error = False + if DEFAULT_MODULE_ID not in rl_module_spec: + error = True + if inference_only: + for mid, spec in rl_module_spec.rl_module_specs.items(): + if mid != DEFAULT_MODULE_ID: + if not spec.learner_only: + error = True + elif len(rl_module_spec) > 1: + error = True + if error: + raise ValueError( + "When calling `AlgorithmConfig.get_rl_module_spec()`, the " + "configuration must contain the `DEFAULT_MODULE_ID` key and all " + "other keys' specs must have the setting `learner_only=True`! If " + "you are using a more complex setup, call " + "`AlgorithmConfig.get_multi_rl_module_spec(...)` instead." + ) + rl_module_spec = rl_module_spec[DEFAULT_MODULE_ID] + + if rl_module_spec.observation_space is None: + if spaces is not None: + rl_module_spec.observation_space = spaces[DEFAULT_MODULE_ID][0] + elif env is not None and isinstance(env, gym.Env): + rl_module_spec.observation_space = getattr( + env, "single_observation_space", env.observation_space + ) + else: + rl_module_spec.observation_space = self.observation_space + + if rl_module_spec.action_space is None: + if spaces is not None: + rl_module_spec.action_space = spaces[DEFAULT_MODULE_ID][1] + elif env is not None and isinstance(env, gym.Env): + rl_module_spec.action_space = getattr( + env, "single_action_space", env.action_space + ) + else: + rl_module_spec.action_space = self.action_space + + # If module_config_dict is not defined, set to our generic one. + if rl_module_spec.model_config is None: + rl_module_spec.model_config = self.model_config + + if inference_only is not None: + rl_module_spec.inference_only = inference_only + + return rl_module_spec + + def get_multi_rl_module_spec( + self, + *, + env: Optional[EnvType] = None, + spaces: Optional[Dict[PolicyID, Tuple[gym.Space, gym.Space]]] = None, + inference_only: bool = False, + # @HybridAPIStack + policy_dict: Optional[Dict[str, PolicySpec]] = None, + single_agent_rl_module_spec: Optional[RLModuleSpec] = None, + ) -> MultiRLModuleSpec: + """Returns the MultiRLModuleSpec based on the given env/spaces. + + Args: + env: An optional environment instance, from which to infer the different + spaces for the individual RLModules. If not provided, tries to infer + from `spaces`, otherwise from `self.observation_space` and + `self.action_space`. Raises an error, if no information on spaces can be + inferred. + spaces: Optional dict mapping ModuleIDs to 2-tuples of observation- and + action space that should be used for the respective RLModule. + These spaces are usually provided by an already instantiated remote + EnvRunner (call `EnvRunner.get_spaces()`). If not provided, tries + to infer from `env`, otherwise from `self.observation_space` and + `self.action_space`. Raises an error, if no information on spaces can be + inferred. + inference_only: If `True`, the returned module spec is used in an + inference-only setting (sampling) and the RLModule can thus be built in + its light version (if available). For example, the `inference_only` + version of an RLModule might only contain the networks required for + computing actions, but misses additional target- or critic networks. + Also, if `True`, the returned spec does NOT contain those (sub) + RLModuleSpecs that have their `learner_only` flag set to True. + + Returns: + A new MultiRLModuleSpec instance that can be used to build a MultiRLModule. + """ + # TODO (Kourosh,sven): When we replace policy entirely there is no need for + # this function to map policy_dict to multi_rl_module_specs anymore. The module + # spec is directly given by the user or inferred from env and spaces. + if policy_dict is None: + policy_dict, _ = self.get_multi_agent_setup(env=env, spaces=spaces) + + # TODO (Kourosh): Raise an error if the config is not frozen + # If the module is single-agent convert it to multi-agent spec + + # The default RLModuleSpec (might be multi-agent or single-agent). + default_rl_module_spec = self.get_default_rl_module_spec() + # The currently configured RLModuleSpec (might be multi-agent or single-agent). + # If None, use the default one. + current_rl_module_spec = self._rl_module_spec or default_rl_module_spec + + # Algorithm is currently setup as a single-agent one. + if isinstance(current_rl_module_spec, RLModuleSpec): + # Use either the provided `single_agent_rl_module_spec` (a + # RLModuleSpec), the currently configured one of this + # AlgorithmConfig object, or the default one. + single_agent_rl_module_spec = ( + single_agent_rl_module_spec or current_rl_module_spec + ) + single_agent_rl_module_spec.inference_only = inference_only + # Now construct the proper MultiRLModuleSpec. + multi_rl_module_spec = MultiRLModuleSpec( + rl_module_specs={ + k: copy.deepcopy(single_agent_rl_module_spec) + for k in policy_dict.keys() + }, + ) + + # Algorithm is currently setup as a multi-agent one. + else: + # The user currently has a MultiAgentSpec setup (either via + # self._rl_module_spec or the default spec of this AlgorithmConfig). + assert isinstance(current_rl_module_spec, MultiRLModuleSpec) + + # Default is single-agent but the user has provided a multi-agent spec + # so the use-case is multi-agent. + if isinstance(default_rl_module_spec, RLModuleSpec): + # The individual (single-agent) module specs are defined by the user + # in the currently setup MultiRLModuleSpec -> Use that + # RLModuleSpec. + if isinstance(current_rl_module_spec.rl_module_specs, RLModuleSpec): + single_agent_spec = single_agent_rl_module_spec or ( + current_rl_module_spec.rl_module_specs + ) + single_agent_spec.inference_only = inference_only + module_specs = { + k: copy.deepcopy(single_agent_spec) for k in policy_dict.keys() + } + + # The individual (single-agent) module specs have not been configured + # via this AlgorithmConfig object -> Use provided single-agent spec or + # the default spec (which is also a RLModuleSpec in this + # case). + else: + single_agent_spec = ( + single_agent_rl_module_spec or default_rl_module_spec + ) + single_agent_spec.inference_only = inference_only + module_specs = { + k: copy.deepcopy( + current_rl_module_spec.rl_module_specs.get( + k, single_agent_spec + ) + ) + for k in ( + policy_dict | current_rl_module_spec.rl_module_specs + ).keys() + } + + # Now construct the proper MultiRLModuleSpec. + # We need to infer the multi-agent class from `current_rl_module_spec` + # and fill in the module_specs dict. + multi_rl_module_spec = current_rl_module_spec.__class__( + multi_rl_module_class=current_rl_module_spec.multi_rl_module_class, + rl_module_specs=module_specs, + modules_to_load=current_rl_module_spec.modules_to_load, + load_state_path=current_rl_module_spec.load_state_path, + ) + + # Default is multi-agent and user wants to override it -> Don't use the + # default. + else: + # User provided an override RLModuleSpec -> Use this to + # construct the individual RLModules within the MultiRLModuleSpec. + if single_agent_rl_module_spec is not None: + pass + # User has NOT provided an override RLModuleSpec. + else: + # But the currently setup multi-agent spec has a SingleAgentRLModule + # spec defined -> Use that to construct the individual RLModules + # within the MultiRLModuleSpec. + if isinstance(current_rl_module_spec.rl_module_specs, RLModuleSpec): + # The individual module specs are not given, it is given as one + # RLModuleSpec to be re-used for all + single_agent_rl_module_spec = ( + current_rl_module_spec.rl_module_specs + ) + # The currently set up multi-agent spec has NO + # RLModuleSpec in it -> Error (there is no way we can + # infer this information from anywhere at this point). + else: + raise ValueError( + "We have a MultiRLModuleSpec " + f"({current_rl_module_spec}), but no " + "`RLModuleSpec`s to compile the individual " + "RLModules' specs! Use " + "`AlgorithmConfig.get_multi_rl_module_spec(" + "policy_dict=.., rl_module_spec=..)`." + ) + + single_agent_rl_module_spec.inference_only = inference_only + + # Now construct the proper MultiRLModuleSpec. + multi_rl_module_spec = current_rl_module_spec.__class__( + multi_rl_module_class=current_rl_module_spec.multi_rl_module_class, + rl_module_specs={ + k: copy.deepcopy(single_agent_rl_module_spec) + for k in policy_dict.keys() + }, + modules_to_load=current_rl_module_spec.modules_to_load, + load_state_path=current_rl_module_spec.load_state_path, + ) + + # Fill in the missing values from the specs that we already have. By combining + # PolicySpecs and the default RLModuleSpec. + for module_id in policy_dict | multi_rl_module_spec.rl_module_specs: + + # Remove/skip `learner_only=True` RLModules if `inference_only` is True. + module_spec = multi_rl_module_spec.rl_module_specs[module_id] + if inference_only and module_spec.learner_only: + multi_rl_module_spec.remove_modules(module_id) + continue + + if module_spec.module_class is None: + if isinstance(default_rl_module_spec, RLModuleSpec): + module_spec.module_class = default_rl_module_spec.module_class + elif isinstance(default_rl_module_spec.rl_module_specs, RLModuleSpec): + module_class = default_rl_module_spec.rl_module_specs.module_class + # This should be already checked in validate() but we check it + # again here just in case + if module_class is None: + raise ValueError( + "The default rl_module spec cannot have an empty " + "module_class under its RLModuleSpec." + ) + module_spec.module_class = module_class + elif module_id in default_rl_module_spec.rl_module_specs: + module_spec.module_class = default_rl_module_spec.rl_module_specs[ + module_id + ].module_class + else: + raise ValueError( + f"Module class for module {module_id} cannot be inferred. " + f"It is neither provided in the rl_module_spec that " + "is passed in nor in the default module spec used in " + "the algorithm." + ) + if module_spec.catalog_class is None: + if isinstance(default_rl_module_spec, RLModuleSpec): + module_spec.catalog_class = default_rl_module_spec.catalog_class + elif isinstance(default_rl_module_spec.rl_module_specs, RLModuleSpec): + catalog_class = default_rl_module_spec.rl_module_specs.catalog_class + module_spec.catalog_class = catalog_class + elif module_id in default_rl_module_spec.rl_module_specs: + module_spec.catalog_class = default_rl_module_spec.rl_module_specs[ + module_id + ].catalog_class + else: + raise ValueError( + f"Catalog class for module {module_id} cannot be inferred. " + f"It is neither provided in the rl_module_spec that " + "is passed in nor in the default module spec used in " + "the algorithm." + ) + # TODO (sven): Find a good way to pack module specific parameters from + # the algorithms into the `model_config_dict`. + if ( + module_spec.observation_space is None + or module_spec.action_space is None + ): + policy_spec = policy_dict.get( + module_id, policy_dict.get(DEFAULT_MODULE_ID) + ) + if policy_spec is not None: + if module_spec.observation_space is None: + module_spec.observation_space = policy_spec.observation_space + if module_spec.action_space is None: + module_spec.action_space = policy_spec.action_space + # In case the `RLModuleSpec` does not have a model config dict, we use the + # the one defined by the auto keys and the `model_config_dict` arguments in + # `self.rl_module()`. + if module_spec.model_config is None: + module_spec.model_config = self.model_config + # Otherwise we combine the two dictionaries where settings from the + # `RLModuleSpec` have higher priority. + else: + module_spec.model_config = ( + self.model_config | module_spec._get_model_config() + ) + + return multi_rl_module_spec + + def __setattr__(self, key, value): + """Gatekeeper in case we are in frozen state and need to error.""" + + # If we are frozen, do not allow to set any attributes anymore. + if hasattr(self, "_is_frozen") and self._is_frozen: + # TODO: Remove `simple_optimizer` entirely. + # Remove need to set `worker_index` in RolloutWorker's c'tor. + if key not in ["simple_optimizer", "worker_index", "_is_frozen"]: + raise AttributeError( + f"Cannot set attribute ({key}) of an already frozen " + "AlgorithmConfig!" + ) + # Backward compatibility for checkpoints taken with wheels, in which + # `self.rl_module_spec` was still settable (now it's a property). + if key == "rl_module_spec": + key = "_rl_module_spec" + + super().__setattr__(key, value) + + def __getitem__(self, item): + """Shim method to still support accessing properties by key lookup. + + This way, an AlgorithmConfig object can still be used as if a dict, e.g. + by Ray Tune. + + Examples: + .. testcode:: + + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + config = AlgorithmConfig() + print(config["lr"]) + + .. testoutput:: + + 0.001 + """ + # TODO: Uncomment this once all algorithms use AlgorithmConfigs under the + # hood (as well as Ray Tune). + # if log_once("algo_config_getitem"): + # logger.warning( + # "AlgorithmConfig objects should NOT be used as dict! " + # f"Try accessing `{item}` directly as a property." + # ) + # In case user accesses "old" keys, e.g. "num_workers", which need to + # be translated to their correct property names. + item = self._translate_special_keys(item) + return getattr(self, item) + + def __setitem__(self, key, value): + # TODO: Remove comments once all methods/functions only support + # AlgorithmConfigs and there is no more ambiguity anywhere in the code + # on whether an AlgorithmConfig is used or an old python config dict. + # raise AttributeError( + # "AlgorithmConfig objects should not have their values set like dicts" + # f"(`config['{key}'] = {value}`), " + # f"but via setting their properties directly (config.{prop} = {value})." + # ) + if key == "multiagent": + raise AttributeError( + "Cannot set `multiagent` key in an AlgorithmConfig!\nTry setting " + "the multi-agent components of your AlgorithmConfig object via the " + "`multi_agent()` method and its arguments.\nE.g. `config.multi_agent(" + "policies=.., policy_mapping_fn.., policies_to_train=..)`." + ) + super().__setattr__(key, value) + + def __contains__(self, item) -> bool: + """Shim method to help pretend we are a dict.""" + prop = self._translate_special_keys(item, warn_deprecated=False) + return hasattr(self, prop) + + def get(self, key, default=None): + """Shim method to help pretend we are a dict.""" + prop = self._translate_special_keys(key, warn_deprecated=False) + return getattr(self, prop, default) + + def pop(self, key, default=None): + """Shim method to help pretend we are a dict.""" + return self.get(key, default) + + def keys(self): + """Shim method to help pretend we are a dict.""" + return self.to_dict().keys() + + def values(self): + """Shim method to help pretend we are a dict.""" + return self.to_dict().values() + + def items(self): + """Shim method to help pretend we are a dict.""" + return self.to_dict().items() + + @property + def _model_config_auto_includes(self) -> Dict[str, Any]: + """Defines which `AlgorithmConfig` settings/properties should be + auto-included into `self.model_config`. + + The dictionary in this property contains the default configuration of an + algorithm. Together with the `self._model`, this method is used to + define the configuration sent to the `RLModule`. + + Returns: + A dictionary with the automatically included properties/settings of this + `AlgorithmConfig` object into `self.model_config`. + """ + return {} + + # ----------------------------------------------------------- + # Various validation methods for different types of settings. + # ----------------------------------------------------------- + def _value_error(self, errmsg) -> None: + msg = errmsg + ( + "\nTo suppress all validation errors, set " + "`config.experimental(_validate_config=False)` at your own risk." + ) + if self._validate_config: + raise ValueError(msg) + else: + logger.warning(errmsg) + + def _validate_env_runner_settings(self) -> None: + allowed_vectorize_modes = set( + list(gym.envs.registration.VectorizeMode.__members__.keys()) + + list(gym.envs.registration.VectorizeMode.__members__.values()) + ) + if self.gym_env_vectorize_mode not in allowed_vectorize_modes: + self._value_error( + f"`gym_env_vectorize_mode` ({self.gym_env_vectorize_mode}) must be a " + "member of `gym.envs.registration.VectorizeMode`! Allowed values " + f"are {allowed_vectorize_modes}." + ) + + def _validate_callbacks_settings(self) -> None: + """Validates callbacks settings.""" + # Old API stack: + # - self.callbacks_cls must be a subclass of RLlibCallback. + # - All self.callbacks_... attributes must be None. + if not self.enable_env_runner_and_connector_v2: + if ( + self.callbacks_on_environment_created is not None + or self.callbacks_on_algorithm_init is not None + or self.callbacks_on_train_result is not None + or self.callbacks_on_evaluate_start is not None + or self.callbacks_on_evaluate_end is not None + or self.callbacks_on_sample_end is not None + or self.callbacks_on_environment_created is not None + or self.callbacks_on_episode_created is not None + or self.callbacks_on_episode_start is not None + or self.callbacks_on_episode_step is not None + or self.callbacks_on_episode_end is not None + or self.callbacks_on_checkpoint_loaded is not None + or self.callbacks_on_env_runners_recreated is not None + or self.callbacks_on_offline_eval_runners_recreated is not None + ): + self._value_error( + "Config settings `config.callbacks(on_....=lambda ..)` aren't " + "supported on the old API stack! Switch to the new API stack " + "through `config.api_stack(enable_env_runner_and_connector_v2=True," + " enable_rl_module_and_learner=True)`." + ) + + def _validate_framework_settings(self) -> None: + """Validates framework settings and checks whether framework is installed.""" + _tf1, _tf, _tfv = None, None, None + _torch = None + if self.framework_str not in {"tf", "tf2"} and self.framework_str != "torch": + return + elif self.framework_str in {"tf", "tf2"}: + _tf1, _tf, _tfv = try_import_tf() + else: + _torch, _ = try_import_torch() + + # Can not use "tf" with learner API. + if self.framework_str == "tf" and self.enable_rl_module_and_learner: + self._value_error( + "Cannot use `framework=tf` with the new API stack! Either switch to tf2" + " via `config.framework('tf2')` OR disable the new API stack via " + "`config.api_stack(enable_rl_module_and_learner=False)`." + ) + + # Check if torch framework supports torch.compile. + if ( + _torch is not None + and self.framework_str == "torch" + and version.parse(_torch.__version__) < TORCH_COMPILE_REQUIRED_VERSION + and (self.torch_compile_learner or self.torch_compile_worker) + ): + self._value_error("torch.compile is only supported from torch 2.0.0") + + # Make sure the Learner's torch-what-to-compile setting is supported. + if self.torch_compile_learner: + from ray.rllib.core.learner.torch.torch_learner import ( + TorchCompileWhatToCompile, + ) + + if self.torch_compile_learner_what_to_compile not in [ + TorchCompileWhatToCompile.FORWARD_TRAIN, + TorchCompileWhatToCompile.COMPLETE_UPDATE, + ]: + self._value_error( + f"`config.torch_compile_learner_what_to_compile` must be one of [" + f"TorchCompileWhatToCompile.forward_train, " + f"TorchCompileWhatToCompile.complete_update] but is" + f" {self.torch_compile_learner_what_to_compile}" + ) + + self._check_if_correct_nn_framework_installed(_tf1, _tf, _torch) + self._resolve_tf_settings(_tf1, _tfv) + + def _validate_resources_settings(self): + """Checks, whether resources related settings make sense.""" + pass + + def _validate_multi_agent_settings(self): + """Checks, whether multi-agent related settings make sense.""" + + # Check `policies_to_train` for invalid entries. + if isinstance(self.policies_to_train, (list, set, tuple)): + for pid in self.policies_to_train: + if pid not in self.policies: + self._value_error( + "`config.multi_agent(policies_to_train=..)` contains " + f"policy ID ({pid}) that was not defined in " + f"`config.multi_agent(policies=..)`!" + ) + + def _validate_evaluation_settings(self): + """Checks, whether evaluation related settings make sense.""" + + # Async evaluation has been deprecated. Use "simple" parallel mode instead + # (which is also async): + # `config.evaluation(evaluation_parallel_to_training=True)`. + if self.enable_async_evaluation is True: + self._value_error( + "`enable_async_evaluation` has been deprecated (you should set this to " + "False)! Use `config.evaluation(evaluation_parallel_to_training=True)` " + "instead." + ) + + # If `evaluation_num_env_runners` > 0, warn if `evaluation_interval` is 0 or + # None. + if self.evaluation_num_env_runners > 0 and not self.evaluation_interval: + logger.warning( + f"You have specified {self.evaluation_num_env_runners} " + "evaluation workers, but your `evaluation_interval` is 0 or None! " + "Therefore, evaluation doesn't occur automatically with each" + " call to `Algorithm.train()`. Instead, you have to call " + "`Algorithm.evaluate()` manually in order to trigger an " + "evaluation run." + ) + # If `evaluation_num_env_runners=0` and + # `evaluation_parallel_to_training=True`, warn that you need + # at least one remote eval worker for parallel training and + # evaluation, and set `evaluation_parallel_to_training` to False. + if ( + self.evaluation_num_env_runners == 0 + and self.num_offline_eval_runners == 0 + and self.evaluation_parallel_to_training + ): + self._value_error( + "`evaluation_parallel_to_training` can only be done if " + "`evaluation_num_env_runners` > 0! Try setting " + "`config.evaluation_parallel_to_training` to False." + ) + + # If `evaluation_duration=auto`, error if + # `evaluation_parallel_to_training=False`. + if self.evaluation_duration == "auto": + if not self.evaluation_parallel_to_training: + self._value_error( + "`evaluation_duration=auto` not supported for " + "`evaluation_parallel_to_training=False`!" + ) + elif self.evaluation_duration_unit == "episodes": + logger.warning( + "When using `config.evaluation_duration='auto'`, the sampling unit " + "used is always 'timesteps'! You have set " + "`config.evaluation_duration_unit='episodes'`, which is ignored." + ) + + # Make sure, `evaluation_duration` is an int otherwise. + elif ( + not isinstance(self.evaluation_duration, int) + or self.evaluation_duration <= 0 + ): + self._value_error( + f"`evaluation_duration` ({self.evaluation_duration}) must be an " + f"int and >0!" + ) + + def _validate_input_settings(self): + """Checks, whether input related settings make sense.""" + + if self.input_ == "sampler" and self.off_policy_estimation_methods: + self._value_error( + "Off-policy estimation methods can only be used if the input is a " + "dataset. We currently do not support applying off_policy_estimation_" + "method on a sampler input." + ) + + if self.input_ == "dataset": + # If you need to read a Ray dataset set the parallelism and + # num_cpus_per_read_task from rollout worker settings + self.input_config["num_cpus_per_read_task"] = self.num_cpus_per_env_runner + if self.in_evaluation: + # If using dataset for evaluation, the parallelism gets set to + # evaluation_num_env_runners for backward compatibility and num_cpus + # gets set to num_cpus_per_env_runner from rollout worker. User only + # needs to set evaluation_num_env_runners. + self.input_config["parallelism"] = self.evaluation_num_env_runners or 1 + else: + # If using dataset for training, the parallelism and num_cpus gets set + # based on rollout worker parameters. This is for backwards + # compatibility for now. User only needs to set num_env_runners. + self.input_config["parallelism"] = self.num_env_runners or 1 + + def _validate_new_api_stack_settings(self): + """Checks, whether settings related to the new API stack make sense.""" + + # Old API stack checks. + if not self.enable_rl_module_and_learner: + # Throw a warning if the user has used `self.rl_module(rl_module_spec=...)` + # but has not enabled the new API stack at the same time. + if self._rl_module_spec is not None: + logger.warning( + "You have setup a RLModuleSpec (via calling " + "`config.rl_module(...)`), but have not enabled the new API stack. " + "To enable it, call `config.api_stack(enable_rl_module_and_learner=" + "True)`." + ) + # Throw a warning if the user has used `self.training(learner_class=...)` + # but has not enabled the new API stack at the same time. + if self._learner_class is not None: + logger.warning( + "You specified a custom Learner class (via " + f"`AlgorithmConfig.training(learner_class={self._learner_class})`, " + f"but have the new API stack disabled. You need to enable it via " + "`AlgorithmConfig.api_stack(enable_rl_module_and_learner=True)`." + ) + # User is using the new EnvRunners, but forgot to switch on + # `enable_rl_module_and_learner`. + if self.enable_env_runner_and_connector_v2: + self._value_error( + "You are using the new API stack EnvRunners (SingleAgentEnvRunner " + "or MultiAgentEnvRunner), but have forgotten to switch on the new " + "API stack! Try setting " + "`config.api_stack(enable_rl_module_and_learner=True)`." + ) + # Early out. The rest of this method is only for + # `enable_rl_module_and_learner=True`. + return + + # Warn about new API stack on by default. + if log_once(f"{self.algo_class.__name__}_on_new_api_stack"): + logger.warning( + f"You are running {self.algo_class.__name__} on the new API stack! " + "This is the new default behavior for this algorithm. If you don't " + "want to use the new API stack, set `config.api_stack(" + "enable_rl_module_and_learner=False," + "enable_env_runner_and_connector_v2=False)`. For a detailed migration " + "guide, see here: https://docs.ray.io/en/master/rllib/new-api-stack-migration-guide.html" # noqa + ) + + # Disabled hybrid API stack. Now, both `enable_rl_module_and_learner` and + # `enable_env_runner_and_connector_v2` must be True or both False. + if not self.enable_env_runner_and_connector_v2: + self._value_error( + "Setting `enable_rl_module_and_learner` to True and " + "`enable_env_runner_and_connector_v2` to False ('hybrid API stack'" + ") is not longer supported! Set both to True (new API stack) or both " + "to False (old API stack), instead." + ) + + # For those users that accidentally use the new API stack (because it's the + # default now for many algos), we need to make sure they are warned. + try: + tree.assert_same_structure(self.model, MODEL_DEFAULTS) + # Create copies excluding the specified key + check( + {k: v for k, v in self.model.items() if k != "vf_share_layers"}, + {k: v for k, v in MODEL_DEFAULTS.items() if k != "vf_share_layers"}, + ) + except Exception: + logger.warning( + "You configured a custom `model` config (probably through calling " + "config.training(model=..), whereas your config uses the new API " + "stack! In order to switch off the new API stack, set in your config: " + "`config.api_stack(enable_rl_module_and_learner=False, " + "enable_env_runner_and_connector_v2=False)`. If you DO want to use " + "the new API stack, configure your model, instead, through: " + "`config.rl_module(model_config={..})`." + ) + + # LR-schedule checking. + Scheduler.validate( + fixed_value_or_schedule=self.lr, + setting_name="lr", + description="learning rate", + ) + + # This is not compatible with RLModules, which all have a method + # `forward_exploration` to specify custom exploration behavior. + if self.exploration_config: + self._value_error( + "When the RLModule API is enabled, exploration_config can not be " + "set. If you want to implement custom exploration behaviour, " + "please modify the `forward_exploration` method of the " + "RLModule at hand. On configs that have a default exploration " + "config, this must be done via " + "`config.exploration_config={}`." + ) + + not_compatible_w_rlm_msg = ( + "Cannot use `{}` option with the new API stack (RLModule and " + "Learner APIs)! `{}` is part of the ModelV2 API and Policy API," + " which are not compatible with the new API stack. You can either " + "deactivate the new stack via `config.api_stack( " + "enable_rl_module_and_learner=False)`," + "or use the new stack (incl. RLModule API) and implement your " + "custom model as an RLModule." + ) + + if self.model["custom_model"] is not None: + self._value_error( + not_compatible_w_rlm_msg.format("custom_model", "custom_model") + ) + + if self.model["custom_model_config"] != {}: + self._value_error( + not_compatible_w_rlm_msg.format( + "custom_model_config", "custom_model_config" + ) + ) + + # TODO (sven): Once everything is on the new API stack, we won't need this method + # anymore. + def _validate_to_be_deprecated_settings(self): + # `render_env` is deprecated on new API stack. + if self.enable_env_runner_and_connector_v2 and self.render_env is not False: + deprecation_warning( + old="AlgorithmConfig.render_env", + help="The `render_env` setting is not supported on the new API stack! " + "In order to log videos to WandB (or other loggers), take a look at " + "this example here: " + "https://github.com/ray-project/ray/blob/master/rllib/examples/envs/env_rendering_and_recording.py", # noqa + ) + + if self.preprocessor_pref not in ["rllib", "deepmind", None]: + self._value_error( + "`config.preprocessor_pref` must be either 'rllib', 'deepmind' or None!" + ) + + # Check model config. + # If no preprocessing, propagate into model's config as well + # (so model knows whether inputs are preprocessed or not). + if self._disable_preprocessor_api is True: + self.model["_disable_preprocessor_api"] = True + # If no action flattening, propagate into model's config as well + # (so model knows whether action inputs are already flattened or not). + if self._disable_action_flattening is True: + self.model["_disable_action_flattening"] = True + if self.model.get("custom_preprocessor"): + deprecation_warning( + old="AlgorithmConfig.training(model={'custom_preprocessor': ...})", + help="Custom preprocessors are deprecated, " + "since they sometimes conflict with the built-in " + "preprocessors for handling complex observation spaces. " + "Please use wrapper classes around your environment " + "instead.", + error=True, + ) + + # Multi-GPU settings. + if self.simple_optimizer is True: + pass + # Multi-GPU setting: Must use MultiGPUTrainOneStep. + elif not self.enable_rl_module_and_learner and self.num_gpus > 1: + # TODO: AlphaStar uses >1 GPUs differently (1 per policy actor), so this is + # ok for tf2 here. + # Remove this hacky check, once we have fully moved to the Learner API. + if self.framework_str == "tf2" and type(self).__name__ != "AlphaStar": + self._value_error( + "`num_gpus` > 1 not supported yet for " + f"framework={self.framework_str}!" + ) + elif self.simple_optimizer is True: + self._value_error( + "Cannot use `simple_optimizer` if `num_gpus` > 1! " + "Consider not setting `simple_optimizer` in your config." + ) + self.simple_optimizer = False + # Auto-setting: Use simple-optimizer for tf-eager or multiagent, + # otherwise: MultiGPUTrainOneStep (if supported by the algo's execution + # plan). + elif self.simple_optimizer == DEPRECATED_VALUE: + # tf-eager: Must use simple optimizer. + if self.framework_str not in ["tf", "torch"]: + self.simple_optimizer = True + # Multi-agent case: Try using MultiGPU optimizer (only + # if all policies used are DynamicTFPolicies or TorchPolicies). + elif self.is_multi_agent: + from ray.rllib.policy.dynamic_tf_policy import DynamicTFPolicy + from ray.rllib.policy.torch_policy import TorchPolicy + + default_policy_cls = None + if self.algo_class: + default_policy_cls = self.algo_class.get_default_policy_class(self) + + policies = self.policies + policy_specs = ( + [ + PolicySpec(*spec) if isinstance(spec, (tuple, list)) else spec + for spec in policies.values() + ] + if isinstance(policies, dict) + else [PolicySpec() for _ in policies] + ) + + if any( + (spec.policy_class or default_policy_cls) is None + or not issubclass( + spec.policy_class or default_policy_cls, + (DynamicTFPolicy, TorchPolicy), + ) + for spec in policy_specs + ): + self.simple_optimizer = True + else: + self.simple_optimizer = False + else: + self.simple_optimizer = False + + # User manually set simple-optimizer to False -> Error if tf-eager. + elif self.simple_optimizer is False: + if self.framework_str == "tf2": + self._value_error( + "`simple_optimizer=False` not supported for " + f"config.framework({self.framework_str})!" + ) + + def _validate_offline_settings(self): + # If a user does not have an environment and cannot run evaluation, + # or does not want to run evaluation, she needs to provide at least + # action and observation spaces. Note, we require here the spaces, + # i.e. a user cannot provide an environment instead because we do + # not want to create the environment to receive spaces. + if ( + self.is_offline + and not self.is_online + and ( + not (self.evaluation_num_env_runners > 0 or self.evaluation_interval) + and (self.action_space is None or self.observation_space is None) + ) + ): + self._value_error( + "If no evaluation should be run, `action_space` and " + "`observation_space` must be provided." + ) + + if self.ignore_final_observation and self.algo_class.__name__ != "BC": + logger.warning( + "`ignore_final_observation=True` (zeros-out truncation observations), " + "but the algorithm isn't `BC`. It is recommended to use this " + "setting only with `BC`, b/c other RL algorithms rely on truncation-" + "observations due to value function estimates." + ) + + from ray.rllib.offline.offline_data import OfflineData + from ray.rllib.offline.offline_prelearner import OfflinePreLearner + + if self.offline_data_class and not issubclass( + self.offline_data_class, OfflineData + ): + self._value_error( + "Unknown `offline_data_class`. OfflineData class needs to inherit " + "from `OfflineData` class." + ) + if self.prelearner_class and not issubclass( + self.prelearner_class, OfflinePreLearner + ): + self._value_error( + "Unknown `prelearner_class`. PreLearner class needs to inherit " + "from `OfflinePreLearner` class." + ) + + from ray.rllib.utils.replay_buffers.episode_replay_buffer import ( + EpisodeReplayBuffer, + ) + + if self.prelearner_buffer_class and not issubclass( + self.prelearner_buffer_class, EpisodeReplayBuffer + ): + self._value_error( + "Unknown `prelearner_buffer_class`. The buffer class for the " + "prelearner needs to inherit from `EpisodeReplayBuffer`. " + "Specifically it needs to store and sample lists of " + "`Single-/MultiAgentEpisode`s." + ) + + if self.input_read_batch_size and not ( + self.input_read_episodes or self.input_read_sample_batches + ): + self._value_error( + "Setting `input_read_batch_size` is only allowed in case of a " + "dataset that holds either `EpisodeType` or `BatchType` data (i.e. " + "rows that contains multiple timesteps), but neither " + "`input_read_episodes` nor `input_read_sample_batches` is set to " + "`True`." + ) + + if ( + self.output + and self.output_write_episodes + and self.batch_mode != "complete_episodes" + ): + self._value_error( + "When recording episodes only complete episodes should be " + "recorded (i.e. `batch_mode=='complete_episodes'`). Otherwise " + "recorded episodes cannot be read in for training." + ) + + # Offline evaluation. + from ray.rllib.offline.offline_policy_evaluation_runner import ( + OfflinePolicyEvaluationTypes, + ) + + offline_eval_types = list(OfflinePolicyEvaluationTypes) + if ( + self.offline_evaluation_type + and self.offline_evaluation_type != "eval_loss" + and self.offline_evaluation_type not in OfflinePolicyEvaluationTypes + ): + self._value_error( + f"Unknown offline evaluation type: {self.offline_evaluation_type}." + "Available types of offline evaluation are either `'eval_loss' to evaluate " + f"the training loss on a validation dataset or {offline_eval_types}." + ) + + from ray.rllib.offline.offline_evaluation_runner import OfflineEvaluationRunner + + if self.offline_eval_runner_class and not issubclass( + self.offline_eval_runner_class, OfflineEvaluationRunner + ): + self._value_error( + "Unknown `offline_eval_runner_class`. OfflineEvaluationRunner class needs to inherit " + "from `OfflineEvaluationRunner` class." + ) + + @property + def is_online(self) -> bool: + """Defines if this config is for online RL. + + Note, a config can be for on- and offline training at the same time. + """ + return self._is_online + + @property + def is_offline(self) -> bool: + """Defines, if this config is for offline RL.""" + return ( + # Does the user provide any input path/class? + bool(self.input_) + # Is it a real string path or list of such paths. + and ( + isinstance(self.input_, str) + or (isinstance(self.input_, list) and isinstance(self.input_[0], str)) + ) + # Could be old stack - which is considered very differently. + and self.input_ != "sampler" + and self.enable_rl_module_and_learner + ) + + @staticmethod + def _serialize_dict(config): + # Serialize classes to classpaths: + if "callbacks_class" in config: + config["callbacks"] = config.pop("callbacks_class") + if "class" in config: + config["class"] = serialize_type(config["class"]) + config["callbacks"] = serialize_type(config["callbacks"]) + config["sample_collector"] = serialize_type(config["sample_collector"]) + if isinstance(config["env"], type): + config["env"] = serialize_type(config["env"]) + if "replay_buffer_config" in config and ( + isinstance(config["replay_buffer_config"].get("type"), type) + ): + config["replay_buffer_config"]["type"] = serialize_type( + config["replay_buffer_config"]["type"] + ) + if isinstance(config["exploration_config"].get("type"), type): + config["exploration_config"]["type"] = serialize_type( + config["exploration_config"]["type"] + ) + if isinstance(config["model"].get("custom_model"), type): + config["model"]["custom_model"] = serialize_type( + config["model"]["custom_model"] + ) + + # List'ify `policies`, iff a set or tuple (these types are not JSON'able). + ma_config = config.get("multiagent") + if ma_config is not None: + if isinstance(ma_config.get("policies"), (set, tuple)): + ma_config["policies"] = list(ma_config["policies"]) + # Do NOT serialize functions/lambdas. + if ma_config.get("policy_mapping_fn"): + ma_config["policy_mapping_fn"] = NOT_SERIALIZABLE + if ma_config.get("policies_to_train"): + ma_config["policies_to_train"] = NOT_SERIALIZABLE + # However, if these "multiagent" settings have been provided directly + # on the top-level (as they should), we override the settings under + # "multiagent". Note that the "multiagent" key should no longer be used anyways. + if isinstance(config.get("policies"), (set, tuple)): + config["policies"] = list(config["policies"]) + # Do NOT serialize functions/lambdas. + if config.get("policy_mapping_fn"): + config["policy_mapping_fn"] = NOT_SERIALIZABLE + if config.get("policies_to_train"): + config["policies_to_train"] = NOT_SERIALIZABLE + + return config + + @staticmethod + def _translate_special_keys(key: str, warn_deprecated: bool = True) -> str: + # Handle special key (str) -> `AlgorithmConfig.[some_property]` cases. + if key == "callbacks": + key = "callbacks_class" + elif key == "create_env_on_driver": + key = "create_env_on_local_worker" + elif key == "custom_eval_function": + key = "custom_evaluation_function" + elif key == "framework": + key = "framework_str" + elif key == "input": + key = "input_" + elif key == "lambda": + key = "lambda_" + elif key == "num_cpus_for_driver": + key = "num_cpus_for_main_process" + elif key == "num_workers": + key = "num_env_runners" + + # Deprecated keys. + if warn_deprecated: + if key == "collect_metrics_timeout": + deprecation_warning( + old="collect_metrics_timeout", + new="metrics_episode_collection_timeout_s", + error=True, + ) + elif key == "metrics_smoothing_episodes": + deprecation_warning( + old="config.metrics_smoothing_episodes", + new="config.metrics_num_episodes_for_smoothing", + error=True, + ) + elif key == "min_iter_time_s": + deprecation_warning( + old="config.min_iter_time_s", + new="config.min_time_s_per_iteration", + error=True, + ) + elif key == "min_time_s_per_reporting": + deprecation_warning( + old="config.min_time_s_per_reporting", + new="config.min_time_s_per_iteration", + error=True, + ) + elif key == "min_sample_timesteps_per_reporting": + deprecation_warning( + old="config.min_sample_timesteps_per_reporting", + new="config.min_sample_timesteps_per_iteration", + error=True, + ) + elif key == "min_train_timesteps_per_reporting": + deprecation_warning( + old="config.min_train_timesteps_per_reporting", + new="config.min_train_timesteps_per_iteration", + error=True, + ) + elif key == "timesteps_per_iteration": + deprecation_warning( + old="config.timesteps_per_iteration", + new="`config.min_sample_timesteps_per_iteration` OR " + "`config.min_train_timesteps_per_iteration`", + error=True, + ) + elif key == "evaluation_num_episodes": + deprecation_warning( + old="config.evaluation_num_episodes", + new="`config.evaluation_duration` and " + "`config.evaluation_duration_unit=episodes`", + error=True, + ) + + return key + + def _check_if_correct_nn_framework_installed(self, _tf1, _tf, _torch): + """Check if tf/torch experiment is running and tf/torch installed.""" + if self.framework_str in {"tf", "tf2"}: + if not (_tf1 or _tf): + raise ImportError( + ( + "TensorFlow was specified as the framework to use (via `config." + "framework([tf|tf2])`)! However, no installation was " + "found. You can install TensorFlow via `pip install tensorflow`" + ) + ) + elif self.framework_str == "torch": + if not _torch: + raise ImportError( + ( + "PyTorch was specified as the framework to use (via `config." + "framework('torch')`)! However, no installation was found. You " + "can install PyTorch via `pip install torch`." + ) + ) + + def _resolve_tf_settings(self, _tf1, _tfv): + """Check and resolve tf settings.""" + if _tf1 and self.framework_str == "tf2": + if self.framework_str == "tf2" and _tfv < 2: + raise ValueError( + "You configured `framework`=tf2, but your installed " + "pip tf-version is < 2.0! Make sure your TensorFlow " + "version is >= 2.x." + ) + if not _tf1.executing_eagerly(): + _tf1.enable_eager_execution() + # Recommend setting tracing to True for speedups. + logger.info( + f"Executing eagerly (framework='{self.framework_str}')," + f" with eager_tracing={self.eager_tracing}. For " + "production workloads, make sure to set eager_tracing=True" + " in order to match the speed of tf-static-graph " + "(framework='tf'). For debugging purposes, " + "`eager_tracing=False` is the best choice." + ) + # Tf-static-graph (framework=tf): Recommend upgrading to tf2 and + # enabling eager tracing for similar speed. + elif _tf1 and self.framework_str == "tf": + logger.info( + "Your framework setting is 'tf', meaning you are using " + "static-graph mode. Set framework='tf2' to enable eager " + "execution with tf2.x. You may also then want to set " + "eager_tracing=True in order to reach similar execution " + "speed as with static-graph mode." + ) + + @OldAPIStack + def get_multi_agent_setup( + self, + *, + policies: Optional[MultiAgentPolicyConfigDict] = None, + env: Optional[EnvType] = None, + spaces: Optional[Dict[PolicyID, Tuple[gym.Space, gym.Space]]] = None, + default_policy_class: Optional[Type[Policy]] = None, + ) -> Tuple[MultiAgentPolicyConfigDict, Callable[[PolicyID, SampleBatchType], bool]]: + r"""Compiles complete multi-agent config (dict) from the information in `self`. + + Infers the observation- and action spaces, the policy classes, and the policy's + configs. The returned `MultiAgentPolicyConfigDict` is fully unified and strictly + maps PolicyIDs to complete PolicySpec objects (with all their fields not-None). + + Examples: + .. testcode:: + + import gymnasium as gym + from ray.rllib.algorithms.ppo import PPOConfig + config = ( + PPOConfig() + .environment("CartPole-v1") + .framework("torch") + .multi_agent(policies={"pol1", "pol2"}, policies_to_train=["pol1"]) + ) + policy_dict, is_policy_to_train = config.get_multi_agent_setup( + env=gym.make("CartPole-v1")) + is_policy_to_train("pol1") + is_policy_to_train("pol2") + + Args: + policies: An optional multi-agent `policies` dict, mapping policy IDs + to PolicySpec objects. If not provided uses `self.policies` + instead. Note that the `policy_class`, `observation_space`, and + `action_space` properties in these PolicySpecs may be None and must + therefore be inferred here. + env: An optional env instance, from which to infer the different spaces for + the different policies. If not provided, tries to infer from + `spaces`. Otherwise from `self.observation_space` and + `self.action_space`. Raises an error, if no information on spaces can be + infered. + spaces: Optional dict mapping policy IDs to tuples of 1) observation space + and 2) action space that should be used for the respective policy. + These spaces were usually provided by an already instantiated remote + EnvRunner. Note that if the `env` argument is provided, tries to + infer spaces from `env` first. + default_policy_class: The Policy class to use should a PolicySpec have its + policy_class property set to None. + + Returns: + A tuple consisting of 1) a MultiAgentPolicyConfigDict and 2) a + `is_policy_to_train(PolicyID, SampleBatchType) -> bool` callable. + + Raises: + ValueError: In case, no spaces can be infered for the policy/ies. + ValueError: In case, two agents in the env map to the same PolicyID + (according to `self.policy_mapping_fn`), but have different action- or + observation spaces according to the infered space information. + """ + policies = copy.deepcopy(policies or self.policies) + + # Policies given as set/list/tuple (of PolicyIDs) -> Setup each policy + # automatically via empty PolicySpec (makes RLlib infer observation- and + # action spaces as well as the Policy's class). + if isinstance(policies, (set, list, tuple)): + policies = {pid: PolicySpec() for pid in policies} + + # Try extracting spaces from env or from given spaces dict. + env_obs_space = None + env_act_space = None + + # Env is a ray.remote: Get spaces via its (automatically added) + # `_get_spaces()` method. + if isinstance(env, ray.actor.ActorHandle): + env_obs_space, env_act_space = ray.get(env._get_spaces.remote()) + # Normal env (gym.Env or MultiAgentEnv): These should have the + # `observation_space` and `action_space` properties. + elif env is not None: + # `env` is a gymnasium.vector.Env. + if hasattr(env, "single_observation_space") and isinstance( + env.single_observation_space, gym.Space + ): + env_obs_space = env.single_observation_space + # `env` is a gymnasium.Env. + elif hasattr(env, "observation_space") and isinstance( + env.observation_space, gym.Space + ): + env_obs_space = env.observation_space + + # `env` is a gymnasium.vector.Env. + if hasattr(env, "single_action_space") and isinstance( + env.single_action_space, gym.Space + ): + env_act_space = env.single_action_space + # `env` is a gymnasium.Env. + elif hasattr(env, "action_space") and isinstance( + env.action_space, gym.Space + ): + env_act_space = env.action_space + + # Last resort: Try getting the env's spaces from the spaces + # dict's special __env__ key. + if spaces is not None: + if env_obs_space is None: + env_obs_space = spaces.get(INPUT_ENV_SPACES, [None])[0] + if env_act_space is None: + env_act_space = spaces.get(INPUT_ENV_SPACES, [None, None])[1] + + # Check each defined policy ID and unify its spec. + for pid, policy_spec in policies.copy().items(): + # Convert to PolicySpec if plain list/tuple. + if not isinstance(policy_spec, PolicySpec): + policies[pid] = policy_spec = PolicySpec(*policy_spec) + + # Infer policy classes for policies dict, if not provided (None). + if policy_spec.policy_class is None and default_policy_class is not None: + policies[pid].policy_class = default_policy_class + + # Infer observation space. + if policy_spec.observation_space is None: + env_unwrapped = env.unwrapped if hasattr(env, "unwrapped") else env + # Module's space is provided -> Use it as-is. + if spaces is not None and pid in spaces: + obs_space = spaces[pid][0] + # MultiAgentEnv -> Check, whether agents have different spaces. + elif isinstance(env_unwrapped, MultiAgentEnv): + obs_space = None + mapping_fn = self.policy_mapping_fn + aids = list( + env_unwrapped.possible_agents + if hasattr(env_unwrapped, "possible_agents") + and env_unwrapped.possible_agents + else env_unwrapped.get_agent_ids() + ) + if len(aids) == 0: + one_obs_space = env_unwrapped.observation_space + else: + one_obs_space = env_unwrapped.get_observation_space(aids[0]) + # If all obs spaces are the same, just use the first space. + if all( + env_unwrapped.get_observation_space(aid) == one_obs_space + for aid in aids + ): + obs_space = one_obs_space + # Need to reverse-map spaces (for the different agents) to certain + # policy IDs. We have to compare the ModuleID with all possible + # AgentIDs and find the agent ID that matches. + elif mapping_fn: + for aid in aids: + # Match: Assign spaces for this agentID to the PolicyID. + if mapping_fn(aid, None, worker=None) == pid: + # Make sure, different agents that map to the same + # policy don't have different spaces. + if ( + obs_space is not None + and env_unwrapped.get_observation_space(aid) + != obs_space + ): + raise ValueError( + "Two agents in your environment map to the " + "same policyID (as per your `policy_mapping" + "_fn`), however, these agents also have " + "different observation spaces!" + ) + obs_space = env_unwrapped.get_observation_space(aid) + # Just use env's obs space as-is. + elif env_obs_space is not None: + obs_space = env_obs_space + # Space given directly in config. + elif self.observation_space: + obs_space = self.observation_space + else: + raise ValueError( + "`observation_space` not provided in PolicySpec for " + f"{pid} and env does not have an observation space OR " + "no spaces received from other workers' env(s) OR no " + "`observation_space` specified in config!" + ) + + policies[pid].observation_space = obs_space + + # Infer action space. + if policy_spec.action_space is None: + env_unwrapped = env.unwrapped if hasattr(env, "unwrapped") else env + # Module's space is provided -> Use it as-is. + if spaces is not None and pid in spaces: + act_space = spaces[pid][1] + # MultiAgentEnv -> Check, whether agents have different spaces. + elif isinstance(env_unwrapped, MultiAgentEnv): + act_space = None + mapping_fn = self.policy_mapping_fn + aids = list( + env_unwrapped.possible_agents + if hasattr(env_unwrapped, "possible_agents") + and env_unwrapped.possible_agents + else env_unwrapped.get_agent_ids() + ) + if len(aids) == 0: + one_act_space = env_unwrapped.action_space + else: + one_act_space = env_unwrapped.get_action_space(aids[0]) + # If all obs spaces are the same, just use the first space. + if all( + env_unwrapped.get_action_space(aid) == one_act_space + for aid in aids + ): + act_space = one_act_space + # Need to reverse-map spaces (for the different agents) to certain + # policy IDs. We have to compare the ModuleID with all possible + # AgentIDs and find the agent ID that matches. + elif mapping_fn: + for aid in aids: + # Match: Assign spaces for this AgentID to the PolicyID. + if mapping_fn(aid, None, worker=None) == pid: + # Make sure, different agents that map to the same + # policy don't have different spaces. + if ( + act_space is not None + and env_unwrapped.get_action_space(aid) != act_space + ): + raise ValueError( + "Two agents in your environment map to the " + "same policyID (as per your `policy_mapping" + "_fn`), however, these agents also have " + "different action spaces!" + ) + act_space = env_unwrapped.get_action_space(aid) + # Just use env's action space as-is. + elif env_act_space is not None: + act_space = env_act_space + elif self.action_space: + act_space = self.action_space + else: + raise ValueError( + "`action_space` not provided in PolicySpec for " + f"{pid} and env does not have an action space OR " + "no spaces received from other workers' env(s) OR no " + "`action_space` specified in config!" + ) + policies[pid].action_space = act_space + + # Create entire AlgorithmConfig object from the provided override. + # If None, use {} as override. + if not isinstance(policies[pid].config, AlgorithmConfig): + assert policies[pid].config is None or isinstance( + policies[pid].config, dict + ) + policies[pid].config = self.copy(copy_frozen=False).update_from_dict( + policies[pid].config or {} + ) + + # If collection given, construct a simple default callable returning True + # if the PolicyID is found in the list/set of IDs. + if self.policies_to_train is not None and not callable(self.policies_to_train): + pols = set(self.policies_to_train) + + def is_policy_to_train(pid, batch=None): + return pid in pols + + else: + is_policy_to_train = self.policies_to_train + + return policies, is_policy_to_train + + @Deprecated(new="AlgorithmConfig.build_algo", error=False) + def build(self, *args, **kwargs): + return self.build_algo(*args, **kwargs) + + @Deprecated(new="AlgorithmConfig.get_multi_rl_module_spec()", error=True) + def get_marl_module_spec(self, *args, **kwargs): + pass + + @Deprecated(new="AlgorithmConfig.env_runners(..)", error=True) + def rollouts(self, *args, **kwargs): + pass + + @Deprecated(new="AlgorithmConfig.env_runners(..)", error=True) + def exploration(self, *args, **kwargs): + pass + + @property + @Deprecated( + new="AlgorithmConfig.fault_tolerance(restart_failed_env_runners=..)", + error=True, + ) + def recreate_failed_env_runners(self): + pass + + @recreate_failed_env_runners.setter + def recreate_failed_env_runners(self, value): + deprecation_warning( + old="AlgorithmConfig.recreate_failed_env_runners", + new="AlgorithmConfig.restart_failed_env_runners", + error=True, + ) + + @property + @Deprecated(new="AlgorithmConfig._enable_new_api_stack", error=True) + def _enable_new_api_stack(self): + pass + + @_enable_new_api_stack.setter + def _enable_new_api_stack(self, value): + deprecation_warning( + old="AlgorithmConfig._enable_new_api_stack", + new="AlgorithmConfig.enable_rl_module_and_learner", + error=True, + ) + + @property + @Deprecated(new="AlgorithmConfig.enable_env_runner_and_connector_v2", error=True) + def uses_new_env_runners(self): + pass + + @property + @Deprecated(new="AlgorithmConfig.num_env_runners", error=True) + def num_rollout_workers(self): + pass + + @num_rollout_workers.setter + def num_rollout_workers(self, value): + deprecation_warning( + old="AlgorithmConfig.num_rollout_workers", + new="AlgorithmConfig.num_env_runners", + error=True, + ) + + @property + @Deprecated(new="AlgorithmConfig.evaluation_num_workers", error=True) + def evaluation_num_workers(self): + pass + + @evaluation_num_workers.setter + def evaluation_num_workers(self, value): + deprecation_warning( + old="AlgorithmConfig.evaluation_num_workers", + new="AlgorithmConfig.evaluation_num_env_runners", + error=True, + ) + pass + + @property + @Deprecated(new="AlgorithmConfig.num_envs_per_env_runner", error=True) + def num_envs_per_worker(self): + pass + + @num_envs_per_worker.setter + def num_envs_per_worker(self, value): + deprecation_warning( + old="AlgorithmConfig.num_envs_per_worker", + new="AlgorithmConfig.num_envs_per_env_runner", + error=True, + ) + pass + + @property + @Deprecated(new="AlgorithmConfig.ignore_env_runner_failures", error=True) + def ignore_worker_failures(self): + pass + + @ignore_worker_failures.setter + def ignore_worker_failures(self, value): + deprecation_warning( + old="AlgorithmConfig.ignore_worker_failures", + new="AlgorithmConfig.ignore_env_runner_failures", + error=True, + ) + pass + + @property + @Deprecated(new="AlgorithmConfig.restart_failed_env_runners", error=True) + def recreate_failed_workers(self): + pass + + @recreate_failed_workers.setter + def recreate_failed_workers(self, value): + deprecation_warning( + old="AlgorithmConfig.recreate_failed_workers", + new="AlgorithmConfig.restart_failed_env_runners", + error=True, + ) + pass + + @property + @Deprecated(new="AlgorithmConfig.max_num_env_runner_restarts", error=True) + def max_num_worker_restarts(self): + pass + + @max_num_worker_restarts.setter + def max_num_worker_restarts(self, value): + deprecation_warning( + old="AlgorithmConfig.max_num_worker_restarts", + new="AlgorithmConfig.max_num_env_runner_restarts", + error=True, + ) + pass + + @property + @Deprecated(new="AlgorithmConfig.delay_between_env_runner_restarts_s", error=True) + def delay_between_worker_restarts_s(self): + pass + + @delay_between_worker_restarts_s.setter + def delay_between_worker_restarts_s(self, value): + deprecation_warning( + old="AlgorithmConfig.delay_between_worker_restarts_s", + new="AlgorithmConfig.delay_between_env_runner_restarts_s", + error=True, + ) + pass + + @property + @Deprecated( + new="AlgorithmConfig.num_consecutive_env_runner_failures_tolerance", error=True + ) + def num_consecutive_worker_failures_tolerance(self): + pass + + @num_consecutive_worker_failures_tolerance.setter + def num_consecutive_worker_failures_tolerance(self, value): + deprecation_warning( + old="AlgorithmConfig.num_consecutive_worker_failures_tolerance", + new="AlgorithmConfig.num_consecutive_env_runner_failures_tolerance", + error=True, + ) + pass + + @property + @Deprecated(new="AlgorithmConfig.env_runner_health_probe_timeout_s", error=True) + def worker_health_probe_timeout_s(self): + pass + + @worker_health_probe_timeout_s.setter + def worker_health_probe_timeout_s(self, value): + deprecation_warning( + old="AlgorithmConfig.worker_health_probe_timeout_s", + new="AlgorithmConfig.env_runner_health_probe_timeout_s", + error=True, + ) + pass + + @property + @Deprecated(new="AlgorithmConfig.env_runner_restore_timeout_s", error=True) + def worker_restore_timeout_s(self): + pass + + @worker_restore_timeout_s.setter + def worker_restore_timeout_s(self, value): + deprecation_warning( + old="AlgorithmConfig.worker_restore_timeout_s", + new="AlgorithmConfig.env_runner_restore_timeout_s", + error=True, + ) + pass + + @property + @Deprecated( + new="AlgorithmConfig.validate_env_runners_after_construction", + error=True, + ) + def validate_workers_after_construction(self): + pass + + @validate_workers_after_construction.setter + def validate_workers_after_construction(self, value): + deprecation_warning( + old="AlgorithmConfig.validate_workers_after_construction", + new="AlgorithmConfig.validate_env_runners_after_construction", + error=True, + ) + pass + + # Cleanups from `resources()`. + @property + @Deprecated(new="AlgorithmConfig.num_cpus_per_env_runner", error=True) + def num_cpus_per_worker(self): + pass + + @num_cpus_per_worker.setter + def num_cpus_per_worker(self, value): + deprecation_warning( + old="AlgorithmConfig.num_cpus_per_worker", + new="AlgorithmConfig.num_cpus_per_env_runner", + error=True, + ) + pass + + @property + @Deprecated(new="AlgorithmConfig.num_gpus_per_env_runner", error=True) + def num_gpus_per_worker(self): + pass + + @num_gpus_per_worker.setter + def num_gpus_per_worker(self, value): + deprecation_warning( + old="AlgorithmConfig.num_gpus_per_worker", + new="AlgorithmConfig.num_gpus_per_env_runner", + error=True, + ) + pass + + @property + @Deprecated(new="AlgorithmConfig.custom_resources_per_env_runner", error=True) + def custom_resources_per_worker(self): + pass + + @custom_resources_per_worker.setter + def custom_resources_per_worker(self, value): + deprecation_warning( + old="AlgorithmConfig.custom_resources_per_worker", + new="AlgorithmConfig.custom_resources_per_env_runner", + error=True, + ) + pass + + @property + @Deprecated(new="AlgorithmConfig.num_learners", error=True) + def num_learner_workers(self): + pass + + @num_learner_workers.setter + def num_learner_workers(self, value): + deprecation_warning( + old="AlgorithmConfig.num_learner_workers", + new="AlgorithmConfig.num_learners", + error=True, + ) + pass + + @property + @Deprecated(new="AlgorithmConfig.num_cpus_per_learner", error=True) + def num_cpus_per_learner_worker(self): + pass + + @num_cpus_per_learner_worker.setter + def num_cpus_per_learner_worker(self, value): + deprecation_warning( + old="AlgorithmConfig.num_cpus_per_learner_worker", + new="AlgorithmConfig.num_cpus_per_learner", + error=True, + ) + pass + + @property + @Deprecated(new="AlgorithmConfig.num_gpus_per_learner", error=True) + def num_gpus_per_learner_worker(self): + pass + + @num_gpus_per_learner_worker.setter + def num_gpus_per_learner_worker(self, value): + deprecation_warning( + old="AlgorithmConfig.num_gpus_per_learner_worker", + new="AlgorithmConfig.num_gpus_per_learner", + error=True, + ) + pass + + @property + @Deprecated(new="AlgorithmConfig.num_cpus_for_local_worker", error=True) + def num_cpus_for_local_worker(self): + pass + + @num_cpus_for_local_worker.setter + def num_cpus_for_local_worker(self, value): + deprecation_warning( + old="AlgorithmConfig.num_cpus_for_local_worker", + new="AlgorithmConfig.num_cpus_for_main_process", + error=True, + ) + pass + + +class DifferentiableAlgorithmConfig(AlgorithmConfig): + """An RLlib DifferentiableAlgorithmConfig builds a Meta algorithm from a given + configuration + + .. testcode:: + + from ray.rllib.algorithm.algorithm_config import DifferentiableAlgorithmConfig + # Construct a generic config for an algorithm that needs differentiable Learners. + config = ( + DifferentiableAlgorithmConfig() + .training(lr=3e-4) + .environment(env="CartPole-v1") + .learners( + differentiable_learner_configs=[ + DifferentiableLearnerConfig( + DifferentiableTorchLearner, + lr=1e-4, + ) + ] + ) + ) + # Similar to `AlgorithmConfig` the config using differentiable Learners can be + # used to build a respective `Algorithm`. + algo = config.build() + + + """ + + # A list of `DifferentiableLearnerConfig` instances that define differentiable + # `Learner`'s. Note, each of them needs to implement the `DifferentiableLearner` + # API. + differentiable_learner_configs: List[DifferentiableLearnerConfig] + + def __init__(self, algo_class=None): + """Initializes the DifferentiableLearnerConfig instance. + + Args: + algo_class: An optional Algorithm class that this config class belongs to. + Used (if provided) to build a respective Algorithm instance from this + config. + """ + # Initialize the `AlgorithmConfig` first. + super().__init__(algo_class=algo_class) + + # Initialize the list of differentiable learner configs to an empty list, which + # defines the default, i.e. the `MetaLearner` will have no nested updates. + self.differentiable_learner_configs: List[DifferentiableLearnerConfig] = [] + + def learners( + self, + *, + learner_class: Optional[Type["Learner"]] = NotProvided, + learner_connector: Optional[ + Callable[["RLModule"], Union["ConnectorV2", List["ConnectorV2"]]] + ] = NotProvided, + add_default_connectors_to_learner_pipeline: Optional[bool] = NotProvided, + learner_config_dict: Optional[Dict[str, Any]] = NotProvided, + differentiable_learner_configs: List[DifferentiableLearnerConfig] = NotProvided, + **kwargs, + ) -> "DifferentiableAlgorithmConfig": + """Sets the configurations for differentiable learners. + + Args: + learner_class: The `Learner` class to use for (distributed) updating of the + RLModule. Only used when `enable_rl_module_and_learner=True`. + learner_connector: A callable taking an env observation space and an env + action space as inputs and returning a learner ConnectorV2 (might be + a pipeline) object. + add_default_connectors_to_learner_pipeline: If True (default), RLlib's + Learners automatically add the default Learner ConnectorV2 + pieces to the LearnerPipeline. These automatically perform: + a) adding observations from episodes to the train batch, if this has not + already been done by a user-provided connector piece + b) if RLModule is stateful, add a time rank to the train batch, zero-pad + the data, and add the correct state inputs, if this has not already been + done by a user-provided connector piece. + c) add all other information (actions, rewards, terminateds, etc..) to + the train batch, if this has not already been done by a user-provided + connector piece. + Only if you know exactly what you are doing, you + should set this setting to False. + Note that this setting is only relevant if the new API stack is used + (including the new EnvRunner classes). + learner_config_dict: A dict to insert any settings accessible from within + the Learner instance. This should only be used in connection with custom + Learner subclasses and in case the user doesn't want to write an extra + `AlgorithmConfig` subclass just to add a few settings to the base Algo's + own config class. + differentiable_learner_configs: A list of `DifferentiableLearnerConfig` instances + defining the `DifferentiableLearner` classes used for the nested updates in + `Algorithm`'s learner. + """ + super().learners(**kwargs) + + if learner_class is not NotProvided: + self._learner_class = learner_class + if learner_connector is not NotProvided: + self._learner_connector = learner_connector + if add_default_connectors_to_learner_pipeline is not NotProvided: + self.add_default_connectors_to_learner_pipeline = ( + add_default_connectors_to_learner_pipeline + ) + if learner_config_dict is not NotProvided: + self.learner_config_dict.update(learner_config_dict) + if differentiable_learner_configs is not NotProvided: + self.differentiable_learner_configs = differentiable_learner_configs + + return self + + def validate(self): + """Validates all values in this config.""" + + # First, call the `validate` method of super. + super().validate() + + # TODO (simon): Maybe moving this to a private method? + # Ensure that the default learner class is derived from `TorchMetaLearner`. + from ray.rllib.core.learner.torch.torch_meta_learner import TorchMetaLearner + + if not issubclass(self.get_default_learner_class(), TorchMetaLearner): + self._value_error( + "`get_default_learner_class` must return a `MetaLearner` class " + f"or sublass but got {self.get_default_learner_class()}." + ) + # Make sure that the differentiable learner configs are contained in a list. + if not isinstance(self.differentiable_learner_configs, list): + self._value_error( + "`differentiable_learner_configs` must be a list of " + "`DifferentiableLearnerConfig` instances, but is " + f"{type(self.differentiable_learner_configs)}." + ) + # In addition, check, if all configurations are wrapped in a + # `DifferentiableLearnerConfig`. + elif not all( + isinstance(learner_cfg, DifferentiableLearnerConfig) + for learner_cfg in self.differentiable_learner_configs + ): + self._value_error( + "`differentiable_learner_configs` must be a list of " + "`DifferentiableLearnerConfig` instances, but at least " + "one instance is not a `DifferentiableLearnerConfig`." + ) + + def get_default_learner_class(self) -> Union[Type["TorchMetaLearner"], str]: + """Returns the `MetaLearner` class to use for this algorithm. + + Override this method in the sub-class to return the `MetaLearner`. + + Returns: + The `MetaLearner` class to use for this algorithm either as a class + type or as a string. (e.g. "ray.rllib.core.learner.torch.torch_meta_learner.TorchMetaLearner") + """ + return NotImplemented + + def get_differentiable_learner_classes( + self, + ) -> List[Union[Type["DifferentiableLearner"], str]]: + """Returns the `DifferentiableLearner` classes to use for this algorithm. + + Override this method in the sub-class to return the `DifferentiableLearner`. + + Returns: + The `DifferentiableLearner` class to use for this algorithm either as a class + type or as a string. (e.g. + "ray.rllib.core.learner.torch.torch_meta_learner.TorchDifferentiableLearner"). + """ + return NotImplemented + + def get_differentiable_learner_configs(self) -> List[DifferentiableLearnerConfig]: + """Returns the `DifferentiableLearnerConfigs` for all `DifferentiableLearner`s. + + Override this method in the sub-class to return the `DifferentiableLearnerConfig`s. + + Returns: + The `DifferentiableLearnerConfig` instances to use for this algorithm. + """ + return self.differentiable_learner_configs + + +class TorchCompileWhatToCompile(str, Enum): + """Enumerates schemes of what parts of the TorchLearner can be compiled. + + This can be either the entire update step of the learner or only the forward + methods (and therein the forward_train method) of the RLModule. + + .. note:: + - torch.compiled code can become slow on graph breaks or even raise + errors on unsupported operations. Empirically, compiling + `forward_train` should introduce little graph breaks, raise no + errors but result in a speedup comparable to compiling the + complete update. + - Using `complete_update` is experimental and may result in errors. + """ + + # Compile the entire update step of the learner. + # This includes the forward pass of the RLModule, the loss computation, and the + # optimizer step. + COMPLETE_UPDATE = "complete_update" + # Only compile the forward methods (and therein the forward_train method) of the + # RLModule. + FORWARD_TRAIN = "forward_train" diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fe4eb9b9a10fb5482dce8bbb4b89589207cbc84f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/__init__.py @@ -0,0 +1,12 @@ +from ray.rllib.algorithms.appo.appo import APPO, APPOConfig +from ray.rllib.algorithms.appo.appo_tf_policy import APPOTF1Policy, APPOTF2Policy +from ray.rllib.algorithms.appo.appo_torch_policy import APPOTorchPolicy + +__all__ = [ + "APPO", + "APPOConfig", + # @OldAPIStack + "APPOTF1Policy", + "APPOTF2Policy", + "APPOTorchPolicy", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d590906c866bfbf4a4e2e03c6c6077ad0a92a2e8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/__pycache__/appo.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/__pycache__/appo.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19597a0bcaae9444915c83c252829715ee2754fa Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/__pycache__/appo.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/__pycache__/appo_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/__pycache__/appo_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9155a674f02d5bd34d632ab5bd41d76070eca83d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/__pycache__/appo_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/__pycache__/appo_rl_module.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/__pycache__/appo_rl_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a45b9966457c8f3a7a3b4d127bff42ec1ed41f1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/__pycache__/appo_rl_module.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/__pycache__/appo_tf_policy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/__pycache__/appo_tf_policy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2092c08b805baa4f688c19a7037dc31cfff49c2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/__pycache__/appo_tf_policy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/__pycache__/appo_torch_policy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/__pycache__/appo_torch_policy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06360593667211e3f0fb6d21d20ba1db5eb10d90 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/__pycache__/appo_torch_policy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/__pycache__/default_appo_rl_module.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/__pycache__/default_appo_rl_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a4a2df30385f5d06fc64e1566e497bf7d0f892c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/__pycache__/default_appo_rl_module.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/__pycache__/utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b8d6b404742acf33a0527b0d902b6456cf95e6f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/__pycache__/utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/appo.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/appo.py new file mode 100644 index 0000000000000000000000000000000000000000..a59636df752d70d7bead0b4bae179fb3341df44f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/appo.py @@ -0,0 +1,433 @@ +"""Asynchronous Proximal Policy Optimization (APPO) + +The algorithm is described in [1] (under the name of "IMPACT"): + +Detailed documentation: +https://docs.ray.io/en/master/rllib-algorithms.html#appo + +[1] IMPACT: Importance Weighted Asynchronous Architectures with Clipped Target Networks. +Luo et al. 2020 +https://arxiv.org/pdf/1912.00167 +""" + +from typing import Optional, Type +import logging + +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig, NotProvided +from ray.rllib.algorithms.impala.impala import IMPALA, IMPALAConfig +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.policy.policy import Policy +from ray.rllib.utils.annotations import override +from ray.rllib.utils.deprecation import DEPRECATED_VALUE, deprecation_warning +from ray.rllib.utils.metrics import ( + LAST_TARGET_UPDATE_TS, + NUM_AGENT_STEPS_SAMPLED, + NUM_ENV_STEPS_SAMPLED, + NUM_TARGET_UPDATES, +) +from ray.rllib.utils.metrics import LEARNER_STATS_KEY + +logger = logging.getLogger(__name__) + + +LEARNER_RESULTS_KL_KEY = "mean_kl_loss" +LEARNER_RESULTS_CURR_KL_COEFF_KEY = "curr_kl_coeff" +OLD_ACTION_DIST_KEY = "old_action_dist" + + +class APPOConfig(IMPALAConfig): + """Defines a configuration class from which an APPO Algorithm can be built. + + .. testcode:: + + from ray.rllib.algorithms.appo import APPOConfig + config = ( + APPOConfig() + .training(lr=0.01, grad_clip=30.0, train_batch_size_per_learner=50) + ) + config = config.learners(num_learners=1) + config = config.env_runners(num_env_runners=1) + config = config.environment("CartPole-v1") + + # Build an Algorithm object from the config and run 1 training iteration. + algo = config.build() + algo.train() + del algo + + .. testcode:: + + from ray.rllib.algorithms.appo import APPOConfig + from ray import tune + + config = APPOConfig() + # Update the config object. + config = config.training(lr=tune.grid_search([0.001,])) + # Set the config object's env. + config = config.environment(env="CartPole-v1") + # Use to_dict() to get the old-style python config dict when running with tune. + tune.Tuner( + "APPO", + run_config=tune.RunConfig( + stop={"training_iteration": 1}, + verbose=0, + ), + param_space=config.to_dict(), + + ).fit() + + .. testoutput:: + :hide: + + ... + """ + + def __init__(self, algo_class=None): + """Initializes a APPOConfig instance.""" + self.exploration_config = { + # The Exploration class to use. In the simplest case, this is the name + # (str) of any class present in the `rllib.utils.exploration` package. + # You can also provide the python class directly or the full location + # of your class (e.g. "ray.rllib.utils.exploration.epsilon_greedy. + # EpsilonGreedy"). + "type": "StochasticSampling", + # Add constructor kwargs here (if any). + } + + super().__init__(algo_class=algo_class or APPO) + + # fmt: off + # __sphinx_doc_begin__ + # APPO specific settings: + self.vtrace = True + self.use_gae = True + self.lambda_ = 1.0 + self.clip_param = 0.4 + self.use_kl_loss = False + self.kl_coeff = 1.0 + self.kl_target = 0.01 + self.target_worker_clipping = 2.0 + + # Circular replay buffer settings. + # Used in [1] for discrete action tasks: + # `circular_buffer_num_batches=4` and `circular_buffer_iterations_per_batch=2` + # For cont. action tasks: + # `circular_buffer_num_batches=16` and `circular_buffer_iterations_per_batch=20` + self.circular_buffer_num_batches = 4 + self.circular_buffer_iterations_per_batch = 2 + + # Override some of IMPALAConfig's default values with APPO-specific values. + self.num_env_runners = 2 + self.target_network_update_freq = 2 + self.broadcast_interval = 1 + self.grad_clip = 40.0 + # Note: Only when using enable_rl_module_and_learner=True can the clipping mode + # be configured by the user. On the old API stack, RLlib will always clip by + # global_norm, no matter the value of `grad_clip_by`. + self.grad_clip_by = "global_norm" + + self.opt_type = "adam" + self.lr = 0.0005 + self.decay = 0.99 + self.momentum = 0.0 + self.epsilon = 0.1 + self.vf_loss_coeff = 0.5 + self.entropy_coeff = 0.01 + self.tau = 1.0 + # __sphinx_doc_end__ + # fmt: on + + self.lr_schedule = None # @OldAPIStack + self.entropy_coeff_schedule = None # @OldAPIStack + self.num_gpus = 0 # @OldAPIStack + self.num_multi_gpu_tower_stacks = 1 # @OldAPIStack + self.minibatch_buffer_size = 1 # @OldAPIStack + self.replay_proportion = 0.0 # @OldAPIStack + self.replay_buffer_num_slots = 100 # @OldAPIStack + self.learner_queue_size = 16 # @OldAPIStack + self.learner_queue_timeout = 300 # @OldAPIStack + + # Deprecated keys. + self.target_update_frequency = DEPRECATED_VALUE + self.use_critic = DEPRECATED_VALUE + + @override(IMPALAConfig) + def training( + self, + *, + vtrace: Optional[bool] = NotProvided, + use_gae: Optional[bool] = NotProvided, + lambda_: Optional[float] = NotProvided, + clip_param: Optional[float] = NotProvided, + use_kl_loss: Optional[bool] = NotProvided, + kl_coeff: Optional[float] = NotProvided, + kl_target: Optional[float] = NotProvided, + target_network_update_freq: Optional[int] = NotProvided, + tau: Optional[float] = NotProvided, + target_worker_clipping: Optional[float] = NotProvided, + circular_buffer_num_batches: Optional[int] = NotProvided, + circular_buffer_iterations_per_batch: Optional[int] = NotProvided, + # Deprecated keys. + target_update_frequency=DEPRECATED_VALUE, + use_critic=DEPRECATED_VALUE, + **kwargs, + ) -> "APPOConfig": + """Sets the training related configuration. + + Args: + vtrace: Whether to use V-trace weighted advantages. If false, PPO GAE + advantages will be used instead. + use_gae: If true, use the Generalized Advantage Estimator (GAE) + with a value function, see https://arxiv.org/pdf/1506.02438.pdf. + Only applies if vtrace=False. + lambda_: GAE (lambda) parameter. + clip_param: PPO surrogate slipping parameter. + use_kl_loss: Whether to use the KL-term in the loss function. + kl_coeff: Coefficient for weighting the KL-loss term. + kl_target: Target term for the KL-term to reach (via adjusting the + `kl_coeff` automatically). + target_network_update_freq: NOTE: This parameter is only applicable on + the new API stack. The frequency with which to update the target + policy network from the main trained policy network. The metric + used is `NUM_ENV_STEPS_TRAINED_LIFETIME` and the unit is `n` (see [1] + 4.1.1), where: `n = [circular_buffer_num_batches (N)] * + [circular_buffer_iterations_per_batch (K)] * [train batch size]` + For example, if you set `target_network_update_freq=2`, and N=4, K=2, + and `train_batch_size_per_learner=500`, then the target net is updated + every 2*4*2*500=8000 trained env steps (every 16 batch updates on each + learner). + The authors in [1] suggests that this setting is robust to a range of + choices (try values between 0.125 and 4). + target_network_update_freq: The frequency to update the target policy and + tune the kl loss coefficients that are used during training. After + setting this parameter, the algorithm waits for at least + `target_network_update_freq` number of environment samples to be trained + on before updating the target networks and tune the kl loss + coefficients. NOTE: This parameter is only applicable when using the + Learner API (enable_rl_module_and_learner=True). + tau: The factor by which to update the target policy network towards + the current policy network. Can range between 0 and 1. + e.g. updated_param = tau * current_param + (1 - tau) * target_param + target_worker_clipping: The maximum value for the target-worker-clipping + used for computing the IS ratio, described in [1] + IS = min(π(i) / π(target), ρ) * (π / π(i)) + circular_buffer_num_batches: The number of train batches that fit + into the circular buffer. Each such train batch can be sampled for + training max. `circular_buffer_iterations_per_batch` times. + circular_buffer_iterations_per_batch: The number of times any train + batch in the circular buffer can be sampled for training. A batch gets + evicted from the buffer either if it's the oldest batch in the buffer + and a new batch is added OR if the batch reaches this max. number of + being sampled. + + Returns: + This updated AlgorithmConfig object. + """ + if target_update_frequency != DEPRECATED_VALUE: + deprecation_warning( + old="target_update_frequency", + new="target_network_update_freq", + error=True, + ) + if use_critic != DEPRECATED_VALUE: + deprecation_warning( + old="use_critic", + help="`use_critic` no longer supported! APPO always uses a value " + "function (critic).", + error=True, + ) + + # Pass kwargs onto super's `training()` method. + super().training(**kwargs) + + if vtrace is not NotProvided: + self.vtrace = vtrace + if use_gae is not NotProvided: + self.use_gae = use_gae + if lambda_ is not NotProvided: + self.lambda_ = lambda_ + if clip_param is not NotProvided: + self.clip_param = clip_param + if use_kl_loss is not NotProvided: + self.use_kl_loss = use_kl_loss + if kl_coeff is not NotProvided: + self.kl_coeff = kl_coeff + if kl_target is not NotProvided: + self.kl_target = kl_target + if target_network_update_freq is not NotProvided: + self.target_network_update_freq = target_network_update_freq + if tau is not NotProvided: + self.tau = tau + if target_worker_clipping is not NotProvided: + self.target_worker_clipping = target_worker_clipping + if circular_buffer_num_batches is not NotProvided: + self.circular_buffer_num_batches = circular_buffer_num_batches + if circular_buffer_iterations_per_batch is not NotProvided: + self.circular_buffer_iterations_per_batch = ( + circular_buffer_iterations_per_batch + ) + + return self + + @override(IMPALAConfig) + def validate(self) -> None: + super().validate() + + # On new API stack, circular buffer should be used, not `minibatch_buffer_size`. + if self.enable_rl_module_and_learner: + if self.minibatch_buffer_size != 1 or self.replay_proportion != 0.0: + self._value_error( + "`minibatch_buffer_size/replay_proportion` not valid on new API " + "stack with APPO! " + "Use `circular_buffer_num_batches` for the number of train batches " + "in the circular buffer. To change the maximum number of times " + "any batch may be sampled, set " + "`circular_buffer_iterations_per_batch`." + ) + if self.num_multi_gpu_tower_stacks != 1: + self._value_error( + "`num_multi_gpu_tower_stacks` not supported on new API stack with " + "APPO! In order to train on multi-GPU, use " + "`config.learners(num_learners=[number of GPUs], " + "num_gpus_per_learner=1)`. To scale the throughput of batch-to-GPU-" + "pre-loading on each of your `Learners`, set " + "`num_gpu_loader_threads` to a higher number (recommended values: " + "1-8)." + ) + if self.learner_queue_size != 16: + self._value_error( + "`learner_queue_size` not supported on new API stack with " + "APPO! In order set the size of the circular buffer (which acts as " + "a 'learner queue'), use " + "`config.training(circular_buffer_num_batches=..)`. To change the " + "maximum number of times any batch may be sampled, set " + "`config.training(circular_buffer_iterations_per_batch=..)`." + ) + + @override(IMPALAConfig) + def get_default_learner_class(self): + if self.framework_str == "torch": + from ray.rllib.algorithms.appo.torch.appo_torch_learner import ( + APPOTorchLearner, + ) + + return APPOTorchLearner + elif self.framework_str in ["tf2", "tf"]: + raise ValueError( + "TensorFlow is no longer supported on the new API stack! " + "Use `framework='torch'`." + ) + else: + raise ValueError( + f"The framework {self.framework_str} is not supported. " + "Use `framework='torch'`." + ) + + @override(IMPALAConfig) + def get_default_rl_module_spec(self) -> RLModuleSpec: + if self.framework_str == "torch": + from ray.rllib.algorithms.appo.torch.appo_torch_rl_module import ( + APPOTorchRLModule as RLModule, + ) + else: + raise ValueError( + f"The framework {self.framework_str} is not supported. " + "Use either 'torch' or 'tf2'." + ) + + return RLModuleSpec(module_class=RLModule) + + @property + @override(AlgorithmConfig) + def _model_config_auto_includes(self): + return super()._model_config_auto_includes | {"vf_share_layers": False} + + +class APPO(IMPALA): + def __init__(self, config, *args, **kwargs): + """Initializes an APPO instance.""" + super().__init__(config, *args, **kwargs) + + # After init: Initialize target net. + + # TODO(avnishn): Does this need to happen in __init__? I think we can move it + # to setup() + if not self.config.enable_rl_module_and_learner: + self.env_runner.foreach_policy_to_train(lambda p, _: p.update_target()) + + @override(IMPALA) + def training_step(self) -> None: + if self.config.enable_rl_module_and_learner: + return super().training_step() + + train_results = super().training_step() + # Update the target network and the KL coefficient for the APPO-loss. + # The target network update frequency is calculated automatically by the product + # of `num_epochs` setting (usually 1 for APPO) and `minibatch_buffer_size`. + last_update = self._counters[LAST_TARGET_UPDATE_TS] + cur_ts = self._counters[ + ( + NUM_AGENT_STEPS_SAMPLED + if self.config.count_steps_by == "agent_steps" + else NUM_ENV_STEPS_SAMPLED + ) + ] + target_update_freq = self.config.num_epochs * self.config.minibatch_buffer_size + if cur_ts - last_update > target_update_freq: + self._counters[NUM_TARGET_UPDATES] += 1 + self._counters[LAST_TARGET_UPDATE_TS] = cur_ts + + # Update our target network. + self.env_runner.foreach_policy_to_train(lambda p, _: p.update_target()) + + # Also update the KL-coefficient for the APPO loss, if necessary. + if self.config.use_kl_loss: + + def update(pi, pi_id): + assert LEARNER_STATS_KEY not in train_results, ( + "{} should be nested under policy id key".format( + LEARNER_STATS_KEY + ), + train_results, + ) + if pi_id in train_results: + kl = train_results[pi_id][LEARNER_STATS_KEY].get("kl") + assert kl is not None, (train_results, pi_id) + # Make the actual `Policy.update_kl()` call. + pi.update_kl(kl) + else: + logger.warning("No data for {}, not updating kl".format(pi_id)) + + # Update KL on all trainable policies within the local (trainer) + # Worker. + self.env_runner.foreach_policy_to_train(update) + + return train_results + + @classmethod + @override(IMPALA) + def get_default_config(cls) -> AlgorithmConfig: + return APPOConfig() + + @classmethod + @override(IMPALA) + def get_default_policy_class( + cls, config: AlgorithmConfig + ) -> Optional[Type[Policy]]: + if config["framework"] == "torch": + from ray.rllib.algorithms.appo.appo_torch_policy import APPOTorchPolicy + + return APPOTorchPolicy + elif config["framework"] == "tf": + if config.enable_rl_module_and_learner: + raise ValueError( + "RLlib's RLModule and Learner API is not supported for" + " tf1. Use " + "framework='tf2' instead." + ) + from ray.rllib.algorithms.appo.appo_tf_policy import APPOTF1Policy + + return APPOTF1Policy + else: + from ray.rllib.algorithms.appo.appo_tf_policy import APPOTF2Policy + + return APPOTF2Policy diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/appo_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/appo_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..235bc823209f8a47c9fe189c0c9cd5b6b4804170 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/appo_learner.py @@ -0,0 +1,147 @@ +import abc +from typing import Any, Dict, Optional + +from ray.rllib.algorithms.appo.appo import APPOConfig +from ray.rllib.algorithms.appo.utils import CircularBuffer +from ray.rllib.algorithms.impala.impala_learner import IMPALALearner +from ray.rllib.core.learner.learner import Learner +from ray.rllib.core.learner.utils import update_target_network +from ray.rllib.core.rl_module.apis import TargetNetworkAPI, ValueFunctionAPI +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.utils.annotations import override +from ray.rllib.utils.lambda_defaultdict import LambdaDefaultDict +from ray.rllib.utils.metrics import ( + LAST_TARGET_UPDATE_TS, + NUM_ENV_STEPS_TRAINED_LIFETIME, + NUM_MODULE_STEPS_TRAINED, + NUM_TARGET_UPDATES, +) +from ray.rllib.utils.schedules.scheduler import Scheduler +from ray.rllib.utils.typing import ModuleID, ShouldModuleBeUpdatedFn + + +class APPOLearner(IMPALALearner): + """Adds KL coeff updates via `after_gradient_based_update()` to IMPALA logic. + + Framework-specific subclasses must override `_update_module_kl_coeff()`. + """ + + @override(IMPALALearner) + def build(self): + self._learner_thread_in_queue = CircularBuffer( + num_batches=self.config.circular_buffer_num_batches, + iterations_per_batch=self.config.circular_buffer_iterations_per_batch, + ) + + super().build() + + # Make target networks. + self.module.foreach_module( + lambda mid, mod: ( + mod.make_target_networks() + if isinstance(mod, TargetNetworkAPI) + else None + ) + ) + + # The current kl coefficients per module as (framework specific) tensor + # variables. + self.curr_kl_coeffs_per_module: LambdaDefaultDict[ + ModuleID, Scheduler + ] = LambdaDefaultDict( + lambda module_id: self._get_tensor_variable( + self.config.get_config_for_module(module_id).kl_coeff + ) + ) + + @override(Learner) + def add_module( + self, + *, + module_id: ModuleID, + module_spec: RLModuleSpec, + config_overrides: Optional[Dict] = None, + new_should_module_be_updated: Optional[ShouldModuleBeUpdatedFn] = None, + ) -> MultiRLModuleSpec: + marl_spec = super().add_module( + module_id=module_id, + module_spec=module_spec, + config_overrides=config_overrides, + new_should_module_be_updated=new_should_module_be_updated, + ) + # Create target networks for added Module, if applicable. + if isinstance(self.module[module_id].unwrapped(), TargetNetworkAPI): + self.module[module_id].unwrapped().make_target_networks() + return marl_spec + + @override(IMPALALearner) + def remove_module(self, module_id: str) -> MultiRLModuleSpec: + marl_spec = super().remove_module(module_id) + self.curr_kl_coeffs_per_module.pop(module_id) + return marl_spec + + @override(Learner) + def after_gradient_based_update(self, *, timesteps: Dict[str, Any]) -> None: + """Updates the target Q Networks.""" + super().after_gradient_based_update(timesteps=timesteps) + + # TODO (sven): Maybe we should have a `after_gradient_based_update` + # method per module? + curr_timestep = timesteps.get(NUM_ENV_STEPS_TRAINED_LIFETIME, 0) + for module_id, module in self.module._rl_modules.items(): + config = self.config.get_config_for_module(module_id) + + last_update_ts_key = (module_id, LAST_TARGET_UPDATE_TS) + if isinstance(module.unwrapped(), TargetNetworkAPI) and ( + curr_timestep - self.metrics.peek(last_update_ts_key, default=0) + >= ( + config.target_network_update_freq + * config.circular_buffer_num_batches + * config.circular_buffer_iterations_per_batch + * config.train_batch_size_per_learner + ) + ): + for ( + main_net, + target_net, + ) in module.unwrapped().get_target_network_pairs(): + update_target_network( + main_net=main_net, + target_net=target_net, + tau=config.tau, + ) + # Increase lifetime target network update counter by one. + self.metrics.log_value((module_id, NUM_TARGET_UPDATES), 1, reduce="sum") + # Update the (single-value -> window=1) last updated timestep metric. + self.metrics.log_value(last_update_ts_key, curr_timestep, window=1) + + if ( + config.use_kl_loss + and self.metrics.peek((module_id, NUM_MODULE_STEPS_TRAINED), default=0) + > 0 + ): + self._update_module_kl_coeff(module_id=module_id, config=config) + + @classmethod + @override(Learner) + def rl_module_required_apis(cls) -> list[type]: + # In order for a PPOLearner to update an RLModule, it must implement the + # following APIs: + return [TargetNetworkAPI, ValueFunctionAPI] + + @abc.abstractmethod + def _update_module_kl_coeff(self, module_id: ModuleID, config: APPOConfig) -> None: + """Dynamically update the KL loss coefficients of each module. + + The update is completed using the mean KL divergence between the action + distributions current policy and old policy of each module. That action + distribution is computed during the most recent update/call to `compute_loss`. + + Args: + module_id: The module whose KL loss coefficient to update. + config: The AlgorithmConfig specific to the given `module_id`. + """ + + +AppoLearner = APPOLearner diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/appo_rl_module.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/appo_rl_module.py new file mode 100644 index 0000000000000000000000000000000000000000..5a2f59f9f201bb2ca46e6136ec7e3882a30bd0bd --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/appo_rl_module.py @@ -0,0 +1,11 @@ +# Backward compat import. +from ray.rllib.algorithms.appo.default_appo_rl_module import ( # noqa + DefaultAPPORLModule as APPORLModule, +) +from ray.rllib.utils.deprecation import deprecation_warning + +deprecation_warning( + old="ray.rllib.algorithms.appo.appo_rl_module.APPORLModule", + new="ray.rllib.algorithms.appo.default_appo_rl_module.DefaultAPPORLModule", + error=False, +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/appo_tf_policy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/appo_tf_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..4af36f099df9216e42e7c9cae039e6a12bddef6f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/appo_tf_policy.py @@ -0,0 +1,393 @@ +""" +TensorFlow policy class used for APPO. + +Adapted from VTraceTFPolicy to use the PPO surrogate loss. +Keep in sync with changes to VTraceTFPolicy. +""" + +import numpy as np +import logging +import gymnasium as gym +from typing import Dict, List, Optional, Type, Union + +from ray.rllib.algorithms.appo.utils import make_appo_models +from ray.rllib.algorithms.impala import vtrace_tf as vtrace +from ray.rllib.algorithms.impala.impala_tf_policy import ( + _make_time_major, + VTraceClipGradients, + VTraceOptimizer, +) +from ray.rllib.evaluation.postprocessing import ( + compute_bootstrap_value, + compute_gae_for_sample_batch, + Postprocessing, +) +from ray.rllib.models.tf.tf_action_dist import Categorical +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy.dynamic_tf_policy_v2 import DynamicTFPolicyV2 +from ray.rllib.policy.eager_tf_policy_v2 import EagerTFPolicyV2 +from ray.rllib.policy.tf_mixins import ( + EntropyCoeffSchedule, + LearningRateSchedule, + KLCoeffMixin, + ValueNetworkMixin, + GradStatsMixin, + TargetNetworkMixin, +) +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.tf.tf_action_dist import TFActionDistribution +from ray.rllib.utils.annotations import ( + override, +) +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.tf_utils import explained_variance +from ray.rllib.utils.typing import TensorType + +tf1, tf, tfv = try_import_tf() + +logger = logging.getLogger(__name__) + + +# TODO (sven): Deprecate once APPO and IMPALA fully on RLModules/Learner APIs. +def get_appo_tf_policy(name: str, base: type) -> type: + """Construct an APPOTFPolicy inheriting either dynamic or eager base policies. + + Args: + base: Base class for this policy. DynamicTFPolicyV2 or EagerTFPolicyV2. + + Returns: + A TF Policy to be used with Impala. + """ + + class APPOTFPolicy( + VTraceClipGradients, + VTraceOptimizer, + LearningRateSchedule, + KLCoeffMixin, + EntropyCoeffSchedule, + ValueNetworkMixin, + TargetNetworkMixin, + GradStatsMixin, + base, + ): + def __init__( + self, + observation_space, + action_space, + config, + existing_model=None, + existing_inputs=None, + ): + # First thing first, enable eager execution if necessary. + base.enable_eager_execution_if_necessary() + + # Although this is a no-op, we call __init__ here to make it clear + # that base.__init__ will use the make_model() call. + VTraceClipGradients.__init__(self) + VTraceOptimizer.__init__(self) + + # Initialize base class. + base.__init__( + self, + observation_space, + action_space, + config, + existing_inputs=existing_inputs, + existing_model=existing_model, + ) + + # TF LearningRateSchedule depends on self.framework, so initialize + # after base.__init__() is called. + LearningRateSchedule.__init__(self, config["lr"], config["lr_schedule"]) + EntropyCoeffSchedule.__init__( + self, config["entropy_coeff"], config["entropy_coeff_schedule"] + ) + ValueNetworkMixin.__init__(self, config) + KLCoeffMixin.__init__(self, config) + + GradStatsMixin.__init__(self) + + # Note: this is a bit ugly, but loss and optimizer initialization must + # happen after all the MixIns are initialized. + self.maybe_initialize_optimizer_and_loss() + + # Initiate TargetNetwork ops after loss initialization. + TargetNetworkMixin.__init__(self) + + @override(base) + def make_model(self) -> ModelV2: + return make_appo_models(self) + + @override(base) + def loss( + self, + model: Union[ModelV2, "tf.keras.Model"], + dist_class: Type[TFActionDistribution], + train_batch: SampleBatch, + ) -> Union[TensorType, List[TensorType]]: + model_out, _ = model(train_batch) + action_dist = dist_class(model_out, model) + + if isinstance(self.action_space, gym.spaces.Discrete): + is_multidiscrete = False + output_hidden_shape = [self.action_space.n] + elif isinstance(self.action_space, gym.spaces.multi_discrete.MultiDiscrete): + is_multidiscrete = True + output_hidden_shape = self.action_space.nvec.astype(np.int32) + else: + is_multidiscrete = False + output_hidden_shape = 1 + + def make_time_major(*args, **kw): + return _make_time_major( + self, train_batch.get(SampleBatch.SEQ_LENS), *args, **kw + ) + + actions = train_batch[SampleBatch.ACTIONS] + dones = train_batch[SampleBatch.TERMINATEDS] + rewards = train_batch[SampleBatch.REWARDS] + behaviour_logits = train_batch[SampleBatch.ACTION_DIST_INPUTS] + + target_model_out, _ = self.target_model(train_batch) + prev_action_dist = dist_class(behaviour_logits, self.model) + values = self.model.value_function() + values_time_major = make_time_major(values) + bootstrap_values_time_major = make_time_major( + train_batch[SampleBatch.VALUES_BOOTSTRAPPED] + ) + bootstrap_value = bootstrap_values_time_major[-1] + + if self.is_recurrent(): + max_seq_len = tf.reduce_max(train_batch[SampleBatch.SEQ_LENS]) + mask = tf.sequence_mask(train_batch[SampleBatch.SEQ_LENS], max_seq_len) + mask = tf.reshape(mask, [-1]) + mask = make_time_major(mask) + + def reduce_mean_valid(t): + return tf.reduce_mean(tf.boolean_mask(t, mask)) + + else: + reduce_mean_valid = tf.reduce_mean + + if self.config["vtrace"]: + logger.debug("Using V-Trace surrogate loss (vtrace=True)") + + # Prepare actions for loss. + loss_actions = ( + actions if is_multidiscrete else tf.expand_dims(actions, axis=1) + ) + + old_policy_behaviour_logits = tf.stop_gradient(target_model_out) + old_policy_action_dist = dist_class(old_policy_behaviour_logits, model) + + # Prepare KL for Loss + mean_kl = make_time_major(old_policy_action_dist.multi_kl(action_dist)) + + unpacked_behaviour_logits = tf.split( + behaviour_logits, output_hidden_shape, axis=1 + ) + unpacked_old_policy_behaviour_logits = tf.split( + old_policy_behaviour_logits, output_hidden_shape, axis=1 + ) + + # Compute vtrace on the CPU for better perf. + with tf.device("/cpu:0"): + vtrace_returns = vtrace.multi_from_logits( + behaviour_policy_logits=make_time_major( + unpacked_behaviour_logits + ), + target_policy_logits=make_time_major( + unpacked_old_policy_behaviour_logits + ), + actions=tf.unstack(make_time_major(loss_actions), axis=2), + discounts=tf.cast( + ~make_time_major(tf.cast(dones, tf.bool)), + tf.float32, + ) + * self.config["gamma"], + rewards=make_time_major(rewards), + values=values_time_major, + bootstrap_value=bootstrap_value, + dist_class=Categorical if is_multidiscrete else dist_class, + model=model, + clip_rho_threshold=tf.cast( + self.config["vtrace_clip_rho_threshold"], tf.float32 + ), + clip_pg_rho_threshold=tf.cast( + self.config["vtrace_clip_pg_rho_threshold"], tf.float32 + ), + ) + + actions_logp = make_time_major(action_dist.logp(actions)) + prev_actions_logp = make_time_major(prev_action_dist.logp(actions)) + old_policy_actions_logp = make_time_major( + old_policy_action_dist.logp(actions) + ) + + is_ratio = tf.clip_by_value( + tf.math.exp(prev_actions_logp - old_policy_actions_logp), 0.0, 2.0 + ) + logp_ratio = is_ratio * tf.exp(actions_logp - prev_actions_logp) + self._is_ratio = is_ratio + + advantages = vtrace_returns.pg_advantages + surrogate_loss = tf.minimum( + advantages * logp_ratio, + advantages + * tf.clip_by_value( + logp_ratio, + 1 - self.config["clip_param"], + 1 + self.config["clip_param"], + ), + ) + + action_kl = ( + tf.reduce_mean(mean_kl, axis=0) if is_multidiscrete else mean_kl + ) + mean_kl_loss = reduce_mean_valid(action_kl) + mean_policy_loss = -reduce_mean_valid(surrogate_loss) + + # The value function loss. + value_targets = vtrace_returns.vs + delta = values_time_major - value_targets + mean_vf_loss = 0.5 * reduce_mean_valid(tf.math.square(delta)) + + # The entropy loss. + actions_entropy = make_time_major(action_dist.multi_entropy()) + mean_entropy = reduce_mean_valid(actions_entropy) + + else: + logger.debug("Using PPO surrogate loss (vtrace=False)") + + # Prepare KL for Loss + mean_kl = make_time_major(prev_action_dist.multi_kl(action_dist)) + + logp_ratio = tf.math.exp( + make_time_major(action_dist.logp(actions)) + - make_time_major(prev_action_dist.logp(actions)) + ) + + advantages = make_time_major(train_batch[Postprocessing.ADVANTAGES]) + surrogate_loss = tf.minimum( + advantages * logp_ratio, + advantages + * tf.clip_by_value( + logp_ratio, + 1 - self.config["clip_param"], + 1 + self.config["clip_param"], + ), + ) + + action_kl = ( + tf.reduce_mean(mean_kl, axis=0) if is_multidiscrete else mean_kl + ) + mean_kl_loss = reduce_mean_valid(action_kl) + mean_policy_loss = -reduce_mean_valid(surrogate_loss) + + # The value function loss. + value_targets = make_time_major( + train_batch[Postprocessing.VALUE_TARGETS] + ) + delta = values_time_major - value_targets + mean_vf_loss = 0.5 * reduce_mean_valid(tf.math.square(delta)) + + # The entropy loss. + mean_entropy = reduce_mean_valid( + make_time_major(action_dist.multi_entropy()) + ) + + # The summed weighted loss. + total_loss = mean_policy_loss - mean_entropy * self.entropy_coeff + # Optional KL loss. + if self.config["use_kl_loss"]: + total_loss += self.kl_coeff * mean_kl_loss + # Optional vf loss (or in a separate term due to separate + # optimizers/networks). + loss_wo_vf = total_loss + if not self.config["_separate_vf_optimizer"]: + total_loss += mean_vf_loss * self.config["vf_loss_coeff"] + + # Store stats in policy for stats_fn. + self._total_loss = total_loss + self._loss_wo_vf = loss_wo_vf + self._mean_policy_loss = mean_policy_loss + # Backward compatibility: Deprecate policy._mean_kl. + self._mean_kl_loss = self._mean_kl = mean_kl_loss + self._mean_vf_loss = mean_vf_loss + self._mean_entropy = mean_entropy + self._value_targets = value_targets + + # Return one total loss or two losses: vf vs rest (policy + kl). + if self.config["_separate_vf_optimizer"]: + return loss_wo_vf, mean_vf_loss + else: + return total_loss + + @override(base) + def stats_fn(self, train_batch: SampleBatch) -> Dict[str, TensorType]: + values_batched = _make_time_major( + self, + train_batch.get(SampleBatch.SEQ_LENS), + self.model.value_function(), + ) + + stats_dict = { + "cur_lr": tf.cast(self.cur_lr, tf.float64), + "total_loss": self._total_loss, + "policy_loss": self._mean_policy_loss, + "entropy": self._mean_entropy, + "var_gnorm": tf.linalg.global_norm(self.model.trainable_variables()), + "vf_loss": self._mean_vf_loss, + "vf_explained_var": explained_variance( + tf.reshape(self._value_targets, [-1]), + tf.reshape(values_batched, [-1]), + ), + "entropy_coeff": tf.cast(self.entropy_coeff, tf.float64), + } + + if self.config["vtrace"]: + is_stat_mean, is_stat_var = tf.nn.moments(self._is_ratio, [0, 1]) + stats_dict["mean_IS"] = is_stat_mean + stats_dict["var_IS"] = is_stat_var + + if self.config["use_kl_loss"]: + stats_dict["kl"] = self._mean_kl_loss + stats_dict["KL_Coeff"] = self.kl_coeff + + return stats_dict + + @override(base) + def postprocess_trajectory( + self, + sample_batch: SampleBatch, + other_agent_batches: Optional[SampleBatch] = None, + episode=None, + ): + # Call super's postprocess_trajectory first. + # sample_batch = super().postprocess_trajectory( + # sample_batch, other_agent_batches, episode + # ) + + if not self.config["vtrace"]: + sample_batch = compute_gae_for_sample_batch( + self, sample_batch, other_agent_batches, episode + ) + else: + # Add the Columns.VALUES_BOOTSTRAPPED column, which we'll need + # inside the loss for vtrace calculations. + sample_batch = compute_bootstrap_value(sample_batch, self) + + return sample_batch + + @override(base) + def get_batch_divisibility_req(self) -> int: + return self.config["rollout_fragment_length"] + + APPOTFPolicy.__name__ = name + APPOTFPolicy.__qualname__ = name + + return APPOTFPolicy + + +APPOTF1Policy = get_appo_tf_policy("APPOTF1Policy", DynamicTFPolicyV2) +APPOTF2Policy = get_appo_tf_policy("APPOTF2Policy", EagerTFPolicyV2) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/appo_torch_policy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/appo_torch_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..1d28138c8c25d066fd3f701fae8c5493c2cc55d9 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/appo_torch_policy.py @@ -0,0 +1,412 @@ +""" +PyTorch policy class used for APPO. + +Adapted from VTraceTFPolicy to use the PPO surrogate loss. +Keep in sync with changes to VTraceTFPolicy. +""" + +import gymnasium as gym +import numpy as np +import logging +from typing import Any, Dict, List, Optional, Type, Union + +import ray +from ray.rllib.algorithms.appo.utils import make_appo_models +import ray.rllib.algorithms.impala.vtrace_torch as vtrace +from ray.rllib.algorithms.impala.impala_torch_policy import ( + make_time_major, + VTraceOptimizer, +) +from ray.rllib.evaluation.postprocessing import ( + compute_bootstrap_value, + compute_gae_for_sample_batch, + Postprocessing, +) +from ray.rllib.models.action_dist import ActionDistribution +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.torch.torch_action_dist import ( + TorchDistributionWrapper, + TorchCategorical, +) +from ray.rllib.models.torch.torch_modelv2 import TorchModelV2 +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy.torch_mixins import ( + EntropyCoeffSchedule, + LearningRateSchedule, + KLCoeffMixin, + ValueNetworkMixin, + TargetNetworkMixin, +) +from ray.rllib.policy.torch_policy_v2 import TorchPolicyV2 +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.torch_utils import ( + apply_grad_clipping, + explained_variance, + global_norm, + sequence_mask, +) +from ray.rllib.utils.typing import TensorType + +torch, nn = try_import_torch() + +logger = logging.getLogger(__name__) + + +# TODO (sven): Deprecate once APPO and IMPALA fully on RLModules/Learner APIs. +class APPOTorchPolicy( + VTraceOptimizer, + LearningRateSchedule, + EntropyCoeffSchedule, + KLCoeffMixin, + ValueNetworkMixin, + TargetNetworkMixin, + TorchPolicyV2, +): + """PyTorch policy class used with APPO.""" + + def __init__(self, observation_space, action_space, config): + config = dict(ray.rllib.algorithms.appo.appo.APPOConfig().to_dict(), **config) + config["enable_rl_module_and_learner"] = False + config["enable_env_runner_and_connector_v2"] = False + + # Although this is a no-op, we call __init__ here to make it clear + # that base.__init__ will use the make_model() call. + VTraceOptimizer.__init__(self) + + lr_schedule_additional_args = [] + if config.get("_separate_vf_optimizer"): + lr_schedule_additional_args = ( + [config["_lr_vf"][0][1], config["_lr_vf"]] + if isinstance(config["_lr_vf"], (list, tuple)) + else [config["_lr_vf"], None] + ) + LearningRateSchedule.__init__( + self, config["lr"], config["lr_schedule"], *lr_schedule_additional_args + ) + + TorchPolicyV2.__init__( + self, + observation_space, + action_space, + config, + max_seq_len=config["model"]["max_seq_len"], + ) + + EntropyCoeffSchedule.__init__( + self, config["entropy_coeff"], config["entropy_coeff_schedule"] + ) + ValueNetworkMixin.__init__(self, config) + KLCoeffMixin.__init__(self, config) + + self._initialize_loss_from_dummy_batch() + + # Initiate TargetNetwork ops after loss initialization. + TargetNetworkMixin.__init__(self) + + @override(TorchPolicyV2) + def init_view_requirements(self): + self.view_requirements = self._get_default_view_requirements() + + @override(TorchPolicyV2) + def make_model(self) -> ModelV2: + return make_appo_models(self) + + @override(TorchPolicyV2) + def loss( + self, + model: ModelV2, + dist_class: Type[ActionDistribution], + train_batch: SampleBatch, + ) -> Union[TensorType, List[TensorType]]: + """Constructs the loss for APPO. + + With IS modifications and V-trace for Advantage Estimation. + + Args: + model (ModelV2): The Model to calculate the loss for. + dist_class (Type[ActionDistribution]): The action distr. class. + train_batch: The training data. + + Returns: + Union[TensorType, List[TensorType]]: A single loss tensor or a list + of loss tensors. + """ + target_model = self.target_models[model] + + model_out, _ = model(train_batch) + action_dist = dist_class(model_out, model) + + if isinstance(self.action_space, gym.spaces.Discrete): + is_multidiscrete = False + output_hidden_shape = [self.action_space.n] + elif isinstance(self.action_space, gym.spaces.multi_discrete.MultiDiscrete): + is_multidiscrete = True + output_hidden_shape = self.action_space.nvec.astype(np.int32) + else: + is_multidiscrete = False + output_hidden_shape = 1 + + def _make_time_major(*args, **kwargs): + return make_time_major( + self, train_batch.get(SampleBatch.SEQ_LENS), *args, **kwargs + ) + + actions = train_batch[SampleBatch.ACTIONS] + dones = train_batch[SampleBatch.TERMINATEDS] + rewards = train_batch[SampleBatch.REWARDS] + behaviour_logits = train_batch[SampleBatch.ACTION_DIST_INPUTS] + + target_model_out, _ = target_model(train_batch) + + prev_action_dist = dist_class(behaviour_logits, model) + values = model.value_function() + values_time_major = _make_time_major(values) + bootstrap_values_time_major = _make_time_major( + train_batch[SampleBatch.VALUES_BOOTSTRAPPED] + ) + bootstrap_value = bootstrap_values_time_major[-1] + + if self.is_recurrent(): + max_seq_len = torch.max(train_batch[SampleBatch.SEQ_LENS]) + mask = sequence_mask(train_batch[SampleBatch.SEQ_LENS], max_seq_len) + mask = torch.reshape(mask, [-1]) + mask = _make_time_major(mask) + num_valid = torch.sum(mask) + + def reduce_mean_valid(t): + return torch.sum(t[mask]) / num_valid + + else: + reduce_mean_valid = torch.mean + + if self.config["vtrace"]: + logger.debug("Using V-Trace surrogate loss (vtrace=True)") + + old_policy_behaviour_logits = target_model_out.detach() + old_policy_action_dist = dist_class(old_policy_behaviour_logits, model) + + if isinstance(output_hidden_shape, (list, tuple, np.ndarray)): + unpacked_behaviour_logits = torch.split( + behaviour_logits, list(output_hidden_shape), dim=1 + ) + unpacked_old_policy_behaviour_logits = torch.split( + old_policy_behaviour_logits, list(output_hidden_shape), dim=1 + ) + else: + unpacked_behaviour_logits = torch.chunk( + behaviour_logits, output_hidden_shape, dim=1 + ) + unpacked_old_policy_behaviour_logits = torch.chunk( + old_policy_behaviour_logits, output_hidden_shape, dim=1 + ) + + # Prepare actions for loss. + loss_actions = ( + actions if is_multidiscrete else torch.unsqueeze(actions, dim=1) + ) + + # Prepare KL for loss. + action_kl = _make_time_major(old_policy_action_dist.kl(action_dist)) + + # Compute vtrace on the CPU for better perf. + vtrace_returns = vtrace.multi_from_logits( + behaviour_policy_logits=_make_time_major(unpacked_behaviour_logits), + target_policy_logits=_make_time_major( + unpacked_old_policy_behaviour_logits + ), + actions=torch.unbind(_make_time_major(loss_actions), dim=2), + discounts=(1.0 - _make_time_major(dones).float()) + * self.config["gamma"], + rewards=_make_time_major(rewards), + values=values_time_major, + bootstrap_value=bootstrap_value, + dist_class=TorchCategorical if is_multidiscrete else dist_class, + model=model, + clip_rho_threshold=self.config["vtrace_clip_rho_threshold"], + clip_pg_rho_threshold=self.config["vtrace_clip_pg_rho_threshold"], + ) + + actions_logp = _make_time_major(action_dist.logp(actions)) + prev_actions_logp = _make_time_major(prev_action_dist.logp(actions)) + old_policy_actions_logp = _make_time_major( + old_policy_action_dist.logp(actions) + ) + is_ratio = torch.clamp( + torch.exp(prev_actions_logp - old_policy_actions_logp), 0.0, 2.0 + ) + logp_ratio = is_ratio * torch.exp(actions_logp - prev_actions_logp) + self._is_ratio = is_ratio + + advantages = vtrace_returns.pg_advantages.to(logp_ratio.device) + surrogate_loss = torch.min( + advantages * logp_ratio, + advantages + * torch.clamp( + logp_ratio, + 1 - self.config["clip_param"], + 1 + self.config["clip_param"], + ), + ) + + mean_kl_loss = reduce_mean_valid(action_kl) + mean_policy_loss = -reduce_mean_valid(surrogate_loss) + + # The value function loss. + value_targets = vtrace_returns.vs.to(values_time_major.device) + delta = values_time_major - value_targets + mean_vf_loss = 0.5 * reduce_mean_valid(torch.pow(delta, 2.0)) + + # The entropy loss. + mean_entropy = reduce_mean_valid(_make_time_major(action_dist.entropy())) + + else: + logger.debug("Using PPO surrogate loss (vtrace=False)") + + # Prepare KL for Loss + action_kl = _make_time_major(prev_action_dist.kl(action_dist)) + + actions_logp = _make_time_major(action_dist.logp(actions)) + prev_actions_logp = _make_time_major(prev_action_dist.logp(actions)) + logp_ratio = torch.exp(actions_logp - prev_actions_logp) + + advantages = _make_time_major(train_batch[Postprocessing.ADVANTAGES]) + surrogate_loss = torch.min( + advantages * logp_ratio, + advantages + * torch.clamp( + logp_ratio, + 1 - self.config["clip_param"], + 1 + self.config["clip_param"], + ), + ) + + mean_kl_loss = reduce_mean_valid(action_kl) + mean_policy_loss = -reduce_mean_valid(surrogate_loss) + + # The value function loss. + value_targets = _make_time_major(train_batch[Postprocessing.VALUE_TARGETS]) + delta = values_time_major - value_targets + mean_vf_loss = 0.5 * reduce_mean_valid(torch.pow(delta, 2.0)) + + # The entropy loss. + mean_entropy = reduce_mean_valid(_make_time_major(action_dist.entropy())) + + # The summed weighted loss. + total_loss = mean_policy_loss - mean_entropy * self.entropy_coeff + # Optional additional KL Loss + if self.config["use_kl_loss"]: + total_loss += self.kl_coeff * mean_kl_loss + + # Optional vf loss (or in a separate term due to separate + # optimizers/networks). + loss_wo_vf = total_loss + if not self.config["_separate_vf_optimizer"]: + total_loss += mean_vf_loss * self.config["vf_loss_coeff"] + + # Store values for stats function in model (tower), such that for + # multi-GPU, we do not override them during the parallel loss phase. + model.tower_stats["total_loss"] = total_loss + model.tower_stats["mean_policy_loss"] = mean_policy_loss + model.tower_stats["mean_kl_loss"] = mean_kl_loss + model.tower_stats["mean_vf_loss"] = mean_vf_loss + model.tower_stats["mean_entropy"] = mean_entropy + model.tower_stats["value_targets"] = value_targets + model.tower_stats["vf_explained_var"] = explained_variance( + torch.reshape(value_targets, [-1]), + torch.reshape(values_time_major, [-1]), + ) + + # Return one total loss or two losses: vf vs rest (policy + kl). + if self.config["_separate_vf_optimizer"]: + return loss_wo_vf, mean_vf_loss + else: + return total_loss + + @override(TorchPolicyV2) + def stats_fn(self, train_batch: SampleBatch) -> Dict[str, TensorType]: + """Stats function for APPO. Returns a dict with important loss stats. + + Args: + policy: The Policy to generate stats for. + train_batch: The SampleBatch (already) used for training. + + Returns: + Dict[str, TensorType]: The stats dict. + """ + stats_dict = { + "cur_lr": self.cur_lr, + "total_loss": torch.mean(torch.stack(self.get_tower_stats("total_loss"))), + "policy_loss": torch.mean( + torch.stack(self.get_tower_stats("mean_policy_loss")) + ), + "entropy": torch.mean(torch.stack(self.get_tower_stats("mean_entropy"))), + "entropy_coeff": self.entropy_coeff, + "var_gnorm": global_norm(self.model.trainable_variables()), + "vf_loss": torch.mean(torch.stack(self.get_tower_stats("mean_vf_loss"))), + "vf_explained_var": torch.mean( + torch.stack(self.get_tower_stats("vf_explained_var")) + ), + } + + if self.config["vtrace"]: + is_stat_mean = torch.mean(self._is_ratio, [0, 1]) + is_stat_var = torch.var(self._is_ratio, [0, 1]) + stats_dict["mean_IS"] = is_stat_mean + stats_dict["var_IS"] = is_stat_var + + if self.config["use_kl_loss"]: + stats_dict["kl"] = torch.mean( + torch.stack(self.get_tower_stats("mean_kl_loss")) + ) + stats_dict["KL_Coeff"] = self.kl_coeff + + return convert_to_numpy(stats_dict) + + @override(TorchPolicyV2) + def extra_action_out( + self, + input_dict: Dict[str, TensorType], + state_batches: List[TensorType], + model: TorchModelV2, + action_dist: TorchDistributionWrapper, + ) -> Dict[str, TensorType]: + return {SampleBatch.VF_PREDS: model.value_function()} + + @override(TorchPolicyV2) + def postprocess_trajectory( + self, + sample_batch: SampleBatch, + other_agent_batches: Optional[Dict[Any, SampleBatch]] = None, + episode=None, + ): + # Call super's postprocess_trajectory first. + # sample_batch = super().postprocess_trajectory( + # sample_batch, other_agent_batches, episode + # ) + + # Do all post-processing always with no_grad(). + # Not using this here will introduce a memory leak + # in torch (issue #6962). + with torch.no_grad(): + if not self.config["vtrace"]: + sample_batch = compute_gae_for_sample_batch( + self, sample_batch, other_agent_batches, episode + ) + else: + # Add the SampleBatch.VALUES_BOOTSTRAPPED column, which we'll need + # inside the loss for vtrace calculations. + sample_batch = compute_bootstrap_value(sample_batch, self) + + return sample_batch + + @override(TorchPolicyV2) + def extra_grad_process( + self, optimizer: "torch.optim.Optimizer", loss: TensorType + ) -> Dict[str, TensorType]: + return apply_grad_clipping(self, optimizer, loss) + + @override(TorchPolicyV2) + def get_batch_divisibility_req(self) -> int: + return self.config["rollout_fragment_length"] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/default_appo_rl_module.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/default_appo_rl_module.py new file mode 100644 index 0000000000000000000000000000000000000000..9152ac43d9d0552953f9106185124df0acb4ab96 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/default_appo_rl_module.py @@ -0,0 +1,57 @@ +import abc +from typing import Any, Dict, List, Tuple + +from ray.rllib.algorithms.ppo.default_ppo_rl_module import DefaultPPORLModule +from ray.rllib.core.learner.utils import make_target_network +from ray.rllib.core.models.base import ACTOR, ENCODER_OUT +from ray.rllib.core.rl_module.apis import ( + TARGET_NETWORK_ACTION_DIST_INPUTS, + TargetNetworkAPI, +) +from ray.rllib.utils.typing import NetworkType + +from ray.rllib.utils.annotations import ( + override, + OverrideToImplementCustomLogic_CallToSuperRecommended, +) +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +class DefaultAPPORLModule(DefaultPPORLModule, TargetNetworkAPI, abc.ABC): + """Default RLModule used by APPO, if user does not specify a custom RLModule. + + Users who want to train their RLModules with APPO may implement any RLModule + (or TorchRLModule) subclass as long as the custom class also implements the + `ValueFunctionAPI` (see ray.rllib.core.rl_module.apis.value_function_api.py) + and the `TargetNetworkAPI` (see + ray.rllib.core.rl_module.apis.target_network_api.py). + """ + + @override(TargetNetworkAPI) + def make_target_networks(self): + self._old_encoder = make_target_network(self.encoder) + self._old_pi = make_target_network(self.pi) + + @override(TargetNetworkAPI) + def get_target_network_pairs(self) -> List[Tuple[NetworkType, NetworkType]]: + return [ + (self.encoder, self._old_encoder), + (self.pi, self._old_pi), + ] + + @override(TargetNetworkAPI) + def forward_target(self, batch: Dict[str, Any]) -> Dict[str, Any]: + old_pi_inputs_encoded = self._old_encoder(batch)[ENCODER_OUT][ACTOR] + old_action_dist_logits = self._old_pi(old_pi_inputs_encoded) + return {TARGET_NETWORK_ACTION_DIST_INPUTS: old_action_dist_logits} + + @OverrideToImplementCustomLogic_CallToSuperRecommended + @override(DefaultPPORLModule) + def get_non_inference_attributes(self) -> List[str]: + # Get the NON inference-only attributes from the parent class. + ret = super().get_non_inference_attributes() + # Add the two (APPO) target networks to it (NOT needed in + # inference-only mode). + ret += ["_old_encoder", "_old_pi"] + return ret diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/torch/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/torch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/torch/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/torch/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4fb46c6872db470e16f0aa67c8ed3d532d417dad Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/torch/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/torch/__pycache__/appo_torch_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/torch/__pycache__/appo_torch_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51713605bf13c4bf2c3383b9107be761418e0f02 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/torch/__pycache__/appo_torch_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/torch/__pycache__/appo_torch_rl_module.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/torch/__pycache__/appo_torch_rl_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e962db5d0f5182cc74e10b6d20cbfff4ff723dd8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/torch/__pycache__/appo_torch_rl_module.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/torch/__pycache__/default_appo_torch_rl_module.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/torch/__pycache__/default_appo_torch_rl_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ff962ef5d4e3857d4ce2950ae072dbfbe182519 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/torch/__pycache__/default_appo_torch_rl_module.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/torch/appo_torch_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/torch/appo_torch_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..62a4198952ecd3ee08947f57b2f5d18d9bd20232 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/torch/appo_torch_learner.py @@ -0,0 +1,234 @@ +"""Asynchronous Proximal Policy Optimization (APPO) + +The algorithm is described in [1] (under the name of "IMPACT"): + +Detailed documentation: +https://docs.ray.io/en/master/rllib-algorithms.html#appo + +[1] IMPACT: Importance Weighted Asynchronous Architectures with Clipped Target Networks. +Luo et al. 2020 +https://arxiv.org/pdf/1912.00167 +""" +from typing import Dict + +from ray.rllib.algorithms.appo.appo import ( + APPOConfig, + LEARNER_RESULTS_CURR_KL_COEFF_KEY, + LEARNER_RESULTS_KL_KEY, +) +from ray.rllib.algorithms.appo.appo_learner import APPOLearner +from ray.rllib.algorithms.impala.torch.impala_torch_learner import IMPALATorchLearner +from ray.rllib.algorithms.impala.torch.vtrace_torch_v2 import ( + make_time_major, + vtrace_torch, +) +from ray.rllib.core.columns import Columns +from ray.rllib.core.learner.learner import POLICY_LOSS_KEY, VF_LOSS_KEY, ENTROPY_KEY +from ray.rllib.core.rl_module.apis import ( + TARGET_NETWORK_ACTION_DIST_INPUTS, + TargetNetworkAPI, + ValueFunctionAPI, +) +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.typing import ModuleID, TensorType + +torch, nn = try_import_torch() + + +class APPOTorchLearner(APPOLearner, IMPALATorchLearner): + """Implements APPO loss / update logic on top of IMPALATorchLearner.""" + + @override(IMPALATorchLearner) + def compute_loss_for_module( + self, + *, + module_id: ModuleID, + config: APPOConfig, + batch: Dict, + fwd_out: Dict[str, TensorType], + ) -> TensorType: + module = self.module[module_id].unwrapped() + assert isinstance(module, TargetNetworkAPI) + assert isinstance(module, ValueFunctionAPI) + + # TODO (sven): Now that we do the +1ts trick to be less vulnerable about + # bootstrap values at the end of rollouts in the new stack, we might make + # this a more flexible, configurable parameter for users, e.g. + # `v_trace_seq_len` (independent of `rollout_fragment_length`). Separation + # of concerns (sampling vs learning). + rollout_frag_or_episode_len = config.get_rollout_fragment_length() + recurrent_seq_len = batch.get("seq_lens") + + loss_mask = batch[Columns.LOSS_MASK].float() + loss_mask_time_major = make_time_major( + loss_mask, + trajectory_len=rollout_frag_or_episode_len, + recurrent_seq_len=recurrent_seq_len, + ) + size_loss_mask = torch.sum(loss_mask) + + values = module.compute_values( + batch, embeddings=fwd_out.get(Columns.EMBEDDINGS) + ) + + action_dist_cls_train = module.get_train_action_dist_cls() + target_policy_dist = action_dist_cls_train.from_logits( + fwd_out[Columns.ACTION_DIST_INPUTS] + ) + + old_target_policy_dist = action_dist_cls_train.from_logits( + module.forward_target(batch)[TARGET_NETWORK_ACTION_DIST_INPUTS] + ) + old_target_policy_actions_logp = old_target_policy_dist.logp( + batch[Columns.ACTIONS] + ) + behaviour_actions_logp = batch[Columns.ACTION_LOGP] + target_actions_logp = target_policy_dist.logp(batch[Columns.ACTIONS]) + + behaviour_actions_logp_time_major = make_time_major( + behaviour_actions_logp, + trajectory_len=rollout_frag_or_episode_len, + recurrent_seq_len=recurrent_seq_len, + ) + target_actions_logp_time_major = make_time_major( + target_actions_logp, + trajectory_len=rollout_frag_or_episode_len, + recurrent_seq_len=recurrent_seq_len, + ) + old_actions_logp_time_major = make_time_major( + old_target_policy_actions_logp, + trajectory_len=rollout_frag_or_episode_len, + recurrent_seq_len=recurrent_seq_len, + ) + rewards_time_major = make_time_major( + batch[Columns.REWARDS], + trajectory_len=rollout_frag_or_episode_len, + recurrent_seq_len=recurrent_seq_len, + ) + values_time_major = make_time_major( + values, + trajectory_len=rollout_frag_or_episode_len, + recurrent_seq_len=recurrent_seq_len, + ) + assert Columns.VALUES_BOOTSTRAPPED not in batch + # Use as bootstrap values the vf-preds in the next "batch row", except + # for the very last row (which doesn't have a next row), for which the + # bootstrap value does not matter b/c it has a +1ts value at its end + # anyways. So we chose an arbitrary item (for simplicity of not having to + # move new data to the device). + bootstrap_values = torch.cat( + [ + values_time_major[0][1:], # 0th ts values from "next row" + values_time_major[0][0:1], # <- can use any arbitrary value here + ], + dim=0, + ) + + # The discount factor that is used should be gamma except for timesteps where + # the episode is terminated. In that case, the discount factor should be 0. + discounts_time_major = ( + 1.0 + - make_time_major( + batch[Columns.TERMINATEDS], + trajectory_len=rollout_frag_or_episode_len, + recurrent_seq_len=recurrent_seq_len, + ).float() + ) * config.gamma + + # Note that vtrace will compute the main loop on the CPU for better performance. + vtrace_adjusted_target_values, pg_advantages = vtrace_torch( + target_action_log_probs=old_actions_logp_time_major, + behaviour_action_log_probs=behaviour_actions_logp_time_major, + discounts=discounts_time_major, + rewards=rewards_time_major, + values=values_time_major, + bootstrap_values=bootstrap_values, + clip_pg_rho_threshold=config.vtrace_clip_pg_rho_threshold, + clip_rho_threshold=config.vtrace_clip_rho_threshold, + ) + pg_advantages = pg_advantages * loss_mask_time_major + + # The policy gradients loss. + is_ratio = torch.clip( + torch.exp(behaviour_actions_logp_time_major - old_actions_logp_time_major), + 0.0, + 2.0, + ) + logp_ratio = is_ratio * torch.exp( + target_actions_logp_time_major - behaviour_actions_logp_time_major + ) + + surrogate_loss = torch.minimum( + pg_advantages * logp_ratio, + pg_advantages + * torch.clip(logp_ratio, 1 - config.clip_param, 1 + config.clip_param), + ) + + if config.use_kl_loss: + action_kl = old_target_policy_dist.kl(target_policy_dist) * loss_mask + mean_kl_loss = torch.sum(action_kl) / size_loss_mask + else: + mean_kl_loss = 0.0 + mean_pi_loss = -(torch.sum(surrogate_loss) / size_loss_mask) + + # The baseline loss. + delta = values_time_major - vtrace_adjusted_target_values + vf_loss = 0.5 * torch.sum(torch.pow(delta, 2.0) * loss_mask_time_major) + mean_vf_loss = vf_loss / size_loss_mask + + # The entropy loss. + mean_entropy_loss = ( + -torch.sum(target_policy_dist.entropy() * loss_mask) / size_loss_mask + ) + + # The summed weighted loss. + total_loss = ( + mean_pi_loss + + (mean_vf_loss * config.vf_loss_coeff) + + ( + mean_entropy_loss + * self.entropy_coeff_schedulers_per_module[ + module_id + ].get_current_value() + ) + + (mean_kl_loss * self.curr_kl_coeffs_per_module[module_id]) + ) + + # Log important loss stats. + self.metrics.log_dict( + { + POLICY_LOSS_KEY: mean_pi_loss, + VF_LOSS_KEY: mean_vf_loss, + ENTROPY_KEY: -mean_entropy_loss, + LEARNER_RESULTS_KL_KEY: mean_kl_loss, + LEARNER_RESULTS_CURR_KL_COEFF_KEY: ( + self.curr_kl_coeffs_per_module[module_id] + ), + }, + key=module_id, + window=1, # <- single items (should not be mean/ema-reduced over time). + ) + # Return the total loss. + return total_loss + + @override(APPOLearner) + def _update_module_kl_coeff(self, module_id: ModuleID, config: APPOConfig) -> None: + # Update the current KL value based on the recently measured value. + # Increase. + kl = convert_to_numpy(self.metrics.peek((module_id, LEARNER_RESULTS_KL_KEY))) + kl_coeff_var = self.curr_kl_coeffs_per_module[module_id] + + if kl > 2.0 * config.kl_target: + # TODO (Kourosh) why not *2.0? + kl_coeff_var.data *= 1.5 + # Decrease. + elif kl < 0.5 * config.kl_target: + kl_coeff_var.data *= 0.5 + + self.metrics.log_value( + (module_id, LEARNER_RESULTS_CURR_KL_COEFF_KEY), + kl_coeff_var.item(), + window=1, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/torch/appo_torch_rl_module.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/torch/appo_torch_rl_module.py new file mode 100644 index 0000000000000000000000000000000000000000..ae60657b2c95ea55f70bd079bad0d9b9a6d4001f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/torch/appo_torch_rl_module.py @@ -0,0 +1,13 @@ +# Backward compat import. +from ray.rllib.algorithms.appo.torch.default_appo_torch_rl_module import ( # noqa + DefaultAPPOTorchRLModule as APPOTorchRLModule, +) +from ray.rllib.utils.deprecation import deprecation_warning + + +deprecation_warning( + old="ray.rllib.algorithms.appo.torch.appo_torch_rl_module.APPOTorchRLModule", + new="ray.rllib.algorithms.appo.torch.default_appo_torch_rl_module." + "DefaultAPPOTorchRLModule", + error=False, +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/torch/default_appo_torch_rl_module.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/torch/default_appo_torch_rl_module.py new file mode 100644 index 0000000000000000000000000000000000000000..637c3de89d29ed98a3460a86c058ee20fac6b813 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/torch/default_appo_torch_rl_module.py @@ -0,0 +1,10 @@ +from ray.rllib.algorithms.appo.default_appo_rl_module import DefaultAPPORLModule +from ray.rllib.algorithms.ppo.torch.default_ppo_torch_rl_module import ( + DefaultPPOTorchRLModule, +) +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +class DefaultAPPOTorchRLModule(DefaultPPOTorchRLModule, DefaultAPPORLModule): + pass diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8c66f080c165a53809b24038225b55d1d20a31b1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/appo/utils.py @@ -0,0 +1,136 @@ +""" +[1] IMPACT: Importance Weighted Asynchronous Architectures with Clipped Target Networks. +Luo et al. 2020 +https://arxiv.org/pdf/1912.00167 +""" +from collections import deque +import threading +import time + +import numpy as np + +from ray.rllib.models.catalog import ModelCatalog +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.utils.annotations import OldAPIStack + + +POLICY_SCOPE = "func" +TARGET_POLICY_SCOPE = "target_func" + + +class CircularBuffer: + """A circular batch-wise buffer as described in [1] for APPO. + + The buffer holds at most N batches, which are sampled at random (uniformly). + If full and a new batch is added, the oldest batch is discarded. Also, each batch + currently in the buffer can be sampled at most K times (after which it is also + discarded). + """ + + def __init__(self, num_batches: int, iterations_per_batch: int): + # N from the paper (buffer size). + self.num_batches = num_batches + # K ("replay coefficient") from the paper. + self.iterations_per_batch = iterations_per_batch + + self._NxK = self.num_batches * self.iterations_per_batch + self._num_added = 0 + + self._buffer = deque([None for _ in range(self._NxK)], maxlen=self._NxK) + self._indices = set() + self._offset = self._NxK + self._lock = threading.Lock() + + self._rng = np.random.default_rng() + + def add(self, batch): + # Add buffer and k=0 information to the deque. + with self._lock: + dropped_entry = self._buffer[0] + for _ in range(self.iterations_per_batch): + self._buffer.append(batch) + self._indices.add(self._offset) + self._indices.discard(self._offset - self._NxK) + self._offset += 1 + self._num_added += 1 + + # A valid entry (w/ a batch whose k has not been reach K yet) was dropped. + dropped_ts = 0 + if dropped_entry is not None: + dropped_ts = dropped_entry.env_steps() + + return dropped_ts + + def sample(self): + # Only initially, the buffer may be empty -> Just wait for some time. + while len(self) == 0: + time.sleep(0.0001) + + # Sample a random buffer index. + with self._lock: + idx = self._rng.choice(list(self._indices)) + actual_buffer_idx = idx - self._offset + self._NxK + batch = self._buffer[actual_buffer_idx] + assert batch is not None, ( + idx, + actual_buffer_idx, + self._offset, + self._indices, + [b is None for b in self._buffer], + ) + self._buffer[actual_buffer_idx] = None + self._indices.discard(idx) + + # Return the sampled batch. + return batch + + @property + def filled(self): + """Whether the buffer has been filled once with at least `self.num_batches`.""" + with self._lock: + return self._num_added >= self.num_batches + + def __len__(self) -> int: + """Returns the number of actually valid (non-expired) batches in the buffer.""" + with self._lock: + return len(self._indices) + + +@OldAPIStack +def make_appo_models(policy) -> ModelV2: + """Builds model and target model for APPO. + + Returns: + ModelV2: The Model for the Policy to use. + Note: The target model will not be returned, just assigned to + `policy.target_model`. + """ + # Get the num_outputs for the following model construction calls. + _, logit_dim = ModelCatalog.get_action_dist( + policy.action_space, policy.config["model"] + ) + + # Construct the (main) model. + policy.model = ModelCatalog.get_model_v2( + policy.observation_space, + policy.action_space, + logit_dim, + policy.config["model"], + name=POLICY_SCOPE, + framework=policy.framework, + ) + policy.model_variables = policy.model.variables() + + # Construct the target model. + policy.target_model = ModelCatalog.get_model_v2( + policy.observation_space, + policy.action_space, + logit_dim, + policy.config["model"], + name=TARGET_POLICY_SCOPE, + framework=policy.framework, + ) + policy.target_model_variables = policy.target_model.variables() + + # Return only the model (not the target model). + return policy.model diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0bf454356c605cccaff3d1fd52671146152779b5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/__init__.py @@ -0,0 +1,6 @@ +from ray.rllib.algorithms.bc.bc import BCConfig, BC + +__all__ = [ + "BC", + "BCConfig", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a655c72a8489f3d5123fc9d98b30bd100a3364de Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/__pycache__/bc.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/__pycache__/bc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3bd542731c062c0878ca6ecba922f4c7e6bb65b4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/__pycache__/bc.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/__pycache__/bc_catalog.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/__pycache__/bc_catalog.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22c989ce432e14d015fae32620a5886184114731 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/__pycache__/bc_catalog.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/bc.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/bc.py new file mode 100644 index 0000000000000000000000000000000000000000..7cc2544078ac6a76bdeecb66bc1bc75c239bceab --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/bc.py @@ -0,0 +1,120 @@ +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig +from ray.rllib.algorithms.marwil.marwil import MARWIL, MARWILConfig +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import RLModuleSpecType + + +class BCConfig(MARWILConfig): + """Defines a configuration class from which a new BC Algorithm can be built + + .. testcode:: + :skipif: True + + from ray.rllib.algorithms.bc import BCConfig + # Run this from the ray directory root. + config = BCConfig().training(lr=0.00001, gamma=0.99) + config = config.offline_data( + input_="./rllib/tests/data/cartpole/large.json") + + # Build an Algorithm object from the config and run 1 training iteration. + algo = config.build() + algo.train() + + .. testcode:: + :skipif: True + + from ray.rllib.algorithms.bc import BCConfig + from ray import tune + config = BCConfig() + # Print out some default values. + print(config.beta) + # Update the config object. + config.training( + lr=tune.grid_search([0.001, 0.0001]), beta=0.75 + ) + # Set the config object's data path. + # Run this from the ray directory root. + config.offline_data( + input_="./rllib/tests/data/cartpole/large.json" + ) + # Set the config object's env, used for evaluation. + config.environment(env="CartPole-v1") + # Use to_dict() to get the old-style python config dict + # when running with tune. + tune.Tuner( + "BC", + param_space=config.to_dict(), + ).fit() + """ + + def __init__(self, algo_class=None): + super().__init__(algo_class=algo_class or BC) + + # fmt: off + # __sphinx_doc_begin__ + # No need to calculate advantages (or do anything else with the rewards). + self.beta = 0.0 + # Advantages (calculated during postprocessing) + # not important for behavioral cloning. + self.postprocess_inputs = False + + # Materialize only the mapped data. This is optimal as long + # as no connector in the connector pipeline holds a state. + self.materialize_data = False + self.materialize_mapped_data = True + # __sphinx_doc_end__ + # fmt: on + + @override(AlgorithmConfig) + def get_default_rl_module_spec(self) -> RLModuleSpecType: + if self.framework_str == "torch": + from ray.rllib.algorithms.bc.torch.default_bc_torch_rl_module import ( + DefaultBCTorchRLModule, + ) + + return RLModuleSpec(module_class=DefaultBCTorchRLModule) + else: + raise ValueError( + f"The framework {self.framework_str} is not supported. " + "Use `torch` instead." + ) + + @override(AlgorithmConfig) + def build_learner_connector( + self, + input_observation_space, + input_action_space, + device=None, + ): + pipeline = super().build_learner_connector( + input_observation_space=input_observation_space, + input_action_space=input_action_space, + device=device, + ) + + # Remove unneeded connectors from the MARWIL connector pipeline. + pipeline.remove("AddOneTsToEpisodesAndTruncate") + pipeline.remove("GeneralAdvantageEstimation") + + return pipeline + + @override(MARWILConfig) + def validate(self) -> None: + # Call super's validation method. + super().validate() + + if self.beta != 0.0: + self._value_error("For behavioral cloning, `beta` parameter must be 0.0!") + + +class BC(MARWIL): + """Behavioral Cloning (derived from MARWIL). + + Uses MARWIL with beta force-set to 0.0. + """ + + @classmethod + @override(MARWIL) + def get_default_config(cls) -> AlgorithmConfig: + return BCConfig() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/bc_catalog.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/bc_catalog.py new file mode 100644 index 0000000000000000000000000000000000000000..1ac0e935266b2f5e263254b9b2c5a7910c56f74f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/bc_catalog.py @@ -0,0 +1,112 @@ +# __sphinx_doc_begin__ +import gymnasium as gym + +from ray.rllib.algorithms.ppo.ppo_catalog import _check_if_diag_gaussian +from ray.rllib.core.models.catalog import Catalog +from ray.rllib.core.models.configs import FreeLogStdMLPHeadConfig, MLPHeadConfig +from ray.rllib.core.models.base import Model +from ray.rllib.utils.annotations import OverrideToImplementCustomLogic + + +class BCCatalog(Catalog): + """The Catalog class used to build models for BC. + + BCCatalog provides the following models: + - Encoder: The encoder used to encode the observations. + - Pi Head: The head used for the policy logits. + + The default encoder is chosen by RLlib dependent on the observation space. + See `ray.rllib.core.models.encoders::Encoder` for details. To define the + network architecture use the `model_config_dict[fcnet_hiddens]` and + `model_config_dict[fcnet_activation]`. + + To implement custom logic, override `BCCatalog.build_encoder()` or modify the + `EncoderConfig` at `BCCatalog.encoder_config`. + + Any custom head can be built by overriding the `build_pi_head()` method. + Alternatively, the `PiHeadConfig` can be overridden to build a custom + policy head during runtime. To change solely the network architecture, + `model_config_dict["head_fcnet_hiddens"]` and + `model_config_dict["head_fcnet_activation"]` can be used. + """ + + def __init__( + self, + observation_space: gym.Space, + action_space: gym.Space, + model_config_dict: dict, + ): + """Initializes the BCCatalog. + + Args: + observation_space: The observation space if the Encoder. + action_space: The action space for the Pi Head. + model_cnfig_dict: The model config to use.. + """ + super().__init__( + observation_space=observation_space, + action_space=action_space, + model_config_dict=model_config_dict, + ) + + self.pi_head_hiddens = self._model_config_dict["head_fcnet_hiddens"] + self.pi_head_activation = self._model_config_dict["head_fcnet_activation"] + + # At this time we do not have the precise (framework-specific) action + # distribution class, i.e. we do not know the output dimension of the + # policy head. The config for the policy head is therefore build in the + # `self.build_pi_head()` method. + self.pi_head_config = None + + @OverrideToImplementCustomLogic + def build_pi_head(self, framework: str) -> Model: + """Builds the policy head. + + The default behavior is to build the head from the pi_head_config. + This can be overridden to build a custom policy head as a means of configuring + the behavior of a BC specific RLModule implementation. + + Args: + framework: The framework to use. Either "torch" or "tf2". + + Returns: + The policy head. + """ + + # Define the output dimension via the action distribution. + action_distribution_cls = self.get_action_dist_cls(framework=framework) + if self._model_config_dict["free_log_std"]: + _check_if_diag_gaussian( + action_distribution_cls=action_distribution_cls, framework=framework + ) + is_diag_gaussian = True + else: + is_diag_gaussian = _check_if_diag_gaussian( + action_distribution_cls=action_distribution_cls, + framework=framework, + no_error=True, + ) + required_output_dim = action_distribution_cls.required_input_dim( + space=self.action_space, model_config=self._model_config_dict + ) + # With the action distribution class and the number of outputs defined, + # we can build the config for the policy head. + pi_head_config_cls = ( + FreeLogStdMLPHeadConfig + if self._model_config_dict["free_log_std"] + else MLPHeadConfig + ) + self.pi_head_config = pi_head_config_cls( + input_dims=self._latent_dims, + hidden_layer_dims=self.pi_head_hiddens, + hidden_layer_activation=self.pi_head_activation, + output_layer_dim=required_output_dim, + output_layer_activation="linear", + clip_log_std=is_diag_gaussian, + log_std_clip_param=self._model_config_dict.get("log_std_clip_param", 20), + ) + + return self.pi_head_config.build(framework=framework) + + +# __sphinx_doc_end__ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/torch/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/torch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/torch/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/torch/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0a6042ed45716d509188b25b4292b8de919e139 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/torch/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/torch/__pycache__/default_bc_torch_rl_module.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/torch/__pycache__/default_bc_torch_rl_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..656ac8f4210f7357fcd60b8efe0ed54e7dac18aa Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/torch/__pycache__/default_bc_torch_rl_module.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/torch/default_bc_torch_rl_module.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/torch/default_bc_torch_rl_module.py new file mode 100644 index 0000000000000000000000000000000000000000..03087d1c883deed1451ce729451fbcae6da73601 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/bc/torch/default_bc_torch_rl_module.py @@ -0,0 +1,45 @@ +import abc +from typing import Any, Dict + +from ray.rllib.algorithms.bc.bc_catalog import BCCatalog +from ray.rllib.core.columns import Columns +from ray.rllib.core.models.base import ENCODER_OUT +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.core.rl_module.torch.torch_rl_module import TorchRLModule +from ray.rllib.utils.annotations import override +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +class DefaultBCTorchRLModule(TorchRLModule, abc.ABC): + """The default TorchRLModule used, if no custom RLModule is provided. + + Builds an encoder net based on the observation space. + Builds a pi head based on the action space. + + Passes observations from the input batch through the encoder, then the pi head to + compute action logits. + """ + + def __init__(self, *args, **kwargs): + catalog_class = kwargs.pop("catalog_class", None) + if catalog_class is None: + catalog_class = BCCatalog + super().__init__(*args, **kwargs, catalog_class=catalog_class) + + @override(RLModule) + def setup(self): + # Build model components (encoder and pi head) from catalog. + super().setup() + self._encoder = self.catalog.build_encoder(framework=self.framework) + self._pi_head = self.catalog.build_pi_head(framework=self.framework) + + @override(TorchRLModule) + def _forward(self, batch: Dict, **kwargs) -> Dict[str, Any]: + """Generic BC forward pass (for all phases of training/evaluation).""" + # Encoder embeddings. + encoder_outs = self._encoder(batch) + # Action dist inputs. + return { + Columns.ACTION_DIST_INPUTS: self._pi_head(encoder_outs[ENCODER_OUT]), + } diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/callbacks.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/callbacks.py new file mode 100644 index 0000000000000000000000000000000000000000..49e59d0c6a3ea8e371f264c4a76e05711835494c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/callbacks.py @@ -0,0 +1,8 @@ +# @OldAPIStack +from ray.rllib.callbacks.callbacks import RLlibCallback +from ray.rllib.callbacks.utils import _make_multi_callbacks + + +# Backward compatibility +DefaultCallbacks = RLlibCallback +make_multi_callbacks = _make_multi_callbacks diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d42d80881e08a491ea72f39338eaba8da9f1eec3 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/__init__.py @@ -0,0 +1,9 @@ +from ray.rllib.algorithms.cql.cql import CQL, CQLConfig +from ray.rllib.algorithms.cql.cql_torch_policy import CQLTorchPolicy + +__all__ = [ + "CQL", + "CQLConfig", + # @OldAPIStack + "CQLTorchPolicy", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22e985a8f69a5b6bf4b57e6f95a2da00a179d822 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/__pycache__/cql.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/__pycache__/cql.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63999b74fe9b558ae566775b82c379d4decd75a0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/__pycache__/cql.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/__pycache__/cql_tf_policy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/__pycache__/cql_tf_policy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32bfe44842f6018603a736bc6ea0b5e13c74fa64 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/__pycache__/cql_tf_policy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/__pycache__/cql_torch_policy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/__pycache__/cql_torch_policy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..abaea2682fbd2d55a7757f2ed35c7c9788410c86 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/__pycache__/cql_torch_policy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/cql.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/cql.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f3ac2eff4470e1f430e38a4b80b2fdc092d942 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/cql.py @@ -0,0 +1,376 @@ +import logging +from typing import Optional, Type, Union + +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig, NotProvided +from ray.rllib.algorithms.cql.cql_tf_policy import CQLTFPolicy +from ray.rllib.algorithms.cql.cql_torch_policy import CQLTorchPolicy +from ray.rllib.algorithms.sac.sac import ( + SAC, + SACConfig, +) +from ray.rllib.connectors.common.add_observations_from_episodes_to_batch import ( + AddObservationsFromEpisodesToBatch, +) +from ray.rllib.connectors.learner.add_next_observations_from_episodes_to_train_batch import ( # noqa + AddNextObservationsFromEpisodesToTrainBatch, +) +from ray.rllib.core.learner.learner import Learner +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.execution.rollout_ops import ( + synchronous_parallel_sample, +) +from ray.rllib.execution.train_ops import ( + multi_gpu_train_one_step, + train_one_step, +) +from ray.rllib.policy.policy import Policy +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.deprecation import ( + DEPRECATED_VALUE, + deprecation_warning, +) +from ray.rllib.utils.framework import try_import_tf, try_import_tfp +from ray.rllib.utils.metrics import ( + LEARNER_RESULTS, + LEARNER_UPDATE_TIMER, + LAST_TARGET_UPDATE_TS, + NUM_AGENT_STEPS_SAMPLED, + NUM_AGENT_STEPS_TRAINED, + NUM_ENV_STEPS_SAMPLED, + NUM_ENV_STEPS_TRAINED, + NUM_TARGET_UPDATES, + OFFLINE_SAMPLING_TIMER, + TARGET_NET_UPDATE_TIMER, + SYNCH_WORKER_WEIGHTS_TIMER, + SAMPLE_TIMER, + TIMERS, +) +from ray.rllib.utils.typing import ResultDict, RLModuleSpecType + +tf1, tf, tfv = try_import_tf() +tfp = try_import_tfp() +logger = logging.getLogger(__name__) + + +class CQLConfig(SACConfig): + """Defines a configuration class from which a CQL can be built. + + .. testcode:: + :skipif: True + + from ray.rllib.algorithms.cql import CQLConfig + config = CQLConfig().training(gamma=0.9, lr=0.01) + config = config.resources(num_gpus=0) + config = config.env_runners(num_env_runners=4) + print(config.to_dict()) + # Build a Algorithm object from the config and run 1 training iteration. + algo = config.build(env="CartPole-v1") + algo.train() + """ + + def __init__(self, algo_class=None): + super().__init__(algo_class=algo_class or CQL) + + # fmt: off + # __sphinx_doc_begin__ + # CQL-specific config settings: + self.bc_iters = 20000 + self.temperature = 1.0 + self.num_actions = 10 + self.lagrangian = False + self.lagrangian_thresh = 5.0 + self.min_q_weight = 5.0 + self.deterministic_backup = True + self.lr = 3e-4 + # Note, the new stack defines learning rates for each component. + # The base learning rate `lr` has to be set to `None`, if using + # the new stack. + self.actor_lr = 1e-4 + self.critic_lr = 1e-3 + self.alpha_lr = 1e-3 + + self.replay_buffer_config = { + "_enable_replay_buffer_api": True, + "type": "MultiAgentPrioritizedReplayBuffer", + "capacity": int(1e6), + # If True prioritized replay buffer will be used. + "prioritized_replay": False, + "prioritized_replay_alpha": 0.6, + "prioritized_replay_beta": 0.4, + "prioritized_replay_eps": 1e-6, + # Whether to compute priorities already on the remote worker side. + "worker_side_prioritization": False, + } + + # Changes to Algorithm's/SACConfig's default: + + # .reporting() + self.min_sample_timesteps_per_iteration = 0 + self.min_train_timesteps_per_iteration = 100 + # fmt: on + # __sphinx_doc_end__ + + self.timesteps_per_iteration = DEPRECATED_VALUE + + @override(SACConfig) + def training( + self, + *, + bc_iters: Optional[int] = NotProvided, + temperature: Optional[float] = NotProvided, + num_actions: Optional[int] = NotProvided, + lagrangian: Optional[bool] = NotProvided, + lagrangian_thresh: Optional[float] = NotProvided, + min_q_weight: Optional[float] = NotProvided, + deterministic_backup: Optional[bool] = NotProvided, + **kwargs, + ) -> "CQLConfig": + """Sets the training-related configuration. + + Args: + bc_iters: Number of iterations with Behavior Cloning pretraining. + temperature: CQL loss temperature. + num_actions: Number of actions to sample for CQL loss + lagrangian: Whether to use the Lagrangian for Alpha Prime (in CQL loss). + lagrangian_thresh: Lagrangian threshold. + min_q_weight: in Q weight multiplier. + deterministic_backup: If the target in the Bellman update should have an + entropy backup. Defaults to `True`. + + Returns: + This updated AlgorithmConfig object. + """ + # Pass kwargs onto super's `training()` method. + super().training(**kwargs) + + if bc_iters is not NotProvided: + self.bc_iters = bc_iters + if temperature is not NotProvided: + self.temperature = temperature + if num_actions is not NotProvided: + self.num_actions = num_actions + if lagrangian is not NotProvided: + self.lagrangian = lagrangian + if lagrangian_thresh is not NotProvided: + self.lagrangian_thresh = lagrangian_thresh + if min_q_weight is not NotProvided: + self.min_q_weight = min_q_weight + if deterministic_backup is not NotProvided: + self.deterministic_backup = deterministic_backup + + return self + + @override(AlgorithmConfig) + def offline_data(self, **kwargs) -> "CQLConfig": + + super().offline_data(**kwargs) + + # Check, if the passed in class incorporates the `OfflinePreLearner` + # interface. + if "prelearner_class" in kwargs: + from ray.rllib.offline.offline_data import OfflinePreLearner + + if not issubclass(kwargs.get("prelearner_class"), OfflinePreLearner): + raise ValueError( + f"`prelearner_class` {kwargs.get('prelearner_class')} is not a " + "subclass of `OfflinePreLearner`. Any class passed to " + "`prelearner_class` needs to implement the interface given by " + "`OfflinePreLearner`." + ) + + return self + + @override(SACConfig) + def get_default_learner_class(self) -> Union[Type["Learner"], str]: + if self.framework_str == "torch": + from ray.rllib.algorithms.cql.torch.cql_torch_learner import CQLTorchLearner + + return CQLTorchLearner + else: + raise ValueError( + f"The framework {self.framework_str} is not supported. " + "Use `'torch'` instead." + ) + + @override(AlgorithmConfig) + def build_learner_connector( + self, + input_observation_space, + input_action_space, + device=None, + ): + pipeline = super().build_learner_connector( + input_observation_space=input_observation_space, + input_action_space=input_action_space, + device=device, + ) + + # Prepend the "add-NEXT_OBS-from-episodes-to-train-batch" connector piece (right + # after the corresponding "add-OBS-..." default piece). + pipeline.insert_after( + AddObservationsFromEpisodesToBatch, + AddNextObservationsFromEpisodesToTrainBatch(), + ) + + return pipeline + + @override(SACConfig) + def validate(self) -> None: + # First check, whether old `timesteps_per_iteration` is used. + if self.timesteps_per_iteration != DEPRECATED_VALUE: + deprecation_warning( + old="timesteps_per_iteration", + new="min_train_timesteps_per_iteration", + error=True, + ) + + # Call super's validation method. + super().validate() + + # CQL-torch performs the optimizer steps inside the loss function. + # Using the multi-GPU optimizer will therefore not work (see multi-GPU + # check above) and we must use the simple optimizer for now. + if self.simple_optimizer is not True and self.framework_str == "torch": + self.simple_optimizer = True + + if self.framework_str in ["tf", "tf2"] and tfp is None: + logger.warning( + "You need `tensorflow_probability` in order to run CQL! " + "Install it via `pip install tensorflow_probability`. Your " + f"tf.__version__={tf.__version__ if tf else None}." + "Trying to import tfp results in the following error:" + ) + try_import_tfp(error=True) + + # Assert that for a local learner the number of iterations is 1. Note, + # this is needed because we have no iterators, but instead a single + # batch returned directly from the `OfflineData.sample` method. + if ( + self.num_learners == 0 + and not self.dataset_num_iters_per_learner + and self.enable_rl_module_and_learner + ): + self._value_error( + "When using a single local learner the number of iterations " + "per learner, `dataset_num_iters_per_learner` has to be defined. " + "Set this hyperparameter in the `AlgorithmConfig.offline_data`." + ) + + @override(SACConfig) + def get_default_rl_module_spec(self) -> RLModuleSpecType: + if self.framework_str == "torch": + from ray.rllib.algorithms.cql.torch.default_cql_torch_rl_module import ( + DefaultCQLTorchRLModule, + ) + + return RLModuleSpec(module_class=DefaultCQLTorchRLModule) + else: + raise ValueError( + f"The framework {self.framework_str} is not supported. Use `torch`." + ) + + @property + def _model_config_auto_includes(self): + return super()._model_config_auto_includes | { + "num_actions": self.num_actions, + } + + +class CQL(SAC): + """CQL (derived from SAC).""" + + @classmethod + @override(SAC) + def get_default_config(cls) -> AlgorithmConfig: + return CQLConfig() + + @classmethod + @override(SAC) + def get_default_policy_class( + cls, config: AlgorithmConfig + ) -> Optional[Type[Policy]]: + if config["framework"] == "torch": + return CQLTorchPolicy + else: + return CQLTFPolicy + + @override(SAC) + def training_step(self) -> None: + # Old API stack (Policy, RolloutWorker, Connector). + if not self.config.enable_env_runner_and_connector_v2: + return self._training_step_old_api_stack() + + # Sampling from offline data. + with self.metrics.log_time((TIMERS, OFFLINE_SAMPLING_TIMER)): + # If we should use an iterator in the learner(s). Note, in case of + # multiple learners we must always return a list of iterators. + return_iterator = return_iterator = ( + self.config.num_learners > 0 + or self.config.dataset_num_iters_per_learner != 1 + ) + + # Return an iterator in case we are using remote learners. + batch_or_iterator = self.offline_data.sample( + num_samples=self.config.train_batch_size_per_learner, + num_shards=self.config.num_learners, + # Return an iterator, if a `Learner` should update + # multiple times per RLlib iteration. + return_iterator=return_iterator, + ) + + # Updating the policy. + with self.metrics.log_time((TIMERS, LEARNER_UPDATE_TIMER)): + learner_results = self.learner_group.update( + data_iterators=batch_or_iterator, + minibatch_size=self.config.train_batch_size_per_learner, + num_iters=self.config.dataset_num_iters_per_learner, + ) + + # Log training results. + self.metrics.aggregate(learner_results, key=LEARNER_RESULTS) + + @OldAPIStack + def _training_step_old_api_stack(self) -> ResultDict: + # Collect SampleBatches from sample workers. + with self._timers[SAMPLE_TIMER]: + train_batch = synchronous_parallel_sample(worker_set=self.env_runner_group) + train_batch = train_batch.as_multi_agent() + self._counters[NUM_AGENT_STEPS_SAMPLED] += train_batch.agent_steps() + self._counters[NUM_ENV_STEPS_SAMPLED] += train_batch.env_steps() + + # Postprocess batch before we learn on it. + post_fn = self.config.get("before_learn_on_batch") or (lambda b, *a: b) + train_batch = post_fn(train_batch, self.env_runner_group, self.config) + + # Learn on training batch. + # Use simple optimizer (only for multi-agent or tf-eager; all other + # cases should use the multi-GPU optimizer, even if only using 1 GPU) + if self.config.get("simple_optimizer") is True: + train_results = train_one_step(self, train_batch) + else: + train_results = multi_gpu_train_one_step(self, train_batch) + + # Update target network every `target_network_update_freq` training steps. + cur_ts = self._counters[ + NUM_AGENT_STEPS_TRAINED + if self.config.count_steps_by == "agent_steps" + else NUM_ENV_STEPS_TRAINED + ] + last_update = self._counters[LAST_TARGET_UPDATE_TS] + if cur_ts - last_update >= self.config.target_network_update_freq: + with self._timers[TARGET_NET_UPDATE_TIMER]: + to_update = self.env_runner.get_policies_to_train() + self.env_runner.foreach_policy_to_train( + lambda p, pid: pid in to_update and p.update_target() + ) + self._counters[NUM_TARGET_UPDATES] += 1 + self._counters[LAST_TARGET_UPDATE_TS] = cur_ts + + # Update remote workers's weights after learning on local worker + # (only those policies that were actually trained). + if self.env_runner_group.num_remote_workers() > 0: + with self._timers[SYNCH_WORKER_WEIGHTS_TIMER]: + self.env_runner_group.sync_weights(policies=list(train_results.keys())) + + # Return all collected metrics for the iteration. + return train_results diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/cql_tf_policy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/cql_tf_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..0bfc871f328db7e431d0865f6f2029b3c5f01bd9 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/cql_tf_policy.py @@ -0,0 +1,425 @@ +""" +TensorFlow policy class used for CQL. +""" +from functools import partial +import numpy as np +import gymnasium as gym +import logging +import tree +from typing import Dict, List, Type, Union + +import ray +from ray.rllib.algorithms.sac.sac_tf_policy import ( + apply_gradients as sac_apply_gradients, + compute_and_clip_gradients as sac_compute_and_clip_gradients, + get_distribution_inputs_and_class, + _get_dist_class, + build_sac_model, + postprocess_trajectory, + setup_late_mixins, + stats, + validate_spaces, + ActorCriticOptimizerMixin as SACActorCriticOptimizerMixin, + ComputeTDErrorMixin, +) +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.tf.tf_action_dist import TFActionDistribution +from ray.rllib.policy.tf_mixins import TargetNetworkMixin +from ray.rllib.policy.tf_policy_template import build_tf_policy +from ray.rllib.policy.policy import Policy +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.exploration.random import Random +from ray.rllib.utils.framework import get_variable, try_import_tf, try_import_tfp +from ray.rllib.utils.typing import ( + LocalOptimizer, + ModelGradients, + TensorType, + AlgorithmConfigDict, +) + +tf1, tf, tfv = try_import_tf() +tfp = try_import_tfp() + +logger = logging.getLogger(__name__) + +MEAN_MIN = -9.0 +MEAN_MAX = 9.0 + + +def _repeat_tensor(t: TensorType, n: int): + # Insert new axis at position 1 into tensor t + t_rep = tf.expand_dims(t, 1) + # Repeat tensor t_rep along new axis n times + multiples = tf.concat([[1, n], tf.tile([1], tf.expand_dims(tf.rank(t) - 1, 0))], 0) + t_rep = tf.tile(t_rep, multiples) + # Merge new axis into batch axis + t_rep = tf.reshape(t_rep, tf.concat([[-1], tf.shape(t)[1:]], 0)) + return t_rep + + +# Returns policy tiled actions and log probabilities for CQL Loss +def policy_actions_repeat(model, action_dist, obs, num_repeat=1): + batch_size = tf.shape(tree.flatten(obs)[0])[0] + obs_temp = tree.map_structure(lambda t: _repeat_tensor(t, num_repeat), obs) + logits, _ = model.get_action_model_outputs(obs_temp) + policy_dist = action_dist(logits, model) + actions, logp_ = policy_dist.sample_logp() + logp = tf.expand_dims(logp_, -1) + return actions, tf.reshape(logp, [batch_size, num_repeat, 1]) + + +def q_values_repeat(model, obs, actions, twin=False): + action_shape = tf.shape(actions)[0] + obs_shape = tf.shape(tree.flatten(obs)[0])[0] + num_repeat = action_shape // obs_shape + obs_temp = tree.map_structure(lambda t: _repeat_tensor(t, num_repeat), obs) + if not twin: + preds_, _ = model.get_q_values(obs_temp, actions) + else: + preds_, _ = model.get_twin_q_values(obs_temp, actions) + preds = tf.reshape(preds_, [obs_shape, num_repeat, 1]) + return preds + + +def cql_loss( + policy: Policy, + model: ModelV2, + dist_class: Type[TFActionDistribution], + train_batch: SampleBatch, +) -> Union[TensorType, List[TensorType]]: + logger.info(f"Current iteration = {policy.cur_iter}") + policy.cur_iter += 1 + + # For best performance, turn deterministic off + deterministic = policy.config["_deterministic_loss"] + assert not deterministic + twin_q = policy.config["twin_q"] + discount = policy.config["gamma"] + + # CQL Parameters + bc_iters = policy.config["bc_iters"] + cql_temp = policy.config["temperature"] + num_actions = policy.config["num_actions"] + min_q_weight = policy.config["min_q_weight"] + use_lagrange = policy.config["lagrangian"] + target_action_gap = policy.config["lagrangian_thresh"] + + obs = train_batch[SampleBatch.CUR_OBS] + actions = tf.cast(train_batch[SampleBatch.ACTIONS], tf.float32) + rewards = tf.cast(train_batch[SampleBatch.REWARDS], tf.float32) + next_obs = train_batch[SampleBatch.NEXT_OBS] + terminals = train_batch[SampleBatch.TERMINATEDS] + + model_out_t, _ = model(SampleBatch(obs=obs, _is_training=True), [], None) + + model_out_tp1, _ = model(SampleBatch(obs=next_obs, _is_training=True), [], None) + + target_model_out_tp1, _ = policy.target_model( + SampleBatch(obs=next_obs, _is_training=True), [], None + ) + + action_dist_class = _get_dist_class(policy, policy.config, policy.action_space) + action_dist_inputs_t, _ = model.get_action_model_outputs(model_out_t) + action_dist_t = action_dist_class(action_dist_inputs_t, model) + policy_t, log_pis_t = action_dist_t.sample_logp() + log_pis_t = tf.expand_dims(log_pis_t, -1) + + # Unlike original SAC, Alpha and Actor Loss are computed first. + # Alpha Loss + alpha_loss = -tf.reduce_mean( + model.log_alpha * tf.stop_gradient(log_pis_t + model.target_entropy) + ) + + # Policy Loss (Either Behavior Clone Loss or SAC Loss) + alpha = tf.math.exp(model.log_alpha) + if policy.cur_iter >= bc_iters: + min_q, _ = model.get_q_values(model_out_t, policy_t) + if twin_q: + twin_q_, _ = model.get_twin_q_values(model_out_t, policy_t) + min_q = tf.math.minimum(min_q, twin_q_) + actor_loss = tf.reduce_mean(tf.stop_gradient(alpha) * log_pis_t - min_q) + else: + bc_logp = action_dist_t.logp(actions) + actor_loss = tf.reduce_mean(tf.stop_gradient(alpha) * log_pis_t - bc_logp) + # actor_loss = -tf.reduce_mean(bc_logp) + + # Critic Loss (Standard SAC Critic L2 Loss + CQL Entropy Loss) + # SAC Loss: + # Q-values for the batched actions. + action_dist_inputs_tp1, _ = model.get_action_model_outputs(model_out_tp1) + action_dist_tp1 = action_dist_class(action_dist_inputs_tp1, model) + policy_tp1, _ = action_dist_tp1.sample_logp() + + q_t, _ = model.get_q_values(model_out_t, actions) + q_t_selected = tf.squeeze(q_t, axis=-1) + if twin_q: + twin_q_t, _ = model.get_twin_q_values(model_out_t, actions) + twin_q_t_selected = tf.squeeze(twin_q_t, axis=-1) + + # Target q network evaluation. + q_tp1, _ = policy.target_model.get_q_values(target_model_out_tp1, policy_tp1) + if twin_q: + twin_q_tp1, _ = policy.target_model.get_twin_q_values( + target_model_out_tp1, policy_tp1 + ) + # Take min over both twin-NNs. + q_tp1 = tf.math.minimum(q_tp1, twin_q_tp1) + + q_tp1_best = tf.squeeze(input=q_tp1, axis=-1) + q_tp1_best_masked = (1.0 - tf.cast(terminals, tf.float32)) * q_tp1_best + + # compute RHS of bellman equation + q_t_target = tf.stop_gradient( + rewards + (discount ** policy.config["n_step"]) * q_tp1_best_masked + ) + + # Compute the TD-error (potentially clipped), for priority replay buffer + base_td_error = tf.math.abs(q_t_selected - q_t_target) + if twin_q: + twin_td_error = tf.math.abs(twin_q_t_selected - q_t_target) + td_error = 0.5 * (base_td_error + twin_td_error) + else: + td_error = base_td_error + + critic_loss_1 = tf.keras.losses.MSE(q_t_selected, q_t_target) + if twin_q: + critic_loss_2 = tf.keras.losses.MSE(twin_q_t_selected, q_t_target) + + # CQL Loss (We are using Entropy version of CQL (the best version)) + rand_actions, _ = policy._random_action_generator.get_exploration_action( + action_distribution=action_dist_class( + tf.tile(action_dist_tp1.inputs, (num_actions, 1)), model + ), + timestep=0, + explore=True, + ) + curr_actions, curr_logp = policy_actions_repeat( + model, action_dist_class, model_out_t, num_actions + ) + next_actions, next_logp = policy_actions_repeat( + model, action_dist_class, model_out_tp1, num_actions + ) + + q1_rand = q_values_repeat(model, model_out_t, rand_actions) + q1_curr_actions = q_values_repeat(model, model_out_t, curr_actions) + q1_next_actions = q_values_repeat(model, model_out_t, next_actions) + + if twin_q: + q2_rand = q_values_repeat(model, model_out_t, rand_actions, twin=True) + q2_curr_actions = q_values_repeat(model, model_out_t, curr_actions, twin=True) + q2_next_actions = q_values_repeat(model, model_out_t, next_actions, twin=True) + + random_density = np.log(0.5 ** int(curr_actions.shape[-1])) + cat_q1 = tf.concat( + [ + q1_rand - random_density, + q1_next_actions - tf.stop_gradient(next_logp), + q1_curr_actions - tf.stop_gradient(curr_logp), + ], + 1, + ) + if twin_q: + cat_q2 = tf.concat( + [ + q2_rand - random_density, + q2_next_actions - tf.stop_gradient(next_logp), + q2_curr_actions - tf.stop_gradient(curr_logp), + ], + 1, + ) + + min_qf1_loss_ = ( + tf.reduce_mean(tf.reduce_logsumexp(cat_q1 / cql_temp, axis=1)) + * min_q_weight + * cql_temp + ) + min_qf1_loss = min_qf1_loss_ - (tf.reduce_mean(q_t) * min_q_weight) + if twin_q: + min_qf2_loss_ = ( + tf.reduce_mean(tf.reduce_logsumexp(cat_q2 / cql_temp, axis=1)) + * min_q_weight + * cql_temp + ) + min_qf2_loss = min_qf2_loss_ - (tf.reduce_mean(twin_q_t) * min_q_weight) + + if use_lagrange: + alpha_prime = tf.clip_by_value(model.log_alpha_prime.exp(), 0.0, 1000000.0)[0] + min_qf1_loss = alpha_prime * (min_qf1_loss - target_action_gap) + if twin_q: + min_qf2_loss = alpha_prime * (min_qf2_loss - target_action_gap) + alpha_prime_loss = 0.5 * (-min_qf1_loss - min_qf2_loss) + else: + alpha_prime_loss = -min_qf1_loss + + cql_loss = [min_qf1_loss] + if twin_q: + cql_loss.append(min_qf2_loss) + + critic_loss = [critic_loss_1 + min_qf1_loss] + if twin_q: + critic_loss.append(critic_loss_2 + min_qf2_loss) + + # Save for stats function. + policy.q_t = q_t_selected + policy.policy_t = policy_t + policy.log_pis_t = log_pis_t + policy.td_error = td_error + policy.actor_loss = actor_loss + policy.critic_loss = critic_loss + policy.alpha_loss = alpha_loss + policy.log_alpha_value = model.log_alpha + policy.alpha_value = alpha + policy.target_entropy = model.target_entropy + # CQL Stats + policy.cql_loss = cql_loss + if use_lagrange: + policy.log_alpha_prime_value = model.log_alpha_prime[0] + policy.alpha_prime_value = alpha_prime + policy.alpha_prime_loss = alpha_prime_loss + + # Return all loss terms corresponding to our optimizers. + if use_lagrange: + return actor_loss + tf.math.add_n(critic_loss) + alpha_loss + alpha_prime_loss + return actor_loss + tf.math.add_n(critic_loss) + alpha_loss + + +def cql_stats(policy: Policy, train_batch: SampleBatch) -> Dict[str, TensorType]: + sac_dict = stats(policy, train_batch) + sac_dict["cql_loss"] = tf.reduce_mean(tf.stack(policy.cql_loss)) + if policy.config["lagrangian"]: + sac_dict["log_alpha_prime_value"] = policy.log_alpha_prime_value + sac_dict["alpha_prime_value"] = policy.alpha_prime_value + sac_dict["alpha_prime_loss"] = policy.alpha_prime_loss + return sac_dict + + +class ActorCriticOptimizerMixin(SACActorCriticOptimizerMixin): + def __init__(self, config): + super().__init__(config) + if config["lagrangian"]: + # Eager mode. + if config["framework"] == "tf2": + self._alpha_prime_optimizer = tf.keras.optimizers.Adam( + learning_rate=config["optimization"]["critic_learning_rate"] + ) + # Static graph mode. + else: + self._alpha_prime_optimizer = tf1.train.AdamOptimizer( + learning_rate=config["optimization"]["critic_learning_rate"] + ) + + +def setup_early_mixins( + policy: Policy, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + config: AlgorithmConfigDict, +) -> None: + """Call mixin classes' constructors before Policy's initialization. + + Adds the necessary optimizers to the given Policy. + + Args: + policy: The Policy object. + obs_space (gym.spaces.Space): The Policy's observation space. + action_space (gym.spaces.Space): The Policy's action space. + config: The Policy's config. + """ + policy.cur_iter = 0 + ActorCriticOptimizerMixin.__init__(policy, config) + if config["lagrangian"]: + policy.model.log_alpha_prime = get_variable( + 0.0, framework="tf", trainable=True, tf_name="log_alpha_prime" + ) + policy.alpha_prime_optim = tf.keras.optimizers.Adam( + learning_rate=config["optimization"]["critic_learning_rate"], + ) + # Generic random action generator for calculating CQL-loss. + policy._random_action_generator = Random( + action_space, + model=None, + framework="tf2", + policy_config=config, + num_workers=0, + worker_index=0, + ) + + +def compute_gradients_fn( + policy: Policy, optimizer: LocalOptimizer, loss: TensorType +) -> ModelGradients: + grads_and_vars = sac_compute_and_clip_gradients(policy, optimizer, loss) + + if policy.config["lagrangian"]: + # Eager: Use GradientTape (which is a property of the `optimizer` + # object (an OptimizerWrapper): see rllib/policy/eager_tf_policy.py). + if policy.config["framework"] == "tf2": + tape = optimizer.tape + log_alpha_prime = [policy.model.log_alpha_prime] + alpha_prime_grads_and_vars = list( + zip( + tape.gradient(policy.alpha_prime_loss, log_alpha_prime), + log_alpha_prime, + ) + ) + # Tf1.x: Use optimizer.compute_gradients() + else: + alpha_prime_grads_and_vars = ( + policy._alpha_prime_optimizer.compute_gradients( + policy.alpha_prime_loss, var_list=[policy.model.log_alpha_prime] + ) + ) + + # Clip if necessary. + if policy.config["grad_clip"]: + clip_func = partial(tf.clip_by_norm, clip_norm=policy.config["grad_clip"]) + else: + clip_func = tf.identity + + # Save grads and vars for later use in `build_apply_op`. + policy._alpha_prime_grads_and_vars = [ + (clip_func(g), v) for (g, v) in alpha_prime_grads_and_vars if g is not None + ] + + grads_and_vars += policy._alpha_prime_grads_and_vars + return grads_and_vars + + +def apply_gradients_fn(policy, optimizer, grads_and_vars): + sac_results = sac_apply_gradients(policy, optimizer, grads_and_vars) + + if policy.config["lagrangian"]: + # Eager mode -> Just apply and return None. + if policy.config["framework"] == "tf2": + policy._alpha_prime_optimizer.apply_gradients( + policy._alpha_prime_grads_and_vars + ) + return + # Tf static graph -> Return grouped op. + else: + alpha_prime_apply_op = policy._alpha_prime_optimizer.apply_gradients( + policy._alpha_prime_grads_and_vars, + global_step=tf1.train.get_or_create_global_step(), + ) + return tf.group([sac_results, alpha_prime_apply_op]) + return sac_results + + +# Build a child class of `TFPolicy`, given the custom functions defined +# above. +CQLTFPolicy = build_tf_policy( + name="CQLTFPolicy", + loss_fn=cql_loss, + get_default_config=lambda: ray.rllib.algorithms.cql.cql.CQLConfig(), + validate_spaces=validate_spaces, + stats_fn=cql_stats, + postprocess_fn=postprocess_trajectory, + before_init=setup_early_mixins, + after_init=setup_late_mixins, + make_model=build_sac_model, + extra_learn_fetches_fn=lambda policy: {"td_error": policy.td_error}, + mixins=[ActorCriticOptimizerMixin, TargetNetworkMixin, ComputeTDErrorMixin], + action_distribution_fn=get_distribution_inputs_and_class, + compute_gradients_fn=compute_gradients_fn, + apply_gradients_fn=apply_gradients_fn, +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/cql_torch_policy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/cql_torch_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..2f67c8d642bb96cf92cd0fc581a169934bbcc418 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/cql_torch_policy.py @@ -0,0 +1,405 @@ +""" +PyTorch policy class used for CQL. +""" +import numpy as np +import gymnasium as gym +import logging +import tree +from typing import Dict, List, Tuple, Type, Union + +import ray +from ray.rllib.algorithms.sac.sac_tf_policy import ( + postprocess_trajectory, + validate_spaces, +) +from ray.rllib.algorithms.sac.sac_torch_policy import ( + _get_dist_class, + stats, + build_sac_model_and_action_dist, + optimizer_fn, + ComputeTDErrorMixin, + setup_late_mixins, + action_distribution_fn, +) +from ray.rllib.models.torch.torch_action_dist import TorchDistributionWrapper +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.policy.policy_template import build_policy_class +from ray.rllib.policy.policy import Policy +from ray.rllib.policy.torch_mixins import TargetNetworkMixin +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.metrics.learner_info import LEARNER_STATS_KEY +from ray.rllib.utils.typing import LocalOptimizer, TensorType, AlgorithmConfigDict +from ray.rllib.utils.torch_utils import ( + apply_grad_clipping, + convert_to_torch_tensor, + concat_multi_gpu_td_errors, +) + +torch, nn = try_import_torch() +F = nn.functional + +logger = logging.getLogger(__name__) + +MEAN_MIN = -9.0 +MEAN_MAX = 9.0 + + +def _repeat_tensor(t: TensorType, n: int): + # Insert new dimension at posotion 1 into tensor t + t_rep = t.unsqueeze(1) + # Repeat tensor t_rep along new dimension n times + t_rep = torch.repeat_interleave(t_rep, n, dim=1) + # Merge new dimension into batch dimension + t_rep = t_rep.view(-1, *t.shape[1:]) + return t_rep + + +# Returns policy tiled actions and log probabilities for CQL Loss +def policy_actions_repeat(model, action_dist, obs, num_repeat=1): + batch_size = tree.flatten(obs)[0].shape[0] + obs_temp = tree.map_structure(lambda t: _repeat_tensor(t, num_repeat), obs) + logits, _ = model.get_action_model_outputs(obs_temp) + policy_dist = action_dist(logits, model) + actions, logp_ = policy_dist.sample_logp() + logp = logp_.unsqueeze(-1) + return actions, logp.view(batch_size, num_repeat, 1) + + +def q_values_repeat(model, obs, actions, twin=False): + action_shape = actions.shape[0] + obs_shape = tree.flatten(obs)[0].shape[0] + num_repeat = int(action_shape / obs_shape) + obs_temp = tree.map_structure(lambda t: _repeat_tensor(t, num_repeat), obs) + if not twin: + preds_, _ = model.get_q_values(obs_temp, actions) + else: + preds_, _ = model.get_twin_q_values(obs_temp, actions) + preds = preds_.view(obs_shape, num_repeat, 1) + return preds + + +def cql_loss( + policy: Policy, + model: ModelV2, + dist_class: Type[TorchDistributionWrapper], + train_batch: SampleBatch, +) -> Union[TensorType, List[TensorType]]: + logger.info(f"Current iteration = {policy.cur_iter}") + policy.cur_iter += 1 + + # Look up the target model (tower) using the model tower. + target_model = policy.target_models[model] + + # For best performance, turn deterministic off + deterministic = policy.config["_deterministic_loss"] + assert not deterministic + twin_q = policy.config["twin_q"] + discount = policy.config["gamma"] + action_low = model.action_space.low[0] + action_high = model.action_space.high[0] + + # CQL Parameters + bc_iters = policy.config["bc_iters"] + cql_temp = policy.config["temperature"] + num_actions = policy.config["num_actions"] + min_q_weight = policy.config["min_q_weight"] + use_lagrange = policy.config["lagrangian"] + target_action_gap = policy.config["lagrangian_thresh"] + + obs = train_batch[SampleBatch.CUR_OBS] + actions = train_batch[SampleBatch.ACTIONS] + rewards = train_batch[SampleBatch.REWARDS].float() + next_obs = train_batch[SampleBatch.NEXT_OBS] + terminals = train_batch[SampleBatch.TERMINATEDS] + + model_out_t, _ = model(SampleBatch(obs=obs, _is_training=True), [], None) + + model_out_tp1, _ = model(SampleBatch(obs=next_obs, _is_training=True), [], None) + + target_model_out_tp1, _ = target_model( + SampleBatch(obs=next_obs, _is_training=True), [], None + ) + + action_dist_class = _get_dist_class(policy, policy.config, policy.action_space) + action_dist_inputs_t, _ = model.get_action_model_outputs(model_out_t) + action_dist_t = action_dist_class(action_dist_inputs_t, model) + policy_t, log_pis_t = action_dist_t.sample_logp() + log_pis_t = torch.unsqueeze(log_pis_t, -1) + + # Unlike original SAC, Alpha and Actor Loss are computed first. + # Alpha Loss + alpha_loss = -(model.log_alpha * (log_pis_t + model.target_entropy).detach()).mean() + + batch_size = tree.flatten(obs)[0].shape[0] + if batch_size == policy.config["train_batch_size"]: + policy.alpha_optim.zero_grad() + alpha_loss.backward() + policy.alpha_optim.step() + + # Policy Loss (Either Behavior Clone Loss or SAC Loss) + alpha = torch.exp(model.log_alpha) + if policy.cur_iter >= bc_iters: + min_q, _ = model.get_q_values(model_out_t, policy_t) + if twin_q: + twin_q_, _ = model.get_twin_q_values(model_out_t, policy_t) + min_q = torch.min(min_q, twin_q_) + actor_loss = (alpha.detach() * log_pis_t - min_q).mean() + else: + bc_logp = action_dist_t.logp(actions) + actor_loss = (alpha.detach() * log_pis_t - bc_logp).mean() + # actor_loss = -bc_logp.mean() + + if batch_size == policy.config["train_batch_size"]: + policy.actor_optim.zero_grad() + actor_loss.backward(retain_graph=True) + policy.actor_optim.step() + + # Critic Loss (Standard SAC Critic L2 Loss + CQL Entropy Loss) + # SAC Loss: + # Q-values for the batched actions. + action_dist_inputs_tp1, _ = model.get_action_model_outputs(model_out_tp1) + action_dist_tp1 = action_dist_class(action_dist_inputs_tp1, model) + policy_tp1, _ = action_dist_tp1.sample_logp() + + q_t, _ = model.get_q_values(model_out_t, train_batch[SampleBatch.ACTIONS]) + q_t_selected = torch.squeeze(q_t, dim=-1) + if twin_q: + twin_q_t, _ = model.get_twin_q_values( + model_out_t, train_batch[SampleBatch.ACTIONS] + ) + twin_q_t_selected = torch.squeeze(twin_q_t, dim=-1) + + # Target q network evaluation. + q_tp1, _ = target_model.get_q_values(target_model_out_tp1, policy_tp1) + if twin_q: + twin_q_tp1, _ = target_model.get_twin_q_values(target_model_out_tp1, policy_tp1) + # Take min over both twin-NNs. + q_tp1 = torch.min(q_tp1, twin_q_tp1) + + q_tp1_best = torch.squeeze(input=q_tp1, dim=-1) + q_tp1_best_masked = (1.0 - terminals.float()) * q_tp1_best + + # compute RHS of bellman equation + q_t_target = ( + rewards + (discount ** policy.config["n_step"]) * q_tp1_best_masked + ).detach() + + # Compute the TD-error (potentially clipped), for priority replay buffer + base_td_error = torch.abs(q_t_selected - q_t_target) + if twin_q: + twin_td_error = torch.abs(twin_q_t_selected - q_t_target) + td_error = 0.5 * (base_td_error + twin_td_error) + else: + td_error = base_td_error + + critic_loss_1 = nn.functional.mse_loss(q_t_selected, q_t_target) + if twin_q: + critic_loss_2 = nn.functional.mse_loss(twin_q_t_selected, q_t_target) + + # CQL Loss (We are using Entropy version of CQL (the best version)) + rand_actions = convert_to_torch_tensor( + torch.FloatTensor(actions.shape[0] * num_actions, actions.shape[-1]).uniform_( + action_low, action_high + ), + policy.device, + ) + curr_actions, curr_logp = policy_actions_repeat( + model, action_dist_class, model_out_t, num_actions + ) + next_actions, next_logp = policy_actions_repeat( + model, action_dist_class, model_out_tp1, num_actions + ) + + q1_rand = q_values_repeat(model, model_out_t, rand_actions) + q1_curr_actions = q_values_repeat(model, model_out_t, curr_actions) + q1_next_actions = q_values_repeat(model, model_out_t, next_actions) + + if twin_q: + q2_rand = q_values_repeat(model, model_out_t, rand_actions, twin=True) + q2_curr_actions = q_values_repeat(model, model_out_t, curr_actions, twin=True) + q2_next_actions = q_values_repeat(model, model_out_t, next_actions, twin=True) + + random_density = np.log(0.5 ** curr_actions.shape[-1]) + cat_q1 = torch.cat( + [ + q1_rand - random_density, + q1_next_actions - next_logp.detach(), + q1_curr_actions - curr_logp.detach(), + ], + 1, + ) + if twin_q: + cat_q2 = torch.cat( + [ + q2_rand - random_density, + q2_next_actions - next_logp.detach(), + q2_curr_actions - curr_logp.detach(), + ], + 1, + ) + + min_qf1_loss_ = ( + torch.logsumexp(cat_q1 / cql_temp, dim=1).mean() * min_q_weight * cql_temp + ) + min_qf1_loss = min_qf1_loss_ - (q_t.mean() * min_q_weight) + if twin_q: + min_qf2_loss_ = ( + torch.logsumexp(cat_q2 / cql_temp, dim=1).mean() * min_q_weight * cql_temp + ) + min_qf2_loss = min_qf2_loss_ - (twin_q_t.mean() * min_q_weight) + + if use_lagrange: + alpha_prime = torch.clamp(model.log_alpha_prime.exp(), min=0.0, max=1000000.0)[ + 0 + ] + min_qf1_loss = alpha_prime * (min_qf1_loss - target_action_gap) + if twin_q: + min_qf2_loss = alpha_prime * (min_qf2_loss - target_action_gap) + alpha_prime_loss = 0.5 * (-min_qf1_loss - min_qf2_loss) + else: + alpha_prime_loss = -min_qf1_loss + + cql_loss = [min_qf1_loss] + if twin_q: + cql_loss.append(min_qf2_loss) + + critic_loss = [critic_loss_1 + min_qf1_loss] + if twin_q: + critic_loss.append(critic_loss_2 + min_qf2_loss) + + if batch_size == policy.config["train_batch_size"]: + policy.critic_optims[0].zero_grad() + critic_loss[0].backward(retain_graph=True) + policy.critic_optims[0].step() + + if twin_q: + policy.critic_optims[1].zero_grad() + critic_loss[1].backward(retain_graph=False) + policy.critic_optims[1].step() + + # Store values for stats function in model (tower), such that for + # multi-GPU, we do not override them during the parallel loss phase. + # SAC stats. + model.tower_stats["q_t"] = q_t_selected + model.tower_stats["policy_t"] = policy_t + model.tower_stats["log_pis_t"] = log_pis_t + model.tower_stats["actor_loss"] = actor_loss + model.tower_stats["critic_loss"] = critic_loss + model.tower_stats["alpha_loss"] = alpha_loss + model.tower_stats["log_alpha_value"] = model.log_alpha + model.tower_stats["alpha_value"] = alpha + model.tower_stats["target_entropy"] = model.target_entropy + # CQL stats. + model.tower_stats["cql_loss"] = cql_loss + + # TD-error tensor in final stats + # will be concatenated and retrieved for each individual batch item. + model.tower_stats["td_error"] = td_error + + if use_lagrange: + model.tower_stats["log_alpha_prime_value"] = model.log_alpha_prime[0] + model.tower_stats["alpha_prime_value"] = alpha_prime + model.tower_stats["alpha_prime_loss"] = alpha_prime_loss + + if batch_size == policy.config["train_batch_size"]: + policy.alpha_prime_optim.zero_grad() + alpha_prime_loss.backward() + policy.alpha_prime_optim.step() + + # Return all loss terms corresponding to our optimizers. + return tuple( + [actor_loss] + + critic_loss + + [alpha_loss] + + ([alpha_prime_loss] if use_lagrange else []) + ) + + +def cql_stats(policy: Policy, train_batch: SampleBatch) -> Dict[str, TensorType]: + # Get SAC loss stats. + stats_dict = stats(policy, train_batch) + + # Add CQL loss stats to the dict. + stats_dict["cql_loss"] = torch.mean( + torch.stack(*policy.get_tower_stats("cql_loss")) + ) + + if policy.config["lagrangian"]: + stats_dict["log_alpha_prime_value"] = torch.mean( + torch.stack(policy.get_tower_stats("log_alpha_prime_value")) + ) + stats_dict["alpha_prime_value"] = torch.mean( + torch.stack(policy.get_tower_stats("alpha_prime_value")) + ) + stats_dict["alpha_prime_loss"] = torch.mean( + torch.stack(policy.get_tower_stats("alpha_prime_loss")) + ) + return stats_dict + + +def cql_optimizer_fn( + policy: Policy, config: AlgorithmConfigDict +) -> Tuple[LocalOptimizer]: + policy.cur_iter = 0 + opt_list = optimizer_fn(policy, config) + if config["lagrangian"]: + log_alpha_prime = nn.Parameter(torch.zeros(1, requires_grad=True).float()) + policy.model.register_parameter("log_alpha_prime", log_alpha_prime) + policy.alpha_prime_optim = torch.optim.Adam( + params=[policy.model.log_alpha_prime], + lr=config["optimization"]["critic_learning_rate"], + eps=1e-7, # to match tf.keras.optimizers.Adam's epsilon default + ) + return tuple( + [policy.actor_optim] + + policy.critic_optims + + [policy.alpha_optim] + + [policy.alpha_prime_optim] + ) + return opt_list + + +def cql_setup_late_mixins( + policy: Policy, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + config: AlgorithmConfigDict, +) -> None: + setup_late_mixins(policy, obs_space, action_space, config) + if config["lagrangian"]: + policy.model.log_alpha_prime = policy.model.log_alpha_prime.to(policy.device) + + +def compute_gradients_fn(policy, postprocessed_batch): + batches = [policy._lazy_tensor_dict(postprocessed_batch)] + model = policy.model + policy._loss(policy, model, policy.dist_class, batches[0]) + stats = {LEARNER_STATS_KEY: policy._convert_to_numpy(cql_stats(policy, batches[0]))} + return [None, stats] + + +def apply_gradients_fn(policy, gradients): + return + + +# Build a child class of `TorchPolicy`, given the custom functions defined +# above. +CQLTorchPolicy = build_policy_class( + name="CQLTorchPolicy", + framework="torch", + loss_fn=cql_loss, + get_default_config=lambda: ray.rllib.algorithms.cql.cql.CQLConfig(), + stats_fn=cql_stats, + postprocess_fn=postprocess_trajectory, + extra_grad_process_fn=apply_grad_clipping, + optimizer_fn=cql_optimizer_fn, + validate_spaces=validate_spaces, + before_loss_init=cql_setup_late_mixins, + make_model_and_action_dist=build_sac_model_and_action_dist, + extra_learn_fetches_fn=concat_multi_gpu_td_errors, + mixins=[TargetNetworkMixin, ComputeTDErrorMixin], + action_distribution_fn=action_distribution_fn, + compute_gradients_fn=compute_gradients_fn, + apply_gradients_fn=apply_gradients_fn, +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/torch/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/torch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/torch/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/torch/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91403011b8a8508bb13379ff014e914346448761 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/torch/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/torch/__pycache__/cql_torch_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/torch/__pycache__/cql_torch_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b64f7af88858b5041d24f34d0f4580b87891fee Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/torch/__pycache__/cql_torch_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/torch/__pycache__/default_cql_torch_rl_module.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/torch/__pycache__/default_cql_torch_rl_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba413eb7e6ed3b25afae081917661c1866cf228b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/torch/__pycache__/default_cql_torch_rl_module.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/torch/cql_torch_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/torch/cql_torch_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..e9f6897d3c83b23ecb7619d1de37373bd5820c19 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/torch/cql_torch_learner.py @@ -0,0 +1,280 @@ +from typing import Dict + +from ray.tune.result import TRAINING_ITERATION +from ray.rllib.algorithms.sac.sac_learner import ( + LOGPS_KEY, + QF_LOSS_KEY, + QF_MEAN_KEY, + QF_MAX_KEY, + QF_MIN_KEY, + QF_PREDS, + QF_TWIN_LOSS_KEY, + QF_TWIN_PREDS, + TD_ERROR_MEAN_KEY, +) +from ray.rllib.algorithms.cql.cql import CQLConfig +from ray.rllib.algorithms.sac.torch.sac_torch_learner import SACTorchLearner +from ray.rllib.core.columns import Columns +from ray.rllib.core.learner.learner import ( + POLICY_LOSS_KEY, +) +from ray.rllib.utils.annotations import override +from ray.rllib.utils.metrics import ALL_MODULES +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.typing import ModuleID, ParamDict, TensorType + +torch, nn = try_import_torch() + + +class CQLTorchLearner(SACTorchLearner): + @override(SACTorchLearner) + def compute_loss_for_module( + self, + *, + module_id: ModuleID, + config: CQLConfig, + batch: Dict, + fwd_out: Dict[str, TensorType], + ) -> TensorType: + + # TODO (simon, sven): Add upstream information pieces into this timesteps + # call arg to Learner.update_...(). + self.metrics.log_value( + (ALL_MODULES, TRAINING_ITERATION), + 1, + reduce="sum", + ) + # Get the train action distribution for the current policy and current state. + # This is needed for the policy (actor) loss and the `alpha`` loss. + action_dist_class = self.module[module_id].get_train_action_dist_cls() + action_dist_curr = action_dist_class.from_logits( + fwd_out[Columns.ACTION_DIST_INPUTS] + ) + + # Optimize also the hyperparameter `alpha` by using the current policy + # evaluated at the current state (from offline data). Note, in contrast + # to the original SAC loss, here the `alpha` and actor losses are + # calculated first. + # TODO (simon): Check, why log(alpha) is used, prob. just better + # to optimize and monotonic function. Original equation uses alpha. + alpha_loss = -torch.mean( + self.curr_log_alpha[module_id] + * (fwd_out["logp_resampled"].detach() + self.target_entropy[module_id]) + ) + + # Get the current alpha. + alpha = torch.exp(self.curr_log_alpha[module_id]) + # Start training with behavior cloning and turn to the classic Soft-Actor Critic + # after `bc_iters` of training iterations. + if ( + self.metrics.peek((ALL_MODULES, TRAINING_ITERATION), default=0) + >= config.bc_iters + ): + actor_loss = torch.mean( + alpha.detach() * fwd_out["logp_resampled"] - fwd_out["q_curr"] + ) + else: + # Use log-probabilities of the current action distribution to clone + # the behavior policy (selected actions in data) in the first `bc_iters` + # training iterations. + bc_logps_curr = action_dist_curr.logp(batch[Columns.ACTIONS]) + actor_loss = torch.mean( + alpha.detach() * fwd_out["logp_resampled"] - bc_logps_curr + ) + + # The critic loss is composed of the standard SAC Critic L2 loss and the + # CQL entropy loss. + + # Get the Q-values for the actually selected actions in the offline data. + # In the critic loss we use these as predictions. + q_selected = fwd_out[QF_PREDS] + if config.twin_q: + q_twin_selected = fwd_out[QF_TWIN_PREDS] + + if not config.deterministic_backup: + q_next = ( + fwd_out["q_target_next"] + - alpha.detach() * fwd_out["logp_next_resampled"] + ) + else: + q_next = fwd_out["q_target_next"] + + # Now mask all Q-values with terminating next states in the targets. + q_next_masked = (1.0 - batch[Columns.TERMINATEDS].float()) * q_next + + # Compute the right hand side of the Bellman equation. Detach this node + # from the computation graph as we do not want to backpropagate through + # the target network when optimizing the Q loss. + # TODO (simon, sven): Kumar et al. (2020) use here also a reward scaler. + q_selected_target = ( + # TODO (simon): Add an `n_step` option to the `AddNextObsToBatch` connector. + batch[Columns.REWARDS] + # TODO (simon): Implement n_step. + + (config.gamma) * q_next_masked + ).detach() + + # Calculate the TD error. + td_error = torch.abs(q_selected - q_selected_target) + # Calculate a TD-error for twin-Q values, if needed. + if config.twin_q: + td_error += torch.abs(q_twin_selected - q_selected_target) + # Rescale the TD error + td_error *= 0.5 + + # MSBE loss for the critic(s) (i.e. Q, see eqs. (7-8) Haarnoja et al. (2018)). + # Note, this needs a sample from the current policy given the next state. + # Note further, we could also use here the Huber loss instead of the MSE. + # TODO (simon): Add the huber loss as an alternative (SAC uses it). + sac_critic_loss = torch.nn.MSELoss(reduction="mean")( + q_selected, + q_selected_target, + ) + if config.twin_q: + sac_critic_twin_loss = torch.nn.MSELoss(reduction="mean")( + q_twin_selected, + q_selected_target, + ) + + # Now calculate the CQL loss (we use the entropy version of the CQL algorithm). + # Note, the entropy version performs best in shown experiments. + + # Compute the log-probabilities for the random actions (note, we generate random + # actions (from the mu distribution as named in Kumar et al. (2020))). + # Note, all actions, action log-probabilities and Q-values are already computed + # by the module's `_forward_train` method. + # TODO (simon): This is the density for a discrete uniform, however, actions + # come from a continuous one. So actually this density should use (1/(high-low)) + # instead of (1/2). + random_density = torch.log( + torch.pow( + 0.5, + torch.tensor( + fwd_out["actions_curr_repeat"].shape[-1], + device=fwd_out["actions_curr_repeat"].device, + ), + ) + ) + # Merge all Q-values and subtract the log-probabilities (note, we use the + # entropy version of CQL). + q_repeat = torch.cat( + [ + fwd_out["q_rand_repeat"] - random_density, + fwd_out["q_next_repeat"] - fwd_out["logps_next_repeat"].detach(), + fwd_out["q_curr_repeat"] - fwd_out["logps_curr_repeat"].detach(), + ], + dim=1, + ) + cql_loss = ( + torch.logsumexp(q_repeat / config.temperature, dim=1).mean() + * config.min_q_weight + * config.temperature + ) + cql_loss -= q_selected.mean() * config.min_q_weight + # Add the CQL loss term to the SAC loss term. + critic_loss = sac_critic_loss + cql_loss + + # If a twin Q-value function is implemented calculated its CQL loss. + if config.twin_q: + q_twin_repeat = torch.cat( + [ + fwd_out["q_twin_rand_repeat"] - random_density, + fwd_out["q_twin_next_repeat"] + - fwd_out["logps_next_repeat"].detach(), + fwd_out["q_twin_curr_repeat"] + - fwd_out["logps_curr_repeat"].detach(), + ], + dim=1, + ) + cql_twin_loss = ( + torch.logsumexp(q_twin_repeat / config.temperature, dim=1).mean() + * config.min_q_weight + * config.temperature + ) + cql_twin_loss -= q_twin_selected.mean() * config.min_q_weight + # Add the CQL loss term to the SAC loss term. + critic_twin_loss = sac_critic_twin_loss + cql_twin_loss + + # TODO (simon): Check, if we need to implement here also a Lagrangian + # loss. + + total_loss = actor_loss + critic_loss + alpha_loss + + # Add the twin critic loss to the total loss, if needed. + if config.twin_q: + # Reweigh the critic loss terms in the total loss. + total_loss += 0.5 * critic_twin_loss - 0.5 * critic_loss + + # Log important loss stats (reduce=mean (default), but with window=1 + # in order to keep them history free). + self.metrics.log_dict( + { + POLICY_LOSS_KEY: actor_loss, + QF_LOSS_KEY: critic_loss, + # TODO (simon): Add these keys to SAC Learner. + "cql_loss": cql_loss, + "alpha_loss": alpha_loss, + "alpha_value": alpha[0], + "log_alpha_value": torch.log(alpha)[0], + "target_entropy": self.target_entropy[module_id], + LOGPS_KEY: torch.mean( + fwd_out["logp_resampled"] + ), # torch.mean(logps_curr), + QF_MEAN_KEY: torch.mean(fwd_out["q_curr_repeat"]), + QF_MAX_KEY: torch.max(fwd_out["q_curr_repeat"]), + QF_MIN_KEY: torch.min(fwd_out["q_curr_repeat"]), + TD_ERROR_MEAN_KEY: torch.mean(td_error), + }, + key=module_id, + window=1, # <- single items (should not be mean/ema-reduced over time). + ) + self._temp_losses[(module_id, POLICY_LOSS_KEY)] = actor_loss + self._temp_losses[(module_id, QF_LOSS_KEY)] = critic_loss + self._temp_losses[(module_id, "alpha_loss")] = alpha_loss + + # TODO (simon): Add loss keys for langrangian, if needed. + # TODO (simon): Add only here then the Langrange parameter optimization. + if config.twin_q: + self.metrics.log_value( + key=(module_id, QF_TWIN_LOSS_KEY), + value=critic_twin_loss, + window=1, # <- single items (should not be mean/ema-reduced over time). + ) + self._temp_losses[(module_id, QF_TWIN_LOSS_KEY)] = critic_twin_loss + + # Return the total loss. + return total_loss + + @override(SACTorchLearner) + def compute_gradients( + self, loss_per_module: Dict[ModuleID, TensorType], **kwargs + ) -> ParamDict: + + grads = {} + for module_id in set(loss_per_module.keys()) - {ALL_MODULES}: + # Loop through optimizers registered for this module. + for optim_name, optim in self.get_optimizers_for_module(module_id): + # Zero the gradients. Note, we need to reset the gradients b/c + # each component for a module operates on the same graph. + optim.zero_grad(set_to_none=True) + + # Compute the gradients for the component and module. + loss_tensor = self._temp_losses.pop((module_id, optim_name + "_loss")) + loss_tensor.backward( + retain_graph=False if optim_name in ["policy", "alpha"] else True + ) + # Store the gradients for the component and module. + # TODO (simon): Check another time the graph for overlapping + # gradients. + grads.update( + { + pid: grads[pid] + p.grad.clone() + if pid in grads + else p.grad.clone() + for pid, p in self.filter_param_dict_for_optimizer( + self._params, optim + ).items() + } + ) + + assert not self._temp_losses + return grads diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/torch/default_cql_torch_rl_module.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/torch/default_cql_torch_rl_module.py new file mode 100644 index 0000000000000000000000000000000000000000..32e90815710e4963b901f9b35ad7b99a9abbf2c3 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/cql/torch/default_cql_torch_rl_module.py @@ -0,0 +1,206 @@ +import tree +from typing import Any, Dict, Optional + +from ray.rllib.algorithms.sac.sac_learner import ( + QF_PREDS, + QF_TWIN_PREDS, +) +from ray.rllib.algorithms.sac.sac_catalog import SACCatalog +from ray.rllib.algorithms.sac.torch.default_sac_torch_rl_module import ( + DefaultSACTorchRLModule, +) +from ray.rllib.core.columns import Columns +from ray.rllib.core.models.base import ENCODER_OUT +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.typing import TensorType + +torch, nn = try_import_torch() + + +class DefaultCQLTorchRLModule(DefaultSACTorchRLModule): + def __init__(self, *args, **kwargs): + catalog_class = kwargs.pop("catalog_class", None) + if catalog_class is None: + catalog_class = SACCatalog + super().__init__(*args, **kwargs, catalog_class=catalog_class) + + @override(DefaultSACTorchRLModule) + def _forward_train(self, batch: Dict) -> Dict[str, Any]: + # Call the super method. + fwd_out = super()._forward_train(batch) + + # Make sure we perform a "straight-through gradient" pass here, + # ignoring the gradients of the q-net, however, still recording + # the gradients of the policy net (which was used to rsample the actions used + # here). This is different from doing `.detach()` or `with torch.no_grads()`, + # as these two methds would fully block all gradient recordings, including + # the needed policy ones. + all_params = list(self.pi_encoder.parameters()) + list(self.pi.parameters()) + # if self.twin_q: + # all_params += list(self.qf_twin.parameters()) + list( + # self.qf_twin_encoder.parameters() + # ) + + for param in all_params: + param.requires_grad = False + + # Compute the repeated actions, action log-probabilites and Q-values for all + # observations. + # First for the random actions (from the mu-distribution as named by Kumar et + # al. (2020)). + low = torch.tensor( + self.action_space.low, + device=fwd_out[QF_PREDS].device, + ) + high = torch.tensor( + self.action_space.high, + device=fwd_out[QF_PREDS].device, + ) + num_samples = batch[Columns.ACTIONS].shape[0] * self.model_config["num_actions"] + actions_rand_repeat = low + (high - low) * torch.rand( + (num_samples, low.shape[0]), device=fwd_out[QF_PREDS].device + ) + + # First for the random actions (from the mu-distribution as named in Kumar + # et al. (2020)) using repeated observations. + rand_repeat_out = self._repeat_actions(batch[Columns.OBS], actions_rand_repeat) + (fwd_out["actions_rand_repeat"], fwd_out["q_rand_repeat"]) = ( + rand_repeat_out[Columns.ACTIONS], + rand_repeat_out[QF_PREDS], + ) + # Sample current and next actions (from the pi distribution as named in Kumar + # et al. (2020)) using repeated observations + # Second for the current observations and the current action distribution. + curr_repeat_out = self._repeat_actions(batch[Columns.OBS]) + ( + fwd_out["actions_curr_repeat"], + fwd_out["logps_curr_repeat"], + fwd_out["q_curr_repeat"], + ) = ( + curr_repeat_out[Columns.ACTIONS], + curr_repeat_out[Columns.ACTION_LOGP], + curr_repeat_out[QF_PREDS], + ) + # Then, for the next observations and the current action distribution. + next_repeat_out = self._repeat_actions(batch[Columns.NEXT_OBS]) + ( + fwd_out["actions_next_repeat"], + fwd_out["logps_next_repeat"], + fwd_out["q_next_repeat"], + ) = ( + next_repeat_out[Columns.ACTIONS], + next_repeat_out[Columns.ACTION_LOGP], + next_repeat_out[QF_PREDS], + ) + if self.twin_q: + # First for the random actions from the mu-distribution. + fwd_out["q_twin_rand_repeat"] = rand_repeat_out[QF_TWIN_PREDS] + # Second for the current observations and the current action distribution. + fwd_out["q_twin_curr_repeat"] = curr_repeat_out[QF_TWIN_PREDS] + # Then, for the next observations and the current action distribution. + fwd_out["q_twin_next_repeat"] = next_repeat_out[QF_TWIN_PREDS] + # Reset the gradient requirements for all Q-function parameters. + for param in all_params: + param.requires_grad = True + + return fwd_out + + def _repeat_tensor(self, tensor: TensorType, repeat: int) -> TensorType: + """Generates a repeated version of a tensor. + + The repetition is done similar `np.repeat` and repeats each value + instead of the complete vector. + + Args: + tensor: The tensor to be repeated. + repeat: How often each value in the tensor should be repeated. + + Returns: + A tensor holding `repeat` repeated values of the input `tensor` + """ + # Insert the new dimension at axis 1 into the tensor. + t_repeat = tensor.unsqueeze(1) + # Repeat the tensor along the new dimension. + t_repeat = torch.repeat_interleave(t_repeat, repeat, dim=1) + # Stack the repeated values into the batch dimension. + t_repeat = t_repeat.view(-1, *tensor.shape[1:]) + # Return the repeated tensor. + return t_repeat + + def _repeat_actions( + self, obs: TensorType, actions: Optional[TensorType] = None + ) -> Dict[str, TensorType]: + """Generated actions and Q-values for repeated observations. + + The `self.model_config["num_actions"]` define a multiplier + used for generating `num_actions` as many actions as the batch size. + Observations are repeated and then a model forward pass is made. + + Args: + obs: A batched observation tensor. + actions: An optional batched actions tensor. + + Returns: + A dictionary holding the (sampled or passed-in actions), the log + probabilities (of sampled actions), the Q-values and if available + the twin-Q values. + """ + output = {} + # Receive the batch size. + batch_size = obs.shape[0] + # Receive the number of action to sample. + num_actions = self.model_config["num_actions"] + # Repeat the observations `num_actions` times. + obs_repeat = tree.map_structure( + lambda t: self._repeat_tensor(t, num_actions), obs + ) + # Generate a batch for the forward pass. + temp_batch = {Columns.OBS: obs_repeat} + if actions is None: + # TODO (simon): Run the forward pass in inference mode. + # Compute the action logits. + pi_encoder_outs = self.pi_encoder(temp_batch) + action_logits = self.pi(pi_encoder_outs[ENCODER_OUT]) + # Generate the squashed Gaussian from the model's logits. + action_dist = self.get_train_action_dist_cls().from_logits(action_logits) + # Sample the actions. Note, we want to make a backward pass through + # these actions. + output[Columns.ACTIONS] = action_dist.rsample() + # Compute the action log-probabilities. + output[Columns.ACTION_LOGP] = action_dist.logp( + output[Columns.ACTIONS] + ).view(batch_size, num_actions, 1) + else: + output[Columns.ACTIONS] = actions + + # Compute all Q-values. + temp_batch.update( + { + Columns.ACTIONS: output[Columns.ACTIONS], + } + ) + output.update( + { + QF_PREDS: self._qf_forward_train_helper( + temp_batch, + self.qf_encoder, + self.qf, + ).view(batch_size, num_actions, 1) + } + ) + # If we have a twin-Q network, compute its Q-values, too. + if self.twin_q: + output.update( + { + QF_TWIN_PREDS: self._qf_forward_train_helper( + temp_batch, + self.qf_twin_encoder, + self.qf_twin, + ).view(batch_size, num_actions, 1) + } + ) + del temp_batch + + # Return + return output diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f6046b585028664e7351193d3ece2e291aa78278 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__init__.py @@ -0,0 +1,10 @@ +from ray.rllib.algorithms.dqn.dqn import DQN, DQNConfig +from ray.rllib.algorithms.dqn.dqn_tf_policy import DQNTFPolicy +from ray.rllib.algorithms.dqn.dqn_torch_policy import DQNTorchPolicy + +__all__ = [ + "DQN", + "DQNConfig", + "DQNTFPolicy", + "DQNTorchPolicy", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42624c07c19985ac765c9cb93c83cba5b9d718cc Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__pycache__/default_dqn_rl_module.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__pycache__/default_dqn_rl_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c255a1d6788f5517314b17e5290786ee64900add Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__pycache__/default_dqn_rl_module.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__pycache__/distributional_q_tf_model.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__pycache__/distributional_q_tf_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..591e7ec8af2b977ac766c5ae2ba4a2e14ba7e939 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__pycache__/distributional_q_tf_model.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__pycache__/dqn.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__pycache__/dqn.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65001241e7c020ae048d700034bb0066d3ee4b55 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__pycache__/dqn.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__pycache__/dqn_catalog.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__pycache__/dqn_catalog.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4790342e9e03a43ffa40327626613ac1820177b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__pycache__/dqn_catalog.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__pycache__/dqn_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__pycache__/dqn_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f795233cea973d47f107910dab3a66e8536890b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__pycache__/dqn_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__pycache__/dqn_tf_policy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__pycache__/dqn_tf_policy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..555eda5d1b48c77663293b8271d7b125565ee307 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__pycache__/dqn_tf_policy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__pycache__/dqn_torch_model.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__pycache__/dqn_torch_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa4d11f68e9a1348978a009a98816a73dd335f41 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__pycache__/dqn_torch_model.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__pycache__/dqn_torch_policy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__pycache__/dqn_torch_policy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e41fc6288336696453a67f3de3866199ab88e70 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/__pycache__/dqn_torch_policy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/default_dqn_rl_module.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/default_dqn_rl_module.py new file mode 100644 index 0000000000000000000000000000000000000000..78f9fe2c2e60c27188947f04703f6fc8db9dfbd2 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/default_dqn_rl_module.py @@ -0,0 +1,167 @@ +import abc +from typing import Any, Dict, List, Tuple, Union + +from ray.rllib.core.learner.utils import make_target_network +from ray.rllib.core.models.base import Encoder, Model +from ray.rllib.core.rl_module.apis import QNetAPI, InferenceOnlyAPI, TargetNetworkAPI +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import ( + override, + OverrideToImplementCustomLogic, +) +from ray.rllib.utils.schedules.scheduler import Scheduler +from ray.rllib.utils.typing import NetworkType, TensorType +from ray.util.annotations import DeveloperAPI + + +QF_PREDS = "qf_preds" +ATOMS = "atoms" +QF_LOGITS = "qf_logits" +QF_NEXT_PREDS = "qf_next_preds" +QF_PROBS = "qf_probs" +QF_TARGET_NEXT_PREDS = "qf_target_next_preds" +QF_TARGET_NEXT_PROBS = "qf_target_next_probs" + + +@DeveloperAPI +class DefaultDQNRLModule(RLModule, InferenceOnlyAPI, TargetNetworkAPI, QNetAPI): + @override(RLModule) + def setup(self): + # If a dueling architecture is used. + self.uses_dueling: bool = self.model_config.get("dueling") + # If double Q learning is used. + self.uses_double_q: bool = self.model_config.get("double_q") + # The number of atoms for a distribution support. + self.num_atoms: int = self.model_config.get("num_atoms") + # If distributional learning is requested configure the support. + if self.num_atoms > 1: + self.v_min: float = self.model_config.get("v_min") + self.v_max: float = self.model_config.get("v_max") + # The epsilon scheduler for epsilon greedy exploration. + self.epsilon_schedule = Scheduler( + fixed_value_or_schedule=self.model_config["epsilon"], + framework=self.framework, + ) + + # Build the encoder for the advantage and value streams. Note, + # the same encoder is used. + # Note further, by using the base encoder the correct encoder + # is chosen for the observation space used. + self.encoder = self.catalog.build_encoder(framework=self.framework) + + # Build heads. + self.af = self.catalog.build_af_head(framework=self.framework) + if self.uses_dueling: + # If in a dueling setting setup the value function head. + self.vf = self.catalog.build_vf_head(framework=self.framework) + + @override(InferenceOnlyAPI) + def get_non_inference_attributes(self) -> List[str]: + return ["_target_encoder", "_target_af"] + ( + ["_target_vf"] if self.uses_dueling else [] + ) + + @override(TargetNetworkAPI) + def make_target_networks(self) -> None: + self._target_encoder = make_target_network(self.encoder) + self._target_af = make_target_network(self.af) + if self.uses_dueling: + self._target_vf = make_target_network(self.vf) + + @override(TargetNetworkAPI) + def get_target_network_pairs(self) -> List[Tuple[NetworkType, NetworkType]]: + return [(self.encoder, self._target_encoder), (self.af, self._target_af)] + ( + # If we have a dueling architecture we need to update the value stream + # target, too. + [ + (self.vf, self._target_vf), + ] + if self.uses_dueling + else [] + ) + + @override(TargetNetworkAPI) + def forward_target(self, batch: Dict[str, Any]) -> Dict[str, Any]: + """Computes Q-values from the target network. + + Note, these can be accompanied by logits and probabilities + in case of distributional Q-learning, i.e. `self.num_atoms > 1`. + + Args: + batch: The batch received in the forward pass. + + Results: + A dictionary containing the target Q-value predictions ("qf_preds") + and in case of distributional Q-learning in addition to the target + Q-value predictions ("qf_preds") the support atoms ("atoms"), the target + Q-logits ("qf_logits"), and the probabilities ("qf_probs"). + """ + # If we have a dueling architecture we have to add the value stream. + return self._qf_forward_helper( + batch, + self._target_encoder, + ( + {"af": self._target_af, "vf": self._target_vf} + if self.uses_dueling + else self._target_af + ), + ) + + @override(QNetAPI) + def compute_q_values(self, batch: Dict[str, TensorType]) -> Dict[str, TensorType]: + """Computes Q-values, given encoder, q-net and (optionally), advantage net. + + Note, these can be accompanied by logits and probabilities + in case of distributional Q-learning, i.e. `self.num_atoms > 1`. + + Args: + batch: The batch received in the forward pass. + + Results: + A dictionary containing the Q-value predictions ("qf_preds") + and in case of distributional Q-learning - in addition to the Q-value + predictions ("qf_preds") - the support atoms ("atoms"), the Q-logits + ("qf_logits"), and the probabilities ("qf_probs"). + """ + # If we have a dueling architecture we have to add the value stream. + return self._qf_forward_helper( + batch, + self.encoder, + {"af": self.af, "vf": self.vf} if self.uses_dueling else self.af, + ) + + @override(RLModule) + def get_initial_state(self) -> dict: + if hasattr(self.encoder, "get_initial_state"): + return self.encoder.get_initial_state() + else: + return {} + + @abc.abstractmethod + @OverrideToImplementCustomLogic + def _qf_forward_helper( + self, + batch: Dict[str, TensorType], + encoder: Encoder, + head: Union[Model, Dict[str, Model]], + ) -> Dict[str, TensorType]: + """Computes Q-values. + + This is a helper function that takes care of all different cases, + i.e. if we use a dueling architecture or not and if we use distributional + Q-learning or not. + + Args: + batch: The batch received in the forward pass. + encoder: The encoder network to use. Here we have a single encoder + for all heads (Q or advantages and value in case of a dueling + architecture). + head: Either a head model or a dictionary of head model (dueling + architecture) containing advantage and value stream heads. + + Returns: + In case of expectation learning the Q-value predictions ("qf_preds") + and in case of distributional Q-learning in addition to the predictions + the atoms ("atoms"), the Q-value predictions ("qf_preds"), the Q-logits + ("qf_logits") and the probabilities for the support atoms ("qf_probs"). + """ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/distributional_q_tf_model.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/distributional_q_tf_model.py new file mode 100644 index 0000000000000000000000000000000000000000..a4dd63f587b7dcbd04d0edac32aa5b565fbd019c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/distributional_q_tf_model.py @@ -0,0 +1,190 @@ +"""Tensorflow model for DQN""" + +from typing import List + +import gymnasium as gym +from ray.rllib.models.tf.layers import NoisyLayer +from ray.rllib.models.tf.tf_modelv2 import TFModelV2 +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.typing import ModelConfigDict, TensorType + +tf1, tf, tfv = try_import_tf() + + +@OldAPIStack +class DistributionalQTFModel(TFModelV2): + """Extension of standard TFModel to provide distributional Q values. + + It also supports options for noisy nets and parameter space noise. + + Data flow: + obs -> forward() -> model_out + model_out -> get_q_value_distributions() -> Q(s, a) atoms + model_out -> get_state_value() -> V(s) + + Note that this class by itself is not a valid model unless you + implement forward() in a subclass.""" + + def __init__( + self, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + num_outputs: int, + model_config: ModelConfigDict, + name: str, + q_hiddens=(256,), + dueling: bool = False, + num_atoms: int = 1, + use_noisy: bool = False, + v_min: float = -10.0, + v_max: float = 10.0, + sigma0: float = 0.5, + # TODO(sven): Move `add_layer_norm` into ModelCatalog as + # generic option, then error if we use ParameterNoise as + # Exploration type and do not have any LayerNorm layers in + # the net. + add_layer_norm: bool = False, + ): + """Initialize variables of this model. + + Extra model kwargs: + q_hiddens (List[int]): List of layer-sizes after(!) the + Advantages(A)/Value(V)-split. Hence, each of the A- and V- + branches will have this structure of Dense layers. To define + the NN before this A/V-split, use - as always - + config["model"]["fcnet_hiddens"]. + dueling: Whether to build the advantage(A)/value(V) heads + for DDQN. If True, Q-values are calculated as: + Q = (A - mean[A]) + V. If False, raw NN output is interpreted + as Q-values. + num_atoms: If >1, enables distributional DQN. + use_noisy: Use noisy nets. + v_min: Min value support for distributional DQN. + v_max: Max value support for distributional DQN. + sigma0 (float): Initial value of noisy layers. + add_layer_norm: Enable layer norm (for param noise). + + Note that the core layers for forward() are not defined here, this + only defines the layers for the Q head. Those layers for forward() + should be defined in subclasses of DistributionalQModel. + """ + super(DistributionalQTFModel, self).__init__( + obs_space, action_space, num_outputs, model_config, name + ) + + # setup the Q head output (i.e., model for get_q_values) + self.model_out = tf.keras.layers.Input(shape=(num_outputs,), name="model_out") + + def build_action_value(prefix: str, model_out: TensorType) -> List[TensorType]: + if q_hiddens: + action_out = model_out + for i in range(len(q_hiddens)): + if use_noisy: + action_out = NoisyLayer( + "{}hidden_{}".format(prefix, i), q_hiddens[i], sigma0 + )(action_out) + elif add_layer_norm: + action_out = tf.keras.layers.Dense( + units=q_hiddens[i], activation=tf.nn.relu + )(action_out) + action_out = tf.keras.layers.LayerNormalization()(action_out) + else: + action_out = tf.keras.layers.Dense( + units=q_hiddens[i], + activation=tf.nn.relu, + name="hidden_%d" % i, + )(action_out) + else: + # Avoid postprocessing the outputs. This enables custom models + # to be used for parametric action DQN. + action_out = model_out + + if use_noisy: + action_scores = NoisyLayer( + "{}output".format(prefix), + self.action_space.n * num_atoms, + sigma0, + activation=None, + )(action_out) + elif q_hiddens: + action_scores = tf.keras.layers.Dense( + units=self.action_space.n * num_atoms, activation=None + )(action_out) + else: + action_scores = model_out + + if num_atoms > 1: + # Distributional Q-learning uses a discrete support z + # to represent the action value distribution + z = tf.range(num_atoms, dtype=tf.float32) + z = v_min + z * (v_max - v_min) / float(num_atoms - 1) + + def _layer(x): + support_logits_per_action = tf.reshape( + tensor=x, shape=(-1, self.action_space.n, num_atoms) + ) + support_prob_per_action = tf.nn.softmax( + logits=support_logits_per_action + ) + x = tf.reduce_sum(input_tensor=z * support_prob_per_action, axis=-1) + logits = support_logits_per_action + dist = support_prob_per_action + return [x, z, support_logits_per_action, logits, dist] + + return tf.keras.layers.Lambda(_layer)(action_scores) + else: + logits = tf.expand_dims(tf.ones_like(action_scores), -1) + dist = tf.expand_dims(tf.ones_like(action_scores), -1) + return [action_scores, logits, dist] + + def build_state_score(prefix: str, model_out: TensorType) -> TensorType: + state_out = model_out + for i in range(len(q_hiddens)): + if use_noisy: + state_out = NoisyLayer( + "{}dueling_hidden_{}".format(prefix, i), q_hiddens[i], sigma0 + )(state_out) + else: + state_out = tf.keras.layers.Dense( + units=q_hiddens[i], activation=tf.nn.relu + )(state_out) + if add_layer_norm: + state_out = tf.keras.layers.LayerNormalization()(state_out) + if use_noisy: + state_score = NoisyLayer( + "{}dueling_output".format(prefix), + num_atoms, + sigma0, + activation=None, + )(state_out) + else: + state_score = tf.keras.layers.Dense(units=num_atoms, activation=None)( + state_out + ) + return state_score + + q_out = build_action_value(name + "/action_value/", self.model_out) + self.q_value_head = tf.keras.Model(self.model_out, q_out) + + if dueling: + state_out = build_state_score(name + "/state_value/", self.model_out) + self.state_value_head = tf.keras.Model(self.model_out, state_out) + + def get_q_value_distributions(self, model_out: TensorType) -> List[TensorType]: + """Returns distributional values for Q(s, a) given a state embedding. + + Override this in your custom model to customize the Q output head. + + Args: + model_out: embedding from the model layers + + Returns: + (action_scores, logits, dist) if num_atoms == 1, otherwise + (action_scores, z, support_logits_per_action, logits, dist) + """ + return self.q_value_head(model_out) + + def get_state_value(self, model_out: TensorType) -> TensorType: + """Returns the state value prediction for the given state embedding.""" + return self.state_value_head(model_out) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/dqn.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/dqn.py new file mode 100644 index 0000000000000000000000000000000000000000..02014e72554c29f62cd7eb5ee9302feabae95079 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/dqn.py @@ -0,0 +1,857 @@ +""" +Deep Q-Networks (DQN, Rainbow, Parametric DQN) +============================================== + +This file defines the distributed Algorithm class for the Deep Q-Networks +algorithm. See `dqn_[tf|torch]_policy.py` for the definition of the policies. + +Detailed documentation: +https://docs.ray.io/en/master/rllib-algorithms.html#deep-q-networks-dqn-rainbow-parametric-dqn +""" # noqa: E501 + +from collections import defaultdict +import logging +from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union +import numpy as np + +from ray.rllib.algorithms.algorithm import Algorithm +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig, NotProvided +from ray.rllib.algorithms.dqn.dqn_tf_policy import DQNTFPolicy +from ray.rllib.algorithms.dqn.dqn_torch_policy import DQNTorchPolicy +from ray.rllib.core.learner import Learner +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.execution.rollout_ops import ( + synchronous_parallel_sample, +) +from ray.rllib.policy.sample_batch import MultiAgentBatch +from ray.rllib.execution.train_ops import ( + train_one_step, + multi_gpu_train_one_step, +) +from ray.rllib.policy.policy import Policy +from ray.rllib.utils import deep_update +from ray.rllib.utils.annotations import override +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.replay_buffers.utils import ( + update_priorities_in_episode_replay_buffer, + update_priorities_in_replay_buffer, + validate_buffer_config, +) +from ray.rllib.utils.typing import ResultDict +from ray.rllib.utils.metrics import ( + ALL_MODULES, + ENV_RUNNER_RESULTS, + ENV_RUNNER_SAMPLING_TIMER, + LAST_TARGET_UPDATE_TS, + LEARNER_RESULTS, + LEARNER_UPDATE_TIMER, + NUM_AGENT_STEPS_SAMPLED, + NUM_AGENT_STEPS_SAMPLED_LIFETIME, + NUM_ENV_STEPS_SAMPLED, + NUM_ENV_STEPS_SAMPLED_LIFETIME, + NUM_TARGET_UPDATES, + REPLAY_BUFFER_ADD_DATA_TIMER, + REPLAY_BUFFER_RESULTS, + REPLAY_BUFFER_SAMPLE_TIMER, + REPLAY_BUFFER_UPDATE_PRIOS_TIMER, + SAMPLE_TIMER, + SYNCH_WORKER_WEIGHTS_TIMER, + TD_ERROR_KEY, + TIMERS, +) +from ray.rllib.utils.deprecation import DEPRECATED_VALUE +from ray.rllib.utils.replay_buffers.utils import sample_min_n_steps_from_buffer +from ray.rllib.utils.typing import ( + LearningRateOrSchedule, + RLModuleSpecType, + SampleBatchType, +) + +logger = logging.getLogger(__name__) + + +class DQNConfig(AlgorithmConfig): + r"""Defines a configuration class from which a DQN Algorithm can be built. + + .. testcode:: + + from ray.rllib.algorithms.dqn.dqn import DQNConfig + + config = ( + DQNConfig() + .environment("CartPole-v1") + .training(replay_buffer_config={ + "type": "PrioritizedEpisodeReplayBuffer", + "capacity": 60000, + "alpha": 0.5, + "beta": 0.5, + }) + .env_runners(num_env_runners=1) + ) + algo = config.build() + algo.train() + algo.stop() + + .. testcode:: + + from ray.rllib.algorithms.dqn.dqn import DQNConfig + from ray import tune + + config = ( + DQNConfig() + .environment("CartPole-v1") + .training( + num_atoms=tune.grid_search([1,]) + ) + ) + tune.Tuner( + "DQN", + run_config=tune.RunConfig(stop={"training_iteration":1}), + param_space=config, + ).fit() + + .. testoutput:: + :hide: + + ... + + + """ + + def __init__(self, algo_class=None): + """Initializes a DQNConfig instance.""" + self.exploration_config = { + "type": "EpsilonGreedy", + "initial_epsilon": 1.0, + "final_epsilon": 0.02, + "epsilon_timesteps": 10000, + } + + super().__init__(algo_class=algo_class or DQN) + + # Overrides of AlgorithmConfig defaults + # `env_runners()` + # Set to `self.n_step`, if 'auto'. + self.rollout_fragment_length: Union[int, str] = "auto" + # New stack uses `epsilon` as either a constant value or a scheduler + # defined like this. + # TODO (simon): Ensure that users can understand how to provide epsilon. + # (sven): Should we add this to `self.env_runners(epsilon=..)`? + self.epsilon = [(0, 1.0), (10000, 0.05)] + + # `training()` + self.grad_clip = 40.0 + # Note: Only when using enable_rl_module_and_learner=True can the clipping mode + # be configured by the user. On the old API stack, RLlib will always clip by + # global_norm, no matter the value of `grad_clip_by`. + self.grad_clip_by = "global_norm" + self.lr = 5e-4 + self.train_batch_size = 32 + + # `evaluation()` + self.evaluation(evaluation_config=AlgorithmConfig.overrides(explore=False)) + + # `reporting()` + self.min_time_s_per_iteration = None + self.min_sample_timesteps_per_iteration = 1000 + + # DQN specific config settings. + # fmt: off + # __sphinx_doc_begin__ + self.target_network_update_freq = 500 + self.num_steps_sampled_before_learning_starts = 1000 + self.store_buffer_in_checkpoints = False + self.adam_epsilon = 1e-8 + + self.tau = 1.0 + + self.num_atoms = 1 + self.v_min = -10.0 + self.v_max = 10.0 + self.noisy = False + self.sigma0 = 0.5 + self.dueling = True + self.hiddens = [256] + self.double_q = True + self.n_step = 1 + self.before_learn_on_batch = None + self.training_intensity = None + self.td_error_loss_fn = "huber" + self.categorical_distribution_temperature = 1.0 + # The burn-in for stateful `RLModule`s. + self.burn_in_len = 0 + + # Replay buffer configuration. + self.replay_buffer_config = { + "type": "PrioritizedEpisodeReplayBuffer", + # Size of the replay buffer. Note that if async_updates is set, + # then each worker will have a replay buffer of this size. + "capacity": 50000, + "alpha": 0.6, + # Beta parameter for sampling from prioritized replay buffer. + "beta": 0.4, + } + # fmt: on + # __sphinx_doc_end__ + + self.lr_schedule = None # @OldAPIStack + + # Deprecated + self.buffer_size = DEPRECATED_VALUE + self.prioritized_replay = DEPRECATED_VALUE + self.learning_starts = DEPRECATED_VALUE + self.replay_batch_size = DEPRECATED_VALUE + # Can not use DEPRECATED_VALUE here because -1 is a common config value + self.replay_sequence_length = None + self.prioritized_replay_alpha = DEPRECATED_VALUE + self.prioritized_replay_beta = DEPRECATED_VALUE + self.prioritized_replay_eps = DEPRECATED_VALUE + + @override(AlgorithmConfig) + def training( + self, + *, + target_network_update_freq: Optional[int] = NotProvided, + replay_buffer_config: Optional[dict] = NotProvided, + store_buffer_in_checkpoints: Optional[bool] = NotProvided, + lr_schedule: Optional[List[List[Union[int, float]]]] = NotProvided, + epsilon: Optional[LearningRateOrSchedule] = NotProvided, + adam_epsilon: Optional[float] = NotProvided, + grad_clip: Optional[int] = NotProvided, + num_steps_sampled_before_learning_starts: Optional[int] = NotProvided, + tau: Optional[float] = NotProvided, + num_atoms: Optional[int] = NotProvided, + v_min: Optional[float] = NotProvided, + v_max: Optional[float] = NotProvided, + noisy: Optional[bool] = NotProvided, + sigma0: Optional[float] = NotProvided, + dueling: Optional[bool] = NotProvided, + hiddens: Optional[int] = NotProvided, + double_q: Optional[bool] = NotProvided, + n_step: Optional[Union[int, Tuple[int, int]]] = NotProvided, + before_learn_on_batch: Callable[ + [Type[MultiAgentBatch], List[Type[Policy]], Type[int]], + Type[MultiAgentBatch], + ] = NotProvided, + training_intensity: Optional[float] = NotProvided, + td_error_loss_fn: Optional[str] = NotProvided, + categorical_distribution_temperature: Optional[float] = NotProvided, + burn_in_len: Optional[int] = NotProvided, + **kwargs, + ) -> "DQNConfig": + """Sets the training related configuration. + + Args: + target_network_update_freq: Update the target network every + `target_network_update_freq` sample steps. + replay_buffer_config: Replay buffer config. + Examples: + { + "_enable_replay_buffer_api": True, + "type": "MultiAgentReplayBuffer", + "capacity": 50000, + "replay_sequence_length": 1, + } + - OR - + { + "_enable_replay_buffer_api": True, + "type": "MultiAgentPrioritizedReplayBuffer", + "capacity": 50000, + "prioritized_replay_alpha": 0.6, + "prioritized_replay_beta": 0.4, + "prioritized_replay_eps": 1e-6, + "replay_sequence_length": 1, + } + - Where - + prioritized_replay_alpha: Alpha parameter controls the degree of + prioritization in the buffer. In other words, when a buffer sample has + a higher temporal-difference error, with how much more probability + should it drawn to use to update the parametrized Q-network. 0.0 + corresponds to uniform probability. Setting much above 1.0 may quickly + result as the sampling distribution could become heavily “pointy” with + low entropy. + prioritized_replay_beta: Beta parameter controls the degree of + importance sampling which suppresses the influence of gradient updates + from samples that have higher probability of being sampled via alpha + parameter and the temporal-difference error. + prioritized_replay_eps: Epsilon parameter sets the baseline probability + for sampling so that when the temporal-difference error of a sample is + zero, there is still a chance of drawing the sample. + store_buffer_in_checkpoints: Set this to True, if you want the contents of + your buffer(s) to be stored in any saved checkpoints as well. + Warnings will be created if: + - This is True AND restoring from a checkpoint that contains no buffer + data. + - This is False AND restoring from a checkpoint that does contain + buffer data. + epsilon: Epsilon exploration schedule. In the format of [[timestep, value], + [timestep, value], ...]. A schedule must start from + timestep 0. + adam_epsilon: Adam optimizer's epsilon hyper parameter. + grad_clip: If not None, clip gradients during optimization at this value. + num_steps_sampled_before_learning_starts: Number of timesteps to collect + from rollout workers before we start sampling from replay buffers for + learning. Whether we count this in agent steps or environment steps + depends on config.multi_agent(count_steps_by=..). + tau: Update the target by \tau * policy + (1-\tau) * target_policy. + num_atoms: Number of atoms for representing the distribution of return. + When this is greater than 1, distributional Q-learning is used. + v_min: Minimum value estimation + v_max: Maximum value estimation + noisy: Whether to use noisy network to aid exploration. This adds parametric + noise to the model weights. + sigma0: Control the initial parameter noise for noisy nets. + dueling: Whether to use dueling DQN. + hiddens: Dense-layer setup for each the advantage branch and the value + branch + double_q: Whether to use double DQN. + n_step: N-step target updates. If >1, sars' tuples in trajectories will be + postprocessed to become sa[discounted sum of R][s t+n] tuples. An + integer will be interpreted as a fixed n-step value. If a tuple of 2 + ints is provided here, the n-step value will be drawn for each sample(!) + in the train batch from a uniform distribution over the closed interval + defined by `[n_step[0], n_step[1]]`. + before_learn_on_batch: Callback to run before learning on a multi-agent + batch of experiences. + training_intensity: The intensity with which to update the model (vs + collecting samples from the env). + If None, uses "natural" values of: + `train_batch_size` / (`rollout_fragment_length` x `num_env_runners` x + `num_envs_per_env_runner`). + If not None, will make sure that the ratio between timesteps inserted + into and sampled from the buffer matches the given values. + Example: + training_intensity=1000.0 + train_batch_size=250 + rollout_fragment_length=1 + num_env_runners=1 (or 0) + num_envs_per_env_runner=1 + -> natural value = 250 / 1 = 250.0 + -> will make sure that replay+train op will be executed 4x asoften as + rollout+insert op (4 * 250 = 1000). + See: rllib/algorithms/dqn/dqn.py::calculate_rr_weights for further + details. + td_error_loss_fn: "huber" or "mse". loss function for calculating TD error + when num_atoms is 1. Note that if num_atoms is > 1, this parameter + is simply ignored, and softmax cross entropy loss will be used. + categorical_distribution_temperature: Set the temperature parameter used + by Categorical action distribution. A valid temperature is in the range + of [0, 1]. Note that this mostly affects evaluation since TD error uses + argmax for return calculation. + burn_in_len: The burn-in period for a stateful RLModule. It allows the + Learner to utilize the initial `burn_in_len` steps in a replay sequence + solely for unrolling the network and establishing a typical starting + state. The network is then updated on the remaining steps of the + sequence. This process helps mitigate issues stemming from a poor + initial state - zero or an outdated recorded state. Consider setting + this parameter to a positive integer if your stateful RLModule faces + convergence challenges or exhibits signs of catastrophic forgetting. + + Returns: + This updated AlgorithmConfig object. + """ + # Pass kwargs onto super's `training()` method. + super().training(**kwargs) + + if target_network_update_freq is not NotProvided: + self.target_network_update_freq = target_network_update_freq + if replay_buffer_config is not NotProvided: + # Override entire `replay_buffer_config` if `type` key changes. + # Update, if `type` key remains the same or is not specified. + new_replay_buffer_config = deep_update( + {"replay_buffer_config": self.replay_buffer_config}, + {"replay_buffer_config": replay_buffer_config}, + False, + ["replay_buffer_config"], + ["replay_buffer_config"], + ) + self.replay_buffer_config = new_replay_buffer_config["replay_buffer_config"] + if store_buffer_in_checkpoints is not NotProvided: + self.store_buffer_in_checkpoints = store_buffer_in_checkpoints + if lr_schedule is not NotProvided: + self.lr_schedule = lr_schedule + if epsilon is not NotProvided: + self.epsilon = epsilon + if adam_epsilon is not NotProvided: + self.adam_epsilon = adam_epsilon + if grad_clip is not NotProvided: + self.grad_clip = grad_clip + if num_steps_sampled_before_learning_starts is not NotProvided: + self.num_steps_sampled_before_learning_starts = ( + num_steps_sampled_before_learning_starts + ) + if tau is not NotProvided: + self.tau = tau + if num_atoms is not NotProvided: + self.num_atoms = num_atoms + if v_min is not NotProvided: + self.v_min = v_min + if v_max is not NotProvided: + self.v_max = v_max + if noisy is not NotProvided: + self.noisy = noisy + if sigma0 is not NotProvided: + self.sigma0 = sigma0 + if dueling is not NotProvided: + self.dueling = dueling + if hiddens is not NotProvided: + self.hiddens = hiddens + if double_q is not NotProvided: + self.double_q = double_q + if n_step is not NotProvided: + self.n_step = n_step + if before_learn_on_batch is not NotProvided: + self.before_learn_on_batch = before_learn_on_batch + if training_intensity is not NotProvided: + self.training_intensity = training_intensity + if td_error_loss_fn is not NotProvided: + self.td_error_loss_fn = td_error_loss_fn + if categorical_distribution_temperature is not NotProvided: + self.categorical_distribution_temperature = ( + categorical_distribution_temperature + ) + if burn_in_len is not NotProvided: + self.burn_in_len = burn_in_len + + return self + + @override(AlgorithmConfig) + def validate(self) -> None: + # Call super's validation method. + super().validate() + + if self.enable_rl_module_and_learner: + # `lr_schedule` checking. + if self.lr_schedule is not None: + self._value_error( + "`lr_schedule` is deprecated and must be None! Use the " + "`lr` setting to setup a schedule." + ) + else: + if not self.in_evaluation: + validate_buffer_config(self) + + # TODO (simon): Find a clean solution to deal with configuration configs + # when using the new API stack. + if self.exploration_config["type"] == "ParameterNoise": + if self.batch_mode != "complete_episodes": + self._value_error( + "ParameterNoise Exploration requires `batch_mode` to be " + "'complete_episodes'. Try setting `config.env_runners(" + "batch_mode='complete_episodes')`." + ) + if self.noisy: + self._value_error( + "ParameterNoise Exploration and `noisy` network cannot be" + " used at the same time!" + ) + + if self.td_error_loss_fn not in ["huber", "mse"]: + self._value_error("`td_error_loss_fn` must be 'huber' or 'mse'!") + + # Check rollout_fragment_length to be compatible with n_step. + if ( + not self.in_evaluation + and self.rollout_fragment_length != "auto" + and self.rollout_fragment_length < self.n_step + ): + self._value_error( + f"Your `rollout_fragment_length` ({self.rollout_fragment_length}) is " + f"smaller than `n_step` ({self.n_step})! " + "Try setting config.env_runners(rollout_fragment_length=" + f"{self.n_step})." + ) + + # Check, if the `max_seq_len` is longer then the burn-in. + if ( + "max_seq_len" in self.model_config + and 0 < self.model_config["max_seq_len"] <= self.burn_in_len + ): + raise ValueError( + f"Your defined `burn_in_len`={self.burn_in_len} is larger or equal " + f"`max_seq_len`={self.model_config['max_seq_len']}! Either decrease " + "the `burn_in_len` or increase your `max_seq_len`." + ) + + # Validate that we use the corresponding `EpisodeReplayBuffer` when using + # episodes. + # TODO (sven, simon): Implement the multi-agent case for replay buffers. + from ray.rllib.utils.replay_buffers.episode_replay_buffer import ( + EpisodeReplayBuffer, + ) + + if ( + self.enable_env_runner_and_connector_v2 + and not isinstance(self.replay_buffer_config["type"], str) + and not issubclass(self.replay_buffer_config["type"], EpisodeReplayBuffer) + ): + self._value_error( + "When using the new `EnvRunner API` the replay buffer must be of type " + "`EpisodeReplayBuffer`." + ) + elif not self.enable_env_runner_and_connector_v2 and ( + ( + isinstance(self.replay_buffer_config["type"], str) + and "Episode" in self.replay_buffer_config["type"] + ) + or issubclass(self.replay_buffer_config["type"], EpisodeReplayBuffer) + ): + self._value_error( + "When using the old API stack the replay buffer must not be of type " + "`EpisodeReplayBuffer`! We suggest you use the following config to run " + "DQN on the old API stack: `config.training(replay_buffer_config={" + "'type': 'MultiAgentPrioritizedReplayBuffer', " + "'prioritized_replay_alpha': [alpha], " + "'prioritized_replay_beta': [beta], " + "'prioritized_replay_eps': [eps], " + "})`." + ) + + @override(AlgorithmConfig) + def get_rollout_fragment_length(self, worker_index: int = 0) -> int: + if self.rollout_fragment_length == "auto": + return ( + self.n_step[1] + if isinstance(self.n_step, (tuple, list)) + else self.n_step + ) + else: + return self.rollout_fragment_length + + @override(AlgorithmConfig) + def get_default_rl_module_spec(self) -> RLModuleSpecType: + if self.framework_str == "torch": + from ray.rllib.algorithms.dqn.torch.default_dqn_torch_rl_module import ( + DefaultDQNTorchRLModule, + ) + + return RLModuleSpec( + module_class=DefaultDQNTorchRLModule, + model_config=self.model_config, + ) + else: + raise ValueError( + f"The framework {self.framework_str} is not supported! " + "Use `config.framework('torch')` instead." + ) + + @property + @override(AlgorithmConfig) + def _model_config_auto_includes(self) -> Dict[str, Any]: + return super()._model_config_auto_includes | { + "double_q": self.double_q, + "dueling": self.dueling, + "epsilon": self.epsilon, + "num_atoms": self.num_atoms, + "std_init": self.sigma0, + "v_max": self.v_max, + "v_min": self.v_min, + } + + @override(AlgorithmConfig) + def get_default_learner_class(self) -> Union[Type["Learner"], str]: + if self.framework_str == "torch": + from ray.rllib.algorithms.dqn.torch.dqn_torch_learner import ( + DQNTorchLearner, + ) + + return DQNTorchLearner + else: + raise ValueError( + f"The framework {self.framework_str} is not supported! " + "Use `config.framework('torch')` instead." + ) + + +def calculate_rr_weights(config: AlgorithmConfig) -> List[float]: + """Calculate the round robin weights for the rollout and train steps""" + if not config.training_intensity: + return [1, 1] + + # Calculate the "native ratio" as: + # [train-batch-size] / [size of env-rolled-out sampled data] + # This is to set freshly rollout-collected data in relation to + # the data we pull from the replay buffer (which also contains old + # samples). + native_ratio = config.total_train_batch_size / ( + config.get_rollout_fragment_length() + * config.num_envs_per_env_runner + # Add one to workers because the local + # worker usually collects experiences as well, and we avoid division by zero. + * max(config.num_env_runners + 1, 1) + ) + + # Training intensity is specified in terms of + # (steps_replayed / steps_sampled), so adjust for the native ratio. + sample_and_train_weight = config.training_intensity / native_ratio + if sample_and_train_weight < 1: + return [int(np.round(1 / sample_and_train_weight)), 1] + else: + return [1, int(np.round(sample_and_train_weight))] + + +class DQN(Algorithm): + @classmethod + @override(Algorithm) + def get_default_config(cls) -> AlgorithmConfig: + return DQNConfig() + + @classmethod + @override(Algorithm) + def get_default_policy_class( + cls, config: AlgorithmConfig + ) -> Optional[Type[Policy]]: + if config["framework"] == "torch": + return DQNTorchPolicy + else: + return DQNTFPolicy + + @override(Algorithm) + def setup(self, config: AlgorithmConfig) -> None: + super().setup(config) + + if self.config.enable_env_runner_and_connector_v2 and self.env_runner_group: + if self.env_runner is None: + self._module_is_stateful = self.env_runner_group.foreach_env_runner( + lambda er: er.module.is_stateful(), + remote_worker_ids=[1], + local_env_runner=False, + )[0] + else: + self._module_is_stateful = self.env_runner.module.is_stateful() + + @override(Algorithm) + def training_step(self) -> None: + """DQN training iteration function. + + Each training iteration, we: + - Sample (MultiAgentBatch) from workers. + - Store new samples in replay buffer. + - Sample training batch (MultiAgentBatch) from replay buffer. + - Learn on training batch. + - Update remote workers' new policy weights. + - Update target network every `target_network_update_freq` sample steps. + - Return all collected metrics for the iteration. + + Returns: + The results dict from executing the training iteration. + """ + # Old API stack (Policy, RolloutWorker, Connector). + if not self.config.enable_env_runner_and_connector_v2: + return self._training_step_old_api_stack() + + # New API stack (RLModule, Learner, EnvRunner, ConnectorV2). + return self._training_step_new_api_stack() + + def _training_step_new_api_stack(self): + # Alternate between storing and sampling and training. + store_weight, sample_and_train_weight = calculate_rr_weights(self.config) + + # Run multiple sampling + storing to buffer iterations. + for _ in range(store_weight): + with self.metrics.log_time((TIMERS, ENV_RUNNER_SAMPLING_TIMER)): + # Sample in parallel from workers. + episodes, env_runner_results = synchronous_parallel_sample( + worker_set=self.env_runner_group, + concat=True, + sample_timeout_s=self.config.sample_timeout_s, + _uses_new_env_runners=True, + _return_metrics=True, + ) + # Reduce EnvRunner metrics over the n EnvRunners. + self.metrics.aggregate(env_runner_results, key=ENV_RUNNER_RESULTS) + + # Add the sampled experiences to the replay buffer. + with self.metrics.log_time((TIMERS, REPLAY_BUFFER_ADD_DATA_TIMER)): + self.local_replay_buffer.add(episodes) + + if self.config.count_steps_by == "agent_steps": + current_ts = sum( + self.metrics.peek( + (ENV_RUNNER_RESULTS, NUM_AGENT_STEPS_SAMPLED_LIFETIME), default={} + ).values() + ) + else: + current_ts = self.metrics.peek( + (ENV_RUNNER_RESULTS, NUM_ENV_STEPS_SAMPLED_LIFETIME), default=0 + ) + + # If enough experiences have been sampled start training. + if current_ts >= self.config.num_steps_sampled_before_learning_starts: + # Run multiple sample-from-buffer and update iterations. + for _ in range(sample_and_train_weight): + # Sample a list of episodes used for learning from the replay buffer. + with self.metrics.log_time((TIMERS, REPLAY_BUFFER_SAMPLE_TIMER)): + + episodes = self.local_replay_buffer.sample( + num_items=self.config.total_train_batch_size, + n_step=self.config.n_step, + # In case an `EpisodeReplayBuffer` is used we need to provide + # the sequence length. + batch_length_T=( + self._module_is_stateful + * self.config.model_config.get("max_seq_len", 0) + ), + lookback=int(self._module_is_stateful), + # TODO (simon): Implement `burn_in_len` in SAC and remove this + # if-else clause. + min_batch_length_T=self.config.burn_in_len + if hasattr(self.config, "burn_in_len") + else 0, + gamma=self.config.gamma, + beta=self.config.replay_buffer_config.get("beta"), + sample_episodes=True, + ) + + # Get the replay buffer metrics. + replay_buffer_results = self.local_replay_buffer.get_metrics() + self.metrics.aggregate( + [replay_buffer_results], key=REPLAY_BUFFER_RESULTS + ) + + # Perform an update on the buffer-sampled train batch. + with self.metrics.log_time((TIMERS, LEARNER_UPDATE_TIMER)): + learner_results = self.learner_group.update( + episodes=episodes, + timesteps={ + NUM_ENV_STEPS_SAMPLED_LIFETIME: ( + self.metrics.peek( + (ENV_RUNNER_RESULTS, NUM_ENV_STEPS_SAMPLED_LIFETIME) + ) + ), + NUM_AGENT_STEPS_SAMPLED_LIFETIME: ( + self.metrics.peek( + ( + ENV_RUNNER_RESULTS, + NUM_AGENT_STEPS_SAMPLED_LIFETIME, + ) + ) + ), + }, + ) + # Isolate TD-errors from result dicts (we should not log these to + # disk or WandB, they might be very large). + td_errors = defaultdict(list) + for res in learner_results: + for module_id, module_results in res.items(): + if TD_ERROR_KEY in module_results: + td_errors[module_id].extend( + convert_to_numpy( + module_results.pop(TD_ERROR_KEY).peek() + ) + ) + td_errors = { + module_id: {TD_ERROR_KEY: np.concatenate(s, axis=0)} + for module_id, s in td_errors.items() + } + self.metrics.aggregate(learner_results, key=LEARNER_RESULTS) + + # Update replay buffer priorities. + with self.metrics.log_time((TIMERS, REPLAY_BUFFER_UPDATE_PRIOS_TIMER)): + update_priorities_in_episode_replay_buffer( + replay_buffer=self.local_replay_buffer, + td_errors=td_errors, + ) + + # Update weights and global_vars - after learning on the local worker - + # on all remote workers. + with self.metrics.log_time((TIMERS, SYNCH_WORKER_WEIGHTS_TIMER)): + modules_to_update = set(learner_results[0].keys()) - {ALL_MODULES} + # NOTE: the new API stack does not use global vars. + self.env_runner_group.sync_weights( + from_worker_or_learner_group=self.learner_group, + policies=modules_to_update, + global_vars=None, + inference_only=True, + ) + + def _training_step_old_api_stack(self) -> ResultDict: + """Training step for the old API stack. + + More specifically this training step relies on `RolloutWorker`. + """ + train_results = {} + + # We alternate between storing new samples and sampling and training + store_weight, sample_and_train_weight = calculate_rr_weights(self.config) + + for _ in range(store_weight): + # Sample (MultiAgentBatch) from workers. + with self._timers[SAMPLE_TIMER]: + new_sample_batch: SampleBatchType = synchronous_parallel_sample( + worker_set=self.env_runner_group, + concat=True, + sample_timeout_s=self.config.sample_timeout_s, + ) + + # Return early if all our workers failed. + if not new_sample_batch: + return {} + + # Update counters + self._counters[NUM_AGENT_STEPS_SAMPLED] += new_sample_batch.agent_steps() + self._counters[NUM_ENV_STEPS_SAMPLED] += new_sample_batch.env_steps() + + # Store new samples in replay buffer. + self.local_replay_buffer.add(new_sample_batch) + + global_vars = { + "timestep": self._counters[NUM_ENV_STEPS_SAMPLED], + } + + # Update target network every `target_network_update_freq` sample steps. + cur_ts = self._counters[ + ( + NUM_AGENT_STEPS_SAMPLED + if self.config.count_steps_by == "agent_steps" + else NUM_ENV_STEPS_SAMPLED + ) + ] + + if cur_ts > self.config.num_steps_sampled_before_learning_starts: + for _ in range(sample_and_train_weight): + # Sample training batch (MultiAgentBatch) from replay buffer. + train_batch = sample_min_n_steps_from_buffer( + self.local_replay_buffer, + self.config.total_train_batch_size, + count_by_agent_steps=self.config.count_steps_by == "agent_steps", + ) + + # Postprocess batch before we learn on it + post_fn = self.config.get("before_learn_on_batch") or (lambda b, *a: b) + train_batch = post_fn(train_batch, self.env_runner_group, self.config) + + # Learn on training batch. + # Use simple optimizer (only for multi-agent or tf-eager; all other + # cases should use the multi-GPU optimizer, even if only using 1 GPU) + if self.config.get("simple_optimizer") is True: + train_results = train_one_step(self, train_batch) + else: + train_results = multi_gpu_train_one_step(self, train_batch) + + # Update replay buffer priorities. + update_priorities_in_replay_buffer( + self.local_replay_buffer, + self.config, + train_batch, + train_results, + ) + + last_update = self._counters[LAST_TARGET_UPDATE_TS] + if cur_ts - last_update >= self.config.target_network_update_freq: + to_update = self.env_runner.get_policies_to_train() + self.env_runner.foreach_policy_to_train( + lambda p, pid, to_update=to_update: ( + pid in to_update and p.update_target() + ) + ) + self._counters[NUM_TARGET_UPDATES] += 1 + self._counters[LAST_TARGET_UPDATE_TS] = cur_ts + + # Update weights and global_vars - after learning on the local worker - + # on all remote workers. + with self._timers[SYNCH_WORKER_WEIGHTS_TIMER]: + self.env_runner_group.sync_weights(global_vars=global_vars) + + # Return all collected metrics for the iteration. + return train_results diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/dqn_catalog.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/dqn_catalog.py new file mode 100644 index 0000000000000000000000000000000000000000..f98dc5429c3a9d61255464e60a5ad3352658d064 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/dqn_catalog.py @@ -0,0 +1,179 @@ +import gymnasium as gym + +from ray.rllib.core.models.catalog import Catalog +from ray.rllib.core.models.base import Model +from ray.rllib.core.models.configs import MLPHeadConfig +from ray.rllib.core.distribution.torch.torch_distribution import TorchCategorical +from ray.rllib.utils.annotations import ( + ExperimentalAPI, + override, + OverrideToImplementCustomLogic, +) + + +@ExperimentalAPI +class DQNCatalog(Catalog): + """The catalog class used to build models for DQN Rainbow. + + `DQNCatalog` provides the following models: + - Encoder: The encoder used to encode the observations. + - Target_Encoder: The encoder used to encode the observations + for the target network. + - Af Head: Either the head of the advantage stream, if a dueling + architecture is used or the head of the Q-function. This is + a multi-node head with `action_space.n` many nodes in case + of expectation learning and `action_space.n` times the number + of atoms (`num_atoms`) in case of distributional Q-learning. + - Vf Head (optional): The head of the value function in case a + dueling architecture is chosen. This is a single node head. + If no dueling architecture is used, this head does not exist. + + Any custom head can be built by overridng the `build_af_head()` and + `build_vf_head()`. Alternatively, the `AfHeadConfig` or `VfHeadConfig` + can be overridden to build custom logic during `RLModule` runtime. + + All heads can optionally use distributional learning. In this case the + number of output neurons corresponds to the number of actions times the + number of support atoms of the discrete distribution. + + Any module built for exploration or inference is built with the flag + `ìnference_only=True` and does not contain any target networks. This flag can + be set in a `SingleAgentModuleSpec` through the `inference_only` boolean flag. + """ + + @override(Catalog) + def __init__( + self, + observation_space: gym.Space, + action_space: gym.Space, + model_config_dict: dict, + view_requirements: dict = None, + ): + """Initializes the DQNCatalog. + + Args: + observation_space: The observation space of the Encoder. + action_space: The action space for the Af Head. + model_config_dict: The model config to use. + """ + assert view_requirements is None, ( + "Instead, use the new ConnectorV2 API to pick whatever information " + "you need from the running episodes" + ) + + super().__init__( + observation_space=observation_space, + action_space=action_space, + model_config_dict=model_config_dict, + ) + + # The number of atoms to be used for distributional Q-learning. + self.num_atoms: bool = self._model_config_dict["num_atoms"] + + # Advantage and value streams have MLP heads. Note, the advantage + # stream will has an output dimension that is the product of the + # action space dimension and the number of atoms to approximate the + # return distribution in distributional reinforcement learning. + self.af_head_config = self._get_head_config( + output_layer_dim=int(self.action_space.n * self.num_atoms) + ) + self.vf_head_config = self._get_head_config(output_layer_dim=1) + + @OverrideToImplementCustomLogic + def build_af_head(self, framework: str) -> Model: + """Build the A/Q-function head. + + Note, if no dueling architecture is chosen, this will + be the Q-function head. + + The default behavior is to build the head from the `af_head_config`. + This can be overridden to build a custom policy head as a means to + configure the behavior of a `DQNRLModule` implementation. + + Args: + framework: The framework to use. Either "torch" or "tf2". + + Returns: + The advantage head in case a dueling architecutre is chosen or + the Q-function head in the other case. + """ + return self.af_head_config.build(framework=framework) + + @OverrideToImplementCustomLogic + def build_vf_head(self, framework: str) -> Model: + """Build the value function head. + + Note, this function is only called in case of a dueling architecture. + + The default behavior is to build the head from the `vf_head_config`. + This can be overridden to build a custom policy head as a means to + configure the behavior of a `DQNRLModule` implementation. + + Args: + framework: The framework to use. Either "torch" or "tf2". + + Returns: + The value function head. + """ + + return self.vf_head_config.build(framework=framework) + + @override(Catalog) + def get_action_dist_cls(self, framework: str) -> "TorchCategorical": + # We only implement DQN Rainbow for Torch. + if framework != "torch": + raise ValueError("DQN Rainbow is only supported for framework `torch`.") + else: + return TorchCategorical + + def _get_head_config(self, output_layer_dim: int): + """Returns a head config. + + Args: + output_layer_dim: Integer defining the output layer dimension. + This is 1 for the Vf-head and `action_space.n * num_atoms` + for the Af(Qf)-head. + + Returns: + A `MLPHeadConfig`. + """ + # Return the appropriate config. + return MLPHeadConfig( + input_dims=self.latent_dims, + hidden_layer_dims=self._model_config_dict["head_fcnet_hiddens"], + # Note, `"post_fcnet_activation"` is `"relu"` by definition. + hidden_layer_activation=self._model_config_dict["head_fcnet_activation"], + # TODO (simon): Not yet available. + # hidden_layer_use_layernorm=self._model_config_dict[ + # "hidden_layer_use_layernorm" + # ], + # hidden_layer_use_bias=self._model_config_dict["hidden_layer_use_bias"], + hidden_layer_weights_initializer=self._model_config_dict[ + "head_fcnet_kernel_initializer" + ], + hidden_layer_weights_initializer_config=self._model_config_dict[ + "head_fcnet_kernel_initializer_kwargs" + ], + hidden_layer_bias_initializer=self._model_config_dict[ + "head_fcnet_bias_initializer" + ], + hidden_layer_bias_initializer_config=self._model_config_dict[ + "head_fcnet_bias_initializer_kwargs" + ], + output_layer_activation="linear", + output_layer_dim=output_layer_dim, + # TODO (simon): Not yet available. + # output_layer_use_bias=self._model_config_dict["output_layer_use_bias"], + output_layer_weights_initializer=self._model_config_dict[ + "head_fcnet_kernel_initializer" + ], + output_layer_weights_initializer_config=self._model_config_dict[ + "head_fcnet_kernel_initializer_kwargs" + ], + output_layer_bias_initializer=self._model_config_dict[ + "head_fcnet_bias_initializer" + ], + output_layer_bias_initializer_config=self._model_config_dict[ + "head_fcnet_bias_initializer_kwargs" + ], + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/dqn_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/dqn_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..b55385eaf939d1f91b7a743257d5f779bbe0cca4 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/dqn_learner.py @@ -0,0 +1,120 @@ +from typing import Any, Dict, Optional + +from ray.rllib.connectors.common.add_observations_from_episodes_to_batch import ( + AddObservationsFromEpisodesToBatch, +) +from ray.rllib.connectors.learner.add_next_observations_from_episodes_to_train_batch import ( # noqa + AddNextObservationsFromEpisodesToTrainBatch, +) +from ray.rllib.core.learner.learner import Learner +from ray.rllib.core.learner.utils import update_target_network +from ray.rllib.core.rl_module.apis import QNetAPI, TargetNetworkAPI +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.utils.annotations import ( + override, + OverrideToImplementCustomLogic_CallToSuperRecommended, +) +from ray.rllib.utils.metrics import ( + LAST_TARGET_UPDATE_TS, + NUM_ENV_STEPS_SAMPLED_LIFETIME, + NUM_TARGET_UPDATES, +) +from ray.rllib.utils.typing import ModuleID, ShouldModuleBeUpdatedFn + + +# Now, this is double defined: In `SACRLModule` and here. I would keep it here +# or push it into the `Learner` as these are recurring keys in RL. +ATOMS = "atoms" +QF_LOSS_KEY = "qf_loss" +QF_LOGITS = "qf_logits" +QF_MEAN_KEY = "qf_mean" +QF_MAX_KEY = "qf_max" +QF_MIN_KEY = "qf_min" +QF_NEXT_PREDS = "qf_next_preds" +QF_TARGET_NEXT_PREDS = "qf_target_next_preds" +QF_TARGET_NEXT_PROBS = "qf_target_next_probs" +QF_PREDS = "qf_preds" +QF_PROBS = "qf_probs" +TD_ERROR_MEAN_KEY = "td_error_mean" + + +class DQNLearner(Learner): + @OverrideToImplementCustomLogic_CallToSuperRecommended + @override(Learner) + def build(self) -> None: + super().build() + + # Make target networks. + self.module.foreach_module( + lambda mid, mod: ( + mod.make_target_networks() + if isinstance(mod, TargetNetworkAPI) + else None + ) + ) + + # Prepend the "add-NEXT_OBS-from-episodes-to-train-batch" connector piece (right + # after the corresponding "add-OBS-..." default piece). + self._learner_connector.insert_after( + AddObservationsFromEpisodesToBatch, + AddNextObservationsFromEpisodesToTrainBatch(), + ) + + @override(Learner) + def add_module( + self, + *, + module_id: ModuleID, + module_spec: RLModuleSpec, + config_overrides: Optional[Dict] = None, + new_should_module_be_updated: Optional[ShouldModuleBeUpdatedFn] = None, + ) -> MultiRLModuleSpec: + marl_spec = super().add_module( + module_id=module_id, + module_spec=module_spec, + config_overrides=config_overrides, + new_should_module_be_updated=new_should_module_be_updated, + ) + # Create target networks for added Module, if applicable. + if isinstance(self.module[module_id].unwrapped(), TargetNetworkAPI): + self.module[module_id].unwrapped().make_target_networks() + return marl_spec + + @override(Learner) + def after_gradient_based_update(self, *, timesteps: Dict[str, Any]) -> None: + """Updates the target Q Networks.""" + super().after_gradient_based_update(timesteps=timesteps) + + timestep = timesteps.get(NUM_ENV_STEPS_SAMPLED_LIFETIME, 0) + + # TODO (sven): Maybe we should have a `after_gradient_based_update` + # method per module? + for module_id, module in self.module._rl_modules.items(): + config = self.config.get_config_for_module(module_id) + last_update_ts_key = (module_id, LAST_TARGET_UPDATE_TS) + if timestep - self.metrics.peek( + last_update_ts_key, default=0 + ) >= config.target_network_update_freq and isinstance( + module.unwrapped(), TargetNetworkAPI + ): + for ( + main_net, + target_net, + ) in module.unwrapped().get_target_network_pairs(): + update_target_network( + main_net=main_net, + target_net=target_net, + tau=config.tau, + ) + # Increase lifetime target network update counter by one. + self.metrics.log_value((module_id, NUM_TARGET_UPDATES), 1, reduce="sum") + # Update the (single-value -> window=1) last updated timestep metric. + self.metrics.log_value(last_update_ts_key, timestep, window=1) + + @classmethod + @override(Learner) + def rl_module_required_apis(cls) -> list[type]: + # In order for a PPOLearner to update an RLModule, it must implement the + # following APIs: + return [QNetAPI, TargetNetworkAPI] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/dqn_tf_policy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/dqn_tf_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..4affad4b0043c50f45ffc3ae0afec10163f49cd5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/dqn_tf_policy.py @@ -0,0 +1,511 @@ +from typing import Dict + +import gymnasium as gym +import numpy as np + +import ray +from ray.rllib.algorithms.dqn.distributional_q_tf_model import DistributionalQTFModel +from ray.rllib.evaluation.postprocessing import adjust_nstep +from ray.rllib.models import ModelCatalog +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.tf.tf_action_dist import get_categorical_class_with_temperature +from ray.rllib.policy.policy import Policy +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy.tf_mixins import LearningRateSchedule, TargetNetworkMixin +from ray.rllib.policy.tf_policy_template import build_tf_policy +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.error import UnsupportedSpaceException +from ray.rllib.utils.exploration import ParameterNoise +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.tf_utils import ( + huber_loss, + l2_loss, + make_tf_callable, + minimize_and_clip, + reduce_mean_ignore_inf, +) +from ray.rllib.utils.typing import AlgorithmConfigDict, ModelGradients, TensorType + +tf1, tf, tfv = try_import_tf() + +# Importance sampling weights for prioritized replay +PRIO_WEIGHTS = "weights" +Q_SCOPE = "q_func" +Q_TARGET_SCOPE = "target_q_func" + + +@OldAPIStack +class QLoss: + def __init__( + self, + q_t_selected: TensorType, + q_logits_t_selected: TensorType, + q_tp1_best: TensorType, + q_dist_tp1_best: TensorType, + importance_weights: TensorType, + rewards: TensorType, + done_mask: TensorType, + gamma: float = 0.99, + n_step: int = 1, + num_atoms: int = 1, + v_min: float = -10.0, + v_max: float = 10.0, + loss_fn=huber_loss, + ): + + if num_atoms > 1: + # Distributional Q-learning which corresponds to an entropy loss + + z = tf.range(num_atoms, dtype=tf.float32) + z = v_min + z * (v_max - v_min) / float(num_atoms - 1) + + # (batch_size, 1) * (1, num_atoms) = (batch_size, num_atoms) + r_tau = tf.expand_dims(rewards, -1) + gamma**n_step * tf.expand_dims( + 1.0 - done_mask, -1 + ) * tf.expand_dims(z, 0) + r_tau = tf.clip_by_value(r_tau, v_min, v_max) + b = (r_tau - v_min) / ((v_max - v_min) / float(num_atoms - 1)) + lb = tf.floor(b) + ub = tf.math.ceil(b) + # indispensable judgement which is missed in most implementations + # when b happens to be an integer, lb == ub, so pr_j(s', a*) will + # be discarded because (ub-b) == (b-lb) == 0 + floor_equal_ceil = tf.cast(tf.less(ub - lb, 0.5), tf.float32) + + l_project = tf.one_hot( + tf.cast(lb, dtype=tf.int32), num_atoms + ) # (batch_size, num_atoms, num_atoms) + u_project = tf.one_hot( + tf.cast(ub, dtype=tf.int32), num_atoms + ) # (batch_size, num_atoms, num_atoms) + ml_delta = q_dist_tp1_best * (ub - b + floor_equal_ceil) + mu_delta = q_dist_tp1_best * (b - lb) + ml_delta = tf.reduce_sum(l_project * tf.expand_dims(ml_delta, -1), axis=1) + mu_delta = tf.reduce_sum(u_project * tf.expand_dims(mu_delta, -1), axis=1) + m = ml_delta + mu_delta + + # Rainbow paper claims that using this cross entropy loss for + # priority is robust and insensitive to `prioritized_replay_alpha` + self.td_error = tf.nn.softmax_cross_entropy_with_logits( + labels=m, logits=q_logits_t_selected + ) + self.loss = tf.reduce_mean( + self.td_error * tf.cast(importance_weights, tf.float32) + ) + self.stats = { + # TODO: better Q stats for dist dqn + "mean_td_error": tf.reduce_mean(self.td_error), + } + else: + q_tp1_best_masked = (1.0 - done_mask) * q_tp1_best + + # compute RHS of bellman equation + q_t_selected_target = rewards + gamma**n_step * q_tp1_best_masked + + # compute the error (potentially clipped) + self.td_error = q_t_selected - tf.stop_gradient(q_t_selected_target) + self.loss = tf.reduce_mean( + tf.cast(importance_weights, tf.float32) * loss_fn(self.td_error) + ) + self.stats = { + "mean_q": tf.reduce_mean(q_t_selected), + "min_q": tf.reduce_min(q_t_selected), + "max_q": tf.reduce_max(q_t_selected), + "mean_td_error": tf.reduce_mean(self.td_error), + } + + +@OldAPIStack +class ComputeTDErrorMixin: + """Assign the `compute_td_error` method to the DQNTFPolicy + + This allows us to prioritize on the worker side. + """ + + def __init__(self): + @make_tf_callable(self.get_session(), dynamic_shape=True) + def compute_td_error( + obs_t, act_t, rew_t, obs_tp1, terminateds_mask, importance_weights + ): + # Do forward pass on loss to update td error attribute + build_q_losses( + self, + self.model, + None, + { + SampleBatch.CUR_OBS: tf.convert_to_tensor(obs_t), + SampleBatch.ACTIONS: tf.convert_to_tensor(act_t), + SampleBatch.REWARDS: tf.convert_to_tensor(rew_t), + SampleBatch.NEXT_OBS: tf.convert_to_tensor(obs_tp1), + SampleBatch.TERMINATEDS: tf.convert_to_tensor(terminateds_mask), + PRIO_WEIGHTS: tf.convert_to_tensor(importance_weights), + }, + ) + + return self.q_loss.td_error + + self.compute_td_error = compute_td_error + + +@OldAPIStack +def build_q_model( + policy: Policy, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + config: AlgorithmConfigDict, +) -> ModelV2: + """Build q_model and target_model for DQN + + Args: + policy: The Policy, which will use the model for optimization. + obs_space (gym.spaces.Space): The policy's observation space. + action_space (gym.spaces.Space): The policy's action space. + config (AlgorithmConfigDict): + + Returns: + ModelV2: The Model for the Policy to use. + Note: The target q model will not be returned, just assigned to + `policy.target_model`. + """ + if not isinstance(action_space, gym.spaces.Discrete): + raise UnsupportedSpaceException( + "Action space {} is not supported for DQN.".format(action_space) + ) + + if config["hiddens"]: + # try to infer the last layer size, otherwise fall back to 256 + num_outputs = ([256] + list(config["model"]["fcnet_hiddens"]))[-1] + config["model"]["no_final_linear"] = True + else: + num_outputs = action_space.n + + q_model = ModelCatalog.get_model_v2( + obs_space=obs_space, + action_space=action_space, + num_outputs=num_outputs, + model_config=config["model"], + framework="tf", + model_interface=DistributionalQTFModel, + name=Q_SCOPE, + num_atoms=config["num_atoms"], + dueling=config["dueling"], + q_hiddens=config["hiddens"], + use_noisy=config["noisy"], + v_min=config["v_min"], + v_max=config["v_max"], + sigma0=config["sigma0"], + # TODO(sven): Move option to add LayerNorm after each Dense + # generically into ModelCatalog. + add_layer_norm=isinstance(getattr(policy, "exploration", None), ParameterNoise) + or config["exploration_config"]["type"] == "ParameterNoise", + ) + + policy.target_model = ModelCatalog.get_model_v2( + obs_space=obs_space, + action_space=action_space, + num_outputs=num_outputs, + model_config=config["model"], + framework="tf", + model_interface=DistributionalQTFModel, + name=Q_TARGET_SCOPE, + num_atoms=config["num_atoms"], + dueling=config["dueling"], + q_hiddens=config["hiddens"], + use_noisy=config["noisy"], + v_min=config["v_min"], + v_max=config["v_max"], + sigma0=config["sigma0"], + # TODO(sven): Move option to add LayerNorm after each Dense + # generically into ModelCatalog. + add_layer_norm=isinstance(getattr(policy, "exploration", None), ParameterNoise) + or config["exploration_config"]["type"] == "ParameterNoise", + ) + + return q_model + + +@OldAPIStack +def get_distribution_inputs_and_class( + policy: Policy, model: ModelV2, input_dict: SampleBatch, *, explore=True, **kwargs +): + q_vals = compute_q_values( + policy, model, input_dict, state_batches=None, explore=explore + ) + q_vals = q_vals[0] if isinstance(q_vals, tuple) else q_vals + + policy.q_values = q_vals + + # Return a Torch TorchCategorical distribution where the temperature + # parameter is partially binded to the configured value. + temperature = policy.config["categorical_distribution_temperature"] + + return ( + policy.q_values, + get_categorical_class_with_temperature(temperature), + [], + ) # state-out + + +@OldAPIStack +def build_q_losses(policy: Policy, model, _, train_batch: SampleBatch) -> TensorType: + """Constructs the loss for DQNTFPolicy. + + Args: + policy: The Policy to calculate the loss for. + model (ModelV2): The Model to calculate the loss for. + train_batch: The training data. + + Returns: + TensorType: A single loss tensor. + """ + config = policy.config + # q network evaluation + q_t, q_logits_t, q_dist_t, _ = compute_q_values( + policy, + model, + SampleBatch({"obs": train_batch[SampleBatch.CUR_OBS]}), + state_batches=None, + explore=False, + ) + + # target q network evalution + q_tp1, q_logits_tp1, q_dist_tp1, _ = compute_q_values( + policy, + policy.target_model, + SampleBatch({"obs": train_batch[SampleBatch.NEXT_OBS]}), + state_batches=None, + explore=False, + ) + if not hasattr(policy, "target_q_func_vars"): + policy.target_q_func_vars = policy.target_model.variables() + + # q scores for actions which we know were selected in the given state. + one_hot_selection = tf.one_hot( + tf.cast(train_batch[SampleBatch.ACTIONS], tf.int32), policy.action_space.n + ) + q_t_selected = tf.reduce_sum(q_t * one_hot_selection, 1) + q_logits_t_selected = tf.reduce_sum( + q_logits_t * tf.expand_dims(one_hot_selection, -1), 1 + ) + + # compute estimate of best possible value starting from state at t + 1 + if config["double_q"]: + ( + q_tp1_using_online_net, + q_logits_tp1_using_online_net, + q_dist_tp1_using_online_net, + _, + ) = compute_q_values( + policy, + model, + SampleBatch({"obs": train_batch[SampleBatch.NEXT_OBS]}), + state_batches=None, + explore=False, + ) + q_tp1_best_using_online_net = tf.argmax(q_tp1_using_online_net, 1) + q_tp1_best_one_hot_selection = tf.one_hot( + q_tp1_best_using_online_net, policy.action_space.n + ) + q_tp1_best = tf.reduce_sum(q_tp1 * q_tp1_best_one_hot_selection, 1) + q_dist_tp1_best = tf.reduce_sum( + q_dist_tp1 * tf.expand_dims(q_tp1_best_one_hot_selection, -1), 1 + ) + else: + q_tp1_best_one_hot_selection = tf.one_hot( + tf.argmax(q_tp1, 1), policy.action_space.n + ) + q_tp1_best = tf.reduce_sum(q_tp1 * q_tp1_best_one_hot_selection, 1) + q_dist_tp1_best = tf.reduce_sum( + q_dist_tp1 * tf.expand_dims(q_tp1_best_one_hot_selection, -1), 1 + ) + + loss_fn = huber_loss if policy.config["td_error_loss_fn"] == "huber" else l2_loss + + policy.q_loss = QLoss( + q_t_selected, + q_logits_t_selected, + q_tp1_best, + q_dist_tp1_best, + train_batch[PRIO_WEIGHTS], + tf.cast(train_batch[SampleBatch.REWARDS], tf.float32), + tf.cast(train_batch[SampleBatch.TERMINATEDS], tf.float32), + config["gamma"], + config["n_step"], + config["num_atoms"], + config["v_min"], + config["v_max"], + loss_fn, + ) + + return policy.q_loss.loss + + +@OldAPIStack +def adam_optimizer( + policy: Policy, config: AlgorithmConfigDict +) -> "tf.keras.optimizers.Optimizer": + if policy.config["framework"] == "tf2": + return tf.keras.optimizers.Adam( + learning_rate=policy.cur_lr, epsilon=config["adam_epsilon"] + ) + else: + return tf1.train.AdamOptimizer( + learning_rate=policy.cur_lr, epsilon=config["adam_epsilon"] + ) + + +@OldAPIStack +def clip_gradients( + policy: Policy, optimizer: "tf.keras.optimizers.Optimizer", loss: TensorType +) -> ModelGradients: + if not hasattr(policy, "q_func_vars"): + policy.q_func_vars = policy.model.variables() + + return minimize_and_clip( + optimizer, + loss, + var_list=policy.q_func_vars, + clip_val=policy.config["grad_clip"], + ) + + +@OldAPIStack +def build_q_stats(policy: Policy, batch) -> Dict[str, TensorType]: + return dict( + { + "cur_lr": tf.cast(policy.cur_lr, tf.float64), + }, + **policy.q_loss.stats + ) + + +@OldAPIStack +def setup_mid_mixins(policy: Policy, obs_space, action_space, config) -> None: + LearningRateSchedule.__init__(policy, config["lr"], config["lr_schedule"]) + ComputeTDErrorMixin.__init__(policy) + + +@OldAPIStack +def setup_late_mixins( + policy: Policy, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + config: AlgorithmConfigDict, +) -> None: + TargetNetworkMixin.__init__(policy) + + +@OldAPIStack +def compute_q_values( + policy: Policy, + model: ModelV2, + input_batch: SampleBatch, + state_batches=None, + seq_lens=None, + explore=None, + is_training: bool = False, +): + + config = policy.config + + model_out, state = model(input_batch, state_batches or [], seq_lens) + + if config["num_atoms"] > 1: + ( + action_scores, + z, + support_logits_per_action, + logits, + dist, + ) = model.get_q_value_distributions(model_out) + else: + (action_scores, logits, dist) = model.get_q_value_distributions(model_out) + + if config["dueling"]: + state_score = model.get_state_value(model_out) + if config["num_atoms"] > 1: + support_logits_per_action_mean = tf.reduce_mean( + support_logits_per_action, 1 + ) + support_logits_per_action_centered = ( + support_logits_per_action + - tf.expand_dims(support_logits_per_action_mean, 1) + ) + support_logits_per_action = ( + tf.expand_dims(state_score, 1) + support_logits_per_action_centered + ) + support_prob_per_action = tf.nn.softmax(logits=support_logits_per_action) + value = tf.reduce_sum(input_tensor=z * support_prob_per_action, axis=-1) + logits = support_logits_per_action + dist = support_prob_per_action + else: + action_scores_mean = reduce_mean_ignore_inf(action_scores, 1) + action_scores_centered = action_scores - tf.expand_dims( + action_scores_mean, 1 + ) + value = state_score + action_scores_centered + else: + value = action_scores + + return value, logits, dist, state + + +@OldAPIStack +def postprocess_nstep_and_prio( + policy: Policy, batch: SampleBatch, other_agent=None, episode=None +) -> SampleBatch: + # N-step Q adjustments. + if policy.config["n_step"] > 1: + adjust_nstep(policy.config["n_step"], policy.config["gamma"], batch) + + # Create dummy prio-weights (1.0) in case we don't have any in + # the batch. + if PRIO_WEIGHTS not in batch: + batch[PRIO_WEIGHTS] = np.ones_like(batch[SampleBatch.REWARDS]) + + # Prioritize on the worker side. + if batch.count > 0 and policy.config["replay_buffer_config"].get( + "worker_side_prioritization", False + ): + td_errors = policy.compute_td_error( + batch[SampleBatch.OBS], + batch[SampleBatch.ACTIONS], + batch[SampleBatch.REWARDS], + batch[SampleBatch.NEXT_OBS], + batch[SampleBatch.TERMINATEDS], + batch[PRIO_WEIGHTS], + ) + # Retain compatibility with old-style Replay args + epsilon = policy.config.get("replay_buffer_config", {}).get( + "prioritized_replay_eps" + ) or policy.config.get("prioritized_replay_eps") + if epsilon is None: + raise ValueError("prioritized_replay_eps not defined in config.") + + new_priorities = np.abs(convert_to_numpy(td_errors)) + epsilon + batch[PRIO_WEIGHTS] = new_priorities + + return batch + + +DQNTFPolicy = build_tf_policy( + name="DQNTFPolicy", + get_default_config=lambda: ray.rllib.algorithms.dqn.dqn.DQNConfig(), + make_model=build_q_model, + action_distribution_fn=get_distribution_inputs_and_class, + loss_fn=build_q_losses, + stats_fn=build_q_stats, + postprocess_fn=postprocess_nstep_and_prio, + optimizer_fn=adam_optimizer, + compute_gradients_fn=clip_gradients, + extra_action_out_fn=lambda policy: {"q_values": policy.q_values}, + extra_learn_fetches_fn=lambda policy: {"td_error": policy.q_loss.td_error}, + before_loss_init=setup_mid_mixins, + after_init=setup_late_mixins, + mixins=[ + TargetNetworkMixin, + ComputeTDErrorMixin, + LearningRateSchedule, + ], +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/dqn_torch_model.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/dqn_torch_model.py new file mode 100644 index 0000000000000000000000000000000000000000..03c109878f73d8b901da3080650473a2cb82ad56 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/dqn_torch_model.py @@ -0,0 +1,175 @@ +"""PyTorch model for DQN""" + +from typing import Sequence +import gymnasium as gym +from ray.rllib.models.torch.misc import SlimFC +from ray.rllib.models.torch.modules.noisy_layer import NoisyLayer +from ray.rllib.models.torch.torch_modelv2 import TorchModelV2 +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.typing import ModelConfigDict + +torch, nn = try_import_torch() + + +@OldAPIStack +class DQNTorchModel(TorchModelV2, nn.Module): + """Extension of standard TorchModelV2 to provide dueling-Q functionality.""" + + def __init__( + self, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + num_outputs: int, + model_config: ModelConfigDict, + name: str, + *, + q_hiddens: Sequence[int] = (256,), + dueling: bool = False, + dueling_activation: str = "relu", + num_atoms: int = 1, + use_noisy: bool = False, + v_min: float = -10.0, + v_max: float = 10.0, + sigma0: float = 0.5, + # TODO(sven): Move `add_layer_norm` into ModelCatalog as + # generic option, then error if we use ParameterNoise as + # Exploration type and do not have any LayerNorm layers in + # the net. + add_layer_norm: bool = False + ): + """Initialize variables of this model. + + Extra model kwargs: + q_hiddens (Sequence[int]): List of layer-sizes after(!) the + Advantages(A)/Value(V)-split. Hence, each of the A- and V- + branches will have this structure of Dense layers. To define + the NN before this A/V-split, use - as always - + config["model"]["fcnet_hiddens"]. + dueling: Whether to build the advantage(A)/value(V) heads + for DDQN. If True, Q-values are calculated as: + Q = (A - mean[A]) + V. If False, raw NN output is interpreted + as Q-values. + dueling_activation: The activation to use for all dueling + layers (A- and V-branch). One of "relu", "tanh", "linear". + num_atoms: If >1, enables distributional DQN. + use_noisy: Use noisy layers. + v_min: Min value support for distributional DQN. + v_max: Max value support for distributional DQN. + sigma0 (float): Initial value of noisy layers. + add_layer_norm: Enable layer norm (for param noise). + """ + nn.Module.__init__(self) + super(DQNTorchModel, self).__init__( + obs_space, action_space, num_outputs, model_config, name + ) + + self.dueling = dueling + self.num_atoms = num_atoms + self.v_min = v_min + self.v_max = v_max + self.sigma0 = sigma0 + ins = num_outputs + + advantage_module = nn.Sequential() + value_module = nn.Sequential() + + # Dueling case: Build the shared (advantages and value) fc-network. + for i, n in enumerate(q_hiddens): + if use_noisy: + advantage_module.add_module( + "dueling_A_{}".format(i), + NoisyLayer( + ins, n, sigma0=self.sigma0, activation=dueling_activation + ), + ) + value_module.add_module( + "dueling_V_{}".format(i), + NoisyLayer( + ins, n, sigma0=self.sigma0, activation=dueling_activation + ), + ) + else: + advantage_module.add_module( + "dueling_A_{}".format(i), + SlimFC(ins, n, activation_fn=dueling_activation), + ) + value_module.add_module( + "dueling_V_{}".format(i), + SlimFC(ins, n, activation_fn=dueling_activation), + ) + # Add LayerNorm after each Dense. + if add_layer_norm: + advantage_module.add_module( + "LayerNorm_A_{}".format(i), nn.LayerNorm(n) + ) + value_module.add_module("LayerNorm_V_{}".format(i), nn.LayerNorm(n)) + ins = n + + # Actual Advantages layer (nodes=num-actions). + if use_noisy: + advantage_module.add_module( + "A", + NoisyLayer( + ins, self.action_space.n * self.num_atoms, sigma0, activation=None + ), + ) + elif q_hiddens: + advantage_module.add_module( + "A", SlimFC(ins, action_space.n * self.num_atoms, activation_fn=None) + ) + + self.advantage_module = advantage_module + + # Value layer (nodes=1). + if self.dueling: + if use_noisy: + value_module.add_module( + "V", NoisyLayer(ins, self.num_atoms, sigma0, activation=None) + ) + elif q_hiddens: + value_module.add_module( + "V", SlimFC(ins, self.num_atoms, activation_fn=None) + ) + self.value_module = value_module + + def get_q_value_distributions(self, model_out): + """Returns distributional values for Q(s, a) given a state embedding. + + Override this in your custom model to customize the Q output head. + + Args: + model_out: Embedding from the model layers. + + Returns: + (action_scores, logits, dist) if num_atoms == 1, otherwise + (action_scores, z, support_logits_per_action, logits, dist) + """ + action_scores = self.advantage_module(model_out) + + if self.num_atoms > 1: + # Distributional Q-learning uses a discrete support z + # to represent the action value distribution + z = torch.arange(0.0, self.num_atoms, dtype=torch.float32).to( + action_scores.device + ) + z = self.v_min + z * (self.v_max - self.v_min) / float(self.num_atoms - 1) + + support_logits_per_action = torch.reshape( + action_scores, shape=(-1, self.action_space.n, self.num_atoms) + ) + support_prob_per_action = nn.functional.softmax( + support_logits_per_action, dim=-1 + ) + action_scores = torch.sum(z * support_prob_per_action, dim=-1) + logits = support_logits_per_action + probs = support_prob_per_action + return action_scores, z, support_logits_per_action, logits, probs + else: + logits = torch.unsqueeze(torch.ones_like(action_scores), -1) + return action_scores, logits, logits + + def get_state_value(self, model_out): + """Returns the state value prediction for the given state embedding.""" + + return self.value_module(model_out) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/dqn_torch_policy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/dqn_torch_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..3229e379c730ab0273df9184a21127932043c6ff --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/dqn_torch_policy.py @@ -0,0 +1,518 @@ +"""PyTorch policy class used for DQN""" + +from typing import Dict, List, Tuple + +import gymnasium as gym +import ray +from ray.rllib.algorithms.dqn.dqn_tf_policy import ( + PRIO_WEIGHTS, + Q_SCOPE, + Q_TARGET_SCOPE, + postprocess_nstep_and_prio, +) +from ray.rllib.algorithms.dqn.dqn_torch_model import DQNTorchModel +from ray.rllib.models.catalog import ModelCatalog +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.torch.torch_action_dist import ( + get_torch_categorical_class_with_temperature, + TorchDistributionWrapper, +) +from ray.rllib.policy.policy import Policy +from ray.rllib.policy.policy_template import build_policy_class +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy.torch_mixins import ( + LearningRateSchedule, + TargetNetworkMixin, +) +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.error import UnsupportedSpaceException +from ray.rllib.utils.exploration.parameter_noise import ParameterNoise +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.torch_utils import ( + apply_grad_clipping, + concat_multi_gpu_td_errors, + FLOAT_MIN, + huber_loss, + l2_loss, + reduce_mean_ignore_inf, + softmax_cross_entropy_with_logits, +) +from ray.rllib.utils.typing import TensorType, AlgorithmConfigDict + +torch, nn = try_import_torch() +F = None +if nn: + F = nn.functional + + +@OldAPIStack +class QLoss: + def __init__( + self, + q_t_selected: TensorType, + q_logits_t_selected: TensorType, + q_tp1_best: TensorType, + q_probs_tp1_best: TensorType, + importance_weights: TensorType, + rewards: TensorType, + done_mask: TensorType, + gamma=0.99, + n_step=1, + num_atoms=1, + v_min=-10.0, + v_max=10.0, + loss_fn=huber_loss, + ): + + if num_atoms > 1: + # Distributional Q-learning which corresponds to an entropy loss + z = torch.arange(0.0, num_atoms, dtype=torch.float32).to(rewards.device) + z = v_min + z * (v_max - v_min) / float(num_atoms - 1) + + # (batch_size, 1) * (1, num_atoms) = (batch_size, num_atoms) + r_tau = torch.unsqueeze(rewards, -1) + gamma**n_step * torch.unsqueeze( + 1.0 - done_mask, -1 + ) * torch.unsqueeze(z, 0) + r_tau = torch.clamp(r_tau, v_min, v_max) + b = (r_tau - v_min) / ((v_max - v_min) / float(num_atoms - 1)) + lb = torch.floor(b) + ub = torch.ceil(b) + + # Indispensable judgement which is missed in most implementations + # when b happens to be an integer, lb == ub, so pr_j(s', a*) will + # be discarded because (ub-b) == (b-lb) == 0. + floor_equal_ceil = ((ub - lb) < 0.5).float() + + # (batch_size, num_atoms, num_atoms) + l_project = F.one_hot(lb.long(), num_atoms) + # (batch_size, num_atoms, num_atoms) + u_project = F.one_hot(ub.long(), num_atoms) + ml_delta = q_probs_tp1_best * (ub - b + floor_equal_ceil) + mu_delta = q_probs_tp1_best * (b - lb) + ml_delta = torch.sum(l_project * torch.unsqueeze(ml_delta, -1), dim=1) + mu_delta = torch.sum(u_project * torch.unsqueeze(mu_delta, -1), dim=1) + m = ml_delta + mu_delta + + # Rainbow paper claims that using this cross entropy loss for + # priority is robust and insensitive to `prioritized_replay_alpha` + self.td_error = softmax_cross_entropy_with_logits( + logits=q_logits_t_selected, labels=m.detach() + ) + self.loss = torch.mean(self.td_error * importance_weights) + self.stats = { + # TODO: better Q stats for dist dqn + } + else: + q_tp1_best_masked = (1.0 - done_mask) * q_tp1_best + + # compute RHS of bellman equation + q_t_selected_target = rewards + gamma**n_step * q_tp1_best_masked + + # compute the error (potentially clipped) + self.td_error = q_t_selected - q_t_selected_target.detach() + self.loss = torch.mean(importance_weights.float() * loss_fn(self.td_error)) + self.stats = { + "mean_q": torch.mean(q_t_selected), + "min_q": torch.min(q_t_selected), + "max_q": torch.max(q_t_selected), + } + + +@OldAPIStack +class ComputeTDErrorMixin: + """Assign the `compute_td_error` method to the DQNTorchPolicy + + This allows us to prioritize on the worker side. + """ + + def __init__(self): + def compute_td_error( + obs_t, act_t, rew_t, obs_tp1, terminateds_mask, importance_weights + ): + input_dict = self._lazy_tensor_dict({SampleBatch.CUR_OBS: obs_t}) + input_dict[SampleBatch.ACTIONS] = act_t + input_dict[SampleBatch.REWARDS] = rew_t + input_dict[SampleBatch.NEXT_OBS] = obs_tp1 + input_dict[SampleBatch.TERMINATEDS] = terminateds_mask + input_dict[PRIO_WEIGHTS] = importance_weights + + # Do forward pass on loss to update td error attribute + build_q_losses(self, self.model, None, input_dict) + + return self.model.tower_stats["q_loss"].td_error + + self.compute_td_error = compute_td_error + + +@OldAPIStack +def build_q_model_and_distribution( + policy: Policy, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + config: AlgorithmConfigDict, +) -> Tuple[ModelV2, TorchDistributionWrapper]: + """Build q_model and target_model for DQN + + Args: + policy: The policy, which will use the model for optimization. + obs_space (gym.spaces.Space): The policy's observation space. + action_space (gym.spaces.Space): The policy's action space. + config (AlgorithmConfigDict): + + Returns: + (q_model, TorchCategorical) + Note: The target q model will not be returned, just assigned to + `policy.target_model`. + """ + if not isinstance(action_space, gym.spaces.Discrete): + raise UnsupportedSpaceException( + "Action space {} is not supported for DQN.".format(action_space) + ) + + if config["hiddens"]: + # try to infer the last layer size, otherwise fall back to 256 + num_outputs = ([256] + list(config["model"]["fcnet_hiddens"]))[-1] + config["model"]["no_final_linear"] = True + else: + num_outputs = action_space.n + + # TODO(sven): Move option to add LayerNorm after each Dense + # generically into ModelCatalog. + add_layer_norm = ( + isinstance(getattr(policy, "exploration", None), ParameterNoise) + or config["exploration_config"]["type"] == "ParameterNoise" + ) + + model = ModelCatalog.get_model_v2( + obs_space=obs_space, + action_space=action_space, + num_outputs=num_outputs, + model_config=config["model"], + framework="torch", + model_interface=DQNTorchModel, + name=Q_SCOPE, + q_hiddens=config["hiddens"], + dueling=config["dueling"], + num_atoms=config["num_atoms"], + use_noisy=config["noisy"], + v_min=config["v_min"], + v_max=config["v_max"], + sigma0=config["sigma0"], + # TODO(sven): Move option to add LayerNorm after each Dense + # generically into ModelCatalog. + add_layer_norm=add_layer_norm, + ) + + policy.target_model = ModelCatalog.get_model_v2( + obs_space=obs_space, + action_space=action_space, + num_outputs=num_outputs, + model_config=config["model"], + framework="torch", + model_interface=DQNTorchModel, + name=Q_TARGET_SCOPE, + q_hiddens=config["hiddens"], + dueling=config["dueling"], + num_atoms=config["num_atoms"], + use_noisy=config["noisy"], + v_min=config["v_min"], + v_max=config["v_max"], + sigma0=config["sigma0"], + # TODO(sven): Move option to add LayerNorm after each Dense + # generically into ModelCatalog. + add_layer_norm=add_layer_norm, + ) + + # Return a Torch TorchCategorical distribution where the temperature + # parameter is partially binded to the configured value. + temperature = config["categorical_distribution_temperature"] + + return model, get_torch_categorical_class_with_temperature(temperature) + + +@OldAPIStack +def get_distribution_inputs_and_class( + policy: Policy, + model: ModelV2, + input_dict: SampleBatch, + *, + explore: bool = True, + is_training: bool = False, + **kwargs +) -> Tuple[TensorType, type, List[TensorType]]: + q_vals = compute_q_values( + policy, model, input_dict, explore=explore, is_training=is_training + ) + q_vals = q_vals[0] if isinstance(q_vals, tuple) else q_vals + + model.tower_stats["q_values"] = q_vals + + # Return a Torch TorchCategorical distribution where the temperature + # parameter is partially binded to the configured value. + temperature = policy.config["categorical_distribution_temperature"] + + return ( + q_vals, + get_torch_categorical_class_with_temperature(temperature), + [], # state-out + ) + + +@OldAPIStack +def build_q_losses(policy: Policy, model, _, train_batch: SampleBatch) -> TensorType: + """Constructs the loss for DQNTorchPolicy. + + Args: + policy: The Policy to calculate the loss for. + model (ModelV2): The Model to calculate the loss for. + train_batch: The training data. + + Returns: + TensorType: A single loss tensor. + """ + + config = policy.config + # Q-network evaluation. + q_t, q_logits_t, q_probs_t, _ = compute_q_values( + policy, + model, + {"obs": train_batch[SampleBatch.CUR_OBS]}, + explore=False, + is_training=True, + ) + + # Target Q-network evaluation. + q_tp1, q_logits_tp1, q_probs_tp1, _ = compute_q_values( + policy, + policy.target_models[model], + {"obs": train_batch[SampleBatch.NEXT_OBS]}, + explore=False, + is_training=True, + ) + + # Q scores for actions which we know were selected in the given state. + one_hot_selection = F.one_hot( + train_batch[SampleBatch.ACTIONS].long(), policy.action_space.n + ) + q_t_selected = torch.sum( + torch.where(q_t > FLOAT_MIN, q_t, torch.tensor(0.0, device=q_t.device)) + * one_hot_selection, + 1, + ) + q_logits_t_selected = torch.sum( + q_logits_t * torch.unsqueeze(one_hot_selection, -1), 1 + ) + + # compute estimate of best possible value starting from state at t + 1 + if config["double_q"]: + ( + q_tp1_using_online_net, + q_logits_tp1_using_online_net, + q_dist_tp1_using_online_net, + _, + ) = compute_q_values( + policy, + model, + {"obs": train_batch[SampleBatch.NEXT_OBS]}, + explore=False, + is_training=True, + ) + q_tp1_best_using_online_net = torch.argmax(q_tp1_using_online_net, 1) + q_tp1_best_one_hot_selection = F.one_hot( + q_tp1_best_using_online_net, policy.action_space.n + ) + q_tp1_best = torch.sum( + torch.where( + q_tp1 > FLOAT_MIN, q_tp1, torch.tensor(0.0, device=q_tp1.device) + ) + * q_tp1_best_one_hot_selection, + 1, + ) + q_probs_tp1_best = torch.sum( + q_probs_tp1 * torch.unsqueeze(q_tp1_best_one_hot_selection, -1), 1 + ) + else: + q_tp1_best_one_hot_selection = F.one_hot( + torch.argmax(q_tp1, 1), policy.action_space.n + ) + q_tp1_best = torch.sum( + torch.where( + q_tp1 > FLOAT_MIN, q_tp1, torch.tensor(0.0, device=q_tp1.device) + ) + * q_tp1_best_one_hot_selection, + 1, + ) + q_probs_tp1_best = torch.sum( + q_probs_tp1 * torch.unsqueeze(q_tp1_best_one_hot_selection, -1), 1 + ) + + loss_fn = huber_loss if policy.config["td_error_loss_fn"] == "huber" else l2_loss + + q_loss = QLoss( + q_t_selected, + q_logits_t_selected, + q_tp1_best, + q_probs_tp1_best, + train_batch[PRIO_WEIGHTS], + train_batch[SampleBatch.REWARDS], + train_batch[SampleBatch.TERMINATEDS].float(), + config["gamma"], + config["n_step"], + config["num_atoms"], + config["v_min"], + config["v_max"], + loss_fn, + ) + + # Store values for stats function in model (tower), such that for + # multi-GPU, we do not override them during the parallel loss phase. + model.tower_stats["td_error"] = q_loss.td_error + # TD-error tensor in final stats + # will be concatenated and retrieved for each individual batch item. + model.tower_stats["q_loss"] = q_loss + + return q_loss.loss + + +@OldAPIStack +def adam_optimizer( + policy: Policy, config: AlgorithmConfigDict +) -> "torch.optim.Optimizer": + + # By this time, the models have been moved to the GPU - if any - and we + # can define our optimizers using the correct CUDA variables. + if not hasattr(policy, "q_func_vars"): + policy.q_func_vars = policy.model.variables() + + return torch.optim.Adam( + policy.q_func_vars, lr=policy.cur_lr, eps=config["adam_epsilon"] + ) + + +@OldAPIStack +def build_q_stats(policy: Policy, batch) -> Dict[str, TensorType]: + stats = {} + for stats_key in policy.model_gpu_towers[0].tower_stats["q_loss"].stats.keys(): + stats[stats_key] = torch.mean( + torch.stack( + [ + t.tower_stats["q_loss"].stats[stats_key].to(policy.device) + for t in policy.model_gpu_towers + if "q_loss" in t.tower_stats + ] + ) + ) + stats["cur_lr"] = policy.cur_lr + return stats + + +@OldAPIStack +def setup_early_mixins( + policy: Policy, obs_space, action_space, config: AlgorithmConfigDict +) -> None: + LearningRateSchedule.__init__(policy, config["lr"], config["lr_schedule"]) + + +@OldAPIStack +def before_loss_init( + policy: Policy, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + config: AlgorithmConfigDict, +) -> None: + ComputeTDErrorMixin.__init__(policy) + TargetNetworkMixin.__init__(policy) + + +@OldAPIStack +def compute_q_values( + policy: Policy, + model: ModelV2, + input_dict, + state_batches=None, + seq_lens=None, + explore=None, + is_training: bool = False, +): + config = policy.config + + model_out, state = model(input_dict, state_batches or [], seq_lens) + + if config["num_atoms"] > 1: + ( + action_scores, + z, + support_logits_per_action, + logits, + probs_or_logits, + ) = model.get_q_value_distributions(model_out) + else: + (action_scores, logits, probs_or_logits) = model.get_q_value_distributions( + model_out + ) + + if config["dueling"]: + state_score = model.get_state_value(model_out) + if policy.config["num_atoms"] > 1: + support_logits_per_action_mean = torch.mean( + support_logits_per_action, dim=1 + ) + support_logits_per_action_centered = ( + support_logits_per_action + - torch.unsqueeze(support_logits_per_action_mean, dim=1) + ) + support_logits_per_action = ( + torch.unsqueeze(state_score, dim=1) + support_logits_per_action_centered + ) + support_prob_per_action = nn.functional.softmax( + support_logits_per_action, dim=-1 + ) + value = torch.sum(z * support_prob_per_action, dim=-1) + logits = support_logits_per_action + probs_or_logits = support_prob_per_action + else: + advantages_mean = reduce_mean_ignore_inf(action_scores, 1) + advantages_centered = action_scores - torch.unsqueeze(advantages_mean, 1) + value = state_score + advantages_centered + else: + value = action_scores + + return value, logits, probs_or_logits, state + + +@OldAPIStack +def grad_process_and_td_error_fn( + policy: Policy, optimizer: "torch.optim.Optimizer", loss: TensorType +) -> Dict[str, TensorType]: + # Clip grads if configured. + return apply_grad_clipping(policy, optimizer, loss) + + +@OldAPIStack +def extra_action_out_fn( + policy: Policy, input_dict, state_batches, model, action_dist +) -> Dict[str, TensorType]: + return {"q_values": model.tower_stats["q_values"]} + + +DQNTorchPolicy = build_policy_class( + name="DQNTorchPolicy", + framework="torch", + loss_fn=build_q_losses, + get_default_config=lambda: ray.rllib.algorithms.dqn.dqn.DQNConfig(), + make_model_and_action_dist=build_q_model_and_distribution, + action_distribution_fn=get_distribution_inputs_and_class, + stats_fn=build_q_stats, + postprocess_fn=postprocess_nstep_and_prio, + optimizer_fn=adam_optimizer, + extra_grad_process_fn=grad_process_and_td_error_fn, + extra_learn_fetches_fn=concat_multi_gpu_td_errors, + extra_action_out_fn=extra_action_out_fn, + before_init=setup_early_mixins, + before_loss_init=before_loss_init, + mixins=[ + TargetNetworkMixin, + ComputeTDErrorMixin, + LearningRateSchedule, + ], +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/torch/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/torch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/torch/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/torch/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f46e78602f711ac04d6ffe1cdd62b20b8214700 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/torch/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/torch/__pycache__/default_dqn_torch_rl_module.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/torch/__pycache__/default_dqn_torch_rl_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28df5e58045aea628c322c184c17cc00e8bc2535 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/torch/__pycache__/default_dqn_torch_rl_module.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/torch/__pycache__/dqn_torch_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/torch/__pycache__/dqn_torch_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d93c81dc92034d01925bb79c0a7fa0e50a524ea Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/torch/__pycache__/dqn_torch_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/torch/default_dqn_torch_rl_module.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/torch/default_dqn_torch_rl_module.py new file mode 100644 index 0000000000000000000000000000000000000000..968ebe2da68d399b632f4d524f619fb1056d31d4 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/torch/default_dqn_torch_rl_module.py @@ -0,0 +1,327 @@ +import tree +from typing import Dict, Union + +from ray.rllib.algorithms.dqn.default_dqn_rl_module import ( + DefaultDQNRLModule, + ATOMS, + QF_LOGITS, + QF_NEXT_PREDS, + QF_PREDS, + QF_PROBS, + QF_TARGET_NEXT_PREDS, + QF_TARGET_NEXT_PROBS, +) +from ray.rllib.algorithms.dqn.dqn_catalog import DQNCatalog +from ray.rllib.core.columns import Columns +from ray.rllib.core.models.base import Encoder, ENCODER_OUT, Model +from ray.rllib.core.rl_module.apis.q_net_api import QNetAPI +from ray.rllib.core.rl_module.torch.torch_rl_module import TorchRLModule +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.typing import TensorType, TensorStructType +from ray.util.annotations import DeveloperAPI + +torch, nn = try_import_torch() + + +@DeveloperAPI +class DefaultDQNTorchRLModule(TorchRLModule, DefaultDQNRLModule): + framework: str = "torch" + + def __init__(self, *args, **kwargs): + catalog_class = kwargs.pop("catalog_class", None) + if catalog_class is None: + catalog_class = DQNCatalog + super().__init__(*args, **kwargs, catalog_class=catalog_class) + + @override(RLModule) + def _forward_inference(self, batch: Dict[str, TensorType]) -> Dict[str, TensorType]: + # Q-network forward pass. + qf_outs = self.compute_q_values(batch) + + # Get action distribution. + action_dist_cls = self.get_exploration_action_dist_cls() + action_dist = action_dist_cls.from_logits(qf_outs[QF_PREDS]) + # Note, the deterministic version of the categorical distribution + # outputs directly the `argmax` of the logits. + exploit_actions = action_dist.to_deterministic().sample() + + output = {Columns.ACTIONS: exploit_actions} + if Columns.STATE_OUT in qf_outs: + output[Columns.STATE_OUT] = qf_outs[Columns.STATE_OUT] + + # In inference, we only need the exploitation actions. + return output + + @override(RLModule) + def _forward_exploration( + self, batch: Dict[str, TensorType], t: int + ) -> Dict[str, TensorType]: + # Define the return dictionary. + output = {} + + # Q-network forward pass. + qf_outs = self.compute_q_values(batch) + + # Get action distribution. + action_dist_cls = self.get_exploration_action_dist_cls() + action_dist = action_dist_cls.from_logits(qf_outs[QF_PREDS]) + # Note, the deterministic version of the categorical distribution + # outputs directly the `argmax` of the logits. + exploit_actions = action_dist.to_deterministic().sample() + + # We need epsilon greedy to support exploration. + # TODO (simon): Implement sampling for nested spaces. + # Update scheduler. + self.epsilon_schedule.update(t) + # Get the actual epsilon, + epsilon = self.epsilon_schedule.get_current_value() + # Apply epsilon-greedy exploration. + B = qf_outs[QF_PREDS].shape[0] + random_actions = torch.squeeze( + torch.multinomial( + ( + torch.nan_to_num( + qf_outs[QF_PREDS].reshape(-1, qf_outs[QF_PREDS].size(-1)), + neginf=0.0, + ) + != 0.0 + ).float(), + num_samples=1, + ), + dim=1, + ) + + actions = torch.where( + torch.rand((B,)) < epsilon, + random_actions, + exploit_actions, + ) + + # Add the actions to the return dictionary. + output[Columns.ACTIONS] = actions + + # If this is a stateful module, add output states. + if Columns.STATE_OUT in qf_outs: + output[Columns.STATE_OUT] = qf_outs[Columns.STATE_OUT] + + return output + + @override(RLModule) + def _forward_train( + self, batch: Dict[str, TensorType] + ) -> Dict[str, TensorStructType]: + if self.inference_only: + raise RuntimeError( + "Trying to train a module that is not a learner module. Set the " + "flag `inference_only=False` when building the module." + ) + output = {} + + # If we use a double-Q setup. + if self.uses_double_q: + # Then we need to make a single forward pass with both, + # current and next observations. + batch_base = { + Columns.OBS: torch.concat( + [batch[Columns.OBS], batch[Columns.NEXT_OBS]], dim=0 + ), + } + # If this is a stateful module add the input states. + if Columns.STATE_IN in batch: + # Add both, the input state for the actual observation and + # the one for the next observation. + batch_base.update( + { + Columns.STATE_IN: tree.map_structure( + lambda t1, t2: torch.cat([t1, t2], dim=0), + batch[Columns.STATE_IN], + batch[Columns.NEXT_STATE_IN], + ) + } + ) + # Otherwise we can just use the current observations. + else: + batch_base = {Columns.OBS: batch[Columns.OBS]} + # If this is a stateful module add the input state. + if Columns.STATE_IN in batch: + batch_base.update({Columns.STATE_IN: batch[Columns.STATE_IN]}) + + batch_target = {Columns.OBS: batch[Columns.NEXT_OBS]} + + # If we have a stateful encoder, add the states for the target forward + # pass. + if Columns.NEXT_STATE_IN in batch: + batch_target.update({Columns.STATE_IN: batch[Columns.NEXT_STATE_IN]}) + + # Q-network forward passes. + qf_outs = self.compute_q_values(batch_base) + if self.uses_double_q: + output[QF_PREDS], output[QF_NEXT_PREDS] = torch.chunk( + qf_outs[QF_PREDS], chunks=2, dim=0 + ) + else: + output[QF_PREDS] = qf_outs[QF_PREDS] + # The target Q-values for the next observations. + qf_target_next_outs = self.forward_target(batch_target) + output[QF_TARGET_NEXT_PREDS] = qf_target_next_outs[QF_PREDS] + # We are learning a Q-value distribution. + if self.num_atoms > 1: + # Add distribution artefacts to the output. + # Distribution support. + output[ATOMS] = qf_target_next_outs[ATOMS] + # Original logits from the Q-head. + output[QF_LOGITS] = qf_outs[QF_LOGITS] + # Probabilities of the Q-value distribution of the current state. + output[QF_PROBS] = qf_outs[QF_PROBS] + # Probabilities of the target Q-value distribution of the next state. + output[QF_TARGET_NEXT_PROBS] = qf_target_next_outs[QF_PROBS] + + # Add the states to the output, if the module is stateful. + if Columns.STATE_OUT in qf_outs: + output[Columns.STATE_OUT] = qf_outs[Columns.STATE_OUT] + # For correctness, also add the output states from the target forward pass. + # Note, we do not backpropagate through this state. + if Columns.STATE_OUT in qf_target_next_outs: + output[Columns.NEXT_STATE_OUT] = qf_target_next_outs[Columns.STATE_OUT] + + return output + + @override(QNetAPI) + def compute_advantage_distribution( + self, + batch: Dict[str, TensorType], + ) -> Dict[str, TensorType]: + output = {} + # Distributional Q-learning uses a discrete support `z` + # to represent the action value distribution. + # TODO (simon): Check, if we still need here the device for torch. + z = torch.arange(0.0, self.num_atoms, dtype=torch.float32).to( + batch.device, + ) + # Rescale the support. + z = self.v_min + z * (self.v_max - self.v_min) / float(self.num_atoms - 1) + # Reshape the action values. + # NOTE: Handcrafted action shape. + logits_per_action_per_atom = torch.reshape( + batch, shape=(*batch.shape[:-1], self.action_space.n, self.num_atoms) + ) + # Calculate the probability for each action value atom. Note, + # the sum along action value atoms of a single action value + # must sum to one. + prob_per_action_per_atom = nn.functional.softmax( + logits_per_action_per_atom, + dim=-1, + ) + # Compute expected action value by weighted sum. + output[ATOMS] = z + output["logits"] = logits_per_action_per_atom + output["probs"] = prob_per_action_per_atom + + return output + + # TODO (simon): Test, if providing the function with a `return_probs` + # improves performance significantly. + @override(DefaultDQNRLModule) + def _qf_forward_helper( + self, + batch: Dict[str, TensorType], + encoder: Encoder, + head: Union[Model, Dict[str, Model]], + ) -> Dict[str, TensorType]: + """Computes Q-values. + + This is a helper function that takes care of all different cases, + i.e. if we use a dueling architecture or not and if we use distributional + Q-learning or not. + + Args: + batch: The batch received in the forward pass. + encoder: The encoder network to use. Here we have a single encoder + for all heads (Q or advantages and value in case of a dueling + architecture). + head: Either a head model or a dictionary of head model (dueling + architecture) containing advantage and value stream heads. + + Returns: + In case of expectation learning the Q-value predictions ("qf_preds") + and in case of distributional Q-learning in addition to the predictions + the atoms ("atoms"), the Q-value predictions ("qf_preds"), the Q-logits + ("qf_logits") and the probabilities for the support atoms ("qf_probs"). + """ + output = {} + + # Encoder forward pass. + encoder_outs = encoder(batch) + + # Do we have a dueling architecture. + if self.uses_dueling: + # Head forward passes for advantage and value stream. + qf_outs = head["af"](encoder_outs[ENCODER_OUT]) + vf_outs = head["vf"](encoder_outs[ENCODER_OUT]) + # We learn a Q-value distribution. + if self.num_atoms > 1: + # Compute the advantage stream distribution. + af_dist_output = self.compute_advantage_distribution(qf_outs) + # Center the advantage stream distribution. + centered_af_logits = af_dist_output["logits"] - af_dist_output[ + "logits" + ].mean(dim=-1, keepdim=True) + # Calculate the Q-value distribution by adding advantage and + # value stream. + qf_logits = centered_af_logits + vf_outs.view( + -1, *((1,) * (centered_af_logits.dim() - 1)) + ) + # Calculate probabilites for the Q-value distribution along + # the support given by the atoms. + qf_probs = nn.functional.softmax(qf_logits, dim=-1) + # Return also the support as we need it in the learner. + output[ATOMS] = af_dist_output[ATOMS] + # Calculate the Q-values by the weighted sum over the atoms. + output[QF_PREDS] = torch.sum(af_dist_output[ATOMS] * qf_probs, dim=-1) + output[QF_LOGITS] = qf_logits + output[QF_PROBS] = qf_probs + # Otherwise we learn an expectation. + else: + # Center advantages. Note, we cannot do an in-place operation here + # b/c we backpropagate through these values. See for a discussion + # https://discuss.pytorch.org/t/gradient-computation-issue-due-to- + # inplace-operation-unsure-how-to-debug-for-custom-model/170133 + # Has to be a mean for each batch element. + af_outs_mean = torch.nan_to_num(qf_outs, neginf=torch.nan).nanmean( + dim=-1, keepdim=True + ) + qf_outs = qf_outs - af_outs_mean + # Add advantage and value stream. Note, we broadcast here. + output[QF_PREDS] = qf_outs + vf_outs + # No dueling architecture. + else: + # Note, in this case the advantage network is the Q-network. + # Forward pass through Q-head. + qf_outs = head(encoder_outs[ENCODER_OUT]) + # We learn a Q-value distribution. + if self.num_atoms > 1: + # Note in a non-dueling architecture the advantage distribution is + # the Q-value distribution. + # Get the Q-value distribution. + qf_dist_outs = self.compute_advantage_distribution(qf_outs) + # Get the support of the Q-value distribution. + output[ATOMS] = qf_dist_outs[ATOMS] + # Calculate the Q-values by the weighted sum over the atoms. + output[QF_PREDS] = torch.sum( + qf_dist_outs[ATOMS] * qf_dist_outs["probs"], dim=-1 + ) + output[QF_LOGITS] = qf_dist_outs["logits"] + output[QF_PROBS] = qf_dist_outs["probs"] + # Otherwise we learn an expectation. + else: + # In this case we have a Q-head of dimension (1, action_space.n). + output[QF_PREDS] = qf_outs + + # If we have a stateful encoder add the output states to the return + # dictionary. + if Columns.STATE_OUT in encoder_outs: + output[Columns.STATE_OUT] = encoder_outs[Columns.STATE_OUT] + + return output diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/torch/dqn_torch_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/torch/dqn_torch_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..4289bcc7cdcf0cde9e70b3b75920cf6f7a0f34b4 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dqn/torch/dqn_torch_learner.py @@ -0,0 +1,295 @@ +from typing import Dict + +from ray.rllib.algorithms.dqn.dqn import DQNConfig +from ray.rllib.algorithms.dqn.dqn_learner import ( + ATOMS, + DQNLearner, + QF_LOSS_KEY, + QF_LOGITS, + QF_MEAN_KEY, + QF_MAX_KEY, + QF_MIN_KEY, + QF_NEXT_PREDS, + QF_TARGET_NEXT_PREDS, + QF_TARGET_NEXT_PROBS, + QF_PREDS, + QF_PROBS, + TD_ERROR_MEAN_KEY, +) +from ray.rllib.core.columns import Columns +from ray.rllib.core.learner.torch.torch_learner import TorchLearner +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.metrics import TD_ERROR_KEY +from ray.rllib.utils.typing import ModuleID, TensorType + + +torch, nn = try_import_torch() + + +class DQNTorchLearner(DQNLearner, TorchLearner): + """Implements `torch`-specific DQN Rainbow loss logic on top of `DQNLearner` + + This ' Learner' class implements the loss in its + `self.compute_loss_for_module()` method. + """ + + @override(TorchLearner) + def compute_loss_for_module( + self, + *, + module_id: ModuleID, + config: DQNConfig, + batch: Dict, + fwd_out: Dict[str, TensorType] + ) -> TensorType: + + # Possibly apply masking to some sub loss terms and to the total loss term + # at the end. Masking could be used for RNN-based model (zero padded `batch`) + # and for PPO's batched value function (and bootstrap value) computations, + # for which we add an (artificial) timestep to each episode to + # simplify the actual computation. + if Columns.LOSS_MASK in batch: + mask = batch[Columns.LOSS_MASK].clone() + # Check, if a burn-in should be used to recover from a poor state. + if self.config.burn_in_len > 0: + # Train only on the timesteps after the burn-in period. + mask[:, : self.config.burn_in_len] = False + num_valid = torch.sum(mask) + + def possibly_masked_mean(data_): + return torch.sum(data_[mask]) / num_valid + + def possibly_masked_min(data_): + # Prevent minimum over empty tensors, which can happened + # when all elements in the mask are `False`. + return ( + torch.tensor(float("nan")) + if data_[mask].numel() == 0 + else torch.min(data_[mask]) + ) + + def possibly_masked_max(data_): + # Prevent maximum over empty tensors, which can happened + # when all elements in the mask are `False`. + return ( + torch.tensor(float("nan")) + if data_[mask].numel() == 0 + else torch.max(data_[mask]) + ) + + else: + possibly_masked_mean = torch.mean + possibly_masked_min = torch.min + possibly_masked_max = torch.max + + q_curr = fwd_out[QF_PREDS] + q_target_next = fwd_out[QF_TARGET_NEXT_PREDS] + + # Get the Q-values for the selected actions in the rollout. + # TODO (simon, sven): Check, if we can use `gather` with a complex action + # space - we might need the one_hot_selection. Also test performance. + q_selected = torch.nan_to_num( + torch.gather( + q_curr, + dim=-1, + index=batch[Columns.ACTIONS] + .view(*batch[Columns.ACTIONS].shape, 1) + .long(), + ), + neginf=0.0, + ).squeeze(dim=-1) + + # Use double Q learning. + if config.double_q: + # Then we evaluate the target Q-function at the best action (greedy action) + # over the online Q-function. + # Mark the best online Q-value of the next state. + q_next_best_idx = ( + torch.argmax(fwd_out[QF_NEXT_PREDS], dim=-1).unsqueeze(dim=-1).long() + ) + # Get the Q-value of the target network at maximum of the online network + # (bootstrap action). + q_next_best = torch.nan_to_num( + torch.gather(q_target_next, dim=-1, index=q_next_best_idx), + neginf=0.0, + ).squeeze() + else: + # Mark the maximum Q-value(s). + q_next_best_idx = ( + torch.argmax(q_target_next, dim=-1).unsqueeze(dim=-1).long() + ) + # Get the maximum Q-value(s). + q_next_best = torch.nan_to_num( + torch.gather(q_target_next, dim=-1, index=q_next_best_idx), + neginf=0.0, + ).squeeze() + + # If we learn a Q-distribution. + if config.num_atoms > 1: + # Extract the Q-logits evaluated at the selected actions. + # (Note, `torch.gather` should be faster than multiplication + # with a one-hot tensor.) + # (32, 2, 10) -> (32, 10) + q_logits_selected = torch.gather( + fwd_out[QF_LOGITS], + dim=1, + # Note, the Q-logits are of shape (B, action_space.n, num_atoms) + # while the actions have shape (B, 1). We reshape actions to + # (B, 1, num_atoms). + index=batch[Columns.ACTIONS] + .view(-1, 1, 1) + .expand(-1, 1, config.num_atoms) + .long(), + ).squeeze(dim=1) + # Get the probabilies for the maximum Q-value(s). + q_probs_next_best = torch.gather( + fwd_out[QF_TARGET_NEXT_PROBS], + dim=1, + # Change the view and then expand to get to the dimensions + # of the probabilities (dims 0 and 2, 1 should be reduced + # from 2 -> 1). + index=q_next_best_idx.view(-1, 1, 1).expand(-1, 1, config.num_atoms), + ).squeeze(dim=1) + + # For distributional Q-learning we use an entropy loss. + + # Extract the support grid for the Q distribution. + z = fwd_out[ATOMS] + # TODO (simon): Enable computing on GPU. + # (batch_size, 1) * (1, num_atoms) = (batch_size, num_atoms)s + r_tau = torch.clamp( + batch[Columns.REWARDS].unsqueeze(dim=-1) + + ( + config.gamma ** batch["n_step"] + * (1.0 - batch[Columns.TERMINATEDS].float()) + ).unsqueeze(dim=-1) + * z, + config.v_min, + config.v_max, + ).squeeze(dim=1) + # (32, 10) + b = (r_tau - config.v_min) / ( + (config.v_max - config.v_min) / float(config.num_atoms - 1.0) + ) + lower_bound = torch.floor(b) + upper_bound = torch.ceil(b) + + floor_equal_ceil = ((upper_bound - lower_bound) < 0.5).float() + + # (B, num_atoms, num_atoms). + lower_projection = nn.functional.one_hot( + lower_bound.long(), config.num_atoms + ) + upper_projection = nn.functional.one_hot( + upper_bound.long(), config.num_atoms + ) + # (32, 10) + ml_delta = q_probs_next_best * (upper_bound - b + floor_equal_ceil) + mu_delta = q_probs_next_best * (b - lower_bound) + # (32, 10) + ml_delta = torch.sum(lower_projection * ml_delta.unsqueeze(dim=-1), dim=1) + mu_delta = torch.sum(upper_projection * mu_delta.unsqueeze(dim=-1), dim=1) + # We do not want to propagate through the distributional targets. + # (32, 10) + m = (ml_delta + mu_delta).detach() + + # The Rainbow paper claims to use the KL-divergence loss. This is identical + # to using the cross-entropy (differs only by entropy which is constant) + # when optimizing by the gradient (the gradient is identical). + td_error = nn.CrossEntropyLoss(reduction="none")(q_logits_selected, m) + # Compute the weighted loss (importance sampling weights). + total_loss = torch.mean(batch["weights"] * td_error) + else: + # Masked all Q-values with terminated next states in the targets. + q_next_best_masked = ( + 1.0 - batch[Columns.TERMINATEDS].float() + ) * q_next_best + + # Compute the RHS of the Bellman equation. + # Detach this node from the computation graph as we do not want to + # backpropagate through the target network when optimizing the Q loss. + q_selected_target = ( + batch[Columns.REWARDS] + + (config.gamma ** batch["n_step"]) * q_next_best_masked + ).detach() + + # Choose the requested loss function. Note, in case of the Huber loss + # we fall back to the default of `delta=1.0`. + loss_fn = nn.HuberLoss if config.td_error_loss_fn == "huber" else nn.MSELoss + # Compute the TD error. + td_error = torch.abs(q_selected - q_selected_target) + # Compute the weighted loss (importance sampling weights). + total_loss = possibly_masked_mean( + batch["weights"] + * loss_fn(reduction="none")(q_selected, q_selected_target) + ) + + # Log the TD-error with reduce=None, such that - in case we have n parallel + # Learners - we will re-concatenate the produced TD-error tensors to yield + # a 1:1 representation of the original batch. + self.metrics.log_value( + key=(module_id, TD_ERROR_KEY), + value=td_error, + reduce=None, + clear_on_reduce=True, + ) + # Log other important loss stats (reduce=mean (default), but with window=1 + # in order to keep them history free). + self.metrics.log_dict( + { + QF_LOSS_KEY: total_loss, + QF_MEAN_KEY: possibly_masked_mean(q_selected), + QF_MAX_KEY: possibly_masked_max(q_selected), + QF_MIN_KEY: possibly_masked_min(q_selected), + TD_ERROR_MEAN_KEY: possibly_masked_mean(td_error), + }, + key=module_id, + window=1, # <- single items (should not be mean/ema-reduced over time). + ) + # If we learn a Q-value distribution log the support and average + # probabilities. + if config.num_atoms > 1: + # Log important loss stats. + self.metrics.log_dict( + { + ATOMS: torch.mean(z), + # The absolute difference in expectation between the actions + # should (at least mildly) rise. + "expectations_abs_diff": torch.mean( + torch.abs( + torch.diff( + torch.sum(fwd_out[QF_PROBS].mean(dim=0) * z, dim=1) + ).mean(dim=0) + ) + ), + # The total variation distance should measure the distance between + # return distributions of different actions. This should (at least + # mildly) increase during training when the agent differentiates + # more between actions. + "dist_total_variation_dist": torch.diff( + fwd_out[QF_PROBS].mean(dim=0), dim=0 + ) + .abs() + .sum() + * 0.5, + # The maximum distance between the action distributions. This metric + # should increase over the course of training. + "dist_max_abs_distance": torch.max( + torch.diff(fwd_out[QF_PROBS].mean(dim=0), dim=0).abs() + ), + # Mean shannon entropy of action distributions. This should decrease + # over the course of training. + "action_dist_mean_entropy": torch.mean( + ( + fwd_out[QF_PROBS].mean(dim=0) + * torch.log(fwd_out[QF_PROBS].mean(dim=0)) + ).sum(dim=1), + dim=0, + ), + }, + key=module_id, + window=1, # <- single items (should not be mean/ema-reduced over time). + ) + + return total_loss diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d4b2adb0d57ed1d44ced601c57fa78c91bc4bede --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/__init__.py @@ -0,0 +1,15 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf + +[2] Mastering Atari with Discrete World Models - 2021 +D. Hafner, T. Lillicrap, M. Norouzi, J. Ba +https://arxiv.org/pdf/2010.02193.pdf +""" +from ray.rllib.algorithms.dreamerv3.dreamerv3 import DreamerV3, DreamerV3Config + +__all__ = [ + "DreamerV3", + "DreamerV3Config", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..991f786e130e8d717a99a1b92fe59800fe0a7c38 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/__pycache__/dreamerv3.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/__pycache__/dreamerv3.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d82ce100d5de66eaf78d6eabe335cd114379705 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/__pycache__/dreamerv3.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/__pycache__/dreamerv3_catalog.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/__pycache__/dreamerv3_catalog.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6eae811f9be09171c6c17271318820eb72096550 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/__pycache__/dreamerv3_catalog.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/__pycache__/dreamerv3_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/__pycache__/dreamerv3_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dda1541eaf9b0568b72b95d7707b109efd3cbe90 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/__pycache__/dreamerv3_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/__pycache__/dreamerv3_rl_module.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/__pycache__/dreamerv3_rl_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74792db4dad23232e536dcb9fe62cecead516d65 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/__pycache__/dreamerv3_rl_module.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/dreamerv3.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/dreamerv3.py new file mode 100644 index 0000000000000000000000000000000000000000..63784d3e09a7d0a59303ea1dc3e216a2387ef014 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/dreamerv3.py @@ -0,0 +1,731 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf + +[2] Mastering Atari with Discrete World Models - 2021 +D. Hafner, T. Lillicrap, M. Norouzi, J. Ba +https://arxiv.org/pdf/2010.02193.pdf +""" + +import logging +from typing import Any, Dict, Optional, Union + +import gymnasium as gym + +from ray.rllib.algorithms.algorithm import Algorithm +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig, NotProvided +from ray.rllib.algorithms.dreamerv3.dreamerv3_catalog import DreamerV3Catalog +from ray.rllib.algorithms.dreamerv3.utils import do_symlog_obs +from ray.rllib.algorithms.dreamerv3.utils.add_is_firsts_to_batch import ( + AddIsFirstsToBatch, +) +from ray.rllib.algorithms.dreamerv3.utils.summaries import ( + report_dreamed_eval_trajectory_vs_samples, + report_predicted_vs_sampled_obs, + report_sampling_and_replay_buffer, +) +from ray.rllib.connectors.common import AddStatesFromEpisodesToBatch +from ray.rllib.core import DEFAULT_MODULE_ID +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.execution.rollout_ops import synchronous_parallel_sample +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils import deep_update +from ray.rllib.utils.annotations import override, PublicAPI +from ray.rllib.utils.numpy import one_hot +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + LEARN_ON_BATCH_TIMER, + LEARNER_RESULTS, + NUM_ENV_STEPS_SAMPLED_LIFETIME, + NUM_ENV_STEPS_TRAINED_LIFETIME, + NUM_GRAD_UPDATES_LIFETIME, + NUM_SYNCH_WORKER_WEIGHTS, + REPLAY_BUFFER_RESULTS, + SAMPLE_TIMER, + SYNCH_WORKER_WEIGHTS_TIMER, + TIMERS, +) +from ray.rllib.utils.replay_buffers.episode_replay_buffer import EpisodeReplayBuffer +from ray.rllib.utils.typing import LearningRateOrSchedule + + +logger = logging.getLogger(__name__) + + +class DreamerV3Config(AlgorithmConfig): + """Defines a configuration class from which a DreamerV3 can be built. + + .. testcode:: + + from ray.rllib.algorithms.dreamerv3 import DreamerV3Config + config = ( + DreamerV3Config() + .environment("CartPole-v1") + .training( + model_size="XS", + training_ratio=1, + # TODO + model={ + "batch_size_B": 1, + "batch_length_T": 1, + "horizon_H": 1, + "gamma": 0.997, + "model_size": "XS", + }, + ) + ) + + config = config.learners(num_learners=0) + # Build a Algorithm object from the config and run 1 training iteration. + algo = config.build() + # algo.train() + del algo + + .. testoutput:: + :hide: + + ... + """ + + def __init__(self, algo_class=None): + """Initializes a DreamerV3Config instance.""" + super().__init__(algo_class=algo_class or DreamerV3) + + # fmt: off + # __sphinx_doc_begin__ + + # DreamerV3 specific settings: + self.model_size = "XS" + self.training_ratio = 1024 + + self.replay_buffer_config = { + "type": "EpisodeReplayBuffer", + "capacity": int(1e6), + } + self.world_model_lr = 1e-4 + self.actor_lr = 3e-5 + self.critic_lr = 3e-5 + self.batch_size_B = 16 + self.batch_length_T = 64 + self.horizon_H = 15 + self.gae_lambda = 0.95 # [1] eq. 7. + self.entropy_scale = 3e-4 # [1] eq. 11. + self.return_normalization_decay = 0.99 # [1] eq. 11 and 12. + self.train_critic = True + self.train_actor = True + self.intrinsic_rewards_scale = 0.1 + self.world_model_grad_clip_by_global_norm = 1000.0 + self.critic_grad_clip_by_global_norm = 100.0 + self.actor_grad_clip_by_global_norm = 100.0 + self.symlog_obs = "auto" + self.use_float16 = False + self.use_curiosity = False + + # Reporting. + # DreamerV3 is super sample efficient and only needs very few episodes + # (normally) to learn. Leaving this at its default value would gravely + # underestimate the learning performance over the course of an experiment. + self.metrics_num_episodes_for_smoothing = 1 + self.report_individual_batch_item_stats = False + self.report_dream_data = False + self.report_images_and_videos = False + + # Override some of AlgorithmConfig's default values with DreamerV3-specific + # values. + self.lr = None + self.gamma = 0.997 # [1] eq. 7. + # Do not use! Set `batch_size_B` and `batch_length_T` instead. + self.train_batch_size = None + self.num_env_runners = 0 + self.rollout_fragment_length = 1 + # Dreamer only runs on the new API stack. + self.enable_rl_module_and_learner = True + self.enable_env_runner_and_connector_v2 = True + # TODO (sven): DreamerV3 still uses its own EnvRunner class. This env-runner + # does not use connectors. We therefore should not attempt to merge/broadcast + # the connector states between EnvRunners (if >0). Note that this is only + # relevant if num_env_runners > 0, which is normally not the case when using + # this algo. + self.use_worker_filter_stats = False + # __sphinx_doc_end__ + # fmt: on + + @override(AlgorithmConfig) + def build_env_to_module_connector(self, env, spaces, device): + connector = super().build_env_to_module_connector(env, spaces, device) + + # Prepend the "is_first" connector such that the RSSM knows, when to insert + # its (learned) internal state into the batch. + # We have to do this before the `AddStatesFromEpisodesToBatch` piece + # such that the column is properly batched/time-ranked. + if self.add_default_connectors_to_learner_pipeline: + connector.insert_before( + AddStatesFromEpisodesToBatch, + AddIsFirstsToBatch(), + ) + return connector + + @property + def batch_size_B_per_learner(self): + """Returns the batch_size_B per Learner worker. + + Needed by some of the DreamerV3 loss math.""" + return self.batch_size_B // (self.num_learners or 1) + + @override(AlgorithmConfig) + def training( + self, + *, + model_size: Optional[str] = NotProvided, + training_ratio: Optional[float] = NotProvided, + batch_size_B: Optional[int] = NotProvided, + batch_length_T: Optional[int] = NotProvided, + horizon_H: Optional[int] = NotProvided, + gae_lambda: Optional[float] = NotProvided, + entropy_scale: Optional[float] = NotProvided, + return_normalization_decay: Optional[float] = NotProvided, + train_critic: Optional[bool] = NotProvided, + train_actor: Optional[bool] = NotProvided, + intrinsic_rewards_scale: Optional[float] = NotProvided, + world_model_lr: Optional[LearningRateOrSchedule] = NotProvided, + actor_lr: Optional[LearningRateOrSchedule] = NotProvided, + critic_lr: Optional[LearningRateOrSchedule] = NotProvided, + world_model_grad_clip_by_global_norm: Optional[float] = NotProvided, + critic_grad_clip_by_global_norm: Optional[float] = NotProvided, + actor_grad_clip_by_global_norm: Optional[float] = NotProvided, + symlog_obs: Optional[Union[bool, str]] = NotProvided, + use_float16: Optional[bool] = NotProvided, + replay_buffer_config: Optional[dict] = NotProvided, + use_curiosity: Optional[bool] = NotProvided, + **kwargs, + ) -> "DreamerV3Config": + """Sets the training related configuration. + + Args: + model_size: The main switch for adjusting the overall model size. See [1] + (table B) for more information on the effects of this setting on the + model architecture. + Supported values are "XS", "S", "M", "L", "XL" (as per the paper), as + well as, "nano", "micro", "mini", and "XXS" (for RLlib's + implementation). See ray.rllib.algorithms.dreamerv3.utils. + __init__.py for the details on what exactly each size does to the layer + sizes, number of layers, etc.. + training_ratio: The ratio of total steps trained (sum of the sizes of all + batches ever sampled from the replay buffer) over the total env steps + taken (in the actual environment, not the dreamed one). For example, + if the training_ratio is 1024 and the batch size is 1024, we would take + 1 env step for every training update: 1024 / 1. If the training ratio + is 512 and the batch size is 1024, we would take 2 env steps and then + perform a single training update (on a 1024 batch): 1024 / 2. + batch_size_B: The batch size (B) interpreted as number of rows (each of + length `batch_length_T`) to sample from the replay buffer in each + iteration. + batch_length_T: The batch length (T) interpreted as the length of each row + sampled from the replay buffer in each iteration. Note that + `batch_size_B` rows will be sampled in each iteration. Rows normally + contain consecutive data (consecutive timesteps from the same episode), + but there might be episode boundaries in a row as well. + horizon_H: The horizon (in timesteps) used to create dreamed data from the + world model, which in turn is used to train/update both actor- and + critic networks. + gae_lambda: The lambda parameter used for computing the GAE-style + value targets for the actor- and critic losses. + entropy_scale: The factor with which to multiply the entropy loss term + inside the actor loss. + return_normalization_decay: The decay value to use when computing the + running EMA values for return normalization (used in the actor loss). + train_critic: Whether to train the critic network. If False, `train_actor` + must also be False (cannot train actor w/o training the critic). + train_actor: Whether to train the actor network. If True, `train_critic` + must also be True (cannot train actor w/o training the critic). + intrinsic_rewards_scale: The factor to multiply intrinsic rewards with + before adding them to the extrinsic (environment) rewards. + world_model_lr: The learning rate or schedule for the world model optimizer. + actor_lr: The learning rate or schedule for the actor optimizer. + critic_lr: The learning rate or schedule for the critic optimizer. + world_model_grad_clip_by_global_norm: World model grad clipping value + (by global norm). + critic_grad_clip_by_global_norm: Critic grad clipping value + (by global norm). + actor_grad_clip_by_global_norm: Actor grad clipping value (by global norm). + symlog_obs: Whether to symlog observations or not. If set to "auto" + (default), will check for the environment's observation space and then + only symlog if not an image space. + use_float16: Whether to train with mixed float16 precision. In this mode, + model parameters are stored as float32, but all computations are + performed in float16 space (except for losses and distribution params + and outputs). + replay_buffer_config: Replay buffer config. + Only serves in DreamerV3 to set the capacity of the replay buffer. + Note though that in the paper ([1]) a size of 1M is used for all + benchmarks and there doesn't seem to be a good reason to change this + parameter. + Examples: + { + "type": "EpisodeReplayBuffer", + "capacity": 100000, + } + + Returns: + This updated AlgorithmConfig object. + """ + # Not fully supported/tested yet. + if use_curiosity is not NotProvided: + raise ValueError( + "`DreamerV3Config.curiosity` is not fully supported and tested yet! " + "It thus remains disabled for now." + ) + + # Pass kwargs onto super's `training()` method. + super().training(**kwargs) + + if model_size is not NotProvided: + self.model_size = model_size + if training_ratio is not NotProvided: + self.training_ratio = training_ratio + if batch_size_B is not NotProvided: + self.batch_size_B = batch_size_B + if batch_length_T is not NotProvided: + self.batch_length_T = batch_length_T + if horizon_H is not NotProvided: + self.horizon_H = horizon_H + if gae_lambda is not NotProvided: + self.gae_lambda = gae_lambda + if entropy_scale is not NotProvided: + self.entropy_scale = entropy_scale + if return_normalization_decay is not NotProvided: + self.return_normalization_decay = return_normalization_decay + if train_critic is not NotProvided: + self.train_critic = train_critic + if train_actor is not NotProvided: + self.train_actor = train_actor + if intrinsic_rewards_scale is not NotProvided: + self.intrinsic_rewards_scale = intrinsic_rewards_scale + if world_model_lr is not NotProvided: + self.world_model_lr = world_model_lr + if actor_lr is not NotProvided: + self.actor_lr = actor_lr + if critic_lr is not NotProvided: + self.critic_lr = critic_lr + if world_model_grad_clip_by_global_norm is not NotProvided: + self.world_model_grad_clip_by_global_norm = ( + world_model_grad_clip_by_global_norm + ) + if critic_grad_clip_by_global_norm is not NotProvided: + self.critic_grad_clip_by_global_norm = critic_grad_clip_by_global_norm + if actor_grad_clip_by_global_norm is not NotProvided: + self.actor_grad_clip_by_global_norm = actor_grad_clip_by_global_norm + if symlog_obs is not NotProvided: + self.symlog_obs = symlog_obs + if use_float16 is not NotProvided: + self.use_float16 = use_float16 + if replay_buffer_config is not NotProvided: + # Override entire `replay_buffer_config` if `type` key changes. + # Update, if `type` key remains the same or is not specified. + new_replay_buffer_config = deep_update( + {"replay_buffer_config": self.replay_buffer_config}, + {"replay_buffer_config": replay_buffer_config}, + False, + ["replay_buffer_config"], + ["replay_buffer_config"], + ) + self.replay_buffer_config = new_replay_buffer_config["replay_buffer_config"] + + return self + + @override(AlgorithmConfig) + def reporting( + self, + *, + report_individual_batch_item_stats: Optional[bool] = NotProvided, + report_dream_data: Optional[bool] = NotProvided, + report_images_and_videos: Optional[bool] = NotProvided, + **kwargs, + ): + """Sets the reporting related configuration. + + Args: + report_individual_batch_item_stats: Whether to include loss and other stats + per individual timestep inside the training batch in the result dict + returned by `training_step()`. If True, besides the `CRITIC_L_total`, + the individual critic loss values per batch row and time axis step + in the train batch (CRITIC_L_total_B_T) will also be part of the + results. + report_dream_data: Whether to include the dreamed trajectory data in the + result dict returned by `training_step()`. If True, however, will + slice each reported item in the dream data down to the shape. + (H, B, t=0, ...), where H is the horizon and B is the batch size. The + original time axis will only be represented by the first timestep + to not make this data too large to handle. + report_images_and_videos: Whether to include any image/video data in the + result dict returned by `training_step()`. + **kwargs: + + Returns: + This updated AlgorithmConfig object. + """ + super().reporting(**kwargs) + + if report_individual_batch_item_stats is not NotProvided: + self.report_individual_batch_item_stats = report_individual_batch_item_stats + if report_dream_data is not NotProvided: + self.report_dream_data = report_dream_data + if report_images_and_videos is not NotProvided: + self.report_images_and_videos = report_images_and_videos + + return self + + @override(AlgorithmConfig) + def validate(self) -> None: + # Call the super class' validation method first. + super().validate() + + # Make sure, users are not using DreamerV3 yet for multi-agent: + if self.is_multi_agent: + self._value_error("DreamerV3 does NOT support multi-agent setups yet!") + + # Make sure, we are configure for the new API stack. + if not self.enable_rl_module_and_learner: + self._value_error( + "DreamerV3 must be run with `config.api_stack(" + "enable_rl_module_and_learner=True)`!" + ) + + # If run on several Learners, the provided batch_size_B must be a multiple + # of `num_learners`. + if self.num_learners > 1 and (self.batch_size_B % self.num_learners != 0): + self._value_error( + f"Your `batch_size_B` ({self.batch_size_B}) must be a multiple of " + f"`num_learners` ({self.num_learners}) in order for " + "DreamerV3 to be able to split batches evenly across your Learner " + "processes." + ) + + # Cannot train actor w/o critic. + if self.train_actor and not self.train_critic: + self._value_error( + "Cannot train actor network (`train_actor=True`) w/o training critic! " + "Make sure you either set `train_critic=True` or `train_actor=False`." + ) + # Use DreamerV3 specific batch size settings. + if self.train_batch_size is not None: + self._value_error( + "`train_batch_size` should NOT be set! Use `batch_size_B` and " + "`batch_length_T` instead." + ) + # Must be run with `EpisodeReplayBuffer` type. + if self.replay_buffer_config.get("type") != "EpisodeReplayBuffer": + self._value_error( + "DreamerV3 must be run with the `EpisodeReplayBuffer` type! None " + "other supported." + ) + + @override(AlgorithmConfig) + def get_default_learner_class(self): + if self.framework_str == "torch": + from ray.rllib.algorithms.dreamerv3.torch.dreamerv3_torch_learner import ( + DreamerV3TorchLearner, + ) + + return DreamerV3TorchLearner + else: + raise ValueError(f"The framework {self.framework_str} is not supported.") + + @override(AlgorithmConfig) + def get_default_rl_module_spec(self) -> RLModuleSpec: + if self.framework_str == "torch": + from ray.rllib.algorithms.dreamerv3.torch.dreamerv3_torch_rl_module import ( + DreamerV3TorchRLModule as module, + ) + + else: + raise ValueError(f"The framework {self.framework_str} is not supported.") + + return RLModuleSpec(module_class=module, catalog_class=DreamerV3Catalog) + + @property + @override(AlgorithmConfig) + def _model_config_auto_includes(self) -> Dict[str, Any]: + return super()._model_config_auto_includes | { + "gamma": self.gamma, + "horizon_H": self.horizon_H, + "model_size": self.model_size, + "symlog_obs": self.symlog_obs, + "use_float16": self.use_float16, + "batch_length_T": self.batch_length_T, + } + + +class DreamerV3(Algorithm): + """Implementation of the model-based DreamerV3 RL algorithm described in [1].""" + + # TODO (sven): Deprecate/do-over the Algorithm.compute_single_action() API. + @override(Algorithm) + def compute_single_action(self, *args, **kwargs): + raise NotImplementedError( + "DreamerV3 does not support the `compute_single_action()` API. Refer to the" + " README here (https://github.com/ray-project/ray/tree/master/rllib/" + "algorithms/dreamerv3) to find more information on how to run action " + "inference with this algorithm." + ) + + @classmethod + @override(Algorithm) + def get_default_config(cls) -> AlgorithmConfig: + return DreamerV3Config() + + @override(Algorithm) + def setup(self, config: AlgorithmConfig): + super().setup(config) + + # Share RLModule between EnvRunner and single (local) Learner instance. + # To avoid possibly expensive weight synching step. + # if self.config.share_module_between_env_runner_and_learner: + # assert self.env_runner.module is None + # self.env_runner.module = self.learner_group._learner.module[ + # DEFAULT_MODULE_ID + # ] + + # Create a replay buffer for storing actual env samples. + self.replay_buffer = EpisodeReplayBuffer( + capacity=self.config.replay_buffer_config["capacity"], + batch_size_B=self.config.batch_size_B, + batch_length_T=self.config.batch_length_T, + ) + + @override(Algorithm) + def training_step(self) -> None: + # Push enough samples into buffer initially before we start training. + if self.training_iteration == 0: + logger.info( + "Filling replay buffer so it contains at least " + f"{self.config.batch_size_B * self.config.batch_length_T} timesteps " + "(required for a single train batch)." + ) + + # Have we sampled yet in this `training_step()` call? + have_sampled = False + with self.metrics.log_time((TIMERS, SAMPLE_TIMER)): + # Continue sampling from the actual environment (and add collected samples + # to our replay buffer) as long as we: + while ( + # a) Don't have at least batch_size_B x batch_length_T timesteps stored + # in the buffer. This is the minimum needed to train. + self.replay_buffer.get_num_timesteps() + < (self.config.batch_size_B * self.config.batch_length_T) + # b) The computed `training_ratio` is >= the configured (desired) + # training ratio (meaning we should continue sampling). + or self.training_ratio >= self.config.training_ratio + # c) we have not sampled at all yet in this `training_step()` call. + or not have_sampled + ): + # Sample using the env runner's module. + episodes, env_runner_results = synchronous_parallel_sample( + worker_set=self.env_runner_group, + max_agent_steps=( + self.config.rollout_fragment_length + * self.config.num_envs_per_env_runner + ), + sample_timeout_s=self.config.sample_timeout_s, + _uses_new_env_runners=True, + _return_metrics=True, + ) + self.metrics.aggregate(env_runner_results, key=ENV_RUNNER_RESULTS) + # Add ongoing and finished episodes into buffer. The buffer will + # automatically take care of properly concatenating (by episode IDs) + # the different chunks of the same episodes, even if they come in via + # separate `add()` calls. + self.replay_buffer.add(episodes=episodes) + have_sampled = True + + # We took B x T env steps. + env_steps_last_regular_sample = sum(len(eps) for eps in episodes) + total_sampled = env_steps_last_regular_sample + + # If we have never sampled before (just started the algo and not + # recovered from a checkpoint), sample B random actions first. + if ( + self.metrics.peek( + (ENV_RUNNER_RESULTS, NUM_ENV_STEPS_SAMPLED_LIFETIME), + default=0, + ) + == 0 + ): + _episodes, _env_runner_results = synchronous_parallel_sample( + worker_set=self.env_runner_group, + max_agent_steps=( + self.config.batch_size_B * self.config.batch_length_T + - env_steps_last_regular_sample + ), + sample_timeout_s=self.config.sample_timeout_s, + random_actions=True, + _uses_new_env_runners=True, + _return_metrics=True, + ) + self.metrics.aggregate(_env_runner_results, key=ENV_RUNNER_RESULTS) + self.replay_buffer.add(episodes=_episodes) + total_sampled += sum(len(eps) for eps in _episodes) + + # Summarize environment interaction and buffer data. + report_sampling_and_replay_buffer( + metrics=self.metrics, replay_buffer=self.replay_buffer + ) + # Get the replay buffer metrics. + replay_buffer_results = self.local_replay_buffer.get_metrics() + self.metrics.aggregate([replay_buffer_results], key=REPLAY_BUFFER_RESULTS) + + # Continue sampling batch_size_B x batch_length_T sized batches from the buffer + # and using these to update our models (`LearnerGroup.update()`) + # until the computed `training_ratio` is larger than the configured one, meaning + # we should go back and collect more samples again from the actual environment. + # However, when calculating the `training_ratio` here, we use only the + # trained steps in this very `training_step()` call over the most recent sample + # amount (`env_steps_last_regular_sample`), not the global values. This is to + # avoid a heavy overtraining at the very beginning when we have just pre-filled + # the buffer with the minimum amount of samples. + replayed_steps_this_iter = sub_iter = 0 + while ( + replayed_steps_this_iter / env_steps_last_regular_sample + ) < self.config.training_ratio: + # Time individual batch updates. + with self.metrics.log_time((TIMERS, LEARN_ON_BATCH_TIMER)): + logger.info(f"\tSub-iteration {self.training_iteration}/{sub_iter})") + + # Draw a new sample from the replay buffer. + sample = self.replay_buffer.sample( + batch_size_B=self.config.batch_size_B, + batch_length_T=self.config.batch_length_T, + ) + replayed_steps = self.config.batch_size_B * self.config.batch_length_T + replayed_steps_this_iter += replayed_steps + + if isinstance( + self.env_runner.env.single_action_space, gym.spaces.Discrete + ): + sample["actions_ints"] = sample[Columns.ACTIONS] + sample[Columns.ACTIONS] = one_hot( + sample["actions_ints"], + depth=self.env_runner.env.single_action_space.n, + ) + + # Perform the actual update via our learner group. + learner_results = self.learner_group.update( + batch=SampleBatch(sample).as_multi_agent(), + # TODO(sven): Maybe we should do this broadcase of global timesteps + # at the end, like for EnvRunner global env step counts. Maybe when + # we request the state from the Learners, we can - at the same + # time - send the current globally summed/reduced-timesteps. + timesteps={ + NUM_ENV_STEPS_SAMPLED_LIFETIME: self.metrics.peek( + (ENV_RUNNER_RESULTS, NUM_ENV_STEPS_SAMPLED_LIFETIME), + default=0, + ) + }, + ) + self.metrics.aggregate(learner_results, key=LEARNER_RESULTS) + + sub_iter += 1 + self.metrics.log_value(NUM_GRAD_UPDATES_LIFETIME, 1, reduce="sum") + + # Log videos showing how the decoder produces observation predictions + # from the posterior states. + # Only every n iterations and only for the first sampled batch row + # (videos are `config.batch_length_T` frames long). + report_predicted_vs_sampled_obs( + # TODO (sven): DreamerV3 is single-agent only. + metrics=self.metrics, + sample=sample, + batch_size_B=self.config.batch_size_B, + batch_length_T=self.config.batch_length_T, + symlog_obs=do_symlog_obs( + self.env_runner.env.single_observation_space, + self.config.symlog_obs, + ), + do_report=( + self.config.report_images_and_videos + and self.training_iteration % 100 == 0 + ), + ) + + # Log videos showing some of the dreamed trajectories and compare them with the + # actual trajectories from the train batch. + # Only every n iterations and only for the first sampled batch row AND first ts. + # (videos are `config.horizon_H` frames long originating from the observation + # at B=0 and T=0 in the train batch). + report_dreamed_eval_trajectory_vs_samples( + metrics=self.metrics, + sample=sample, + burn_in_T=0, + dreamed_T=self.config.horizon_H + 1, + dreamer_model=self.env_runner.module.dreamer_model, + symlog_obs=do_symlog_obs( + self.env_runner.env.single_observation_space, + self.config.symlog_obs, + ), + do_report=( + self.config.report_dream_data and self.training_iteration % 100 == 0 + ), + framework=self.config.framework_str, + ) + + # Update weights - after learning on the LearnerGroup - on all EnvRunner + # workers. + with self.metrics.log_time((TIMERS, SYNCH_WORKER_WEIGHTS_TIMER)): + # Only necessary if RLModule is not shared between (local) EnvRunner and + # (local) Learner. + # if not self.config.share_module_between_env_runner_and_learner: + self.metrics.log_value(NUM_SYNCH_WORKER_WEIGHTS, 1, reduce="sum") + self.env_runner_group.sync_weights( + from_worker_or_learner_group=self.learner_group, + inference_only=True, + ) + + # Add train results and the actual training ratio to stats. The latter should + # be close to the configured `training_ratio`. + self.metrics.log_value("actual_training_ratio", self.training_ratio, window=1) + + @property + def training_ratio(self) -> float: + """Returns the actual training ratio of this Algorithm (not the configured one). + + The training ratio is copmuted by dividing the total number of steps + trained thus far (replayed from the buffer) over the total number of actual + env steps taken thus far. + """ + eps = 0.0001 + return self.metrics.peek(NUM_ENV_STEPS_TRAINED_LIFETIME, default=0) / ( + ( + self.metrics.peek( + (ENV_RUNNER_RESULTS, NUM_ENV_STEPS_SAMPLED_LIFETIME), + default=eps, + ) + or eps + ) + ) + + # TODO (sven): Remove this once DreamerV3 is on the new SingleAgentEnvRunner. + @PublicAPI + def __setstate__(self, state) -> None: + """Sts the algorithm to the provided state + + Args: + state: The state dictionary to restore this `DreamerV3` instance to. + `state` may have been returned by a call to an `Algorithm`'s + `__getstate__()` method. + """ + # Call the `Algorithm`'s `__setstate__()` method. + super().__setstate__(state=state) + + # Assign the module to the local `EnvRunner` if sharing is enabled. + # Note, in `Learner.restore_from_path()` the module is first deleted + # and then a new one is built - therefore the worker has no + # longer a copy of the learner. + if self.config.share_module_between_env_runner_and_learner: + assert id(self.env_runner.module) != id( + self.learner_group._learner.module[DEFAULT_MODULE_ID] + ) + self.env_runner.module = self.learner_group._learner.module[ + DEFAULT_MODULE_ID + ] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/dreamerv3_catalog.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/dreamerv3_catalog.py new file mode 100644 index 0000000000000000000000000000000000000000..a2cca266ec64dfe55777c69ff574d175ad6766e2 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/dreamerv3_catalog.py @@ -0,0 +1,184 @@ +import gymnasium as gym +import numpy as np + +from ray.rllib.algorithms.dreamerv3.utils import ( + do_symlog_obs, + get_gru_units, + get_num_z_classes, + get_num_z_categoricals, +) +from ray.rllib.core.models.catalog import Catalog +from ray.rllib.core.models.base import Encoder, Model +from ray.rllib.utils import override + + +class DreamerV3Catalog(Catalog): + """The Catalog class used to build all the models needed for DreamerV3 training.""" + + def __init__( + self, + observation_space: gym.Space, + action_space: gym.Space, + model_config_dict: dict, + ): + """Initializes a DreamerV3Catalog instance. + + Args: + observation_space: The observation space of the environment. + action_space: The action space of the environment. + model_config_dict: The model config to use. + """ + super().__init__( + observation_space=observation_space, + action_space=action_space, + model_config_dict=model_config_dict, + ) + + self.model_size = self._model_config_dict["model_size"] + self.is_img_space = len(self.observation_space.shape) in [2, 3] + self.is_gray_scale = ( + self.is_img_space and len(self.observation_space.shape) == 2 + ) + # Compute the size of the vector coming out of the sequence model. + self.h_plus_z_flat = get_gru_units(self.model_size) + ( + get_num_z_categoricals(self.model_size) * get_num_z_classes(self.model_size) + ) + + # TODO (sven): We should work with sub-component configurations here, + # and even try replacing all current Dreamer model components with + # our default primitives. But for now, we'll construct the DreamerV3Model + # directly in our `build_...()` methods. + + @override(Catalog) + def build_encoder(self, framework: str) -> Encoder: + """Builds the World-Model's encoder network depending on the obs space.""" + if self.is_img_space: + if framework == "torch": + from ray.rllib.algorithms.dreamerv3.torch.models.components import ( + cnn_atari, + ) + + return cnn_atari.CNNAtari( + gray_scaled=self.is_gray_scale, + model_size=self.model_size, + ) + else: + raise ValueError(f"`framework={framework}` not supported!") + + else: + if framework == "torch": + from ray.rllib.algorithms.dreamerv3.torch.models.components import mlp + + return mlp.MLP( + input_size=int(np.prod(self.observation_space.shape)), + model_size=self.model_size, + ) + else: + raise ValueError(f"`framework={framework}` not supported!") + + def build_decoder(self, framework: str) -> Model: + """Builds the World-Model's decoder network depending on the obs space.""" + + if self.is_img_space: + if framework == "torch": + from ray.rllib.algorithms.dreamerv3.torch.models.components import ( + conv_transpose_atari, + ) + + return conv_transpose_atari.ConvTransposeAtari( + input_size=self.h_plus_z_flat, + gray_scaled=self.is_gray_scale, + model_size=self.model_size, + ) + else: + raise ValueError(f"`framework={framework}` not supported!") + + else: + if framework == "torch": + from ray.rllib.algorithms.dreamerv3.torch.models.components import ( + vector_decoder, + ) + + return vector_decoder.VectorDecoder( + input_size=self.h_plus_z_flat, + model_size=self.model_size, + observation_space=self.observation_space, + ) + else: + raise ValueError(f"`framework={framework}` not supported!") + + def build_world_model(self, framework: str, *, encoder, decoder) -> Model: + symlog_obs = do_symlog_obs( + self.observation_space, + self._model_config_dict.get("symlog_obs", "auto"), + ) + + if framework == "torch": + from ray.rllib.algorithms.dreamerv3.torch.models.world_model import ( + WorldModel, + ) + else: + raise ValueError(f"`framework={framework}` not supported!") + + return WorldModel( + model_size=self.model_size, + observation_space=self.observation_space, + action_space=self.action_space, + batch_length_T=self._model_config_dict["batch_length_T"], + encoder=encoder, + decoder=decoder, + symlog_obs=symlog_obs, + ) + + def build_actor(self, framework: str) -> Model: + if framework == "torch": + from ray.rllib.algorithms.dreamerv3.torch.models.actor_network import ( + ActorNetwork, + ) + + return ActorNetwork( + input_size=self.h_plus_z_flat, + action_space=self.action_space, + model_size=self.model_size, + ) + else: + raise ValueError(f"`framework={framework}` not supported!") + + def build_critic(self, framework: str) -> Model: + if framework == "torch": + from ray.rllib.algorithms.dreamerv3.torch.models.critic_network import ( + CriticNetwork, + ) + + return CriticNetwork( + input_size=self.h_plus_z_flat, + model_size=self.model_size, + ) + else: + raise ValueError(f"`framework={framework}` not supported!") + + def build_dreamer_model( + self, framework: str, *, world_model, actor, critic, horizon=None, gamma=None + ) -> Model: + if framework == "torch": + from ray.rllib.algorithms.dreamerv3.torch.models.dreamer_model import ( + DreamerModel, + ) + else: + raise ValueError(f"`framework={framework}` not supported!") + + return DreamerModel( + model_size=self.model_size, + action_space=self.action_space, + world_model=world_model, + actor=actor, + critic=critic, + **( + {} + if framework == "torch" + else { + "horizon": horizon, + "gamma": gamma, + } + ), + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/dreamerv3_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/dreamerv3_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..2bd634ca76e86a8c0499b5e039cfbb17de8ab14c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/dreamerv3_learner.py @@ -0,0 +1,31 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf + +[2] Mastering Atari with Discrete World Models - 2021 +D. Hafner, T. Lillicrap, M. Norouzi, J. Ba +https://arxiv.org/pdf/2010.02193.pdf +""" +from ray.rllib.core.learner.learner import Learner +from ray.rllib.utils.annotations import ( + override, + OverrideToImplementCustomLogic_CallToSuperRecommended, +) + + +class DreamerV3Learner(Learner): + """DreamerV3 specific Learner class. + + Only implements the `after_gradient_based_update()` method to define the logic + for updating the critic EMA-copy after each training step. + """ + + @OverrideToImplementCustomLogic_CallToSuperRecommended + @override(Learner) + def after_gradient_based_update(self, *, timesteps): + super().after_gradient_based_update(timesteps=timesteps) + + # Update EMA weights of the critic. + for module_id, module in self.module._rl_modules.items(): + module.unwrapped().critic.update_ema() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/dreamerv3_rl_module.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/dreamerv3_rl_module.py new file mode 100644 index 0000000000000000000000000000000000000000..20e0b8140b162e70598642dab4cb7d68273f7564 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/dreamerv3_rl_module.py @@ -0,0 +1,86 @@ +""" +This file holds framework-agnostic components for DreamerV3's RLModule. +""" + +import abc +from typing import Dict + +from ray.rllib.algorithms.dreamerv3.utils import ( + do_symlog_obs, + get_gru_units, + get_num_z_categoricals, + get_num_z_classes, +) +from ray.rllib.algorithms.dreamerv3.torch.models.actor_network import ActorNetwork +from ray.rllib.algorithms.dreamerv3.torch.models.critic_network import CriticNetwork +from ray.rllib.algorithms.dreamerv3.torch.models.dreamer_model import DreamerModel +from ray.rllib.algorithms.dreamerv3.torch.models.world_model import WorldModel +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.util.annotations import DeveloperAPI + + +ACTIONS_ONE_HOT = "actions_one_hot" + + +@DeveloperAPI(stability="alpha") +class DreamerV3RLModule(RLModule, abc.ABC): + @override(RLModule) + def setup(self): + super().setup() + + # Gather model-relevant settings. + T = self.model_config["batch_length_T"] + symlog_obs = do_symlog_obs( + self.observation_space, + self.model_config.get("symlog_obs", "auto"), + ) + model_size = self.model_config["model_size"] + + # Build encoder and decoder from catalog. + self.encoder = self.catalog.build_encoder(framework=self.framework) + self.decoder = self.catalog.build_decoder(framework=self.framework) + + # Build the world model (containing encoder and decoder). + self.world_model = WorldModel( + model_size=model_size, + observation_space=self.observation_space, + action_space=self.action_space, + batch_length_T=T, + encoder=self.encoder, + decoder=self.decoder, + symlog_obs=symlog_obs, + ) + input_size = get_gru_units(model_size) + get_num_z_classes( + model_size + ) * get_num_z_categoricals(model_size) + self.actor = ActorNetwork( + input_size=input_size, + action_space=self.action_space, + model_size=model_size, + ) + self.critic = CriticNetwork( + input_size=input_size, + model_size=model_size, + ) + # Build the final dreamer model (containing the world model). + self.dreamer_model = DreamerModel( + model_size=self.model_config["model_size"], + action_space=self.action_space, + world_model=self.world_model, + actor=self.actor, + critic=self.critic, + # horizon=horizon_H, + # gamma=gamma, + ) + self.action_dist_cls = self.catalog.get_action_dist_cls( + framework=self.framework + ) + + # Initialize the critic EMA net: + self.critic.init_ema() + + @override(RLModule) + def get_initial_state(self) -> Dict: + # Use `DreamerModel`'s `get_initial_state` method. + return self.dreamer_model.get_initial_state() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cde87d426dc44726c34a60cc9d459918b45a971e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/__pycache__/dreamerv3_torch_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/__pycache__/dreamerv3_torch_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9920d3ff0923dd553804a1f664266dcbba83424c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/__pycache__/dreamerv3_torch_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/__pycache__/dreamerv3_torch_rl_module.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/__pycache__/dreamerv3_torch_rl_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e2d19fe0136e6e434f68bece7c861f9f3772c85 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/__pycache__/dreamerv3_torch_rl_module.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/dreamerv3_torch_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/dreamerv3_torch_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..f33b9d2deb575459a655434fec119d03ec095f4b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/dreamerv3_torch_learner.py @@ -0,0 +1,925 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf + +[2] Mastering Atari with Discrete World Models - 2021 +D. Hafner, T. Lillicrap, M. Norouzi, J. Ba +https://arxiv.org/pdf/2010.02193.pdf +""" +from typing import Any, Dict, Tuple + +import gymnasium as gym + +from ray.rllib.algorithms.dreamerv3.dreamerv3 import DreamerV3Config +from ray.rllib.algorithms.dreamerv3.dreamerv3_learner import DreamerV3Learner +from ray.rllib.core import DEFAULT_MODULE_ID +from ray.rllib.core.columns import Columns +from ray.rllib.core.learner.learner import ParamDict +from ray.rllib.core.learner.torch.torch_learner import TorchLearner +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.torch_utils import symlog, two_hot, clip_gradients +from ray.rllib.utils.typing import ModuleID, TensorType + +torch, nn = try_import_torch() + + +class DreamerV3TorchLearner(DreamerV3Learner, TorchLearner): + """Implements DreamerV3 losses and gradient-based update logic in PyTorch. + + The critic EMA-copy update step can be found in the `DreamerV3Learner` base class, + as it is framework independent. + + We define 3 local PyTorch optimizers for the sub components "world_model", + "actor", and "critic". Each of these optimizers might use a different learning rate, + epsilon parameter, and gradient clipping thresholds and procedures. + """ + + def build(self) -> None: + super().build() + + # Store loss tensors here temporarily inside the loss function for (exact) + # consumption later by the compute gradients function. + # Keys=(module_id, optimizer_name), values=loss tensors (in-graph). + self._temp_losses = {} + + @override(TorchLearner) + def configure_optimizers_for_module( + self, module_id: ModuleID, config: DreamerV3Config = None + ): + """Create the 3 optimizers for Dreamer learning: world_model, actor, critic. + + The learning rates used are described in [1] and the epsilon values used here + - albeit probably not that important - are used by the author's own + implementation. + """ + + dreamerv3_module = self._module[module_id] + + # World Model optimizer. + optim_world_model = torch.optim.Adam( + dreamerv3_module.world_model.parameters(), + eps=1e-8, + ) + self.register_optimizer( + module_id=module_id, + optimizer_name="world_model", + optimizer=optim_world_model, + params=list(dreamerv3_module.world_model.parameters()), + lr_or_lr_schedule=config.world_model_lr, + ) + + # Actor optimizer. + optim_actor = torch.optim.Adam(dreamerv3_module.actor.parameters(), eps=1e-5) + self.register_optimizer( + module_id=module_id, + optimizer_name="actor", + optimizer=optim_actor, + params=list(dreamerv3_module.actor.parameters()), + lr_or_lr_schedule=config.actor_lr, + ) + + # Critic optimizer. + optim_critic = torch.optim.Adam(dreamerv3_module.critic.parameters(), eps=1e-5) + self.register_optimizer( + module_id=module_id, + optimizer_name="critic", + optimizer=optim_critic, + params=list(dreamerv3_module.critic.parameters()), + lr_or_lr_schedule=config.critic_lr, + ) + + @override(TorchLearner) + def postprocess_gradients_for_module( + self, + *, + module_id: ModuleID, + config: DreamerV3Config, + module_gradients_dict: Dict[str, Any], + ) -> ParamDict: + """Performs gradient clipping on the 3 module components' computed grads. + + Note that different grad global-norm clip values are used for the 3 + module components: world model, actor, and critic. + """ + for optimizer_name, optimizer in self.get_optimizers_for_module( + module_id=module_id + ): + grads_sub_dict = self.filter_param_dict_for_optimizer( + module_gradients_dict, optimizer + ) + # Figure out which grad clip setting to use. + grad_clip = ( + config.world_model_grad_clip_by_global_norm + if optimizer_name == "world_model" + else config.actor_grad_clip_by_global_norm + if optimizer_name == "actor" + else config.critic_grad_clip_by_global_norm + ) + global_norm = clip_gradients( + grads_sub_dict, grad_clip=grad_clip, grad_clip_by="global_norm" + ) + module_gradients_dict.update(grads_sub_dict) + + # DreamerV3 stats have the format: [WORLD_MODEL|ACTOR|CRITIC]_[stats name]. + self.metrics.log_dict( + { + optimizer_name.upper() + + "_gradients_global_norm": (global_norm.item()), + optimizer_name.upper() + + "_gradients_maxabs_after_clipping": ( + torch.max( + torch.abs( + torch.cat( + [g.flatten() for g in grads_sub_dict.values()] + ) + ) + ).item() + ), + }, + key=module_id, + window=1, # <- single items (should not be mean/ema-reduced over time). + ) + + return module_gradients_dict + + @override(TorchLearner) + def compute_gradients( + self, + loss_per_module, + **kwargs, + ): + """Override of the default gradient computation method. + + For DreamerV3, we need to compute gradients over the individual loss terms + as otherwise, the world model's parameters would have their gradients also + be influenced by the actor- and critic loss terms/gradient computations. + """ + grads = {} + + # Do actor and critic's grad computations first, such that after those two, + # we can zero out the gradients of the world model again (they will have values + # in them from the actor/critic backwards). + for component in ["actor", "critic", "world_model"]: + optim = self.get_optimizer(DEFAULT_MODULE_ID, component) + optim.zero_grad(set_to_none=True) + # Do the backward pass + loss = self._temp_losses.pop(component.upper()) + loss.backward(retain_graph=component in ["actor", "critic"]) + optim_grads = { + pid: p.grad + for pid, p in self.filter_param_dict_for_optimizer( + self._params, optim + ).items() + } + for ref, grad in optim_grads.items(): + assert ref not in grads + grads[ref] = grad + + return grads + + @override(TorchLearner) + def compute_loss_for_module( + self, + module_id: ModuleID, + config: DreamerV3Config, + batch: Dict[str, TensorType], + fwd_out: Dict[str, TensorType], + ) -> TensorType: + # World model losses. + prediction_losses = self._compute_world_model_prediction_losses( + config=config, + rewards_B_T=batch[Columns.REWARDS], + continues_B_T=(1.0 - batch["is_terminated"].float()), + fwd_out=fwd_out, + ) + + ( + L_dyn_B_T, + L_rep_B_T, + ) = self._compute_world_model_dynamics_and_representation_loss( + config=config, fwd_out=fwd_out + ) + L_dyn = torch.mean(L_dyn_B_T) + L_rep = torch.mean(L_rep_B_T) + # Make sure values for L_rep and L_dyn are the same (they only differ in their + # gradients). + assert torch.allclose(L_dyn, L_rep) + + # Compute the actual total loss using fixed weights described in [1] eq. 4. + L_world_model_total_B_T = ( + 1.0 * prediction_losses["L_prediction_B_T"] + + 0.5 * L_dyn_B_T + + 0.1 * L_rep_B_T + ) + + # In the paper, it says to sum up timesteps, and average over + # batch (see eq. 4 in [1]). But Danijar's implementation only does + # averaging (over B and T), so we'll do this here as well. This is generally + # true for all other loss terms as well (we'll always just average, no summing + # over T axis!). + L_world_model_total = torch.mean(L_world_model_total_B_T) + + # Log world model loss stats. + self.metrics.log_dict( + { + "WORLD_MODEL_learned_initial_h": self.module[module_id] + .unwrapped() + .world_model.initial_h.mean(), + # Prediction losses. + # Decoder (obs) loss. + "WORLD_MODEL_L_decoder": prediction_losses["L_decoder"], + # Reward loss. + "WORLD_MODEL_L_reward": prediction_losses["L_reward"], + # Continue loss. + "WORLD_MODEL_L_continue": prediction_losses["L_continue"], + # Total. + "WORLD_MODEL_L_prediction": prediction_losses["L_prediction"], + # Dynamics loss. + "WORLD_MODEL_L_dynamics": L_dyn, + # Representation loss. + "WORLD_MODEL_L_representation": L_rep, + # Total loss. + "WORLD_MODEL_L_total": L_world_model_total, + }, + key=module_id, + window=1, # <- single items (should not be mean/ema-reduced over time). + ) + + # Add the predicted obs distributions for possible (video) summarization. + if config.report_images_and_videos: + self.metrics.log_value( + (module_id, "WORLD_MODEL_fwd_out_obs_distribution_means_b0xT"), + fwd_out["obs_distribution_means_BxT"][: self.config.batch_length_T], + reduce=None, # No reduction, we want the obs tensor to stay in-tact. + window=1, # <- single items (should not be mean/ema-reduced over time). + ) + + if config.report_individual_batch_item_stats: + # Log important world-model loss stats. + self.metrics.log_dict( + { + "WORLD_MODEL_L_decoder_B_T": prediction_losses["L_decoder_B_T"], + "WORLD_MODEL_L_reward_B_T": prediction_losses["L_reward_B_T"], + "WORLD_MODEL_L_continue_B_T": prediction_losses["L_continue_B_T"], + "WORLD_MODEL_L_prediction_B_T": ( + prediction_losses["L_prediction_B_T"] + ), + "WORLD_MODEL_L_dynamics_B_T": L_dyn_B_T, + "WORLD_MODEL_L_representation_B_T": L_rep_B_T, + "WORLD_MODEL_L_total_B_T": L_world_model_total_B_T, + }, + key=module_id, + window=1, # <- single items (should not be mean/ema-reduced over time). + ) + + # Dream trajectories starting in all internal states (h + z_posterior) that were + # computed during world model training. + # Everything goes in as BxT: We are starting a new dream trajectory at every + # actually encountered timestep in the batch, so we are creating B*T + # trajectories of len `horizon_H`. + dream_data = ( + self.module[module_id] + .unwrapped() + .dreamer_model.dream_trajectory( + start_states={ + "h": fwd_out["h_states_BxT"], + "z": fwd_out["z_posterior_states_BxT"], + }, + start_is_terminated=batch["is_terminated"].reshape(-1), # -> BxT + timesteps_H=config.horizon_H, + gamma=config.gamma, + ) + ) + if config.report_dream_data: + # To reduce this massive amount of data a little, slice out a T=1 piece + # from each stats that has the shape (H, BxT), meaning convert e.g. + # `rewards_dreamed_t0_to_H_BxT` into `rewards_dreamed_t0_to_H_Bx1`. + # This will reduce the amount of data to be transferred and reported + # by the factor of `batch_length_T`. + self.metrics.log_dict( + { + # Replace 'T' with '1'. + key[:-1] + "1": value[:, :: config.batch_length_T] + for key, value in dream_data.items() + if key.endswith("H_BxT") + }, + key=(module_id, "dream_data"), + reduce=None, + window=1, # <- single items (should not be mean/ema-reduced over time). + ) + + value_targets_t0_to_Hm1_BxT = self._compute_value_targets( + config=config, + # Learn critic in symlog'd space. + rewards_t0_to_H_BxT=dream_data["rewards_dreamed_t0_to_H_BxT"], + intrinsic_rewards_t1_to_H_BxT=( + dream_data["rewards_intrinsic_t1_to_H_B"] + if config.use_curiosity + else None + ), + continues_t0_to_H_BxT=dream_data["continues_dreamed_t0_to_H_BxT"], + value_predictions_t0_to_H_BxT=dream_data["values_dreamed_t0_to_H_BxT"], + ) + # self.metrics.log_value( + # key=(module_id, "VALUE_TARGETS_H_BxT"), + # value=value_targets_t0_to_Hm1_BxT, + # window=1, # <- single items (should not be mean/ema-reduced over time). + # ) + + CRITIC_L_total = self._compute_critic_loss( + module_id=module_id, + config=config, + dream_data=dream_data, + value_targets_t0_to_Hm1_BxT=value_targets_t0_to_Hm1_BxT, + ) + if config.train_actor: + ACTOR_L_total = self._compute_actor_loss( + module_id=module_id, + config=config, + dream_data=dream_data, + value_targets_t0_to_Hm1_BxT=value_targets_t0_to_Hm1_BxT, + ) + else: + ACTOR_L_total = 0.0 + + self._temp_losses["ACTOR"] = ACTOR_L_total + self._temp_losses["CRITIC"] = CRITIC_L_total + self._temp_losses["WORLD_MODEL"] = L_world_model_total + + # Return the total loss as a sum of all individual losses. + return L_world_model_total + CRITIC_L_total + ACTOR_L_total + + def _compute_world_model_prediction_losses( + self, + *, + config: DreamerV3Config, + rewards_B_T: TensorType, + continues_B_T: TensorType, + fwd_out: Dict[str, TensorType], + ) -> Dict[str, TensorType]: + """Helper method computing all world-model related prediction losses. + + Prediction losses are used to train the predictors of the world model, which + are: Reward predictor, continue predictor, and the decoder (which predicts + observations). + + Args: + config: The DreamerV3Config to use. + rewards_B_T: The rewards batch in the shape (B, T) and of type float32. + continues_B_T: The continues batch in the shape (B, T) and of type float32 + (1.0 -> continue; 0.0 -> end of episode). + fwd_out: The `forward_train` outputs of the DreamerV3RLModule. + """ + + # Learn to produce symlog'd observation predictions. + # If symlog is disabled (e.g. for uint8 image inputs), `obs_symlog_BxT` is the + # same as `obs_BxT`. + obs_BxT = fwd_out["sampled_obs_symlog_BxT"] + obs_distr_means = fwd_out["obs_distribution_means_BxT"] + + # Leave time dim folded (BxT) and flatten all other (e.g. image) dims. + obs_BxT = obs_BxT.reshape(obs_BxT.shape[0], -1) + + # Squared diff loss w/ sum(!) over all (already folded) obs dims. + # decoder_loss_BxT = SUM[ (obs_distr.loc - observations)^2 ] + # Note: This is described strangely in the paper (stating a neglogp loss here), + # but the author's own implementation actually uses simple MSE with the loc + # of the Gaussian. + decoder_loss_BxT = torch.sum(torch.square(obs_distr_means - obs_BxT), dim=-1) + + # Unfold time rank back in. + decoder_loss_B_T = decoder_loss_BxT.reshape( + config.batch_size_B_per_learner, config.batch_length_T + ) + L_decoder = torch.mean(decoder_loss_B_T) + + # The FiniteDiscrete reward bucket distribution computed by our reward + # predictor. + # [B x num_buckets]. + reward_logits_BxT = fwd_out["reward_logits_BxT"] + # Learn to produce symlog'd reward predictions. + rewards_symlog_B_T = symlog(rewards_B_T) + # Fold time dim. + rewards_symlog_BxT = rewards_symlog_B_T.reshape(-1) + + # Two-hot encode. + two_hot_rewards_symlog_BxT = two_hot(rewards_symlog_BxT, device=self._device) + # two_hot_rewards_symlog_BxT=[B*T, num_buckets] + reward_log_pred_BxT = reward_logits_BxT - torch.logsumexp( + reward_logits_BxT, dim=-1, keepdim=True + ) + # Multiply with two-hot targets and neg. + reward_loss_two_hot_BxT = -torch.sum( + reward_log_pred_BxT * two_hot_rewards_symlog_BxT, dim=-1 + ) + # Unfold time rank back in. + reward_loss_two_hot_B_T = reward_loss_two_hot_BxT.reshape( + config.batch_size_B_per_learner, config.batch_length_T + ) + L_reward_two_hot = torch.mean(reward_loss_two_hot_B_T) + + # Probabilities that episode continues, computed by our continue predictor. + # [B] + continue_distr = fwd_out["continue_distribution_BxT"] + # -log(p) loss + # Fold time dim. + continues_BxT = continues_B_T.reshape(-1) + continue_loss_BxT = -continue_distr.log_prob(continues_BxT) + # Unfold time rank back in. + continue_loss_B_T = continue_loss_BxT.reshape( + config.batch_size_B_per_learner, config.batch_length_T + ) + L_continue = torch.mean(continue_loss_B_T) + + # Sum all losses together as the "prediction" loss. + L_pred_B_T = decoder_loss_B_T + reward_loss_two_hot_B_T + continue_loss_B_T + L_pred = torch.mean(L_pred_B_T) + + return { + "L_decoder_B_T": decoder_loss_B_T, + "L_decoder": L_decoder, + "L_reward": L_reward_two_hot, + "L_reward_B_T": reward_loss_two_hot_B_T, + "L_continue": L_continue, + "L_continue_B_T": continue_loss_B_T, + "L_prediction": L_pred, + "L_prediction_B_T": L_pred_B_T, + } + + def _compute_world_model_dynamics_and_representation_loss( + self, *, config: DreamerV3Config, fwd_out: Dict[str, Any] + ) -> Tuple[TensorType, TensorType]: + """Helper method computing the world-model's dynamics and representation losses. + + Args: + config: The DreamerV3Config to use. + fwd_out: The `forward_train` outputs of the DreamerV3RLModule. + + Returns: + Tuple consisting of a) dynamics loss: Trains the prior network, predicting + z^ prior states from h-states and b) representation loss: Trains posterior + network, predicting z posterior states from h-states and (encoded) + observations. + """ + + # Actual distribution over stochastic internal states (z) produced by the + # encoder. + z_posterior_probs_BxT = fwd_out["z_posterior_probs_BxT"] + z_posterior_distr_BxT = torch.distributions.Independent( + torch.distributions.OneHotCategorical(probs=z_posterior_probs_BxT), + reinterpreted_batch_ndims=1, + ) + + # Actual distribution over stochastic internal states (z) produced by the + # dynamics network. + z_prior_probs_BxT = fwd_out["z_prior_probs_BxT"] + z_prior_distr_BxT = torch.distributions.Independent( + torch.distributions.OneHotCategorical(probs=z_prior_probs_BxT), + reinterpreted_batch_ndims=1, + ) + + # Stop gradient for encoder's z-outputs: + sg_z_posterior_distr_BxT = torch.distributions.Independent( + torch.distributions.OneHotCategorical(probs=z_posterior_probs_BxT.detach()), + reinterpreted_batch_ndims=1, + ) + # Stop gradient for dynamics model's z-outputs: + sg_z_prior_distr_BxT = torch.distributions.Independent( + torch.distributions.OneHotCategorical(probs=z_prior_probs_BxT.detach()), + reinterpreted_batch_ndims=1, + ) + + # Implement free bits. According to [1]: + # "To avoid a degenerate solution where the dynamics are trivial to predict but + # contain not enough information about the inputs, we employ free bits by + # clipping the dynamics and representation losses below the value of + # 1 nat ≈ 1.44 bits. This disables them while they are already minimized well to + # focus the world model on its prediction loss" + L_dyn_BxT = torch.clamp( + torch.distributions.kl.kl_divergence( + sg_z_posterior_distr_BxT, z_prior_distr_BxT + ), + min=1.0, + ) + # Unfold time rank back in. + L_dyn_B_T = L_dyn_BxT.reshape( + config.batch_size_B_per_learner, config.batch_length_T + ) + + L_rep_BxT = torch.clamp( + torch.distributions.kl.kl_divergence( + z_posterior_distr_BxT, sg_z_prior_distr_BxT + ), + min=1.0, + ) + # Unfold time rank back in. + L_rep_B_T = L_rep_BxT.reshape( + config.batch_size_B_per_learner, config.batch_length_T + ) + + return L_dyn_B_T, L_rep_B_T + + def _compute_actor_loss( + self, + *, + module_id: ModuleID, + config: DreamerV3Config, + dream_data: Dict[str, TensorType], + value_targets_t0_to_Hm1_BxT: TensorType, + ) -> TensorType: + """Helper method computing the actor's loss terms. + + Args: + module_id: The module_id for which to compute the actor loss. + config: The DreamerV3Config to use. + dream_data: The data generated by dreaming for H steps (horizon) starting + from any BxT state (sampled from the buffer for the train batch). + value_targets_t0_to_Hm1_BxT: The computed value function targets of the + shape (t0 to H-1, BxT). + + Returns: + The total actor loss tensor. + """ + actor = self.module[module_id].unwrapped().actor + + # Note: `scaled_value_targets_t0_to_Hm1_B` are NOT stop_gradient'd yet. + scaled_value_targets_t0_to_Hm1_B = self._compute_scaled_value_targets( + module_id=module_id, + config=config, + value_targets_t0_to_Hm1_BxT=value_targets_t0_to_Hm1_BxT, + value_predictions_t0_to_Hm1_BxT=dream_data["values_dreamed_t0_to_H_BxT"][ + :-1 + ], + ) + + # Actions actually taken in the dream. + actions_dreamed = dream_data["actions_dreamed_t0_to_H_BxT"][:-1].detach() + actions_dreamed_dist_params_t0_to_Hm1_B = dream_data[ + "actions_dreamed_dist_params_t0_to_H_BxT" + ][:-1] + + dist_t0_to_Hm1_B = actor.get_action_dist_object( + actions_dreamed_dist_params_t0_to_Hm1_B + ) + + # Compute log(p)s of all possible actions in the dream. + if isinstance( + self.module[module_id].unwrapped().actor.action_space, gym.spaces.Discrete + ): + # Note that when we create the Categorical action distributions, we compute + # unimix probs, then math.log these and provide these log(p) as "logits" to + # the Categorical. So here, we'll continue to work with log(p)s (not + # really "logits")! + logp_actions_t0_to_Hm1_B = actions_dreamed_dist_params_t0_to_Hm1_B + + # Log probs of actions actually taken in the dream. + logp_actions_dreamed_t0_to_Hm1_B = torch.sum( + actions_dreamed * logp_actions_t0_to_Hm1_B, + dim=-1, + ) + # First term of loss function. [1] eq. 11. + logp_loss_H_B = ( + logp_actions_dreamed_t0_to_Hm1_B + * scaled_value_targets_t0_to_Hm1_B.detach() + ) + # Box space. + else: + logp_actions_dreamed_t0_to_Hm1_B = dist_t0_to_Hm1_B.log_prob( + actions_dreamed + ) + # First term of loss function. [1] eq. 11. + logp_loss_H_B = scaled_value_targets_t0_to_Hm1_B + + assert logp_loss_H_B.ndim == 2 + + # Add entropy loss term (second term [1] eq. 11). + entropy_H_B = dist_t0_to_Hm1_B.entropy() + assert entropy_H_B.ndim == 2 + entropy = torch.mean(entropy_H_B) + + L_actor_reinforce_term_H_B = -logp_loss_H_B + L_actor_action_entropy_term_H_B = -config.entropy_scale * entropy_H_B + + L_actor_H_B = L_actor_reinforce_term_H_B + L_actor_action_entropy_term_H_B + # Mask out everything that goes beyond a predicted continue=False boundary. + L_actor_H_B *= dream_data["dream_loss_weights_t0_to_H_BxT"][:-1].detach() + L_actor = torch.mean(L_actor_H_B) + + # Log important actor loss stats. + self.metrics.log_dict( + { + "ACTOR_L_total": L_actor, + "ACTOR_value_targets_pct95_ema": actor.ema_value_target_pct95, + "ACTOR_value_targets_pct5_ema": actor.ema_value_target_pct5, + "ACTOR_action_entropy": entropy, + # Individual loss terms. + "ACTOR_L_neglogp_reinforce_term": torch.mean( + L_actor_reinforce_term_H_B + ), + "ACTOR_L_neg_entropy_term": torch.mean(L_actor_action_entropy_term_H_B), + }, + key=module_id, + window=1, # <- single items (should not be mean/ema-reduced over time). + ) + if config.report_individual_batch_item_stats: + self.metrics.log_dict( + { + "ACTOR_L_total_H_BxT": L_actor_H_B, + "ACTOR_logp_actions_dreamed_H_BxT": ( + logp_actions_dreamed_t0_to_Hm1_B + ), + "ACTOR_scaled_value_targets_H_BxT": ( + scaled_value_targets_t0_to_Hm1_B + ), + "ACTOR_action_entropy_H_BxT": entropy_H_B, + # Individual loss terms. + "ACTOR_L_neglogp_reinforce_term_H_BxT": L_actor_reinforce_term_H_B, + "ACTOR_L_neg_entropy_term_H_BxT": L_actor_action_entropy_term_H_B, + }, + key=module_id, + window=1, # <- single items (should not be mean/ema-reduced over time). + ) + + return L_actor + + def _compute_critic_loss( + self, + *, + module_id: ModuleID, + config: DreamerV3Config, + dream_data: Dict[str, TensorType], + value_targets_t0_to_Hm1_BxT: TensorType, + ) -> TensorType: + """Helper method computing the critic's loss terms. + + Args: + module_id: The ModuleID for which to compute the critic loss. + config: The DreamerV3Config to use. + dream_data: The data generated by dreaming for H steps (horizon) starting + from any BxT state (sampled from the buffer for the train batch). + value_targets_t0_to_Hm1_BxT: The computed value function targets of the + shape (t0 to H-1, BxT). + + Returns: + The total critic loss tensor. + """ + # B=BxT + H, B = dream_data["rewards_dreamed_t0_to_H_BxT"].shape[:2] + Hm1 = H - 1 + + # Note that value targets are NOT symlog'd and go from t0 to H-1, not H, like + # all the other dream data. + + # From here on: B=BxT + value_targets_t0_to_Hm1_B = value_targets_t0_to_Hm1_BxT.detach() + value_symlog_targets_t0_to_Hm1_B = symlog(value_targets_t0_to_Hm1_B) + # Fold time rank (for two_hot'ing). + value_symlog_targets_HxB = value_symlog_targets_t0_to_Hm1_B.view( + -1, + ) + value_symlog_targets_two_hot_HxB = two_hot( + value_symlog_targets_HxB, device=self._device + ) + # Unfold time rank. + value_symlog_targets_two_hot_t0_to_Hm1_B = ( + value_symlog_targets_two_hot_HxB.view( + [Hm1, B, value_symlog_targets_two_hot_HxB.shape[-1]] + ) + ) + + # Get (B x T x probs) tensor from return distributions. + # Use the value function outputs that don't graph-trace back through the + # world model. The other corresponding value function outputs + # which do trace back through the world model are only used for cont. actions + # for the actor loss (to compute the scaled value targets). + value_symlog_logits_HxB = dream_data[ + "values_symlog_dreamed_logits_t0_to_HxBxT_wm_detached" + ] + # Unfold time rank and cut last time index to match value targets. + value_symlog_logits_t0_to_Hm1_B = value_symlog_logits_HxB.view( + [H, B, value_symlog_logits_HxB.shape[-1]] + )[:-1] + + values_log_pred_Hm1_B = value_symlog_logits_t0_to_Hm1_B - torch.logsumexp( + value_symlog_logits_t0_to_Hm1_B, dim=-1, keepdim=True + ) + # Multiply with two-hot targets and neg. + value_loss_two_hot_H_B = -torch.sum( + values_log_pred_Hm1_B * value_symlog_targets_two_hot_t0_to_Hm1_B, dim=-1 + ) + + # Compute EMA regularization loss. + # Expected values (dreamed) from the EMA (slow critic) net. + value_symlog_ema_t0_to_Hm1_B = dream_data[ + "v_symlog_dreamed_ema_t0_to_H_BxT" + ].detach()[:-1] + # Fold time rank (for two_hot'ing). + value_symlog_ema_HxB = value_symlog_ema_t0_to_Hm1_B.view( + -1, + ) + value_symlog_ema_two_hot_HxB = two_hot( + value_symlog_ema_HxB, device=self._device + ) + # Unfold time rank. + value_symlog_ema_two_hot_t0_to_Hm1_B = value_symlog_ema_two_hot_HxB.view( + [Hm1, B, value_symlog_ema_two_hot_HxB.shape[-1]] + ) + + # Compute ema regularizer loss. + # In the paper, it is not described how exactly to form this regularizer term + # and how to weigh it. + # So we follow Danijar's repo here: + # `reg = -dist.log_prob(sg(self.slow(traj).mean()))` + # with a weight of 1.0, where dist is the bucket'ized distribution output by the + # fast critic. sg=stop gradient; mean() -> use the expected EMA values. + # Multiply with two-hot targets and neg. + ema_regularization_loss_H_B = -torch.sum( + values_log_pred_Hm1_B * value_symlog_ema_two_hot_t0_to_Hm1_B, dim=-1 + ) + + L_critic_H_B = value_loss_two_hot_H_B + ema_regularization_loss_H_B + + # Mask out everything that goes beyond a predicted continue=False boundary. + L_critic_H_B *= dream_data["dream_loss_weights_t0_to_H_BxT"].detach()[:-1] + + # Reduce over both H- (time) axis and B-axis (mean). + L_critic = L_critic_H_B.mean() + + # Log important critic loss stats. + self.metrics.log_dict( + { + "CRITIC_L_total": L_critic, + "CRITIC_L_neg_logp_of_value_targets": torch.mean( + value_loss_two_hot_H_B + ), + "CRITIC_L_slow_critic_regularization": torch.mean( + ema_regularization_loss_H_B + ), + }, + key=module_id, + window=1, # <- single items (should not be mean/ema-reduced over time). + ) + if config.report_individual_batch_item_stats: + # Log important critic loss stats. + self.metrics.log_dict( + { + # Symlog'd value targets. Critic learns to predict symlog'd values. + "VALUE_TARGETS_symlog_H_BxT": value_symlog_targets_t0_to_Hm1_B, + # Critic loss terms. + "CRITIC_L_total_H_BxT": L_critic_H_B, + "CRITIC_L_neg_logp_of_value_targets_H_BxT": value_loss_two_hot_H_B, + "CRITIC_L_slow_critic_regularization_H_BxT": ( + ema_regularization_loss_H_B + ), + }, + key=module_id, + window=1, # <- single items (should not be mean/ema-reduced over time). + ) + + return L_critic + + def _compute_value_targets( + self, + *, + config: DreamerV3Config, + rewards_t0_to_H_BxT: torch.Tensor, + intrinsic_rewards_t1_to_H_BxT: torch.Tensor, + continues_t0_to_H_BxT: torch.Tensor, + value_predictions_t0_to_H_BxT: torch.Tensor, + ) -> torch.Tensor: + """Helper method computing the value targets. + + All args are (H, BxT, ...) and in non-symlog'd (real) reward space. + Non-symlog is important b/c log(a+b) != log(a) + log(b). + See [1] eq. 8 and 10. + Thus, targets are always returned in real (non-symlog'd space). + They need to be re-symlog'd before computing the critic loss from them (b/c the + critic produces predictions in symlog space). + Note that the original B and T ranks together form the new batch dimension + (folded into BxT) and the new time rank is the dream horizon (hence: [H, BxT]). + + Variable names nomenclature: + `H`=1+horizon_H (start state + H steps dreamed), + `BxT`=batch_size * batch_length (meaning the original trajectory time rank has + been folded). + + Rewards, continues, and value predictions are all of shape [t0-H, BxT] + (time-major), whereas returned targets are [t0 to H-1, B] (last timestep missing + b/c the target value equals vf prediction in that location anyways. + + Args: + config: The DreamerV3Config to use. + rewards_t0_to_H_BxT: The reward predictor's predictions over the + dreamed trajectory t0 to H (and for the batch BxT). + intrinsic_rewards_t1_to_H_BxT: The predicted intrinsic rewards over the + dreamed trajectory t0 to H (and for the batch BxT). + continues_t0_to_H_BxT: The continue predictor's predictions over the + dreamed trajectory t0 to H (and for the batch BxT). + value_predictions_t0_to_H_BxT: The critic's value predictions over the + dreamed trajectory t0 to H (and for the batch BxT). + + Returns: + The value targets in the shape: [t0toH-1, BxT]. Note that the last step (H) + does not require a value target as it matches the critic's value prediction + anyways. + """ + # The first reward is irrelevant (not used for any VF target). + rewards_t1_to_H_BxT = rewards_t0_to_H_BxT[1:] + if intrinsic_rewards_t1_to_H_BxT is not None: + rewards_t1_to_H_BxT += intrinsic_rewards_t1_to_H_BxT + + # In all the following, when building value targets for t=1 to T=H, + # exclude rewards & continues for t=1 b/c we don't need r1 or c1. + # The target (R1) for V1 is built from r2, c2, and V2/R2. + discount = continues_t0_to_H_BxT[1:] * config.gamma # shape=[2-16, BxT] + Rs = [value_predictions_t0_to_H_BxT[-1]] # Rs indices=[16] + intermediates = ( + rewards_t1_to_H_BxT + + discount * (1 - config.gae_lambda) * value_predictions_t0_to_H_BxT[1:] + ) + # intermediates.shape=[2-16, BxT] + + # Loop through reversed timesteps (axis=1) from T+1 to t=2. + for t in reversed(range(discount.shape[0])): + Rs.append(intermediates[t] + discount[t] * config.gae_lambda * Rs[-1]) + + # Reverse time axis and cut the last entry (value estimate at very end + # cannot be learnt from as it's the same as the ... well ... value estimate). + targets_t0toHm1_BxT = torch.stack(list(reversed(Rs))[:-1], dim=0) + # targets.shape=[t0 to H-1,BxT] + + return targets_t0toHm1_BxT + + def _compute_scaled_value_targets( + self, + *, + module_id: ModuleID, + config: DreamerV3Config, + value_targets_t0_to_Hm1_BxT: torch.Tensor, + value_predictions_t0_to_Hm1_BxT: torch.Tensor, + ) -> torch.Tensor: + """Helper method computing the scaled value targets. + + Args: + module_id: The module_id to compute value targets for. + config: The DreamerV3Config to use. + value_targets_t0_to_Hm1_BxT: The value targets computed by + `self._compute_value_targets` in the shape of (t0 to H-1, BxT) + and of type float32. + value_predictions_t0_to_Hm1_BxT: The critic's value predictions over the + dreamed trajectories (w/o the last timestep). The shape of this + tensor is (t0 to H-1, BxT) and the type is float32. + + Returns: + The scaled value targets used by the actor for REINFORCE policy updates + (using scaled advantages). See [1] eq. 12 for more details. + """ + actor = self.module[module_id].unwrapped().actor + + value_targets_H_B = value_targets_t0_to_Hm1_BxT + value_predictions_H_B = value_predictions_t0_to_Hm1_BxT + + # Compute S: [1] eq. 12. + Per_R_5 = torch.quantile(value_targets_H_B, 0.05) + Per_R_95 = torch.quantile(value_targets_H_B, 0.95) + + # Update EMA values for 5 and 95 percentile, stored as actor network's + # parameters. + # 5 percentile + new_val_pct5 = torch.where( + torch.isnan(actor.ema_value_target_pct5), + # is NaN: Initial values: Just set. + Per_R_5, + # Later update (something already stored in EMA variable): Update EMA. + ( + config.return_normalization_decay * actor.ema_value_target_pct5 + + (1.0 - config.return_normalization_decay) * Per_R_5 + ), + ) + actor.ema_value_target_pct5.data = new_val_pct5 + # 95 percentile + new_val_pct95 = torch.where( + # is NaN: Initial values: Just set. + torch.isnan(actor.ema_value_target_pct95), + # Later update (something already stored in EMA variable): Update EMA. + Per_R_95, + ( + config.return_normalization_decay * actor.ema_value_target_pct95 + + (1.0 - config.return_normalization_decay) * Per_R_95 + ), + ) + actor.ema_value_target_pct95.data = new_val_pct95 + + # [1] eq. 11 (first term). + offset = actor.ema_value_target_pct5 + invscale = torch.clamp( + (actor.ema_value_target_pct95 - actor.ema_value_target_pct5), + min=1e-8, + ) + scaled_value_targets_H_B = (value_targets_H_B - offset) / invscale + scaled_value_predictions_H_B = (value_predictions_H_B - offset) / invscale + + # Return advantages. + return scaled_value_targets_H_B - scaled_value_predictions_H_B diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/dreamerv3_torch_rl_module.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/dreamerv3_torch_rl_module.py new file mode 100644 index 0000000000000000000000000000000000000000..ea7b31c5a1d6fcf50961f3f93b54756d5a813aa2 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/dreamerv3_torch_rl_module.py @@ -0,0 +1,78 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf + +[2] Mastering Atari with Discrete World Models - 2021 +D. Hafner, T. Lillicrap, M. Norouzi, J. Ba +https://arxiv.org/pdf/2010.02193.pdf +""" +from typing import Any, Dict + +import gymnasium as gym +import torch + +from ray.rllib.algorithms.dreamerv3.dreamerv3_rl_module import ( + ACTIONS_ONE_HOT, + DreamerV3RLModule, +) +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.core.rl_module.torch.torch_rl_module import TorchRLModule +from ray.rllib.utils.annotations import override + + +class DreamerV3TorchRLModule(TorchRLModule, DreamerV3RLModule): + """The torch-specific RLModule class for DreamerV3. + + Serves mainly as a thin-wrapper around the `DreamerModel` (a torch.nn.Module) class. + """ + + framework = "torch" + + @override(TorchRLModule) + def _forward_inference(self, batch: Dict[str, Any], **kwargs) -> Dict[str, Any]: + # Call the Dreamer-Model's forward_inference method and return a dict. + with torch.no_grad(): + actions, next_state = self.dreamer_model.forward_inference( + observations=batch[Columns.OBS], + previous_states=batch[Columns.STATE_IN], + is_first=batch["is_first"], + ) + return self._forward_inference_or_exploration_helper(batch, actions, next_state) + + @override(TorchRLModule) + def _forward_exploration(self, batch: Dict[str, Any], **kwargs) -> Dict[str, Any]: + # Call the Dreamer-Model's forward_exploration method and return a dict. + with torch.no_grad(): + actions, next_state = self.dreamer_model.forward_exploration( + observations=batch[Columns.OBS], + previous_states=batch[Columns.STATE_IN], + is_first=batch["is_first"], + ) + return self._forward_inference_or_exploration_helper(batch, actions, next_state) + + @override(RLModule) + def _forward_train(self, batch: Dict[str, Any], **kwargs): + # Call the Dreamer-Model's forward_train method and return its outputs as-is. + return self.dreamer_model.forward_train( + observations=batch[Columns.OBS], + actions=batch[Columns.ACTIONS], + is_first=batch["is_first"], + ) + + def _forward_inference_or_exploration_helper(self, batch, actions, next_state): + # Unfold time dimension. + shape = batch[Columns.OBS].shape + B, T = shape[0], shape[1] + actions = actions.view((B, T) + actions.shape[1:]) + + output = { + Columns.ACTIONS: actions, + ACTIONS_ONE_HOT: actions, + Columns.STATE_OUT: next_state, + } + # Undo one-hot actions? + if isinstance(self.action_space, gym.spaces.Discrete): + output[Columns.ACTIONS] = torch.argmax(actions, dim=-1) + return output diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb51ec4b2ab1bc20c618c6992f53aa8c94723a11 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/__pycache__/actor_network.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/__pycache__/actor_network.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf3bd4d30119d5b3512f9d9b3e04ed0d9e8d2454 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/__pycache__/actor_network.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/__pycache__/critic_network.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/__pycache__/critic_network.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73c8aa19b38e5eb519d43877887b0c50264f01c3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/__pycache__/critic_network.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/__pycache__/dreamer_model.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/__pycache__/dreamer_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6383ac364eaf414b68484cdb17aba24c530ff60d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/__pycache__/dreamer_model.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/__pycache__/world_model.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/__pycache__/world_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b0b3c13f986c6d23ba7490106ddc0d1d386f8b6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/__pycache__/world_model.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/actor_network.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/actor_network.py new file mode 100644 index 0000000000000000000000000000000000000000..8a02a41bd9bfb902085b1fc8b5ad61f0ca0d619a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/actor_network.py @@ -0,0 +1,179 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf +""" +import gymnasium as gym +import numpy as np + +from ray.rllib.algorithms.dreamerv3.torch.models.components.mlp import MLP +from ray.rllib.utils.framework import try_import_torch + + +torch, nn = try_import_torch() + + +class ActorNetwork(nn.Module): + """The `actor` (policy net) of DreamerV3. + + Consists of a simple MLP for Discrete actions and two MLPs for cont. actions (mean + and stddev). + Also contains two scalar variables to keep track of the percentile-5 and + percentile-95 values of the computed value targets within a batch. This is used to + compute the "scaled value targets" for actor learning. These two variables decay + over time exponentially (see [1] for more details). + """ + + def __init__( + self, + *, + input_size: int, + model_size: str = "XS", + action_space: gym.Space, + ): + """Initializes an ActorNetwork instance. + + Args: + input_size: The input size of the actor network. + model_size: The "Model Size" used according to [1] Appendinx B. + Use None for manually setting the different network sizes. + action_space: The action space the our environment used. + """ + super().__init__() + + self.input_size = input_size + self.model_size = model_size + self.action_space = action_space + + # The EMA decay variables used for the [Percentile(R, 95%) - Percentile(R, 5%)] + # diff to scale value targets for the actor loss. + self.ema_value_target_pct5 = nn.Parameter( + torch.tensor(float("nan")), requires_grad=False + ) + self.ema_value_target_pct95 = nn.Parameter( + torch.tensor(float("nan")), requires_grad=False + ) + + # For discrete actions, use a single MLP that computes logits. + if isinstance(self.action_space, gym.spaces.Discrete): + self.mlp = MLP( + input_size=self.input_size, + model_size=self.model_size, + output_layer_size=self.action_space.n, + ) + # For cont. actions, use separate MLPs for Gaussian mean and stddev. + # TODO (sven): In the author's original code repo, this is NOT the case, + # inputs are pushed through a shared MLP, then only the two output linear + # layers are separate for std- and mean logits. + elif isinstance(action_space, gym.spaces.Box): + output_layer_size = np.prod(action_space.shape) + self.mlp = MLP( + input_size=self.input_size, + model_size=self.model_size, + output_layer_size=output_layer_size, + ) + self.std_mlp = MLP( + input_size=self.input_size, + model_size=self.model_size, + output_layer_size=output_layer_size, + ) + else: + raise ValueError(f"Invalid action space: {action_space}") + + def forward(self, h, z, return_distr_params=False): + """Performs a forward pass through this policy network. + + Args: + h: The deterministic hidden state of the sequence model. [B, dim(h)]. + z: The stochastic discrete representations of the original + observation input. [B, num_categoricals, num_classes]. + return_distr_params: Whether to return (as a second tuple item) the action + distribution parameter tensor created by the policy. + """ + # Flatten last two dims of z. + assert len(z.shape) == 3 + z_shape = z.shape + z = z.view(z_shape[0], -1) + assert len(z.shape) == 2 + out = torch.cat([h, z], dim=-1) + # Send h-cat-z through MLP. + action_logits = self.mlp(out) + + if isinstance(self.action_space, gym.spaces.Discrete): + action_probs = nn.functional.softmax(action_logits, dim=-1) + + # Add the unimix weighting (1% uniform) to the probs. + # See [1]: "Unimix categoricals: We parameterize the categorical + # distributions for the world model representations and dynamics, as well as + # for the actor network, as mixtures of 1% uniform and 99% neural network + # output to ensure a minimal amount of probability mass on every class and + # thus keep log probabilities and KL divergences well behaved." + action_probs = 0.99 * action_probs + 0.01 * (1.0 / self.action_space.n) + + # Danijar's code does: distr = [Distr class](logits=torch.log(probs)). + # Not sure why we don't directly use the already available probs instead. + action_logits = torch.log(action_probs) + + # Distribution parameters are the log(probs) directly. + distr_params = action_logits + distr = self.get_action_dist_object(distr_params) + + action = distr.sample().float().detach() + ( + action_probs - action_probs.detach() + ) + + elif isinstance(self.action_space, gym.spaces.Box): + # Send h-cat-z through MLP to compute stddev logits for Normal dist + std_logits = self.std_mlp(out) + # minstd, maxstd taken from [1] from configs.yaml + minstd = 0.1 + maxstd = 1.0 + + # Distribution parameters are the squashed std_logits and the tanh'd + # mean logits. + # squash std_logits from (-inf, inf) to (minstd, maxstd) + std_logits = (maxstd - minstd) * torch.sigmoid(std_logits + 2.0) + minstd + mean_logits = torch.tanh(action_logits) + + distr_params = torch.cat([mean_logits, std_logits], dim=-1) + distr = self.get_action_dist_object(distr_params) + + action = distr.rsample() + + if return_distr_params: + return action, distr_params + return action + + def get_action_dist_object(self, action_dist_params_T_B): + """Helper method to create an action distribution object from (T, B, ..) params. + + Args: + action_dist_params_T_B: The time-major action distribution parameters. + This could be simply the logits (discrete) or a to-be-split-in-2 + tensor for mean and stddev (continuous). + + Returns: + The torch action distribution object, from which one can sample, compute + log probs, entropy, etc.. + """ + if isinstance(self.action_space, gym.spaces.Discrete): + # Create the distribution object using the unimix'd logits. + distr = torch.distributions.OneHotCategorical(logits=action_dist_params_T_B) + + elif isinstance(self.action_space, gym.spaces.Box): + # Compute Normal distribution from action_logits and std_logits + loc, scale = torch.split( + action_dist_params_T_B, + action_dist_params_T_B.shape[-1] // 2, + dim=-1, + ) + distr = torch.distributions.Normal(loc=loc, scale=scale) + + # If action_space is a box with multiple dims, make individual dims + # independent. + distr = torch.distributions.Independent(distr, len(self.action_space.shape)) + + else: + raise ValueError(f"Action space {self.action_space} not supported!") + + return distr diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..590f20e221c1ca19f9002dde1b490fa1865cb043 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__init__.py @@ -0,0 +1,37 @@ +import numpy as np + +from ray.rllib.utils import force_list +from ray.rllib.utils.framework import try_import_torch + +torch, _ = try_import_torch() + + +def dreamerv3_normal_initializer(parameters): + """From Danijar Hafner's DreamerV3 JAX repo. + + Used on any layer whenever the config for that layer has `winit="normal"`. + + Note: Not identical with Glorot normal. Differs in the std computation + glorot_std = sqrt(2/(fanin+fanout)) + this_std = sqrt(1/AVG(fanin, fanout)) / [somemagicnumber=0.879...] + """ + for param in force_list(parameters): + if param.dim() > 1: + fanin, fanout = _fans(param.shape) + scale = 1.0 / np.mean([fanin, fanout]) + std = np.sqrt(scale) / 0.87962566103423978 + with torch.no_grad(): + param.normal_(0, std) + param.clamp_(-2, 2) + + +def _fans(shape): + if len(shape) == 0: + return 1, 1 + elif len(shape) == 1: + return shape[0], shape[0] + elif len(shape) == 2: + return shape + else: + space = int(np.prod(shape[:-2])) + return shape[-2] * space, shape[-1] * space diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60d01baf6630519b6911e0d17fe7c73a362c87f0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/cnn_atari.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/cnn_atari.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b217a091afb8d4fa6cd6b4c3257657433eb7e002 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/cnn_atari.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/continue_predictor.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/continue_predictor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6bca9182c7d3b411717201461c9637915beabcb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/continue_predictor.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/conv_transpose_atari.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/conv_transpose_atari.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb9fa2c3d4431ae62e44d7aa2a373f48277fc303 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/conv_transpose_atari.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/dynamics_predictor.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/dynamics_predictor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c90273852bd0128a945d1c7b616314f3e337c38 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/dynamics_predictor.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/mlp.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/mlp.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f9af76312648bb308e8abf35de8d6599ddc6a63 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/mlp.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/representation_layer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/representation_layer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ed6f14c8845c9145c91d5280541cc90e7eefe8f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/representation_layer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/reward_predictor.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/reward_predictor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..998a85636d83ebea8f3d912f7c4c7983ae10d979 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/reward_predictor.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/reward_predictor_layer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/reward_predictor_layer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac4c62f4ac7b6349f0c6481b6b7d279d55dd8901 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/reward_predictor_layer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/sequence_model.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/sequence_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4dacd63b2fefc9983b02d86f5b9b58d1665b0b48 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/sequence_model.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/vector_decoder.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/vector_decoder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..413c2199101d36567414a9443a6bd262ab58a016 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/__pycache__/vector_decoder.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/cnn_atari.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/cnn_atari.py new file mode 100644 index 0000000000000000000000000000000000000000..d75abc9086dd09ff6f95935a604eb0cc93e28d06 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/cnn_atari.py @@ -0,0 +1,70 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf +""" +from typing import Optional + +from ray.rllib.algorithms.dreamerv3.torch.models.components import ( + dreamerv3_normal_initializer, +) +from ray.rllib.algorithms.dreamerv3.utils import get_cnn_multiplier +from ray.rllib.core.models.base import ENCODER_OUT +from ray.rllib.core.models.configs import CNNEncoderConfig +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.framework import try_import_torch + +torch, nn = try_import_torch() + + +class CNNAtari(nn.Module): + """An image encoder mapping 64x64 RGB images via 4 CNN layers into a 1D space.""" + + def __init__( + self, + *, + model_size: str = "XS", + cnn_multiplier: Optional[int] = None, + gray_scaled: bool, + ): + """Initializes a CNNAtari instance. + + Args: + model_size: The "Model Size" used according to [1] Appendix B. + Use None for manually setting the `cnn_multiplier`. + cnn_multiplier: Optional override for the additional factor used to multiply + the number of filters with each CNN layer. Starting with + 1 * `cnn_multiplier` filters in the first CNN layer, the number of + filters then increases via `2*cnn_multiplier`, `4*cnn_multiplier`, till + `8*cnn_multiplier`. + gray_scaled: Whether the input is a gray-scaled image (1 color channel) or + not (3 RGB channels). + """ + super().__init__() + + cnn_multiplier = get_cnn_multiplier(model_size, override=cnn_multiplier) + + config = CNNEncoderConfig( + input_dims=[64, 64, 1 if gray_scaled else 3], + cnn_filter_specifiers=[ + [1 * cnn_multiplier, 4, 2], + [2 * cnn_multiplier, 4, 2], + [4 * cnn_multiplier, 4, 2], + [8 * cnn_multiplier, 4, 2], + ], + cnn_use_bias=False, + cnn_use_layernorm=True, + cnn_activation="silu", + cnn_kernel_initializer=dreamerv3_normal_initializer, + flatten_at_end=True, + ) + self.cnn_stack = config.build(framework="torch") + self.output_size = config.output_dims + + def forward(self, inputs): + """Performs a forward pass through the CNN Atari encoder. + + Args: + inputs: The image inputs of shape (B, 64, 64, 3). + """ + return self.cnn_stack({SampleBatch.OBS: inputs})[ENCODER_OUT] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/continue_predictor.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/continue_predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..1bc3c64cfb75ae316d74a6e61208e1de454fd7ef --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/continue_predictor.py @@ -0,0 +1,62 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf +""" +from ray.rllib.algorithms.dreamerv3.torch.models.components.mlp import MLP +from ray.rllib.utils.framework import try_import_torch + +torch, nn = try_import_torch() + + +class ContinuePredictor(nn.Module): + """The world-model network sub-component used to predict the `continue` flags . + + Predicted continue flags are used to produce "dream data" to learn the policy in. + + The continue flags are predicted via a linear output used to parameterize a + Bernoulli distribution, from which simply the mode is used (no stochastic + sampling!). In other words, if the sigmoid of the output of the linear layer is + >0.5, we predict a continuation of the episode, otherwise we predict an episode + terminal. + """ + + def __init__(self, *, input_size: int, model_size: str = "XS"): + """Initializes a ContinuePredictor instance. + + Args: + input_size: The input size of the continue predictor. + model_size: The "Model Size" used according to [1] Appendinx B. + Determines the exact size of the underlying MLP. + """ + super().__init__() + + self.mlp = MLP( + input_size=input_size, + model_size=model_size, + output_layer_size=1, + ) + + def forward(self, h, z, return_distribution=False): + """Performs a forward pass through the continue predictor. + + Args: + h: The deterministic hidden state of the sequence model. [B, dim(h)]. + z: The stochastic discrete representations of the original + observation input. [B, num_categoricals, num_classes]. + return_distribution: Whether to return (as a second tuple item) the + Bernoulli distribution object created by the underlying MLP. + """ + z_shape = z.size() + z = z.view(z_shape[0], -1) + + out = torch.cat([h, z], dim=-1) + out = self.mlp(out) + logits = out.squeeze(dim=-1) + bernoulli = torch.distributions.Bernoulli(logits=logits) + # Use the mode of the Bernoulli distribution (greedy, deterministic "sample"). + continue_ = bernoulli.probs > 0.5 + + if return_distribution: + return continue_, bernoulli + return continue_ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/conv_transpose_atari.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/conv_transpose_atari.py new file mode 100644 index 0000000000000000000000000000000000000000..30597f52aea092145c3c815088007b63f6e7fa38 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/conv_transpose_atari.py @@ -0,0 +1,95 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf +""" +from typing import Optional + +from ray.rllib.algorithms.dreamerv3.torch.models.components import ( + dreamerv3_normal_initializer, +) +from ray.rllib.algorithms.dreamerv3.utils import get_cnn_multiplier +from ray.rllib.core.models.configs import CNNTransposeHeadConfig +from ray.rllib.utils.framework import try_import_torch + +torch, nn = try_import_torch() + + +class ConvTransposeAtari(nn.Module): + """A Conv2DTranspose decoder to generate Atari images from a latent space. + + Wraps an initial single linear layer with a stack of 4 Conv2DTranspose layers (with + layer normalization) and a diag Gaussian, from which we then sample the final image. + """ + + def __init__( + self, + *, + input_size: int, + model_size: str = "XS", + cnn_multiplier: Optional[int] = None, + gray_scaled: bool, + ): + """Initializes a ConvTransposeAtari instance. + + Args: + input_size: The input size of the ConvTransposeAtari network. + model_size: The "Model Size" used according to [1] Appendinx B. + Use None for manually setting the `cnn_multiplier`. + cnn_multiplier: Optional override for the additional factor used to multiply + the number of filters with each CNN transpose layer. Starting with + 8 * `cnn_multiplier` filters in the first CNN transpose layer, the + number of filters then decreases via `4*cnn_multiplier`, + `2*cnn_multiplier`, till `1*cnn_multiplier`. + gray_scaled: Whether the last Conv2DTranspose layer's output has only 1 + color channel (gray_scaled=True) or 3 RGB channels (gray_scaled=False). + """ + super().__init__() + + cnn_multiplier = get_cnn_multiplier(model_size, override=cnn_multiplier) + self.gray_scaled = gray_scaled + config = CNNTransposeHeadConfig( + input_dims=[input_size], + initial_image_dims=(4, 4, 8 * cnn_multiplier), + initial_dense_weights_initializer=dreamerv3_normal_initializer, + cnn_transpose_filter_specifiers=[ + [4 * cnn_multiplier, 4, 2], + [2 * cnn_multiplier, 4, 2], + [1 * cnn_multiplier, 4, 2], + [1 if self.gray_scaled else 3, 4, 2], + ], + cnn_transpose_use_bias=False, + cnn_transpose_use_layernorm=True, + cnn_transpose_activation="silu", + cnn_transpose_kernel_initializer=dreamerv3_normal_initializer, + ) + # Make sure the output dims match Atari. + # assert config.output_dims == (64, 64, 1 if self.gray_scaled else 3) + + self._transpose_2d_head = config.build(framework="torch") + + def forward(self, h, z): + """Performs a forward pass through the Conv2D transpose decoder. + + Args: + h: The deterministic hidden state of the sequence model. + z: The sequence of stochastic discrete representations of the original + observation input. Note: `z` is not used for the dynamics predictor + model (which predicts z from h). + """ + z_shape = z.size() + z = z.view(z_shape[0], -1) + + input_ = torch.cat([h, z], dim=-1) + + out = self._transpose_2d_head(input_) + + # Interpret output as means of a diag-Gaussian with std=1.0: + # From [2]: + # "Distributions: The image predictor outputs the mean of a diagonal Gaussian + # likelihood with unit variance, ..." + + # Reshape `out` for the diagonal multi-variate Gaussian (each pixel is its own + # independent (b/c diagonal co-variance matrix) variable). + loc = torch.reshape(out, (z_shape[0], -1)) + return loc diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/dynamics_predictor.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/dynamics_predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..14e8a39c829ac35b5176961ae8e7c9d1b4de272c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/dynamics_predictor.py @@ -0,0 +1,74 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf +""" +from typing import Optional + +from ray.rllib.algorithms.dreamerv3.torch.models.components.mlp import MLP +from ray.rllib.algorithms.dreamerv3.torch.models.components import ( + representation_layer, +) +from ray.rllib.algorithms.dreamerv3.utils import get_dense_hidden_units +from ray.rllib.utils.framework import try_import_torch + +torch, nn = try_import_torch() + + +class DynamicsPredictor(nn.Module): + """The dynamics (or "prior") network described in [1], producing prior z-states. + + The dynamics net is used to: + - compute the initial z-state (from the tanh'd initial h-state variable) at the + beginning of a sequence. + - compute prior-z-states during dream data generation. Note that during dreaming, + no actual observations are available and thus no posterior z-states can be computed. + """ + + def __init__( + self, + *, + input_size: int, + model_size: str = "XS", + num_categoricals: Optional[int] = None, + num_classes_per_categorical: Optional[int] = None, + ): + """Initializes a DynamicsPredictor instance. + + Args: + input_size: The input size of the dynamics predictor. + model_size: The "Model Size" used according to [1] Appendinx B. + Use None for manually setting the different parameters. + num_categoricals: Overrides the number of categoricals used in the z-states. + In [1], 32 is used for any model size. + num_classes_per_categorical: Overrides the number of classes within each + categorical used for the z-states. In [1], 32 is used for any model + dimension. + """ + super().__init__() + + self.mlp = MLP( + input_size=input_size, + num_dense_layers=1, + model_size=model_size, + output_layer_size=None, + ) + representation_layer_input_size = get_dense_hidden_units(model_size) + self.representation_layer = representation_layer.RepresentationLayer( + input_size=representation_layer_input_size, + model_size=model_size, + num_categoricals=num_categoricals, + num_classes_per_categorical=num_classes_per_categorical, + ) + + def forward(self, h, return_z_probs=False): + """Performs a forward pass through the dynamics (or "prior") network. + + Args: + h: The deterministic hidden state of the sequence model. + return_z_probs: Whether to return the probabilities for the categorical + distribution (in the shape of [B, num_categoricals, num_classes]) + as a second return value. + """ + out = self.mlp(h) + return self.representation_layer(out, return_z_probs=return_z_probs) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/mlp.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/mlp.py new file mode 100644 index 0000000000000000000000000000000000000000..4e8ed5333684c9ce0bed4a7b29b858b9a4b04ff4 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/mlp.py @@ -0,0 +1,93 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf + +[2] Mastering Atari with Discrete World Models - 2021 +D. Hafner, T. Lillicrap, M. Norouzi, J. Ba +https://arxiv.org/pdf/2010.02193.pdf +""" +from typing import Optional + +from ray.rllib.algorithms.dreamerv3.torch.models.components import ( + dreamerv3_normal_initializer, +) +from ray.rllib.algorithms.dreamerv3.utils import ( + get_dense_hidden_units, + get_num_dense_layers, +) +from ray.rllib.utils.framework import try_import_torch + +torch, nn = try_import_torch() + + +class MLP(nn.Module): + """An MLP primitive used by several DreamerV3 components and described in [1] Fig 5. + + MLP=multi-layer perceptron. + + See Appendix B in [1] for the MLP sizes depending on the given `model_size`. + """ + + def __init__( + self, + *, + input_size: int, + model_size: str = "XS", + num_dense_layers: Optional[int] = None, + dense_hidden_units: Optional[int] = None, + output_layer_size=None, + ): + """Initializes an MLP instance. + + Args: + input_size: The input size of the MLP. + model_size: The "Model Size" used according to [1] Appendinx B. + Use None for manually setting the different network sizes. + num_dense_layers: The number of hidden layers in the MLP. If None, + will use `model_size` and appendix B to figure out this value. + dense_hidden_units: The number of nodes in each hidden layer. If None, + will use `model_size` and appendix B to figure out this value. + output_layer_size: The size of an optional linear (no activation) output + layer. If None, no output layer will be added on top of the MLP dense + stack. + """ + super().__init__() + + self.output_size = None + + num_dense_layers = get_num_dense_layers(model_size, override=num_dense_layers) + dense_hidden_units = get_dense_hidden_units( + model_size, override=dense_hidden_units + ) + + layers = [] + for _ in range(num_dense_layers): + # In this order: layer, normalization, activation. + linear = nn.Linear(input_size, dense_hidden_units, bias=False) + # Use same initializers as the Author in their JAX repo. + dreamerv3_normal_initializer(linear.weight) + layers.append(linear) + layers.append(nn.LayerNorm(dense_hidden_units, eps=0.001)) + layers.append(nn.SiLU()) + input_size = dense_hidden_units + self.output_size = (dense_hidden_units,) + + self.output_layer = None + if output_layer_size: + linear = nn.Linear(input_size, output_layer_size, bias=True) + # Use same initializers as the Author in their JAX repo. + dreamerv3_normal_initializer(linear.weight) + nn.init.zeros_(linear.bias) + layers.append(linear) + self.output_size = (output_layer_size,) + + self._net = nn.Sequential(*layers) + + def forward(self, input_): + """Performs a forward pass through this MLP. + + Args: + input_: The input tensor for the MLP dense stack. + """ + return self._net(input_) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/representation_layer.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/representation_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..caf58c2b657901a9e76e8bbdebe2e30527a17fde --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/representation_layer.py @@ -0,0 +1,133 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf + +[2] Mastering Atari with Discrete World Models - 2021 +D. Hafner, T. Lillicrap, M. Norouzi, J. Ba +https://arxiv.org/pdf/2010.02193.pdf +""" +from typing import Optional + +from ray.rllib.algorithms.dreamerv3.torch.models.components import ( + dreamerv3_normal_initializer, +) +from ray.rllib.algorithms.dreamerv3.utils import ( + get_num_z_categoricals, + get_num_z_classes, +) +from ray.rllib.utils.framework import try_import_torch + +torch, nn = try_import_torch() +if torch: + F = nn.functional + + +class RepresentationLayer(nn.Module): + """A representation (z-state) generating layer. + + The value for z is the result of sampling from a categorical distribution with + shape B x `num_classes`. So a computed z-state consists of `num_categoricals` + one-hot vectors, each of size `num_classes_per_categorical`. + """ + + def __init__( + self, + *, + input_size: int, + model_size: str = "XS", + num_categoricals: Optional[int] = None, + num_classes_per_categorical: Optional[int] = None, + ): + """Initializes a RepresentationLayer instance. + + Args: + input_size: The input size of the representation layer. + model_size: The "Model Size" used according to [1] Appendinx B. + Use None for manually setting the different parameters. + num_categoricals: Overrides the number of categoricals used in the z-states. + In [1], 32 is used for any model size. + num_classes_per_categorical: Overrides the number of classes within each + categorical used for the z-states. In [1], 32 is used for any model + dimension. + """ + self.num_categoricals = get_num_z_categoricals( + model_size, override=num_categoricals + ) + self.num_classes_per_categorical = get_num_z_classes( + model_size, override=num_classes_per_categorical + ) + + super().__init__() + + self.z_generating_layer = nn.Linear( + input_size, + self.num_categoricals * self.num_classes_per_categorical, + bias=True, + ) + # Use same initializers as the Author in their JAX repo. + dreamerv3_normal_initializer(self.z_generating_layer.weight) + + def forward(self, inputs, return_z_probs=False): + """Produces a discrete, differentiable z-sample from some 1D input tensor. + + Pushes the input_ tensor through our dense layer, which outputs + 32(B=num categoricals)*32(c=num classes) logits. Logits are used to: + + 1) sample stochastically + 2) compute probs (via softmax) + 3) make sure the sampling step is differentiable (see [2] Algorithm 1): + sample=one_hot(draw(logits)) + probs=softmax(logits) + sample=sample + probs - stop_grad(probs) + -> Now sample has the gradients of the probs. + + Args: + inputs: The input to our z-generating layer. This might be a) the combined + (concatenated) outputs of the (image?) encoder + the last hidden + deterministic state, or b) the output of the dynamics predictor MLP + network. + return_z_probs: Whether to return the probabilities for the categorical + distribution (in the shape of [B, num_categoricals, num_classes]) + as a second return value. + """ + # Compute the logits (no activation) for our `num_categoricals` Categorical + # distributions (with `num_classes_per_categorical` classes each). + logits = self.z_generating_layer(inputs) + # Reshape the logits to [B, num_categoricals, num_classes] + logits = logits.reshape( + -1, self.num_categoricals, self.num_classes_per_categorical + ) + # Compute the probs (based on logits) via softmax. + probs = F.softmax(logits, dim=-1) + # Add the unimix weighting (1% uniform) to the probs. + # See [1]: "Unimix categoricals: We parameterize the categorical distributions + # for the world model representations and dynamics, as well as for the actor + # network, as mixtures of 1% uniform and 99% neural network output to ensure + # a minimal amount of probability mass on every class and thus keep log + # probabilities and KL divergences well behaved." + probs = 0.99 * probs + 0.01 * (1.0 / self.num_classes_per_categorical) + + # Danijar's code does: distr = [Distr class](logits=torch.log(probs)). + # Not sure why we don't directly use the already available probs instead. + logits = torch.log(probs) + + # Create the distribution object using the unimix'd logits. + distribution = torch.distributions.Independent( + torch.distributions.OneHotCategorical(logits=logits), + reinterpreted_batch_ndims=1, + ) + + # Draw a one-hot sample (B, num_categoricals, num_classes). + sample = distribution.sample() + # Make sure we can take gradients "straight-through" the sampling step + # by adding the probs and subtracting the sg(probs). Note that `sample` + # does not have any gradients as it's the result of a Categorical sample step, + # which is non-differentiable (other than say a Gaussian sample step). + # [1] "The representations are sampled from a vector of softmax distributions + # and we take straight-through gradients through the sampling step." + # [2] Algorithm 1. + differentiable_sample = sample.detach() + probs - probs.detach() + if return_z_probs: + return differentiable_sample, probs + return differentiable_sample diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/reward_predictor.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/reward_predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..2733dd2cc13297720d1f680fbfdaabf8e0627e99 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/reward_predictor.py @@ -0,0 +1,87 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf +""" +from ray.rllib.algorithms.dreamerv3.torch.models.components.mlp import MLP +from ray.rllib.algorithms.dreamerv3.torch.models.components import ( + reward_predictor_layer, +) +from ray.rllib.algorithms.dreamerv3.utils import get_dense_hidden_units + +from ray.rllib.utils.framework import try_import_torch + +torch, nn = try_import_torch() + + +class RewardPredictor(nn.Module): + """Wrapper of MLP and RewardPredictorLayer to predict rewards for the world model. + + Predicted rewards are used to produce "dream data" to learn the policy in. + """ + + def __init__( + self, + *, + input_size: int, + model_size: str = "XS", + num_buckets: int = 255, + lower_bound: float = -20.0, + upper_bound: float = 20.0, + ): + """Initializes a RewardPredictor instance. + + Args: + input_size: The input size of the reward predictor. + model_size: The "Model Size" used according to [1] Appendinx B. + Determines the exact size of the underlying MLP. + num_buckets: The number of buckets to create. Note that the number of + possible symlog'd outcomes from the used distribution is + `num_buckets` + 1: + lower_bound --bucket-- o[1] --bucket-- o[2] ... --bucket-- upper_bound + o=outcomes + lower_bound=o[0] + upper_bound=o[num_buckets] + lower_bound: The symlog'd lower bound for a possible reward value. + Note that a value of -20.0 here already allows individual (actual env) + rewards to be as low as -400M. Buckets will be created between + `lower_bound` and `upper_bound`. + upper_bound: The symlog'd upper bound for a possible reward value. + Note that a value of +20.0 here already allows individual (actual env) + rewards to be as high as 400M. Buckets will be created between + `lower_bound` and `upper_bound`. + """ + super().__init__() + + self.mlp = MLP( + input_size=input_size, + model_size=model_size, + output_layer_size=None, + ) + reward_predictor_input_size = get_dense_hidden_units(model_size) + self.reward_layer = reward_predictor_layer.RewardPredictorLayer( + input_size=reward_predictor_input_size, + num_buckets=num_buckets, + lower_bound=lower_bound, + upper_bound=upper_bound, + ) + + def forward(self, h, z, return_logits=False): + """Computes the expected reward using N equal sized buckets of possible values. + + Args: + h: The deterministic hidden state of the sequence model. [B, dim(h)]. + z: The stochastic discrete representations of the original + observation input. [B, num_categoricals, num_classes]. + return_logits: Whether to return the logits over the reward buckets + as a second return value (besides the expected reward). + """ + # Flatten last two dims of z. + z_shape = z.shape + z = z.view(z_shape[0], -1) + out = torch.cat([h, z], dim=-1) + # Send h-cat-z through MLP. + out = self.mlp(out) + # Return a) mean reward OR b) a tuple: (mean reward, logits over the reward + # buckets). + return self.reward_layer(out, return_logits=return_logits) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/reward_predictor_layer.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/reward_predictor_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..934e322c53027e3750e062a8962c6cdbccf72f6b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/reward_predictor_layer.py @@ -0,0 +1,106 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf + +[2] Mastering Atari with Discrete World Models - 2021 +D. Hafner, T. Lillicrap, M. Norouzi, J. Ba +https://arxiv.org/pdf/2010.02193.pdf +""" + +from ray.rllib.utils.framework import try_import_torch + +torch, nn = try_import_torch() +if torch: + F = nn.functional + + +class RewardPredictorLayer(nn.Module): + """A layer outputting reward predictions using K bins and two-hot encoding. + + This layer is used in two models in DreamerV3: The reward predictor of the world + model and the value function. K is 255 by default (see [1]) and doesn't change + with the model size. + + Possible predicted reward/values range from symexp(-20.0) to symexp(20.0), which + should cover any possible environment. Outputs of this layer are generated by + generating logits/probs via a single linear layer, then interpreting the probs + as weights for a weighted average of the different possible reward (binned) values. + """ + + def __init__( + self, + *, + input_size: int, + num_buckets: int = 255, + lower_bound: float = -20.0, + upper_bound: float = 20.0, + ): + """Initializes a RewardPredictorLayer instance. + + Args: + input_size: The input size of the reward predictor layer. + num_buckets: The number of buckets to create. Note that the number of + possible symlog'd outcomes from the used distribution is + `num_buckets` + 1: + lower_bound --bucket-- o[1] --bucket-- o[2] ... --bucket-- upper_bound + o=outcomes + lower_bound=o[0] + upper_bound=o[num_buckets] + lower_bound: The symlog'd lower bound for a possible reward value. + Note that a value of -20.0 here already allows individual (actual env) + rewards to be as low as -400M. Buckets will be created between + `lower_bound` and `upper_bound`. + upper_bound: The symlog'd upper bound for a possible reward value. + Note that a value of +20.0 here already allows individual (actual env) + rewards to be as high as 400M. Buckets will be created between + `lower_bound` and `upper_bound`. + """ + self.num_buckets = num_buckets + super().__init__() + + self.lower_bound = lower_bound + self.upper_bound = upper_bound + self.reward_buckets_layer = nn.Linear( + in_features=input_size, out_features=self.num_buckets, bias=True + ) + nn.init.zeros_(self.reward_buckets_layer.weight) + nn.init.zeros_(self.reward_buckets_layer.bias) + # self.reward_buckets_layer.weight.data.fill_(0.0) + # self.reward_buckets_layer.bias.data.fill_(0.0) + + def forward(self, inputs, return_logits=False): + """Computes the expected reward using N equal sized buckets of possible values. + + Args: + inputs: The input tensor for the layer, which computes the reward bucket + weights (logits). [B, dim]. + return_logits: Whether to return the logits over the reward buckets + as a second return value (besides the expected reward). + + Returns: + The expected reward OR a tuple consisting of the expected reward and the + torch `FiniteDiscrete` distribution object. To get the individual bucket + probs, do `[FiniteDiscrete object].probs`. + """ + # Compute the `num_buckets` weights. + logits = self.reward_buckets_layer(inputs) + + # Compute the expected(!) reward using the formula: + # `softmax(Linear(x))` [vectordot] `possible_outcomes`, where + # `possible_outcomes` is the even-spaced (binned) encoding of all possible + # symexp'd reward/values. + probs = F.softmax(logits, dim=-1) + possible_outcomes = torch.linspace( + self.lower_bound, self.upper_bound, self.num_buckets, device=logits.device + ) + # probs=possible_outcomes=[B, `num_buckets`] + + # Simple vector dot product (over last dim) to get the mean reward + # weighted sum, where all weights sum to 1.0. + expected_rewards = torch.sum(probs * possible_outcomes, dim=-1) + # expected_rewards=[B] + + if return_logits: + return expected_rewards, logits + return expected_rewards diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/sequence_model.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/sequence_model.py new file mode 100644 index 0000000000000000000000000000000000000000..1fbd695d54ccee0d5f7dd9898fdca8ace380202e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/sequence_model.py @@ -0,0 +1,132 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf +""" +from typing import Optional + +import gymnasium as gym + +from ray.rllib.algorithms.dreamerv3.torch.models.components import ( + dreamerv3_normal_initializer, +) +from ray.rllib.algorithms.dreamerv3.torch.models.components.mlp import MLP +from ray.rllib.algorithms.dreamerv3.utils import get_gru_units, get_dense_hidden_units +from ray.rllib.utils.framework import try_import_torch + +torch, nn = try_import_torch() + + +class SequenceModel(nn.Module): + """The "sequence model" of the RSSM, computing ht+1 given (ht, zt, at). + + Note: The "internal state" always consists of: + The actions `a` (initially, this is a zeroed-out action), `h`-states (deterministic, + continuous), and `z`-states (stochastic, discrete). + There are two versions of z-states: "posterior" for world model training and "prior" + for creating the dream data. + + Initial internal state values (`a`, `h`, and `z`) are used where ever a new episode + starts within a batch row OR at the beginning of each train batch's B rows, + regardless of whether there was an actual episode boundary or not. Thus, internal + states are not required to be stored in or retrieved from the replay buffer AND + retrieved batches from the buffer must not be zero padded. + + Initial `a` is the zero "one hot" action, e.g. [0.0, 0.0] for Discrete(2), initial + `h` is a separate learned variable, and initial `z` are computed by the "dynamics" + (or "prior") net, using only the initial-h state as input. + + The GRU in this SequenceModel always produces the next h-state, then. + """ + + def __init__( + self, + *, + input_size: int, + model_size: str = "XS", + action_space: gym.Space, + num_gru_units: Optional[int] = None, + ): + """Initializes a SequenceModel instance. + + Args: + input_size: The input size of the pre-layer (Dense) of the sequence model. + model_size: The "Model Size" used according to [1] Appendinx B. + Use None for manually setting the number of GRU units used. + action_space: The action space the our environment used. + num_gru_units: Overrides the number of GRU units (dimension of the h-state). + If None, use the value given through `model_size` + (see [1] Appendix B). + """ + super().__init__() + + num_gru_units = get_gru_units(model_size, override=num_gru_units) + self.action_space = action_space + + # In Danijar's code, there is an additional layer (units=[model_size]) + # prior to the GRU (but always only with 1 layer), which is not mentioned in + # the paper. + # In Danijar's code, this layer is called: `img_in`. + self.pre_gru_layer = MLP( + input_size=input_size, + num_dense_layers=1, + model_size=model_size, + output_layer_size=None, + ) + gru_input_size = get_dense_hidden_units(model_size) + + # Use a custom GRU implementation w/ Normal init, layernorm, no bias + # (just like Danijar's GRU). + # In Danijar's code, this layer is called: `gru`. + self.gru_unit = DreamerV3GRU(input_size=gru_input_size, cell_size=num_gru_units) + + def forward(self, a, h, z): + """ + + Args: + a: The previous action (already one-hot'd if applicable). (B, ...). + h: The previous deterministic hidden state of the sequence model. + (B, num_gru_units) + z: The previous stochastic discrete representations of the original + observation input. (B, num_categoricals, num_classes_per_categorical). + """ + # Flatten last two dims of z. + z_shape = z.shape + z = z.view(z_shape[0], -1) + out = torch.cat([z, a], dim=-1) + # Pass through pre-GRU layer. + out = self.pre_gru_layer(out) + # Pass through GRU (add extra time axis at 0 to make time-major). + h_next, _ = self.gru_unit(out.unsqueeze(0), h.unsqueeze(0)) + h_next = h_next.squeeze(0) # Remove extra time dimension again. + # Return the GRU's output (the next h-state). + return h_next + + +class DreamerV3GRU(nn.Module): + """Analogous to Danijar's JAX GRU unit code.""" + + def __init__(self, input_size, cell_size): + super().__init__() + self.cell_size = cell_size + self.output_size = 3 * self.cell_size + + self.linear = nn.Linear( + input_size + self.cell_size, + self.output_size, + bias=False, + ) + dreamerv3_normal_initializer(list(self.linear.parameters())) + + self.layer_norm = nn.LayerNorm(self.output_size, eps=0.001) + + def forward(self, x, h): + x = torch.cat([h, x], dim=-1) + x = self.linear(x) + x = self.layer_norm(x) + reset, cand, update = torch.split(x, self.cell_size, dim=-1) + reset = torch.sigmoid(reset) + cand = torch.tanh(reset * cand) + update = torch.sigmoid(update - 1) + h = update * cand + (1 - update) * h + return h, h diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/vector_decoder.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/vector_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..f71931f68f72fefbccf668753322bfe82db75777 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/components/vector_decoder.py @@ -0,0 +1,68 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf +""" +import gymnasium as gym + +from ray.rllib.algorithms.dreamerv3.torch.models.components.mlp import MLP +from ray.rllib.utils.framework import try_import_torch + +torch, nn = try_import_torch() + + +class VectorDecoder(nn.Module): + """A simple vector decoder to reproduce non-image (1D vector) observations. + + Wraps an MLP for mean parameter computations and a Gaussian distribution, + from which we then sample using these mean values and a fixed stddev of 1.0. + """ + + def __init__( + self, + *, + input_size: int, + model_size: str = "XS", + observation_space: gym.Space, + ): + """Initializes a VectorDecoder instance. + + Args: + input_size: The input size of the vector decoder. + model_size: The "Model Size" used according to [1] Appendinx B. + Determines the exact size of the underlying MLP. + observation_space: The observation space to decode back into. This must + be a Box of shape (d,), where d >= 1. + """ + super().__init__() + + assert ( + isinstance(observation_space, gym.spaces.Box) + and len(observation_space.shape) == 1 + ) + + self.mlp = MLP( + input_size=input_size, + model_size=model_size, + output_layer_size=observation_space.shape[0], + ) + + def forward(self, h, z): + """Performs a forward pass through the vector encoder. + + Args: + h: The deterministic hidden state of the sequence model. [B, dim(h)]. + z: The stochastic discrete representations of the original + observation input. [B, num_categoricals, num_classes]. + """ + # Flatten last two dims of z. + assert len(z.shape) == 3 + z_shape = z.shape + z = z.view(z_shape[0], -1) + assert len(z.shape) == 2 + out = torch.cat([h, z], dim=-1) + # Send h-cat-z through MLP to get mean values of diag gaussian. + loc = self.mlp(out) + + # Return only the predicted observations (mean, no sample). + return loc diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/critic_network.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/critic_network.py new file mode 100644 index 0000000000000000000000000000000000000000..d4b5798eb55a06147469a1165db1a89a2d39ba32 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/critic_network.py @@ -0,0 +1,168 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf +""" +from ray.rllib.algorithms.dreamerv3.utils import get_dense_hidden_units +from ray.rllib.algorithms.dreamerv3.torch.models.components.mlp import MLP +from ray.rllib.algorithms.dreamerv3.torch.models.components import ( + reward_predictor_layer, +) +from ray.rllib.utils.framework import try_import_torch + +torch, nn = try_import_torch() + + +class CriticNetwork(nn.Module): + """The critic network described in [1], predicting values for policy learning. + + Contains a copy of itself (EMA net) for weight regularization. + The EMA net is updated after each train step via EMA (using the `ema_decay` + parameter and the actual critic's weights). The EMA net is NOT used for target + computations (we use the actual critic for that), its only purpose is to compute a + weights regularizer term for the critic's loss such that the actual critic does not + move too quickly. + """ + + def __init__( + self, + *, + input_size: int, + model_size: str = "XS", + num_buckets: int = 255, + lower_bound: float = -20.0, + upper_bound: float = 20.0, + ema_decay: float = 0.98, + ): + """Initializes a CriticNetwork instance. + + Args: + input_size: The input size of the critic network. + model_size: The "Model Size" used according to [1] Appendinx B. + Use None for manually setting the different network sizes. + num_buckets: The number of buckets to create. Note that the number of + possible symlog'd outcomes from the used distribution is + `num_buckets` + 1: + lower_bound --bucket-- o[1] --bucket-- o[2] ... --bucket-- upper_bound + o=outcomes + lower_bound=o[0] + upper_bound=o[num_buckets] + lower_bound: The symlog'd lower bound for a possible reward value. + Note that a value of -20.0 here already allows individual (actual env) + rewards to be as low as -400M. Buckets will be created between + `lower_bound` and `upper_bound`. + upper_bound: The symlog'd upper bound for a possible reward value. + Note that a value of +20.0 here already allows individual (actual env) + rewards to be as high as 400M. Buckets will be created between + `lower_bound` and `upper_bound`. + ema_decay: The weight to use for updating the weights of the critic's copy + vs the actual critic. After each training update, the EMA copy of the + critic gets updated according to: + ema_net=(`ema_decay`*ema_net) + (1.0-`ema_decay`)*critic_net + The EMA copy of the critic is used inside the critic loss function only + to produce a regularizer term against the current critic's weights, NOT + to compute any target values. + """ + super().__init__() + + self.input_size = input_size + self.model_size = model_size + self.ema_decay = ema_decay + + # "Fast" critic network(s) (mlp + reward-pred-layer). This is the network + # we actually train with our critic loss. + # IMPORTANT: We also use this to compute the return-targets, BUT we regularize + # the critic loss term such that the weights of this fast critic stay close + # to the EMA weights (see below). + self.mlp = MLP( + input_size=self.input_size, + model_size=self.model_size, + output_layer_size=None, + ) + reward_predictor_input_size = get_dense_hidden_units(self.model_size) + self.return_layer = reward_predictor_layer.RewardPredictorLayer( + input_size=reward_predictor_input_size, + num_buckets=num_buckets, + lower_bound=lower_bound, + upper_bound=upper_bound, + ) + + # Weights-EMA (EWMA) containing networks for critic loss (similar to a + # target net, BUT not used to compute anything, just for the + # weights regularizer term inside the critic loss). + self.mlp_ema = MLP( + input_size=self.input_size, + model_size=self.model_size, + output_layer_size=None, + ) + self.return_layer_ema = reward_predictor_layer.RewardPredictorLayer( + input_size=reward_predictor_input_size, + num_buckets=num_buckets, + lower_bound=lower_bound, + upper_bound=upper_bound, + ) + + def forward(self, h, z, return_logits=False, use_ema=False): + """Performs a forward pass through the critic network. + + Args: + h: The deterministic hidden state of the sequence model. [B, dim(h)]. + z: The stochastic discrete representations of the original + observation input. [B, num_categoricals, num_classes]. + return_logits: Whether also return (as a second tuple item) the logits + computed by the binned return layer (instead of only the value itself). + use_ema: Whether to use the EMA-copy of the critic instead of the actual + critic to perform this computation. + """ + # Flatten last two dims of z. + assert len(z.shape) == 3 + z_shape = z.shape + z = z.view(z_shape[0], -1) + assert len(z.shape) == 2 + out = torch.cat([h, z], dim=-1) + + if not use_ema: + # Send h-cat-z through MLP. + out = self.mlp(out) + # Return expected return OR (expected return, probs of bucket values). + return self.return_layer(out, return_logits=return_logits) + else: + out = self.mlp_ema(out) + return self.return_layer_ema(out, return_logits=return_logits) + + def init_ema(self) -> None: + """Initializes the EMA-copy of the critic from the critic's weights. + + After calling this method, the two networks have identical weights and the EMA + net will be non-trainable. + """ + for param_ema, param in zip(self.mlp_ema.parameters(), self.mlp.parameters()): + param_ema.data.copy_(param.data) + # Make all EMA parameters non-trainable. + param_ema.requires_grad = False + assert param_ema.grad is None + + for param_ema, param in zip( + self.return_layer_ema.parameters(), self.return_layer.parameters() + ): + param_ema.data.copy_(param.data) + # Make all EMA parameters non-trainable. + param_ema.requires_grad = False + assert param_ema.grad is None + + def update_ema(self) -> None: + """Updates the EMA-copy of the critic according to the update formula: + + ema_net=(`ema_decay`*ema_net) + (1.0-`ema_decay`)*critic_net + """ + for param_ema, param in zip(self.mlp_ema.parameters(), self.mlp.parameters()): + param_ema.data.mul_(self.ema_decay).add_( + (1.0 - self.ema_decay) * param.data + ) + + for param_ema, param in zip( + self.return_layer_ema.parameters(), self.return_layer.parameters() + ): + param_ema.data.mul_(self.ema_decay).add_( + (1.0 - self.ema_decay) * param.data + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/dreamer_model.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/dreamer_model.py new file mode 100644 index 0000000000000000000000000000000000000000..60e4e044a1bdaadeaea7e4c7025ed5287804056b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/dreamer_model.py @@ -0,0 +1,518 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf +""" +import re + +import gymnasium as gym +import numpy as np + +from ray.rllib.algorithms.dreamerv3.torch.models.actor_network import ActorNetwork +from ray.rllib.algorithms.dreamerv3.torch.models.critic_network import CriticNetwork +from ray.rllib.algorithms.dreamerv3.torch.models.world_model import WorldModel +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.torch_utils import inverse_symlog + +torch, nn = try_import_torch() + + +class DreamerModel(nn.Module): + """The main PyTorch model containing all necessary components for DreamerV3. + + Includes: + - The world model with encoder, decoder, sequence-model (RSSM), dynamics + (generates prior z-state), and "posterior" model (generates posterior z-state). + Predicts env dynamics and produces dreamed trajectories for actor- and critic + learning. + - The actor network (policy). + - The critic network for value function prediction. + """ + + def __init__( + self, + *, + model_size: str = "XS", + action_space: gym.Space, + world_model: WorldModel, + actor: ActorNetwork, + critic: CriticNetwork, + use_curiosity: bool = False, + intrinsic_rewards_scale: float = 0.1, + ): + """Initializes a DreamerModel instance. + + Args: + model_size: The "Model Size" used according to [1] Appendinx B. + Use None for manually setting the different network sizes. + action_space: The action space the our environment used. + world_model: The WorldModel component. + actor: The ActorNetwork component. + critic: The CriticNetwork component. + """ + super().__init__() + + self.model_size = model_size + self.action_space = action_space + self.use_curiosity = use_curiosity + + self.world_model = world_model + self.actor = actor + self.critic = critic + + self.disagree_nets = None + if self.use_curiosity: + raise NotImplementedError + + def forward_inference(self, observations, previous_states, is_first): + """Performs a (non-exploring) action computation step given obs and states. + + Note that all input data should not have a time rank (only a batch dimension). + + Args: + observations: The current environment observation with shape (B, ...). + previous_states: Dict with keys `a`, `h`, and `z` used as input to the RSSM + to produce the next h-state, from which then to compute the action + using the actor network. All values in the dict should have shape + (B, ...) (no time rank). + is_first: Batch of is_first flags. These should be True if a new episode + has been started at the current timestep (meaning `observations` is the + reset observation from the environment). + """ + # Perform one step in the world model (starting from `previous_state` and + # using the observations to yield a current (posterior) state). + states = self.world_model.forward_inference( + observations=observations, + previous_states=previous_states, + is_first=is_first, + ) + # Compute action using our actor network and the current states. + _, distr_params = self.actor( + h=states["h"], z=states["z"], return_distr_params=True + ) + # Use the mode of the distribution (Discrete=argmax, Normal=mean). + distr = self.actor.get_action_dist_object(distr_params) + actions = distr.mode + return actions, {"h": states["h"], "z": states["z"], "a": actions} + + def forward_exploration(self, observations, previous_states, is_first): + """Performs an exploratory action computation step given obs and states. + + Note that all input data should not have a time rank (only a batch dimension). + + Args: + observations: The current environment observation with shape (B, ...). + previous_states: Dict with keys `a`, `h`, and `z` used as input to the RSSM + to produce the next h-state, from which then to compute the action + using the actor network. All values in the dict should have shape + (B, ...) (no time rank). + is_first: Batch of is_first flags. These should be True if a new episode + has been started at the current timestep (meaning `observations` is the + reset observation from the environment). + """ + # Perform one step in the world model (starting from `previous_state` and + # using the observations to yield a current (posterior) state). + states = self.world_model.forward_inference( + observations=observations, + previous_states=previous_states, + is_first=is_first, + ) + # Compute action using our actor network and the current states. + actions = self.actor(h=states["h"], z=states["z"]) + return actions, {"h": states["h"], "z": states["z"], "a": actions} + + def forward_train(self, observations, actions, is_first): + """Performs a training forward pass given observations and actions. + + Note that all input data must have a time rank (batch-major: [B, T, ...]). + + Args: + observations: The environment observations with shape (B, T, ...). Thus, + the batch has B rows of T timesteps each. Note that it's ok to have + episode boundaries (is_first=True) within a batch row. DreamerV3 will + simply insert an initial state before these locations and continue the + sequence modelling (with the RSSM). Hence, there will be no zero + padding. + actions: The actions actually taken in the environment with shape + (B, T, ...). See `observations` docstring for details on how B and T are + handled. + is_first: Batch of is_first flags. These should be True: + - if a new episode has been started at the current timestep (meaning + `observations` is the reset observation from the environment). + - in each batch row at T=0 (first timestep of each of the B batch + rows), regardless of whether the actual env had an episode boundary + there or not. + """ + return self.world_model.forward_train( + observations=observations, + actions=actions, + is_first=is_first, + ) + + def get_initial_state(self): + """Returns the initial state of the dreamer model (a, h-, z-states). + + An initial state is generated using the previous action, the tanh of the + (learned) h-state variable and the dynamics predictor (or "prior net") to + compute z^0 from h0. In this last step, it is important that we do NOT sample + the z^-state (as we would usually do during dreaming), but rather take the mode + (argmax, then one-hot again). + + Note that the initial state is returned without batch dimension. + """ + states = self.world_model.get_initial_state() + + action_dim = ( + self.action_space.n + if isinstance(self.action_space, gym.spaces.Discrete) + else np.prod(self.action_space.shape) + ) + states["a"] = torch.zeros((action_dim,), dtype=torch.float32) + return states + + def dream_trajectory(self, start_states, start_is_terminated, timesteps_H, gamma): + """Dreams trajectories of length H from batch of h- and z-states. + + Note that incoming data will have the shapes (BxT, ...), where the original + batch- and time-dimensions are already folded together. Beginning from this + new batch dim (BxT), we will unroll `timesteps_H` timesteps in a time-major + fashion, such that the dreamed data will have shape (H, BxT, ...). + + Args: + start_states: Dict of `h` and `z` states in the shape of (B, ...) and + (B, num_categoricals, num_classes), respectively, as + computed by a train forward pass. From each individual h-/z-state pair + in the given batch, we will branch off a dreamed trajectory of len + `timesteps_H`. + start_is_terminated: Float flags of shape (B,) indicating whether the + first timesteps of each batch row is already a terminated timestep + (given by the actual environment). + timesteps_H: The number of timesteps to dream for. + gamma: The discount factor gamma. + """ + # Dreamed actions (one-hot encoded for discrete actions). + a_dreamed_t0_to_H = [] + a_dreamed_dist_params_t0_to_H = [] + + h = start_states["h"].detach() + z = start_states["z"].detach() + + # GRU outputs. + h_states_t0_to_H = [h] + # Dynamics model outputs. + z_states_prior_t0_to_H = [z] + + # Compute `a` using actor network (already the first step uses a dreamed action, + # not a sampled one). + a, a_dist_params = self.actor( + # We have to stop the gradients through the states. B/c we are using a + # differentiable Discrete action distribution (straight through gradients + # with `a = stop_gradient(sample(probs)) + probs - stop_gradient(probs)`, + # we otherwise would add dependencies of the `-log(pi(a|s))` REINFORCE loss + # term on actions further back in the trajectory. + h=h.detach(), + z=z.detach(), + return_distr_params=True, + ) + a_dreamed_t0_to_H.append(a) + a_dreamed_dist_params_t0_to_H.append(a_dist_params) + + # Disable all gradients from the world model so they don't get backprop'd + # through twice when computing the actor loss (for cont. actions). + for p in self.world_model.parameters(): + p.requires_grad_(False) + + for i in range(timesteps_H): + # Move one step in the dream using the RSSM. + h = self.world_model.sequence_model(a=a, h=h, z=z) + h_states_t0_to_H.append(h) + + # Compute prior z using dynamics model. + z = self.world_model.dynamics_predictor(h=h) + z_states_prior_t0_to_H.append(z) + + # Compute `a` using actor network. + a, a_dist_params = self.actor( + h=h.detach(), + z=z.detach(), + return_distr_params=True, + ) + a_dreamed_t0_to_H.append(a) + a_dreamed_dist_params_t0_to_H.append(a_dist_params) + + h_states_H_B = torch.stack(h_states_t0_to_H, dim=0) # (T, B, ...) + h_states_HxB = h_states_H_B.reshape([-1] + list(h_states_H_B.shape[2:])) + + z_states_prior_H_B = torch.stack(z_states_prior_t0_to_H, dim=0) # (T, B, ...) + z_states_prior_HxB = z_states_prior_H_B.reshape( + [-1] + list(z_states_prior_H_B.shape[2:]) + ) + + a_dreamed_H_B = torch.stack(a_dreamed_t0_to_H, dim=0) # (T, B, ...) + a_dreamed_dist_params_H_B = torch.stack(a_dreamed_dist_params_t0_to_H, dim=0) + + # Compute r using reward predictor. + r_dreamed_H_B = inverse_symlog( + self.world_model.reward_predictor(h=h_states_HxB, z=z_states_prior_HxB) + ) + r_dreamed_H_B = r_dreamed_H_B.reshape([timesteps_H + 1, -1]) + + # Compute intrinsic rewards. + if self.use_curiosity: + results_HxB = self.disagree_nets.compute_intrinsic_rewards( + h=h_states_HxB, + z=z_states_prior_HxB, + a=a_dreamed_H_B.reshape([-1] + a_dreamed_H_B.shape[2:]), + ) + r_intrinsic_H_B = results_HxB["rewards_intrinsic"] + r_intrinsic_H_B = r_intrinsic_H_B.reshape([timesteps_H + 1, -1])[1:] + curiosity_forward_train_outs = results_HxB["forward_train_outs"] + del results_HxB + + # Compute continues using continue predictor. + c_dreamed_HxB = self.world_model.continue_predictor( + h=h_states_HxB, + z=z_states_prior_HxB, + ) + c_dreamed_H_B = c_dreamed_HxB.reshape([timesteps_H + 1, -1]) + # Force-set first `continue` flags to False iff `start_is_terminated`. + # Note: This will cause the loss-weights for this row in the batch to be + # completely zero'd out. In general, we don't use dreamed data past any + # predicted (or actual first) continue=False flags. + c_dreamed_H_B = torch.cat( + [1.0 - start_is_terminated.unsqueeze(0).float(), c_dreamed_H_B[1:]], dim=0 + ) + + # Loss weights for each individual dreamed timestep. Zero-out all timesteps + # that lie past continue=False flags. B/c our world model does NOT learn how + # to skip terminal/reset episode boundaries, dreamed data crossing such a + # boundary should not be used for critic/actor learning either. + dream_loss_weights_H_B = torch.cumprod(gamma * c_dreamed_H_B, dim=0) / gamma + + # Reactivate world model gradients. + for p in self.world_model.parameters(): + p.requires_grad_(True) + + # Compute the symlog'd value logits (w/o world model gradients; used for the + # critic loss). + _, v_symlog_dreamed_logits_HxB_wm_detached = self.critic( + h=h_states_HxB.detach(), + z=z_states_prior_HxB.detach(), + use_ema=False, + return_logits=True, + ) + + # Compute the value estimates (including world model gradients -> 1 sequence + # model step after the action has been computed; used for the scaled value + # target used in the actor loss for cont. actions). + # Disable all gradients from the critic so they don't get backprop'd + # through twice when computing the actor loss (for cont. actions). + for p in self.critic.parameters(): + p.requires_grad_(False) + v, _ = self.critic( + h=h_states_HxB, + z=z_states_prior_HxB, + use_ema=False, + return_logits=True, + ) + # Reactivate critic gradients. + for p in self.critic.parameters(): + p.requires_grad_(True) + v_dreamed_HxB = inverse_symlog(v) + v_dreamed_H_B = v_dreamed_HxB.reshape([timesteps_H + 1, -1]) + + # Compute the EMA net outputs w/o any gradients. + with torch.no_grad(): + v_symlog_dreamed_ema_HxB = self.critic( + h=h_states_HxB.detach(), + z=z_states_prior_HxB.detach(), + return_logits=False, + use_ema=True, + ) + v_symlog_dreamed_ema_H_B = v_symlog_dreamed_ema_HxB.reshape( + [timesteps_H + 1, -1] + ) + + ret = { + "h_states_t0_to_H_BxT": h_states_H_B, + "z_states_prior_t0_to_H_BxT": z_states_prior_H_B, + "rewards_dreamed_t0_to_H_BxT": r_dreamed_H_B, + "continues_dreamed_t0_to_H_BxT": c_dreamed_H_B, + "actions_dreamed_t0_to_H_BxT": a_dreamed_H_B, + "actions_dreamed_dist_params_t0_to_H_BxT": a_dreamed_dist_params_H_B, + # Critic (w/ world-model grads for actor loss). + "values_dreamed_t0_to_H_BxT": v_dreamed_H_B, + # Critic (world-model detached, for critic loss). + "values_symlog_dreamed_logits_t0_to_HxBxT_wm_detached": v_symlog_dreamed_logits_HxB_wm_detached, + # Critic EMA. + "v_symlog_dreamed_ema_t0_to_H_BxT": v_symlog_dreamed_ema_H_B, + # Loss weights for critic- and actor losses. + "dream_loss_weights_t0_to_H_BxT": dream_loss_weights_H_B, + } + + if self.use_curiosity: + ret["rewards_intrinsic_t1_to_H_B"] = r_intrinsic_H_B + ret.update(curiosity_forward_train_outs) + + if isinstance(self.action_space, gym.spaces.Discrete): + ret["actions_ints_dreamed_t0_to_H_B"] = torch.argmax(a_dreamed_H_B, dim=-1) + + return ret + + def dream_trajectory_with_burn_in( + self, + *, + start_states, + timesteps_burn_in: int, + timesteps_H: int, + observations, # [B, >=timesteps_burn_in] + actions, # [B, timesteps_burn_in (+timesteps_H)?] + use_sampled_actions_in_dream: bool = False, + use_random_actions_in_dream: bool = False, + ): + """Dreams trajectory from N initial observations and initial states. + + Note: This is only used for reporting and debugging, not for actual world-model + or policy training. + + Args: + start_states: The batch of start states (dicts with `a`, `h`, and `z` keys) + to begin dreaming with. These are used to compute the first h-state + using the sequence model. + timesteps_burn_in: For how many timesteps should be use the posterior + z-states (computed by the posterior net and actual observations from + the env)? + timesteps_H: For how many timesteps should we dream using the prior + z-states (computed by the dynamics (prior) net and h-states only)? + Note that the total length of the returned trajectories will + be `timesteps_burn_in` + `timesteps_H`. + observations: The batch (B, T, ...) of observations (to be used only during + burn-in over `timesteps_burn_in` timesteps). + actions: The batch (B, T, ...) of actions to use during a) burn-in over the + first `timesteps_burn_in` timesteps and - possibly - b) during + actual dreaming, iff use_sampled_actions_in_dream=True. + use_sampled_actions_in_dream: If True, instead of using our actor network + to compute fresh actions, we will use the one provided via the `actions` + argument. Note that in the latter case, the `actions` time dimension + must be at least `timesteps_burn_in` + `timesteps_H` long. + use_random_actions_in_dream: Whether to use randomly sampled actions in the + dream. Note that this does not apply to the burn-in phase, during which + we will always use the actions given in the `actions` argument. + """ + assert not (use_sampled_actions_in_dream and use_random_actions_in_dream) + + B = observations.shape[0] + + # Produce initial N internal posterior states (burn-in) using the given + # observations: + states = start_states + for i in range(timesteps_burn_in): + states = self.world_model.forward_inference( + observations=observations[:, i : i + 1], + previous_states=states, + is_first=torch.full((B,), 1.0 if i == 0 else 0.0), + ) + states["a"] = actions[:, i] + + # Start producing the actual dream, using prior states and either the given + # actions, dreamed, or random ones. + h_states_t0_to_H = [states["h"]] + z_states_prior_t0_to_H = [states["z"]] + a_t0_to_H = [states["a"]] + + for j in range(timesteps_H): + # Compute next h using sequence model. + h = self.world_model.sequence_model( + a=states["a"], + h=states["h"], + z=states["z"], + ) + h_states_t0_to_H.append(h) + # Compute z from h, using the dynamics model (we don't have an actual + # observation at this timestep). + z = self.world_model.dynamics_predictor(h=h) + z_states_prior_t0_to_H.append(z) + + # Compute next dreamed action or use sampled one or random one. + if use_sampled_actions_in_dream: + a = actions[:, timesteps_burn_in + j] + elif use_random_actions_in_dream: + if isinstance(self.action_space, gym.spaces.Discrete): + a = torch.randint(self.action_space.n, (B,), dtype=torch.int64) + a = torch.nn.functional.one_hot(a, num_classes=self.action_space.n) + else: + a = torch.rand( + (B,) + self.action_space.shape, dtype=self.action_space.dtype + ) + else: + a = self.actor(h=h, z=z) + a_t0_to_H.append(a) + + states = {"h": h, "z": z, "a": a} + + # Fold time-rank for upcoming batch-predictions (no sequences needed anymore). + h_states_t0_to_H_B = torch.stack(h_states_t0_to_H, dim=0) + h_states_t0_to_HxB = h_states_t0_to_H_B.reshape( + [-1] + list(h_states_t0_to_H_B.shape[2:]) + ) + + z_states_prior_t0_to_H_B = torch.stack(z_states_prior_t0_to_H, dim=0) + z_states_prior_t0_to_HxB = z_states_prior_t0_to_H_B.reshape( + [-1] + list(z_states_prior_t0_to_H_B.shape[2:]) + ) + + a_t0_to_H_B = torch.stack(a_t0_to_H, dim=0) + + # Compute o using decoder. + o_dreamed_t0_to_HxB = self.world_model.decoder( + h=h_states_t0_to_HxB, + z=z_states_prior_t0_to_HxB, + ) + if self.world_model.symlog_obs: + o_dreamed_t0_to_HxB = inverse_symlog(o_dreamed_t0_to_HxB) + + # Compute r using reward predictor. + r_dreamed_t0_to_H_B = inverse_symlog( + self.world_model.reward_predictor( + h=h_states_t0_to_HxB, + z=z_states_prior_t0_to_HxB, + ) + ).reshape([-1, B]) + + # Compute continues using continue predictor. + c_dreamed_t0_to_H_B = self.world_model.continue_predictor( + h=h_states_t0_to_HxB, + z=z_states_prior_t0_to_HxB, + ).reshape([-1, B]) + + # Return everything as time-major (H, B, ...), where H is the timesteps dreamed + # (NOT burn-in'd) and B is a batch dimension (this might or might not include + # an original time dimension from the real env, from all of which we then branch + # out our dream trajectories). + ret = { + "h_states_t0_to_H_BxT": h_states_t0_to_H_B, + "z_states_prior_t0_to_H_BxT": z_states_prior_t0_to_H_B, + # Unfold time-ranks in predictions. + "observations_dreamed_t0_to_H_BxT": torch.reshape( + o_dreamed_t0_to_HxB, [-1, B] + list(observations.shape)[2:] + ), + "rewards_dreamed_t0_to_H_BxT": r_dreamed_t0_to_H_B, + "continues_dreamed_t0_to_H_BxT": c_dreamed_t0_to_H_B, + } + + # Figure out action key (random, sampled from env, dreamed?). + if use_sampled_actions_in_dream: + key = "actions_sampled_t0_to_H_BxT" + elif use_random_actions_in_dream: + key = "actions_random_t0_to_H_BxT" + else: + key = "actions_dreamed_t0_to_H_BxT" + ret[key] = a_t0_to_H_B + + # Also provide int-actions, if discrete action space. + if isinstance(self.action_space, gym.spaces.Discrete): + ret[re.sub("^actions_", "actions_ints_", key)] = torch.argmax( + a_t0_to_H_B, dim=-1 + ) + + return ret diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/world_model.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/world_model.py new file mode 100644 index 0000000000000000000000000000000000000000..c8851ea8dd71b3ef3d3e0da9742c5be00cd0d543 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/torch/models/world_model.py @@ -0,0 +1,431 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf +""" +from typing import Optional + +import gymnasium as gym +import numpy as np +import tree # pip install dm_tree + +from ray.rllib.algorithms.dreamerv3.torch.models.components.continue_predictor import ( + ContinuePredictor, +) +from ray.rllib.algorithms.dreamerv3.torch.models.components.dynamics_predictor import ( + DynamicsPredictor, +) +from ray.rllib.algorithms.dreamerv3.torch.models.components.mlp import MLP +from ray.rllib.algorithms.dreamerv3.torch.models.components import ( + representation_layer, +) +from ray.rllib.algorithms.dreamerv3.torch.models.components.reward_predictor import ( + RewardPredictor, +) +from ray.rllib.algorithms.dreamerv3.torch.models.components.sequence_model import ( + SequenceModel, +) +from ray.rllib.algorithms.dreamerv3.utils import get_dense_hidden_units, get_gru_units +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.torch_utils import symlog + +torch, nn = try_import_torch() +if torch: + F = nn.functional + + +class WorldModel(nn.Module): + """WorldModel component of [1] w/ encoder, decoder, RSSM, reward/cont. predictors. + + See eq. 3 of [1] for all components and their respective in- and outputs. + Note that in the paper, the "encoder" includes both the raw encoder plus the + "posterior net", which produces posterior z-states from observations and h-states. + + Note: The "internal state" of the world model always consists of: + The actions `a` (initially, this is a zeroed-out action), `h`-states (deterministic, + continuous), and `z`-states (stochastic, discrete). + There are two versions of z-states: "posterior" for world model training and "prior" + for creating the dream data. + + Initial internal state values (`a`, `h`, and `z`) are inserted where ever a new + episode starts within a batch row OR at the beginning of each train batch's B rows, + regardless of whether there was an actual episode boundary or not. Thus, internal + states are not required to be stored in or retrieved from the replay buffer AND + retrieved batches from the buffer must not be zero padded. + + Initial `a` is the zero "one hot" action, e.g. [0.0, 0.0] for Discrete(2), initial + `h` is a separate learned variable, and initial `z` are computed by the "dynamics" + (or "prior") net, using only the initial-h state as input. + """ + + def __init__( + self, + *, + model_size: str = "XS", + observation_space: gym.Space, + action_space: gym.Space, + batch_length_T: int = 64, + encoder: nn.Module, + decoder: nn.Module, + num_gru_units: Optional[int] = None, + symlog_obs: bool = True, + ): + """Initializes a WorldModel instance. + + Args: + model_size: The "Model Size" used according to [1] Appendinx B. + Use None for manually setting the different network sizes. + action_space: The action space the our environment used. + batch_length_T: The length (T) of the sequences used for training. The + actual shape of the input data (e.g. rewards) is then: [B, T, ...], + where B is the "batch size", T is the "batch length" (this arg) and + "..." is the dimension of the data (e.g. (64, 64, 3) for Atari image + observations). Note that a single row (within a batch) may contain data + from different episodes, but an already on-going episode is always + finished, before a new one starts within the same row. + encoder: The encoder Model taking observations as inputs and + outputting a 1D latent vector that will be used as input into the + posterior net (z-posterior state generating layer). Inputs are symlogged + if inputs are NOT images. For images, we use normalization between -1.0 + and 1.0 (x / 128 - 1.0) + decoder: The decoder Model taking h- and z-states as inputs and generating + a (possibly symlogged) predicted observation. Note that for images, + the last decoder layer produces the exact, normalized pixel values + (not a Gaussian as described in [1]!). + num_gru_units: The number of GRU units to use. If None, use + `model_size` to figure out this parameter. + symlog_obs: Whether to predict decoded observations in symlog space. + This should be False for image based observations. + According to the paper [1] Appendix E: "NoObsSymlog: This ablation + removes the symlog encoding of inputs to the world model and also + changes the symlog MSE loss in the decoder to a simple MSE loss. + *Because symlog encoding is only used for vector observations*, this + ablation is equivalent to DreamerV3 on purely image-based environments". + """ + super().__init__() + + self.model_size = model_size + self.batch_length_T = batch_length_T + self.symlog_obs = symlog_obs + self.action_space = action_space + a_flat = ( + action_space.n + if isinstance(action_space, gym.spaces.Discrete) + else (np.prod(action_space.shape)) + ) + + # Encoder (latent 1D vector generator) (xt -> lt). + self.encoder = encoder + + self.num_gru_units = get_gru_units( + model_size=self.model_size, + override=num_gru_units, + ) + + # Posterior predictor consisting of an MLP and a RepresentationLayer: + # [ht, lt] -> zt. + # In Danijar's code, this is called: `obs_out`. + self.posterior_mlp = MLP( + input_size=(self.num_gru_units + encoder.output_size[0]), + model_size=self.model_size, + output_layer_size=None, + # In Danijar's code, the posterior predictor only has a single layer, + # no matter the model size: + num_dense_layers=1, + ) + # The (posterior) z-state generating layer. + # In Danijar's code, this is called: `obs_stats`. + self.posterior_representation_layer = representation_layer.RepresentationLayer( + input_size=get_dense_hidden_units(self.model_size), + model_size=self.model_size, + ) + + z_flat = ( + self.posterior_representation_layer.num_categoricals + * self.posterior_representation_layer.num_classes_per_categorical + ) + h_plus_z_flat = self.num_gru_units + z_flat + + # Dynamics (prior z-state) predictor: ht -> z^t + # In Danijar's code, the layers in this network are called: + # `img_out` (1 Linear) and `img_stats` (representation layer). + self.dynamics_predictor = DynamicsPredictor( + input_size=self.num_gru_units, model_size=self.model_size + ) + + # GRU for the RSSM: [at, ht, zt] -> ht+1 + # Initial h-state variable (learnt). + # -> tanh(self.initial_h) -> deterministic state + # Use our Dynamics predictor for initial stochastic state, BUT with greedy + # (mode) instead of sampling. + self.initial_h = nn.Parameter( + torch.zeros(self.num_gru_units), requires_grad=True + ) + # The actual sequence model containing the GRU layer. + # In Danijar's code, the layers in this network are called: + # `img_in` (1 Linear) and `gru` (custom GRU implementation). + self.sequence_model = SequenceModel( + # Only z- and a-state go into pre-layer. The output of that goes then + # into GRU (together with h-state). + input_size=int(z_flat + a_flat), + model_size=self.model_size, + action_space=self.action_space, + num_gru_units=self.num_gru_units, + ) + + # Reward Predictor: [ht, zt] -> rt. + self.reward_predictor = RewardPredictor( + input_size=h_plus_z_flat, + model_size=self.model_size, + ) + # Continue Predictor: [ht, zt] -> ct. + self.continue_predictor = ContinuePredictor( + input_size=h_plus_z_flat, + model_size=self.model_size, + ) + + # Decoder: [ht, zt] -> x^t. + self.decoder = decoder + + def get_initial_state(self) -> dict: + """Returns the (current) initial state of the world model (h- and z-states). + + An initial state is generated using the tanh of the (learned) h-state variable + and the dynamics predictor (or "prior net") to compute z^0 from h0. In this last + step, it is important that we do NOT sample the z^-state (as we would usually + do during dreaming), but rather take the mode (argmax, then one-hot again). + """ + h = torch.tanh(self.initial_h) + # Use the mode, NOT a sample for the initial z-state. + _, z_probs = self.dynamics_predictor(h.unsqueeze(0), return_z_probs=True) + z = z_probs.squeeze(0).argmax(dim=-1) + z = F.one_hot(z, num_classes=z_probs.shape[-1]) + + return {"h": h, "z": z} + + def forward_inference( + self, + observations: "torch.Tensor", + previous_states: dict, + is_first: "torch.Tensor", + ) -> dict: + """Performs a forward step for inference (e.g. environment stepping). + + Works analogous to `forward_train`, except that all inputs are provided + for a single timestep in the shape of [B, ...] (no time dimension!). + + Args: + observations: The batch (B, ...) of observations to be passed through + the encoder network to yield the inputs to the representation layer + (which then can compute the z-states). + previous_states: A dict with `h`, `z`, and `a` keys mapping to the + respective previous states/actions. All of the shape (B, ...), no time + rank. + is_first: The batch (B) of `is_first` flags. + + Returns: + The next deterministic h-state (h(t+1)) as predicted by the sequence model. + """ + B = observations.shape[0] + initial_states = tree.map_structure( + # Repeat only the batch dimension (B times). + lambda s: s.unsqueeze(0).repeat(B, *([1] * len(s.shape))), + self.get_initial_state(), + ) + + # If first, mask it with initial state/actions. + previous_h = self._mask(previous_states["h"], 1.0 - is_first) # zero out + previous_h = previous_h + self._mask(initial_states["h"], is_first) # add init + + previous_z = self._mask(previous_states["z"], 1.0 - is_first) # zero out + previous_z = previous_z + self._mask(initial_states["z"], is_first) # add init + + # Zero out actions (no special learnt initial state). + previous_a = self._mask(previous_states["a"], 1.0 - is_first) + + # Compute new states. + h = self.sequence_model(a=previous_a, h=previous_h, z=previous_z) + z = self.compute_posterior_z(observations=observations, initial_h=h) + + return {"h": h, "z": z} + + def forward_train( + self, + observations: "torch.Tensor", + actions: "torch.Tensor", + is_first: "torch.Tensor", + ) -> dict: + """Performs a forward step for training. + + 1) Forwards all observations [B, T, ...] through the encoder network to yield + o_processed[B, T, ...]. + 2) Uses initial state (h0/z^0/a0[B, 0, ...]) and sequence model (RSSM) to + compute the first internal state (h1 and z^1). + 3) Uses action a[B, 1, ...], z[B, 1, ...] and h[B, 1, ...] to compute the + next h-state (h[B, 2, ...]), etc.. + 4) Repeats 2) and 3) until t=T. + 5) Uses all h[B, T, ...] and z[B, T, ...] to compute predicted/reconstructed + observations, rewards, and continue signals. + 6) Returns predictions from 5) along with all z-states z[B, T, ...] and + the final h-state (h[B, ...] for t=T). + + Should we encounter is_first=True flags in the middle of a batch row (somewhere + within an ongoing sequence of length T), we insert this world model's initial + state again (zero-action, learned init h-state, and prior-computed z^) and + simply continue (no zero-padding). + + Args: + observations: The batch (B, T, ...) of observations to be passed through + the encoder network to yield the inputs to the representation layer + (which then can compute the posterior z-states). + actions: The batch (B, T, ...) of actions to be used in combination with + h-states and computed z-states to yield the next h-states. + is_first: The batch (B, T) of `is_first` flags. + """ + if self.symlog_obs: + observations = symlog(observations) + + # Compute bare encoder outs (not z; this is done later with involvement of the + # sequence model and the h-states). + # Fold time dimension for CNN pass. + shape = observations.shape + B, T = shape[0], shape[1] + observations = observations.view((-1,) + shape[2:]) + encoder_out = self.encoder(observations) + # Unfold time dimension. + encoder_out = encoder_out.view( + ( + B, + T, + ) + + encoder_out.shape[1:] + ) + # Make time major for faster upcoming loop. + encoder_out = encoder_out.transpose(0, 1) + # encoder_out=[T, B, ...] + + initial_states = tree.map_structure( + # Repeat only the batch dimension (B times). + lambda s: s.unsqueeze(0).repeat(B, *([1] * len(s.shape))), + self.get_initial_state(), + ) + + # Make actions and `is_first` time-major. + actions = actions.transpose(0, 1) + is_first = is_first.transpose(0, 1).float() + + # Loop through the T-axis of our samples and perform one computation step at + # a time. This is necessary because the sequence model's output (h(t+1)) depends + # on the current z(t), but z(t) depends on the current sequence model's output + # h(t). + z_t0_to_T = [initial_states["z"]] + z_posterior_probs = [] + z_prior_probs = [] + h_t0_to_T = [initial_states["h"]] + for t in range(self.batch_length_T): + # If first, mask it with initial state/actions. + h_tm1 = self._mask(h_t0_to_T[-1], 1.0 - is_first[t]) # zero out + h_tm1 = h_tm1 + self._mask(initial_states["h"], is_first[t]) # add init + + z_tm1 = self._mask(z_t0_to_T[-1], 1.0 - is_first[t]) # zero out + z_tm1 = z_tm1 + self._mask(initial_states["z"], is_first[t]) # add init + + # Zero out actions (no special learnt initial state). + a_tm1 = self._mask(actions[t - 1], 1.0 - is_first[t]) + + # Perform one RSSM (sequence model) step to get the current h. + h_t = self.sequence_model(a=a_tm1, h=h_tm1, z=z_tm1) + h_t0_to_T.append(h_t) + + posterior_mlp_input = torch.cat([encoder_out[t], h_t], dim=-1) + repr_input = self.posterior_mlp(posterior_mlp_input) + # Draw one z-sample (z(t)) and also get the z-distribution for dynamics and + # representation loss computations. + z_t, z_probs = self.posterior_representation_layer( + repr_input, + return_z_probs=True, + ) + # z_t=[B, num_categoricals, num_classes] + z_posterior_probs.append(z_probs) + z_t0_to_T.append(z_t) + + # Compute the predicted z_t (z^) using the dynamics model. + _, z_probs = self.dynamics_predictor(h_t, return_z_probs=True) + z_prior_probs.append(z_probs) + + # Stack at time dimension to yield: [B, T, ...]. + h_t1_to_T = torch.stack(h_t0_to_T[1:], dim=1) + z_t1_to_T = torch.stack(z_t0_to_T[1:], dim=1) + + # Fold time axis to retrieve the final (loss ready) Independent distribution + # (over `num_categoricals` Categoricals). + z_posterior_probs = torch.stack(z_posterior_probs, dim=1) + z_posterior_probs = z_posterior_probs.view( + (-1,) + z_posterior_probs.shape[2:], + ) + # Fold time axis to retrieve the final (loss ready) Independent distribution + # (over `num_categoricals` Categoricals). + z_prior_probs = torch.stack(z_prior_probs, dim=1) + z_prior_probs = z_prior_probs.view((-1,) + z_prior_probs.shape[2:]) + + # Fold time dimension for parallelization of all dependent predictions: + # observations (reproduction via decoder), rewards, continues. + h_BxT = h_t1_to_T.view((-1,) + h_t1_to_T.shape[2:]) + z_BxT = z_t1_to_T.view((-1,) + z_t1_to_T.shape[2:]) + + obs_distribution_means = self.decoder(h=h_BxT, z=z_BxT) + + # Compute (predicted) reward distributions. + rewards, reward_logits = self.reward_predictor( + h=h_BxT, z=z_BxT, return_logits=True + ) + + # Compute (predicted) continue distributions. + continues, continue_distribution = self.continue_predictor( + h=h_BxT, z=z_BxT, return_distribution=True + ) + + # Return outputs for loss computation. + # Note that all shapes are [BxT, ...] (time axis already folded). + return { + # Obs. + "sampled_obs_symlog_BxT": observations, + "obs_distribution_means_BxT": obs_distribution_means, + # Rewards. + "reward_logits_BxT": reward_logits, + "rewards_BxT": rewards, + # Continues. + "continue_distribution_BxT": continue_distribution, + "continues_BxT": continues, + # Deterministic, continuous h-states (t1 to T). + "h_states_BxT": h_BxT, + # Sampled, discrete posterior z-states and their probs (t1 to T). + "z_posterior_states_BxT": z_BxT, + "z_posterior_probs_BxT": z_posterior_probs, + # Probs of the prior z-states (t1 to T). + "z_prior_probs_BxT": z_prior_probs, + } + + def compute_posterior_z( + self, observations: "torch.Tensor", initial_h: "torch.Tensor" + ) -> "torch.Tensor": + # Fold time dimension for possible CNN pass. + shape = observations.shape + observations = observations.view((-1,) + shape[2:]) + # Compute bare encoder outputs (not including z, which is computed in next step + # with involvement of the previous output (initial_h) of the sequence model). + # encoder_outs=[B, ...] + if self.symlog_obs: + observations = symlog(observations) + encoder_out = self.encoder(observations) + # Concat encoder outs with the h-states. + posterior_mlp_input = torch.cat([encoder_out, initial_h], dim=-1) + # Compute z. + repr_input = self.posterior_mlp(posterior_mlp_input) + # Draw one z-sample (no need to return the distribution here). + z_t = self.posterior_representation_layer(repr_input, return_z_probs=False) + return z_t + + @staticmethod + def _mask(value: "torch.Tensor", mask: "torch.Tensor") -> "torch.Tensor": + return torch.einsum("b...,b->b...", value, mask) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/utils/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fe7b58cf515ee0c01b83dac8b515a07489c11c91 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/utils/__init__.py @@ -0,0 +1,168 @@ +""" +Utility functions for the DreamerV3 ([1]) algorithm. + +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf +""" + +_ALLOWED_MODEL_DIMS = [ + # RLlib debug sizes (not mentioned in [1]). + "nano", + "micro", + "mini", + "XXS", + # Regular sizes (listed in table B in [1]). + "XS", + "S", + "M", + "L", + "XL", +] + + +def get_cnn_multiplier(model_size, override=None): + if override is not None: + return override + + assert model_size in _ALLOWED_MODEL_DIMS + cnn_multipliers = { + "nano": 2, + "micro": 4, + "mini": 8, + "XXS": 16, + "XS": 24, + "S": 32, + "M": 48, + "L": 64, + "XL": 96, + } + return cnn_multipliers[model_size] + + +def get_dense_hidden_units(model_size, override=None): + if override is not None: + return override + + assert model_size in _ALLOWED_MODEL_DIMS + dense_units = { + "nano": 16, + "micro": 32, + "mini": 64, + "XXS": 128, + "XS": 256, + "S": 512, + "M": 640, + "L": 768, + "XL": 1024, + } + return dense_units[model_size] + + +def get_gru_units(model_size, override=None): + if override is not None: + return override + + assert model_size in _ALLOWED_MODEL_DIMS + gru_units = { + "nano": 16, + "micro": 32, + "mini": 64, + "XXS": 128, + "XS": 256, + "S": 512, + "M": 1024, + "L": 2048, + "XL": 4096, + } + return gru_units[model_size] + + +def get_num_z_categoricals(model_size, override=None): + if override is not None: + return override + + assert model_size in _ALLOWED_MODEL_DIMS + gru_units = { + "nano": 4, + "micro": 8, + "mini": 16, + "XXS": 32, + "XS": 32, + "S": 32, + "M": 32, + "L": 32, + "XL": 32, + } + return gru_units[model_size] + + +def get_num_z_classes(model_size, override=None): + if override is not None: + return override + + assert model_size in _ALLOWED_MODEL_DIMS + gru_units = { + "nano": 4, + "micro": 8, + "mini": 16, + "XXS": 32, + "XS": 32, + "S": 32, + "M": 32, + "L": 32, + "XL": 32, + } + return gru_units[model_size] + + +def get_num_curiosity_nets(model_size, override=None): + if override is not None: + return override + + assert model_size in _ALLOWED_MODEL_DIMS + num_curiosity_nets = { + "nano": 8, + "micro": 8, + "mini": 8, + "XXS": 8, + "XS": 8, + "S": 8, + "M": 8, + "L": 8, + "XL": 8, + } + return num_curiosity_nets[model_size] + + +def get_num_dense_layers(model_size, override=None): + if override is not None: + return override + + assert model_size in _ALLOWED_MODEL_DIMS + num_dense_layers = { + "nano": 1, + "micro": 1, + "mini": 1, + "XXS": 1, + "XS": 1, + "S": 2, + "M": 3, + "L": 4, + "XL": 5, + } + return num_dense_layers[model_size] + + +def do_symlog_obs(observation_space, symlog_obs_user_setting): + # If our symlog_obs setting is NOT set specifically (it's set to "auto"), return + # True if we don't have an image observation space, otherwise return False. + + # TODO (sven): Support mixed observation spaces. + + is_image_space = len(observation_space.shape) in [2, 3] + return ( + not is_image_space + if symlog_obs_user_setting == "auto" + else symlog_obs_user_setting + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/utils/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea7e4c8b966aa32ecccbbf9a9e63a70411a11d84 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/utils/__pycache__/add_is_firsts_to_batch.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/utils/__pycache__/add_is_firsts_to_batch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9942171bd054e350cae16ed3c68b3988c7d162ba Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/utils/__pycache__/add_is_firsts_to_batch.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/utils/__pycache__/debugging.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/utils/__pycache__/debugging.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3ee442575faed20cd7a8d798a382939e741e45c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/utils/__pycache__/debugging.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/utils/__pycache__/summaries.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/utils/__pycache__/summaries.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da2b973edc5d2b92989450347484eb3a3a2cd43b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/utils/__pycache__/summaries.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/utils/add_is_firsts_to_batch.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/utils/add_is_firsts_to_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..3479693bf1e7d8421513be9ebb74e7e9ce29ff3d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/utils/add_is_firsts_to_batch.py @@ -0,0 +1,36 @@ +from typing import Any, List, Optional + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import EpisodeType + + +class AddIsFirstsToBatch(ConnectorV2): + """Adds the "is_first" column to the batch.""" + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Optional[Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + # If "is_first" already in batch, early out. + if "is_first" in batch: + return batch + + for sa_episode in self.single_agent_episode_iterator(episodes): + self.add_batch_item( + batch, + "is_first", + item_to_add=( + 1.0 if sa_episode.t_started == 0 and len(sa_episode) == 0 else 0.0 + ), + single_agent_episode=sa_episode, + ) + return batch diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/utils/debugging.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/utils/debugging.py new file mode 100644 index 0000000000000000000000000000000000000000..d69281713a38d479d0a0c752df4b656bb649ce0d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/utils/debugging.py @@ -0,0 +1,190 @@ +import gymnasium as gym +import numpy as np +from PIL import Image, ImageDraw + +from gymnasium.envs.classic_control.cartpole import CartPoleEnv + +from ray.rllib.utils.framework import try_import_torch + +torch, _ = try_import_torch() + + +class CartPoleDebug(CartPoleEnv): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + low = np.concatenate([np.array([0.0]), self.observation_space.low]) + high = np.concatenate([np.array([1000.0]), self.observation_space.high]) + + self.observation_space = gym.spaces.Box(low, high, shape=(5,), dtype=np.float32) + + self.timesteps_ = 0 + self._next_action = 0 + self._seed = 1 + + def reset(self, *, seed=None, options=None): + ret = super().reset(seed=self._seed) + self._seed += 1 + self.timesteps_ = 0 + self._next_action = 0 + obs = np.concatenate([np.array([self.timesteps_]), ret[0]]) + return obs, ret[1] + + def step(self, action): + ret = super().step(self._next_action) + + self.timesteps_ += 1 + self._next_action = 0 if self._next_action else 1 + + obs = np.concatenate([np.array([self.timesteps_]), ret[0]]) + reward = 0.1 * self.timesteps_ + return (obs, reward) + ret[2:] + + +gym.register("CartPoleDebug-v0", CartPoleDebug) +cartpole_env = gym.make("CartPoleDebug-v0", render_mode="rgb_array") +cartpole_env.reset() + +frozenlake_env = gym.make( + "FrozenLake-v1", render_mode="rgb_array", is_slippery=False, map_name="4x4" +) # desc=["SF", "HG"]) +frozenlake_env.reset() + + +def create_cartpole_dream_image( + dreamed_obs, # real space (not symlog'd) + dreamed_V, # real space (not symlog'd) + dreamed_a, + dreamed_r_tp1, # real space (not symlog'd) + dreamed_ri_tp1, # intrinsic reward + dreamed_c_tp1, # continue flag + value_target, # real space (not symlog'd) + initial_h, + as_tensor=False, +): + # CartPoleDebug + if dreamed_obs.shape == (5,): + # Set the state of our env to the given observation. + cartpole_env.unwrapped.state = np.array(dreamed_obs[1:], dtype=np.float32) + # Normal CartPole-v1 + else: + cartpole_env.unwrapped.state = np.array(dreamed_obs, dtype=np.float32) + + # Produce an RGB-image of the current state. + rgb_array = cartpole_env.render() + + # Add value-, action-, reward-, and continue-prediction information. + image = Image.fromarray(rgb_array) + draw_obj = ImageDraw.Draw(image) + + # fnt = ImageFont.load_default(size=40) + + draw_obj.text( + (5, 6), f"Vt={dreamed_V:.2f} (Rt={value_target:.2f})", fill=(0, 0, 0) + ) # , font=fnt.font, size=30) + draw_obj.text( + (5, 18), + f"at={'<--' if dreamed_a == 0 else '-->'} ({dreamed_a})", + fill=(0, 0, 0), + ) + draw_obj.text((5, 30), f"rt+1={dreamed_r_tp1:.2f}", fill=(0, 0, 0)) + if dreamed_ri_tp1 is not None: + draw_obj.text((5, 42), f"rit+1={dreamed_ri_tp1:.6f}", fill=(0, 0, 0)) + draw_obj.text((5, 54), f"ct+1={dreamed_c_tp1}", fill=(0, 0, 0)) + draw_obj.text((5, 66), f"|h|t={np.mean(np.abs(initial_h)):.5f}", fill=(0, 0, 0)) + + if dreamed_obs.shape == (5,): + draw_obj.text((20, 100), f"t={dreamed_obs[0]}", fill=(0, 0, 0)) + + # Return image. + np_img = np.asarray(image) + if as_tensor: + return torch.from_numpy(np_img, dtype=torch.uint8) + return np_img + + +def create_frozenlake_dream_image( + dreamed_obs, # real space (not symlog'd) + dreamed_V, # real space (not symlog'd) + dreamed_a, + dreamed_r_tp1, # real space (not symlog'd) + dreamed_ri_tp1, # intrinsic reward + dreamed_c_tp1, # continue flag + value_target, # real space (not symlog'd) + initial_h, + as_tensor=False, +): + frozenlake_env.unwrapped.s = np.argmax(dreamed_obs, axis=0) + + # Produce an RGB-image of the current state. + rgb_array = frozenlake_env.render() + + # Add value-, action-, reward-, and continue-prediction information. + image = Image.fromarray(rgb_array) + draw_obj = ImageDraw.Draw(image) + + draw_obj.text((5, 6), f"Vt={dreamed_V:.2f} (Rt={value_target:.2f})", fill=(0, 0, 0)) + action_arrow = ( + "<--" + if dreamed_a == 0 + else "v" + if dreamed_a == 1 + else "-->" + if dreamed_a == 2 + else "^" + ) + draw_obj.text((5, 18), f"at={action_arrow} ({dreamed_a})", fill=(0, 0, 0)) + draw_obj.text((5, 30), f"rt+1={dreamed_r_tp1:.2f}", fill=(0, 0, 0)) + if dreamed_ri_tp1 is not None: + draw_obj.text((5, 42), f"rit+1={dreamed_ri_tp1:.6f}", fill=(0, 0, 0)) + draw_obj.text((5, 54), f"ct+1={dreamed_c_tp1}", fill=(0, 0, 0)) + draw_obj.text((5, 66), f"|h|t={np.mean(np.abs(initial_h)):.5f}", fill=(0, 0, 0)) + + # Return image. + np_img = np.asarray(image) + if as_tensor: + return torch.from_numpy(np_img, dtype=torch.uint8) + return np_img + + +if __name__ == "__main__": + # CartPole debug. + rgb_array = create_cartpole_dream_image( + dreamed_obs=np.array([100.0, 1.0, -0.01, 1.5, 0.02]), + dreamed_V=4.3, + dreamed_a=1, + dreamed_r_tp1=1.0, + dreamed_c_tp1=True, + initial_h=0.0, + value_target=8.0, + ) + # ImageFont.load("arial.pil") + image = Image.fromarray(rgb_array) + image.show() + + # Normal CartPole. + rgb_array = create_cartpole_dream_image( + dreamed_obs=np.array([1.0, -0.01, 1.5, 0.02]), + dreamed_V=4.3, + dreamed_a=1, + dreamed_r_tp1=1.0, + dreamed_c_tp1=True, + initial_h=0.1, + value_target=8.0, + ) + # ImageFont.load("arial.pil") + image = Image.fromarray(rgb_array) + image.show() + + # Frozenlake + rgb_array = create_frozenlake_dream_image( + dreamed_obs=np.array([1.0] + [0.0] * (frozenlake_env.observation_space.n - 1)), + dreamed_V=4.3, + dreamed_a=1, + dreamed_r_tp1=1.0, + dreamed_c_tp1=True, + initial_h=0.1, + value_target=8.0, + ) + image = Image.fromarray(rgb_array) + image.show() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/utils/summaries.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/utils/summaries.py new file mode 100644 index 0000000000000000000000000000000000000000..bcd3898387f12b5b17ad42736ca338351e025755 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/dreamerv3/utils/summaries.py @@ -0,0 +1,407 @@ +""" +[1] Mastering Diverse Domains through World Models - 2023 +D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap +https://arxiv.org/pdf/2301.04104v1.pdf + +[2] Mastering Atari with Discrete World Models - 2021 +D. Hafner, T. Lillicrap, M. Norouzi, J. Ba +https://arxiv.org/pdf/2010.02193.pdf +""" +import numpy as np + +from ray.rllib.algorithms.dreamerv3.utils.debugging import ( + create_cartpole_dream_image, + create_frozenlake_dream_image, +) +from ray.rllib.core import DEFAULT_MODULE_ID +from ray.rllib.core.columns import Columns +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.metrics import ( + LEARNER_RESULTS, + REPLAY_BUFFER_RESULTS, +) +from ray.rllib.utils.torch_utils import inverse_symlog + +torch, _ = try_import_torch() + + +def reconstruct_obs_from_h_and_z( + h_t0_to_H, + z_t0_to_H, + dreamer_model, + obs_dims_shape, + framework="torch", +): + """Returns""" + shape = h_t0_to_H.shape + T = shape[0] # inputs are time-major + B = shape[1] + # Compute actual observations using h and z and the decoder net. + # Note that the last h-state (T+1) is NOT used here as it's already part of + # a new trajectory. + # Use mean() of the Gaussian, no sample! -> No need to construct dist object here. + if framework == "torch": + device = next(iter(dreamer_model.world_model.decoder.parameters())).device + reconstructed_obs_distr_means_TxB = ( + dreamer_model.world_model.decoder( + # Fold time rank. + h=torch.from_numpy(h_t0_to_H).reshape((T * B, -1)).to(device), + z=torch.from_numpy(z_t0_to_H) + .reshape((T * B,) + z_t0_to_H.shape[2:]) + .to(device), + ) + .detach() + .cpu() + .numpy() + ) + else: + reconstructed_obs_distr_means_TxB = dreamer_model.world_model.decoder( + # Fold time rank. + h=h_t0_to_H.reshape((T * B, -1)), + z=z_t0_to_H.reshape((T * B,) + z_t0_to_H.shape[2:]), + ) + + # Unfold time rank again. + reconstructed_obs_T_B = np.reshape( + reconstructed_obs_distr_means_TxB, (T, B) + obs_dims_shape + ) + # Return inverse symlog'd (real env obs space) reconstructed observations. + return reconstructed_obs_T_B + + +def report_dreamed_trajectory( + *, + results, + env, + dreamer_model, + obs_dims_shape, + batch_indices=(0,), + desc=None, + include_images=True, + framework="torch", +): + if not include_images: + return + + dream_data = results["dream_data"] + dreamed_obs_H_B = reconstruct_obs_from_h_and_z( + h_t0_to_H=dream_data["h_states_t0_to_H_BxT"], + z_t0_to_H=dream_data["z_states_prior_t0_to_H_BxT"], + dreamer_model=dreamer_model, + obs_dims_shape=obs_dims_shape, + framework=framework, + ) + func = ( + create_cartpole_dream_image + if env.startswith("CartPole") + else create_frozenlake_dream_image + ) + # Take 0th dreamed trajectory and produce series of images. + for b in batch_indices: + images = [] + for t in range(len(dreamed_obs_H_B) - 1): + images.append( + func( + dreamed_obs=dreamed_obs_H_B[t][b], + dreamed_V=dream_data["values_dreamed_t0_to_H_BxT"][t][b], + dreamed_a=(dream_data["actions_ints_dreamed_t0_to_H_BxT"][t][b]), + dreamed_r_tp1=(dream_data["rewards_dreamed_t0_to_H_BxT"][t + 1][b]), + # `DISAGREE_intrinsic_rewards_H_B` are shifted by 1 already + # (from t1 to H, not t0 to H like all other data here). + dreamed_ri_tp1=( + results["DISAGREE_intrinsic_rewards_H_BxT"][t][b] + if "DISAGREE_intrinsic_rewards_H_BxT" in results + else None + ), + dreamed_c_tp1=( + dream_data["continues_dreamed_t0_to_H_BxT"][t + 1][b] + ), + value_target=results["VALUE_TARGETS_H_BxT"][t][b], + initial_h=dream_data["h_states_t0_to_H_BxT"][t][b], + as_tensor=True, + ).numpy() + ) + # Concat images along width-axis (so they show as a "film sequence" next to each + # other). + results.update( + { + f"dreamed_trajectories{('_'+desc) if desc else ''}_B{b}": ( + np.concatenate(images, axis=1) + ), + } + ) + + +def report_predicted_vs_sampled_obs( + *, + metrics, + sample, + batch_size_B, + batch_length_T, + symlog_obs: bool = True, + do_report: bool = True, +): + """Summarizes sampled data (from the replay buffer) vs world-model predictions. + + World model predictions are based on the posterior states (z computed from actual + observation encoder input + the current h-states). + + Observations: Computes MSE (sampled vs predicted/recreated) over all features. + For image observations, also creates direct image comparisons (sampled images + vs predicted (posterior) ones). + Rewards: Compute MSE (sampled vs predicted). + Continues: Compute MSE (sampled vs predicted). + + Args: + metrics: The MetricsLogger object of the DreamerV3 algo. + sample: The sampled data (dict) from the replay buffer. Already torch-tensor + converted. + batch_size_B: The batch size (B). This is the number of trajectories sampled + from the buffer. + batch_length_T: The batch length (T). This is the length of an individual + trajectory sampled from the buffer. + do_report: Whether to actually log the report (default). If this is set to + False, this function serves as a clean-up on the given metrics, making sure + they do NOT contain anymore any (spacious) data relevant for producing + the report/videos. + """ + fwd_output_key = ( + LEARNER_RESULTS, + DEFAULT_MODULE_ID, + "WORLD_MODEL_fwd_out_obs_distribution_means_b0xT", + ) + # logged as a non-reduced item (still a list) + predicted_observation_means_single_example = metrics.peek( + fwd_output_key, default=[None] + )[-1] + metrics.delete(fwd_output_key, key_error=False) + + final_result_key = ( + f"WORLD_MODEL_sampled_vs_predicted_posterior_b0x{batch_length_T}_videos" + ) + if not do_report: + metrics.delete(final_result_key, key_error=False) + return + + _report_obs( + metrics=metrics, + computed_float_obs_B_T_dims=np.reshape( + predicted_observation_means_single_example, + # WandB videos need to be channels first. + (1, batch_length_T) + sample[Columns.OBS].shape[2:], + ), + sampled_obs_B_T_dims=sample[Columns.OBS][0:1], + metrics_key=final_result_key, + symlog_obs=symlog_obs, + ) + + +def report_dreamed_eval_trajectory_vs_samples( + *, + metrics, + sample, + burn_in_T, + dreamed_T, + dreamer_model, + symlog_obs: bool = True, + do_report: bool = True, + framework="torch", +) -> None: + """Logs dreamed observations, rewards, continues and compares them vs sampled data. + + For obs, we'll try to create videos (side-by-side comparison) of the dreamed, + recreated-from-prior obs vs the sampled ones (over dreamed_T timesteps). + + Args: + metrics: The MetricsLogger object of the DreamerV3 algo. + sample: The sampled data (dict) from the replay buffer. Already torch-tensor + converted. + burn_in_T: The number of burn-in timesteps (these will be skipped over in the + reported video comparisons and MSEs). + dreamed_T: The number of timesteps to produce dreamed data for. + dreamer_model: The DreamerModel to use to create observation vectors/images + from dreamed h- and (prior) z-states. + symlog_obs: Whether to inverse-symlog the computed observations or not. Set this + to True for environments, in which we should symlog the observations. + do_report: Whether to actually log the report (default). If this is set to + False, this function serves as a clean-up on the given metrics, making sure + they do NOT contain anymore any (spacious) data relevant for producing + the report/videos. + """ + dream_data = metrics.peek( + (LEARNER_RESULTS, DEFAULT_MODULE_ID, "dream_data"), + default={}, + ) + metrics.delete(LEARNER_RESULTS, DEFAULT_MODULE_ID, "dream_data", key_error=False) + + final_result_key_obs = f"EVALUATION_sampled_vs_dreamed_prior_H{dreamed_T}_obs" + final_result_key_rew = ( + f"EVALUATION_sampled_vs_dreamed_prior_H{dreamed_T}_rewards_MSE" + ) + final_result_key_cont = ( + f"EVALUATION_sampled_vs_dreamed_prior_H{dreamed_T}_continues_MSE" + ) + if not do_report: + metrics.delete(final_result_key_obs, key_error=False) + metrics.delete(final_result_key_rew, key_error=False) + metrics.delete(final_result_key_cont, key_error=False) + return + + # Obs MSE. + dreamed_obs_H_B = reconstruct_obs_from_h_and_z( + h_t0_to_H=dream_data["h_states_t0_to_H_Bx1"][0], # [0] b/c reduce=None (list) + z_t0_to_H=dream_data["z_states_prior_t0_to_H_Bx1"][0], + dreamer_model=dreamer_model, + obs_dims_shape=sample[Columns.OBS].shape[2:], + framework=framework, + ) + t0 = burn_in_T + tH = t0 + dreamed_T + # Observation MSE and - if applicable - images comparisons. + _report_obs( + metrics=metrics, + # WandB videos need to be 5D (B, L, c, h, w) -> transpose/swap H and B axes. + computed_float_obs_B_T_dims=np.swapaxes(dreamed_obs_H_B, 0, 1)[ + 0:1 + ], # for now: only B=1 + sampled_obs_B_T_dims=sample[Columns.OBS][0:1, t0:tH], + metrics_key=final_result_key_obs, + symlog_obs=symlog_obs, + ) + + # Reward MSE. + _report_rewards( + metrics=metrics, + computed_rewards=dream_data["rewards_dreamed_t0_to_H_Bx1"][0], + sampled_rewards=sample[Columns.REWARDS][:, t0:tH], + metrics_key=final_result_key_rew, + ) + + # Continues MSE. + _report_continues( + metrics=metrics, + computed_continues=dream_data["continues_dreamed_t0_to_H_Bx1"][0], + sampled_continues=(1.0 - sample["is_terminated"])[:, t0:tH], + metrics_key=final_result_key_cont, + ) + + +def report_sampling_and_replay_buffer(*, metrics, replay_buffer): + episodes_in_buffer = replay_buffer.get_num_episodes() + ts_in_buffer = replay_buffer.get_num_timesteps() + replayed_steps = replay_buffer.get_sampled_timesteps() + added_steps = replay_buffer.get_added_timesteps() + + # Summarize buffer, sampling, and train ratio stats. + metrics.log_dict( + { + "capacity": replay_buffer.capacity, + "size_num_episodes": episodes_in_buffer, + "size_timesteps": ts_in_buffer, + "replayed_steps": replayed_steps, + "added_steps": added_steps, + }, + key=REPLAY_BUFFER_RESULTS, + window=1, + ) # window=1 b/c these are current (total count/state) values. + + +def _report_obs( + *, + metrics, + computed_float_obs_B_T_dims, + sampled_obs_B_T_dims, + metrics_key, + symlog_obs, +): + """Summarizes computed- vs sampled observations: MSE and (if applicable) images. + + Args: + metrics: The MetricsLogger object of the DreamerV3 algo. + computed_float_obs_B_T_dims: Computed float observations + (not clipped, not cast'd). Shape=(B, T, [dims ...]). + sampled_obs_B_T_dims: Sampled observations (as-is from the environment, meaning + this could be uint8, 0-255 clipped images). Shape=(B, T, [dims ...]). + metrics_key: The metrics key (or key sequence) under which to log ths resulting + video sequence. + symlog_obs: Whether to inverse-symlog the computed observations or not. Set this + to True for environments, in which we should symlog the observations. + """ + # Videos: Create summary, comparing computed images with actual sampled ones. + # 4=[B, T, w, h] grayscale image; 5=[B, T, w, h, C] RGB image. + if len(sampled_obs_B_T_dims.shape) in [4, 5]: + # WandB videos need to be channels first. + transpose_axes = ( + (0, 1, 4, 2, 3) if len(sampled_obs_B_T_dims.shape) == 5 else (0, 3, 1, 2) + ) + + if symlog_obs: + computed_float_obs_B_T_dims = inverse_symlog(computed_float_obs_B_T_dims) + + # Restore image pixels from normalized (non-symlog'd) data. + if not symlog_obs: + computed_float_obs_B_T_dims = (computed_float_obs_B_T_dims + 1.0) * 128 + sampled_obs_B_T_dims = (sampled_obs_B_T_dims + 1.0) * 128 + sampled_obs_B_T_dims = np.clip(sampled_obs_B_T_dims, 0.0, 255.0).astype( + np.uint8 + ) + sampled_obs_B_T_dims = np.transpose(sampled_obs_B_T_dims, transpose_axes) + computed_images = np.clip(computed_float_obs_B_T_dims, 0.0, 255.0).astype( + np.uint8 + ) + computed_images = np.transpose(computed_images, transpose_axes) + # Concat sampled and computed images along the height axis (3) such that + # real images show below respective predicted ones. + # (B, T, C, h, w) + sampled_vs_computed_images = np.concatenate( + [computed_images, sampled_obs_B_T_dims], + axis=-1, # concat on width axis (looks nicer) + ) + # Add grayscale dim, if necessary. + if len(sampled_obs_B_T_dims.shape) == 2 + 2: + sampled_vs_computed_images = np.expand_dims(sampled_vs_computed_images, -1) + + metrics.log_value( + metrics_key, + sampled_vs_computed_images, + reduce=None, # No reduction, we want the obs tensor to stay in-tact. + window=1, + ) + + +def _report_rewards( + *, + metrics, + computed_rewards, + sampled_rewards, + metrics_key, +): + mse_sampled_vs_computed_rewards = np.mean( + np.square(computed_rewards - sampled_rewards) + ) + mse_sampled_vs_computed_rewards = np.mean(mse_sampled_vs_computed_rewards) + metrics.log_value( + metrics_key, + mse_sampled_vs_computed_rewards, + window=1, + ) + + +def _report_continues( + *, + metrics, + computed_continues, + sampled_continues, + metrics_key, +): + # Continue MSE. + mse_sampled_vs_computed_continues = np.mean( + np.square( + computed_continues - sampled_continues.astype(computed_continues.dtype) + ) + ) + metrics.log_value( + metrics_key, + mse_sampled_vs_computed_continues, + window=1, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..913c1b77198e0ee941198fdfefbd8bc29ef875cf --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/__init__.py @@ -0,0 +1,23 @@ +from ray.rllib.algorithms.impala.impala import ( + IMPALA, + IMPALAConfig, + Impala, + ImpalaConfig, +) +from ray.rllib.algorithms.impala.impala_tf_policy import ( + ImpalaTF1Policy, + ImpalaTF2Policy, +) +from ray.rllib.algorithms.impala.impala_torch_policy import ImpalaTorchPolicy + +__all__ = [ + "IMPALA", + "IMPALAConfig", + # @OldAPIStack + "ImpalaTF1Policy", + "ImpalaTF2Policy", + "ImpalaTorchPolicy", + # Deprecated names (lowercase) + "ImpalaConfig", + "Impala", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..465c76c1fdce14784d3fe7ee59d653e9e6fb9423 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/__pycache__/impala.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/__pycache__/impala.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7009b4316f90a4dde1a0ad192303690fa8b3ec96 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/__pycache__/impala.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/__pycache__/impala_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/__pycache__/impala_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e932fb91f8fb64a4b2d18f06d1d3959f0fd5772 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/__pycache__/impala_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/__pycache__/impala_tf_policy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/__pycache__/impala_tf_policy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74c50b42bb6eedf892d78580b86952f59ea291e7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/__pycache__/impala_tf_policy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/__pycache__/impala_torch_policy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/__pycache__/impala_torch_policy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2f3e641d549e3ef822eb838d1e2fe6c8c1a586f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/__pycache__/impala_torch_policy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/__pycache__/utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8fb88f569eda6fc03286d6fff89d2885a6de086b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/__pycache__/utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/__pycache__/vtrace_tf.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/__pycache__/vtrace_tf.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8876de9ac03ab327f4dfd4ba2b88d3fbdc760235 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/__pycache__/vtrace_tf.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/__pycache__/vtrace_torch.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/__pycache__/vtrace_torch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ccf906d69cf305a60ca2ca8b0c7474ac180a1ea Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/__pycache__/vtrace_torch.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/impala.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/impala.py new file mode 100644 index 0000000000000000000000000000000000000000..e3c2abfa1f376cf59f7c6aa5271d5ad4039544fa --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/impala.py @@ -0,0 +1,1251 @@ +import copy +import logging +import queue +from typing import Dict, List, Optional, Set, Tuple, Type, Union + +import ray +from ray import ObjectRef +from ray.rllib import SampleBatch +from ray.rllib.algorithms.algorithm import Algorithm +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig, NotProvided +from ray.rllib.connectors.learner import AddOneTsToEpisodesAndTruncate, NumpyToTensor +from ray.rllib.core import ( + COMPONENT_ENV_TO_MODULE_CONNECTOR, + COMPONENT_MODULE_TO_ENV_CONNECTOR, +) +from ray.rllib.core.learner.training_data import TrainingData +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.execution.buffers.mixin_replay_buffer import MixInMultiAgentReplayBuffer +from ray.rllib.execution.learner_thread import LearnerThread +from ray.rllib.execution.multi_gpu_learner_thread import MultiGPULearnerThread +from ray.rllib.policy.policy import Policy +from ray.rllib.policy.sample_batch import concat_samples +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.deprecation import DEPRECATED_VALUE, deprecation_warning +from ray.rllib.utils.metrics import ( + AGGREGATOR_ACTOR_RESULTS, + ALL_MODULES, + ENV_RUNNER_RESULTS, + LEARNER_GROUP, + LEARNER_RESULTS, + LEARNER_UPDATE_TIMER, + MEAN_NUM_EPISODE_LISTS_RECEIVED, + MEAN_NUM_LEARNER_RESULTS_RECEIVED, + MEAN_NUM_LEARNER_GROUP_UPDATE_CALLED, + NUM_AGENT_STEPS_SAMPLED, + NUM_AGENT_STEPS_TRAINED, + NUM_ENV_STEPS_SAMPLED, + NUM_ENV_STEPS_SAMPLED_LIFETIME, + NUM_ENV_STEPS_TRAINED, + NUM_ENV_STEPS_TRAINED_LIFETIME, + NUM_SYNCH_WORKER_WEIGHTS, + NUM_TRAINING_STEP_CALLS_SINCE_LAST_SYNCH_WORKER_WEIGHTS, + SYNCH_WORKER_WEIGHTS_TIMER, + SAMPLE_TIMER, + TIMERS, +) +from ray.rllib.utils.metrics.learner_info import LearnerInfoBuilder +from ray.rllib.utils.replay_buffers.multi_agent_replay_buffer import ReplayMode +from ray.rllib.utils.replay_buffers.replay_buffer import _ALL_POLICIES +from ray.rllib.utils.schedules.scheduler import Scheduler +from ray.rllib.utils.typing import ( + LearningRateOrSchedule, + PolicyID, + ResultDict, + SampleBatchType, +) + + +logger = logging.getLogger(__name__) + + +LEARNER_RESULTS_CURR_ENTROPY_COEFF_KEY = "curr_entropy_coeff" + + +class IMPALAConfig(AlgorithmConfig): + """Defines a configuration class from which an Impala can be built. + + .. testcode:: + + from ray.rllib.algorithms.impala import IMPALAConfig + + config = ( + IMPALAConfig() + .environment("CartPole-v1") + .env_runners(num_env_runners=1) + .training(lr=0.0003, train_batch_size_per_learner=512) + .learners(num_learners=1) + ) + # Build a Algorithm object from the config and run 1 training iteration. + algo = config.build() + algo.train() + del algo + + .. testcode:: + + from ray.rllib.algorithms.impala import IMPALAConfig + from ray import tune + + config = ( + IMPALAConfig() + .environment("CartPole-v1") + .env_runners(num_env_runners=1) + .training(lr=tune.grid_search([0.0001, 0.0002]), grad_clip=20.0) + .learners(num_learners=1) + ) + # Run with tune. + tune.Tuner( + "IMPALA", + param_space=config, + run_config=tune.RunConfig(stop={"training_iteration": 1}), + ).fit() + """ + + def __init__(self, algo_class=None): + """Initializes a IMPALAConfig instance.""" + self.exploration_config = { # @OldAPIstack + # The Exploration class to use. In the simplest case, this is the name + # (str) of any class present in the `rllib.utils.exploration` package. + # You can also provide the python class directly or the full location + # of your class (e.g. "ray.rllib.utils.exploration.epsilon_greedy. + # EpsilonGreedy"). + "type": "StochasticSampling", + # Add constructor kwargs here (if any). + } + + super().__init__(algo_class=algo_class or IMPALA) + + # fmt: off + # __sphinx_doc_begin__ + + # IMPALA specific settings: + self.vtrace = True + self.vtrace_clip_rho_threshold = 1.0 + self.vtrace_clip_pg_rho_threshold = 1.0 + self.learner_queue_size = 3 + self.timeout_s_sampler_manager = 0.0 + self.timeout_s_aggregator_manager = 0.0 + self.broadcast_interval = 1 + self.num_gpu_loader_threads = 8 + + self.grad_clip = 40.0 + # Note: Only when using enable_rl_module_and_learner=True can the clipping mode + # be configured by the user. On the old API stack, RLlib will always clip by + # global_norm, no matter the value of `grad_clip_by`. + self.grad_clip_by = "global_norm" + + self.vf_loss_coeff = 0.5 + self.entropy_coeff = 0.01 + + # Override some of AlgorithmConfig's default values with IMPALA-specific values. + self.num_learners = 1 + self.num_aggregator_actors_per_learner = 0 + self.rollout_fragment_length = 50 + self.train_batch_size = 500 # @OldAPIstack + self.num_env_runners = 2 + self.lr = 0.0005 + self.min_time_s_per_iteration = 10 + # __sphinx_doc_end__ + # fmt: on + + # IMPALA takes care of its own EnvRunner (weights, connector, metrics) synching. + self._dont_auto_sync_env_runner_states = True + + # `.debugging()` + self._env_runners_only = False + self._skip_learners = False + + self.lr_schedule = None # @OldAPIStack + self.entropy_coeff_schedule = None # @OldAPIStack + self.num_multi_gpu_tower_stacks = 1 # @OldAPIstack + self.minibatch_buffer_size = 1 # @OldAPIstack + self.replay_proportion = 0.0 # @OldAPIstack + self.replay_buffer_num_slots = 0 # @OldAPIstack + self.learner_queue_timeout = 300 # @OldAPIstack + self.opt_type = "adam" # @OldAPIstack + self.decay = 0.99 # @OldAPIstack + self.momentum = 0.0 # @OldAPIstack + self.epsilon = 0.1 # @OldAPIstack + self._separate_vf_optimizer = False # @OldAPIstack + self._lr_vf = 0.0005 # @OldAPIstack + self.num_gpus = 1 # @OldAPIstack + self._tf_policy_handles_more_than_one_loss = True # @OldAPIstack + + # Deprecated settings. + self.num_aggregation_workers = DEPRECATED_VALUE + self.max_requests_in_flight_per_aggregator_worker = DEPRECATED_VALUE + + @override(AlgorithmConfig) + def training( + self, + *, + vtrace: Optional[bool] = NotProvided, + vtrace_clip_rho_threshold: Optional[float] = NotProvided, + vtrace_clip_pg_rho_threshold: Optional[float] = NotProvided, + num_gpu_loader_threads: Optional[int] = NotProvided, + num_multi_gpu_tower_stacks: Optional[int] = NotProvided, + minibatch_buffer_size: Optional[int] = NotProvided, + replay_proportion: Optional[float] = NotProvided, + replay_buffer_num_slots: Optional[int] = NotProvided, + learner_queue_size: Optional[int] = NotProvided, + learner_queue_timeout: Optional[float] = NotProvided, + timeout_s_sampler_manager: Optional[float] = NotProvided, + timeout_s_aggregator_manager: Optional[float] = NotProvided, + broadcast_interval: Optional[int] = NotProvided, + grad_clip: Optional[float] = NotProvided, + opt_type: Optional[str] = NotProvided, + lr_schedule: Optional[List[List[Union[int, float]]]] = NotProvided, + decay: Optional[float] = NotProvided, + momentum: Optional[float] = NotProvided, + epsilon: Optional[float] = NotProvided, + vf_loss_coeff: Optional[float] = NotProvided, + entropy_coeff: Optional[LearningRateOrSchedule] = NotProvided, + entropy_coeff_schedule: Optional[List[List[Union[int, float]]]] = NotProvided, + _separate_vf_optimizer: Optional[bool] = NotProvided, + _lr_vf: Optional[float] = NotProvided, + # Deprecated args. + num_aggregation_workers=DEPRECATED_VALUE, + max_requests_in_flight_per_aggregator_worker=DEPRECATED_VALUE, + **kwargs, + ) -> "IMPALAConfig": + """Sets the training related configuration. + + Args: + vtrace: V-trace params (see vtrace_tf/torch.py). + vtrace_clip_rho_threshold: + vtrace_clip_pg_rho_threshold: + num_gpu_loader_threads: The number of GPU-loader threads (per Learner + worker), used to load incoming (CPU) batches to the GPU, if applicable. + The incoming batches are produced by each Learner's LearnerConnector + pipeline. After loading the batches on the GPU, the threads place them + on yet another queue for the Learner thread (only one per Learner + worker) to pick up and perform `forward_train/loss` computations. + num_multi_gpu_tower_stacks: For each stack of multi-GPU towers, how many + slots should we reserve for parallel data loading? Set this to >1 to + load data into GPUs in parallel. This will increase GPU memory usage + proportionally with the number of stacks. + Example: + 2 GPUs and `num_multi_gpu_tower_stacks=3`: + - One tower stack consists of 2 GPUs, each with a copy of the + model/graph. + - Each of the stacks will create 3 slots for batch data on each of its + GPUs, increasing memory requirements on each GPU by 3x. + - This enables us to preload data into these stacks while another stack + is performing gradient calculations. + minibatch_buffer_size: How many train batches should be retained for + minibatching. This conf only has an effect if `num_epochs > 1`. + replay_proportion: Set >0 to enable experience replay. Saved samples will + be replayed with a p:1 proportion to new data samples. + replay_buffer_num_slots: Number of sample batches to store for replay. + The number of transitions saved total will be + (replay_buffer_num_slots * rollout_fragment_length). + learner_queue_size: Max queue size for train batches feeding into the + learner. + learner_queue_timeout: Wait for train batches to be available in minibatch + buffer queue this many seconds. This may need to be increased e.g. when + training with a slow environment. + timeout_s_sampler_manager: The timeout for waiting for sampling results + for workers -- typically if this is too low, the manager won't be able + to retrieve ready sampling results. + timeout_s_aggregator_manager: The timeout for waiting for replay worker + results -- typically if this is too low, the manager won't be able to + retrieve ready replay requests. + broadcast_interval: Number of training step calls before weights are + broadcasted to rollout workers that are sampled during any iteration. + grad_clip: If specified, clip the global norm of gradients by this amount. + opt_type: Either "adam" or "rmsprop". + lr_schedule: Learning rate schedule. In the format of + [[timestep, lr-value], [timestep, lr-value], ...] + Intermediary timesteps will be assigned to interpolated learning rate + values. A schedule should normally start from timestep 0. + decay: Decay setting for the RMSProp optimizer, in case `opt_type=rmsprop`. + momentum: Momentum setting for the RMSProp optimizer, in case + `opt_type=rmsprop`. + epsilon: Epsilon setting for the RMSProp optimizer, in case + `opt_type=rmsprop`. + vf_loss_coeff: Coefficient for the value function term in the loss function. + entropy_coeff: Coefficient for the entropy regularizer term in the loss + function. + entropy_coeff_schedule: Decay schedule for the entropy regularizer. + _separate_vf_optimizer: Set this to true to have two separate optimizers + optimize the policy-and value networks. Only supported for some + algorithms (APPO, IMPALA) on the old API stack. + _lr_vf: If _separate_vf_optimizer is True, define separate learning rate + for the value network. + + Returns: + This updated AlgorithmConfig object. + """ + if num_aggregation_workers != DEPRECATED_VALUE: + deprecation_warning( + old="config.training(num_aggregation_workers=..)", + help="Aggregator workers are no longer supported on the old API " + "stack! To use aggregation (and GPU pre-loading) on the new API " + "stack, activate the new API stack, then set " + "`config.learners(num_aggregator_actors_per_learner=..)`. Good " + "choices are normally 1 or 2, but this depends on your overall " + "setup, especially your `EnvRunner` throughput.", + error=True, + ) + if max_requests_in_flight_per_aggregator_worker != DEPRECATED_VALUE: + deprecation_warning( + old="config.training(max_requests_in_flight_per_aggregator_worker=..)", + help="Aggregator workers are no longer supported on the old API " + "stack! To use aggregation (and GPU pre-loading) on the new API " + "stack, activate the new API stack and THEN set " + "`config.learners(max_requests_in_flight_per_aggregator_actor=..)" + "`.", + error=True, + ) + + # Pass kwargs onto super's `training()` method. + super().training(**kwargs) + + if vtrace is not NotProvided: + self.vtrace = vtrace + if vtrace_clip_rho_threshold is not NotProvided: + self.vtrace_clip_rho_threshold = vtrace_clip_rho_threshold + if vtrace_clip_pg_rho_threshold is not NotProvided: + self.vtrace_clip_pg_rho_threshold = vtrace_clip_pg_rho_threshold + if num_gpu_loader_threads is not NotProvided: + self.num_gpu_loader_threads = num_gpu_loader_threads + if num_multi_gpu_tower_stacks is not NotProvided: + self.num_multi_gpu_tower_stacks = num_multi_gpu_tower_stacks + if minibatch_buffer_size is not NotProvided: + self.minibatch_buffer_size = minibatch_buffer_size + if replay_proportion is not NotProvided: + self.replay_proportion = replay_proportion + if replay_buffer_num_slots is not NotProvided: + self.replay_buffer_num_slots = replay_buffer_num_slots + if learner_queue_size is not NotProvided: + self.learner_queue_size = learner_queue_size + if learner_queue_timeout is not NotProvided: + self.learner_queue_timeout = learner_queue_timeout + if broadcast_interval is not NotProvided: + self.broadcast_interval = broadcast_interval + if timeout_s_sampler_manager is not NotProvided: + self.timeout_s_sampler_manager = timeout_s_sampler_manager + if timeout_s_aggregator_manager is not NotProvided: + self.timeout_s_aggregator_manager = timeout_s_aggregator_manager + if grad_clip is not NotProvided: + self.grad_clip = grad_clip + if opt_type is not NotProvided: + self.opt_type = opt_type + if lr_schedule is not NotProvided: + self.lr_schedule = lr_schedule + if decay is not NotProvided: + self.decay = decay + if momentum is not NotProvided: + self.momentum = momentum + if epsilon is not NotProvided: + self.epsilon = epsilon + if vf_loss_coeff is not NotProvided: + self.vf_loss_coeff = vf_loss_coeff + if entropy_coeff is not NotProvided: + self.entropy_coeff = entropy_coeff + if entropy_coeff_schedule is not NotProvided: + self.entropy_coeff_schedule = entropy_coeff_schedule + if _separate_vf_optimizer is not NotProvided: + self._separate_vf_optimizer = _separate_vf_optimizer + if _lr_vf is not NotProvided: + self._lr_vf = _lr_vf + + return self + + def debugging( + self, + *, + _env_runners_only: Optional[bool] = NotProvided, + _skip_learners: Optional[bool] = NotProvided, + **kwargs, + ) -> "IMPALAConfig": + """Sets the debugging related configuration. + + Args: + _env_runners_only: If True, only run (remote) EnvRunner requests, discard + their episode/training data, but log their metrics results. Aggregator- + and Learner actors won't be used. + _skip_learners: If True, no `update` requests are sent to the LearnerGroup + and Learner actors. Only EnvRunners and aggregator actors (if + applicable) are used. + """ + super().debugging(**kwargs) + + if _env_runners_only is not NotProvided: + self._env_runners_only = _env_runners_only + if _skip_learners is not NotProvided: + self._skip_learners = _skip_learners + + return self + + @override(AlgorithmConfig) + def validate(self) -> None: + # Call the super class' validation method first. + super().validate() + + # IMPALA and APPO need vtrace (A3C Policies no longer exist). + if not self.vtrace: + self._value_error( + "IMPALA and APPO do NOT support vtrace=False anymore! Set " + "`config.training(vtrace=True)`." + ) + + # New API stack checks. + if self.enable_env_runner_and_connector_v2: + # Does NOT support aggregation workers yet or a mixin replay buffer. + if self.replay_ratio != 0.0: + self._value_error( + "The new API stack in combination with the new EnvRunner API " + "does NOT support a mixin replay buffer yet for " + f"{self} (set `config.replay_proportion` to 0.0)!" + ) + # `lr_schedule` checking. + if self.lr_schedule is not None: + self._value_error( + "`lr_schedule` is deprecated and must be None! Use the " + "`lr` setting to setup a schedule." + ) + # Entropy coeff schedule checking. + if self.entropy_coeff_schedule is not None: + self._value_error( + "`entropy_coeff_schedule` is deprecated and must be None! Use the " + "`entropy_coeff` setting to setup a schedule." + ) + Scheduler.validate( + fixed_value_or_schedule=self.entropy_coeff, + setting_name="entropy_coeff", + description="entropy coefficient", + ) + if self.minibatch_size is not None and not ( + (self.minibatch_size % self.rollout_fragment_length == 0) + and self.minibatch_size <= self.total_train_batch_size + ): + self._value_error( + f"`minibatch_size` ({self._minibatch_size}) must either be None " + "or a multiple of `rollout_fragment_length` " + f"({self.rollout_fragment_length}) while at the same time smaller " + "than or equal to `total_train_batch_size` " + f"({self.total_train_batch_size})!" + ) + # Old API stack checks. + else: + if isinstance(self.entropy_coeff, float) and self.entropy_coeff < 0.0: + self._value_error("`entropy_coeff` must be >= 0.0") + + # If two separate optimizers/loss terms used for tf, must also set + # `_tf_policy_handles_more_than_one_loss` to True. + if ( + self.framework_str in ["tf", "tf2"] + and self._separate_vf_optimizer is True + and self._tf_policy_handles_more_than_one_loss is False + ): + self._value_error( + "`_tf_policy_handles_more_than_one_loss` must be set to True, for " + "TFPolicy to support more than one loss term/optimizer! Try setting " + "config.training(_tf_policy_handles_more_than_one_loss=True)." + ) + + @property + def replay_ratio(self) -> float: + """Returns replay ratio (between 0.0 and 1.0) based off self.replay_proportion. + + Formula: ratio = 1 / proportion + """ + return (1 / self.replay_proportion) if self.replay_proportion > 0 else 0.0 + + @override(AlgorithmConfig) + def get_default_learner_class(self): + if self.framework_str == "torch": + from ray.rllib.algorithms.impala.torch.impala_torch_learner import ( + IMPALATorchLearner, + ) + + return IMPALATorchLearner + elif self.framework_str in ["tf2", "tf"]: + raise ValueError( + "TensorFlow is no longer supported on the new API stack! " + "Use `framework='torch'`." + ) + else: + raise ValueError( + f"The framework {self.framework_str} is not supported. " + "Use `framework='torch'`." + ) + + @override(AlgorithmConfig) + def get_default_rl_module_spec(self) -> RLModuleSpec: + if self.framework_str == "torch": + from ray.rllib.algorithms.ppo.torch.default_ppo_torch_rl_module import ( + DefaultPPOTorchRLModule, + ) + + return RLModuleSpec(module_class=DefaultPPOTorchRLModule) + else: + raise ValueError( + f"The framework {self.framework_str} is not supported. " + "Use either 'torch' or 'tf2'." + ) + + @override(AlgorithmConfig) + def build_learner_connector( + self, + input_observation_space, + input_action_space, + device=None, + ): + connector = super().build_learner_connector( + input_observation_space, + input_action_space, + device, + ) + if self.add_default_connectors_to_learner_pipeline: + # Extend all episodes by one artificial timestep to allow the value function + # net to compute the bootstrap values (and add a mask to the batch to know, + # which slots to mask out). + connector.prepend(AddOneTsToEpisodesAndTruncate()) + # Remove the NumpyToTensor connector if we have the GPULoaderThreads. + if self.num_aggregator_actors_per_learner > 0: + connector.remove(NumpyToTensor) + return connector + + +ImpalaConfig = IMPALAConfig + + +class IMPALA(Algorithm): + """Importance weighted actor/learner architecture (IMPALA) Algorithm + + == Overview of data flow in IMPALA == + 1. Policy evaluation in parallel across `num_env_runners` actors produces + batches of size `rollout_fragment_length * num_envs_per_env_runner`. + 2. If enabled, the replay buffer stores and produces batches of size + `rollout_fragment_length * num_envs_per_env_runner`. + 3. If enabled, the minibatch ring buffer stores and replays batches of + size `train_batch_size` up to `num_epochs` times per batch. + 4. The learner thread executes data parallel SGD across `num_gpus` GPUs + on batches of size `train_batch_size`. + """ + + @classmethod + @override(Algorithm) + def get_default_config(cls) -> AlgorithmConfig: + return IMPALAConfig() + + @classmethod + @override(Algorithm) + def get_default_policy_class( + cls, config: AlgorithmConfig + ) -> Optional[Type[Policy]]: + if config.framework_str == "torch": + from ray.rllib.algorithms.impala.impala_torch_policy import ( + ImpalaTorchPolicy, + ) + + return ImpalaTorchPolicy + + elif config.framework_str == "tf": + from ray.rllib.algorithms.impala.impala_tf_policy import ( + ImpalaTF1Policy, + ) + + return ImpalaTF1Policy + else: + from ray.rllib.algorithms.impala.impala_tf_policy import ( + ImpalaTF2Policy, + ) + + return ImpalaTF2Policy + + @override(Algorithm) + def setup(self, config: AlgorithmConfig): + super().setup(config) + + # Queue of data to be sent to the Learner. + self.data_to_place_on_learner = [] + self.local_mixin_buffer = None # @OldAPIStack + self._batch_being_built = [] # @OldAPIStack + + # Create extra aggregation workers and assign each rollout worker to one of + # them. + self._episode_packs_being_built = [] + self._ma_batches_being_built: Dict[int, list] = { + i: [] for i in range(self.config.num_learners or 1) + } + + # Create local mixin buffer if on old API stack and replay + # proportion is set. + if not self.config.enable_rl_module_and_learner: + if self.config.replay_proportion > 0.0: + self.local_mixin_buffer = MixInMultiAgentReplayBuffer( + capacity=( + self.config.replay_buffer_num_slots + if self.config.replay_buffer_num_slots > 0 + else 1 + ), + replay_ratio=self.config.replay_ratio, + replay_mode=ReplayMode.LOCKSTEP, + ) + + # This variable is used to keep track of the statistics from the most recent + # update of the learner group + self._results = {} + + if not self.config.enable_rl_module_and_learner: + # Create and start the learner thread. + self._learner_thread = make_learner_thread(self.env_runner, self.config) + self._learner_thread.start() + + @override(Algorithm) + def training_step(self): + # Old API stack. + if not self.config.enable_rl_module_and_learner: + return self._training_step_old_api_stack() + + do_async_updates = self.config.num_learners > 0 + + # Asynchronously request all EnvRunners to sample and return their current + # (e.g. ConnectorV2) states and sampling metrics/stats. + # Note that each item in `episode_refs` is a reference to a list of Episodes. + with self.metrics.log_time((TIMERS, SAMPLE_TIMER)): + ( + episode_refs, + connector_states, + env_runner_metrics, + env_runner_indices_to_update, + ) = self._sample_and_get_connector_states() + # Reduce EnvRunner metrics over the n EnvRunners. + self.metrics.aggregate( + env_runner_metrics, + key=ENV_RUNNER_RESULTS, + ) + + # Log the average number of sample results (list of episodes) received. + self.metrics.log_value( + (ENV_RUNNER_RESULTS, MEAN_NUM_EPISODE_LISTS_RECEIVED), + len(episode_refs), + ) + + # Only run EnvRunners, nothing else. + if self.config._env_runners_only: + return + + # "Batch" collected episode refs into groups, such that exactly + # `total_train_batch_size` timesteps are sent to + # `LearnerGroup.update()`. + if self.config.num_aggregator_actors_per_learner > 0: + data_packages_for_aggregators = self._pre_queue_episode_refs( + episode_refs, package_size=self.config.train_batch_size_per_learner + ) + self.metrics.log_value( + (AGGREGATOR_ACTOR_RESULTS, "mean_num_input_packages"), + len(episode_refs), + ) + + ma_batches_refs_remote_results = ( + self._aggregator_actor_manager.fetch_ready_async_reqs( + timeout_seconds=0.0, + return_obj_refs=True, + tags="batches", + ) + ) + ma_batches_refs = [] + for call_result in ma_batches_refs_remote_results: + ma_batches_refs.append((call_result.actor_id, call_result.get())) + self.metrics.log_value( + (AGGREGATOR_ACTOR_RESULTS, "mean_num_output_batches"), + len(ma_batches_refs), + ) + + while data_packages_for_aggregators: + num_agg = self.config.num_aggregator_actors_per_learner * ( + self.config.num_learners or 1 + ) + packs, data_packages_for_aggregators = ( + data_packages_for_aggregators[:num_agg], + data_packages_for_aggregators[num_agg:], + ) + sent = self._aggregator_actor_manager.foreach_actor_async( + func="get_batch", + kwargs=[dict(episode_refs=p) for p in packs], + tag="batches", + ) + self.metrics.log_value( + (AGGREGATOR_ACTOR_RESULTS, "num_env_steps_dropped_lifetime"), + self.config.train_batch_size_per_learner * (len(packs) - sent), + reduce="sum", + ) + + # Get n lists of m ObjRef[MABatch] (m=num_learners) to perform n calls to + # all learner workers with the already GPU-located batches. + data_packages_for_learner_group = self._pre_queue_batch_refs( + ma_batches_refs + ) + self.metrics.log_value( + (AGGREGATOR_ACTOR_RESULTS, "num_env_steps_aggregated_lifetime"), + self.config.train_batch_size_per_learner + * (self.config.num_learners or 1) + * len(data_packages_for_learner_group), + reduce="sum", + with_throughput=True, + ) + + else: + data_packages_for_learner_group = self._pre_queue_episode_refs( + episode_refs, package_size=self.config.total_train_batch_size + ) + + # Skip Learner update calls. + if self.config._skip_learners: + return + + # Call the LearnerGroup's `update()` method. + with self.metrics.log_time((TIMERS, LEARNER_UPDATE_TIMER)): + self.metrics.log_value( + key=MEAN_NUM_LEARNER_GROUP_UPDATE_CALLED, + value=len(data_packages_for_learner_group), + ) + rl_module_state = None + num_learner_group_results_received = 0 + + return_state = ( + self.metrics.peek( + NUM_TRAINING_STEP_CALLS_SINCE_LAST_SYNCH_WORKER_WEIGHTS, + default=0, + ) + >= self.config.broadcast_interval + ) + + for batch_ref_or_episode_list_ref in data_packages_for_learner_group: + timesteps = { + NUM_ENV_STEPS_SAMPLED_LIFETIME: self.metrics.peek( + (ENV_RUNNER_RESULTS, NUM_ENV_STEPS_SAMPLED_LIFETIME), default=0 + ), + NUM_ENV_STEPS_TRAINED_LIFETIME: self.metrics.peek( + (LEARNER_RESULTS, ALL_MODULES, NUM_ENV_STEPS_TRAINED_LIFETIME), + default=0, + ), + } + # Update from batch refs coming from AggregatorActors. + if self.config.num_aggregator_actors_per_learner > 0: + assert len(batch_ref_or_episode_list_ref) == ( + self.config.num_learners or 1 + ) + training_data = TrainingData( + batch_refs=batch_ref_or_episode_list_ref + ) + # Update from episodes refs coming from EnvRunner actors. + else: + training_data = TrainingData( + episodes_refs=batch_ref_or_episode_list_ref + ) + learner_results = self.learner_group.update( + training_data=training_data, + async_update=do_async_updates, + return_state=return_state, + timesteps=timesteps, + num_epochs=self.config.num_epochs, + minibatch_size=self.config.minibatch_size, + shuffle_batch_per_epoch=self.config.shuffle_batch_per_epoch, + ) + # Only request weights from 1st Learner - at most - once per + # `training_step` call. + return_state = False + + num_learner_group_results_received += len(learner_results) + # Extract the last (most recent) weights matrix, if available. + for result_from_1_learner in learner_results: + rl_module_state = result_from_1_learner.pop( + "_rl_module_state_after_update", rl_module_state + ) + self.metrics.aggregate( + stats_dicts=learner_results, + key=LEARNER_RESULTS, + ) + self.metrics.log_value( + key=(LEARNER_GROUP, MEAN_NUM_LEARNER_RESULTS_RECEIVED), + value=num_learner_group_results_received, + ) + + self.metrics.log_value( + NUM_TRAINING_STEP_CALLS_SINCE_LAST_SYNCH_WORKER_WEIGHTS, 1, reduce="sum" + ) + + # Update LearnerGroup's own stats. + self.metrics.log_dict(self.learner_group.get_stats(), key=LEARNER_GROUP) + + # Figure out, whether we should sync/broadcast the (remote) EnvRunner states. + # Note: `learner_results` is a List of n (num async calls) Lists of m + # (num Learner workers) ResultDicts each. + if rl_module_state is not None: + self.metrics.set_value( + NUM_TRAINING_STEP_CALLS_SINCE_LAST_SYNCH_WORKER_WEIGHTS, 0 + ) + self.metrics.log_value(NUM_SYNCH_WORKER_WEIGHTS, 1, reduce="sum") + with self.metrics.log_time((TIMERS, SYNCH_WORKER_WEIGHTS_TIMER)): + self.env_runner_group.sync_env_runner_states( + config=self.config, + connector_states=connector_states, + rl_module_state=rl_module_state, + env_to_module=self.env_to_module_connector, + module_to_env=self.module_to_env_connector, + ) + + def _sample_and_get_connector_states(self): + env_runner_indices_to_update = set() + episode_refs = [] + connector_states = [] + env_runner_metrics = [] + num_healthy_remote_workers = self.env_runner_group.num_healthy_remote_workers() + + # Perform asynchronous sampling on all (healthy) remote rollout workers. + if num_healthy_remote_workers > 0: + async_results: List[ + Tuple[int, ObjectRef] + ] = self.env_runner_group.fetch_ready_async_reqs( + timeout_seconds=self.config.timeout_s_sampler_manager, + return_obj_refs=False, + ) + self.env_runner_group.foreach_env_runner_async( + "sample_get_state_and_metrics" + ) + # Get results from the n different async calls and store those EnvRunner + # indices we should update. + results = [] + for r in async_results: + env_runner_indices_to_update.add(r[0]) + results.append(r[1]) + + for (episodes, states, metrics) in results: + episode_refs.append(episodes) + connector_states.append(states) + env_runner_metrics.append(metrics) + # Sample from the local EnvRunner. + else: + episodes = self.env_runner.sample() + env_runner_metrics = [self.env_runner.get_metrics()] + episode_refs = [ray.put(episodes)] + connector_states = [ + self.env_runner.get_state( + components=[ + COMPONENT_ENV_TO_MODULE_CONNECTOR, + COMPONENT_MODULE_TO_ENV_CONNECTOR, + ] + ) + ] + + return ( + episode_refs, + connector_states, + env_runner_metrics, + env_runner_indices_to_update, + ) + + def _pre_queue_episode_refs( + self, episode_refs: List[ObjectRef], package_size: int + ) -> List[List[ObjectRef]]: + # Each element in this list is itself a list of ObjRef[Episodes]. + # Each ObjRef was returned by one EnvRunner from a single sample() call. + episodes: List[List[ObjectRef]] = [] + + for ref in episode_refs: + self._episode_packs_being_built.append(ref) + if ( + len(self._episode_packs_being_built) + * self.config.num_envs_per_env_runner + * self.config.get_rollout_fragment_length() + >= package_size + ): + episodes.append(self._episode_packs_being_built) + self._episode_packs_being_built = [] + + return episodes + + def _pre_queue_batch_refs( + self, batch_refs: List[Tuple[int, ObjectRef]] + ) -> List[List[ObjectRef]]: + # `batch_refs` is a list of tuple(aggregator_actor_id, ObjRef[MABatch]). + + # Each ObjRef[MABatch] was returned by one AggregatorActor from a single + # `get_batch()` call. + # TODO (sven): Add this comment, once valid: + # .. and the underlying MABatch is already located on a particular GPU + # (matching one particular Learner). + for agg_actor_id, ma_batch_ref in batch_refs: + learner_actor_id = self._aggregator_actor_to_learner[agg_actor_id] + self._ma_batches_being_built[learner_actor_id].append(ma_batch_ref) + + # Construct an n-group of batches (n=num_learners) as long as we still have + # at least one batch per learner in our queue. + batch_refs_for_learner_group: List[List[ObjectRef]] = [] + while all( + learner_list for learner_list in self._ma_batches_being_built.values() + ): + batch_refs_for_learner_group.append( + [ + learner_list.pop(0) + for learner_list in self._ma_batches_being_built.values() + ] + ) + + return batch_refs_for_learner_group + + @OldAPIStack + def _training_step_old_api_stack(self): + # First, check, whether our learner thread is still healthy. + if not self._learner_thread.is_alive(): + raise RuntimeError("The learner thread died while training!") + + # Get sampled SampleBatches from our workers (by ray references if we use + # tree-aggregation). + unprocessed_sample_batches = self._get_samples_from_workers_old_api_stack( + return_object_refs=False, + ) + # Tag workers that actually produced ready sample batches this iteration. + # Those workers will have to get updated at the end of the iteration. + workers_that_need_updates = { + worker_id for worker_id, _ in unprocessed_sample_batches + } + + # Resolve collected batches here on local process (using the mixin buffer). + batches = self._process_experiences_old_api_stack(unprocessed_sample_batches) + + # Increase sampling counters now that we have the actual SampleBatches on + # the local process (and can measure their sizes). + for batch in batches: + self._counters[NUM_ENV_STEPS_SAMPLED] += batch.count + self._counters[NUM_AGENT_STEPS_SAMPLED] += batch.agent_steps() + # Concatenate single batches into batches of size `total_train_batch_size`. + self._concatenate_batches_and_pre_queue(batches) + # Move train batches (of size `total_train_batch_size`) onto learner queue. + self._place_processed_samples_on_learner_thread_queue() + # Extract most recent train results from learner thread. + train_results = self._process_trained_results() + + # Sync worker weights (only those policies that were actually updated). + with self._timers[SYNCH_WORKER_WEIGHTS_TIMER]: + pids = list(train_results.keys()) + self._update_workers_old_api_stack( + workers_that_need_updates=workers_that_need_updates, + policy_ids=pids, + ) + + # With a training step done, try to bring any aggregators back to life + # if necessary. + # AggregatorActor are stateless, so we do not need to restore any + # state here. + if self._aggregator_actor_manager: + self._aggregator_actor_manager.probe_unhealthy_actors( + timeout_seconds=self.config.env_runner_health_probe_timeout_s, + mark_healthy=True, + ) + + return train_results + + @OldAPIStack + def _get_samples_from_workers_old_api_stack( + self, + return_object_refs: Optional[bool] = False, + ) -> List[Tuple[int, Union[ObjectRef, SampleBatchType]]]: + """Get samples from rollout workers for training. + + Args: + return_object_refs: If True, return ObjectRefs instead of the samples + directly. This is useful when using aggregator workers so that data + collected on rollout workers is directly de referenced on the aggregator + workers instead of first in the driver and then on the aggregator + workers. + + Returns: + a list of tuples of (worker_index, sample batch or ObjectRef to a sample + batch) + + """ + with self._timers[SAMPLE_TIMER]: + # Sample from healthy remote workers by default. If there is no healthy + # worker (either because they have all died, or because there was none to + # begin) check if the local_worker exists. If the local worker has an + # env_instance (either because there are no remote workers or + # self.config.create_local_env_runner == True), then sample from the + # local worker. Otherwise just return an empty list. + if self.env_runner_group.num_healthy_remote_workers() > 0: + # Perform asynchronous sampling on all (remote) rollout workers. + self.env_runner_group.foreach_env_runner_async( + lambda worker: worker.sample() + ) + sample_batches: List[ + Tuple[int, ObjectRef] + ] = self.env_runner_group.fetch_ready_async_reqs( + timeout_seconds=self.config.timeout_s_sampler_manager, + return_obj_refs=return_object_refs, + ) + elif self.config.num_env_runners == 0 or ( + self.env_runner and self.env_runner.async_env is not None + ): + # Sampling from the local worker + sample_batch = self.env_runner.sample() + if return_object_refs: + sample_batch = ray.put(sample_batch) + sample_batches = [(0, sample_batch)] + else: + # Not much we can do. Return empty list and wait. + sample_batches = [] + + return sample_batches + + @OldAPIStack + def _process_experiences_old_api_stack( + self, + worker_to_sample_batches: List[Tuple[int, SampleBatch]], + ) -> List[SampleBatchType]: + """Process sample batches directly on the driver, for training. + + Args: + worker_to_sample_batches: List of (worker_id, sample_batch) tuples. + + Returns: + Batches that have been processed by the mixin buffer. + + """ + batches = [b for _, b in worker_to_sample_batches] + processed_batches = [] + + for batch in batches: + assert not isinstance( + batch, ObjectRef + ), "`IMPALA._process_experiences_old_api_stack` can not handle ObjectRefs!" + batch = batch.decompress_if_needed() + # Only make a pass through the buffer, if replay proportion is > 0.0 (and + # we actually have one). + if self.local_mixin_buffer: + self.local_mixin_buffer.add(batch) + batch = self.local_mixin_buffer.replay(_ALL_POLICIES) + else: + # TODO(jjyao) somehow deep copy the batch + # fix a memory leak issue. Need to investigate more + # to know why. + batch = batch.copy() + if batch: + processed_batches.append(batch) + + return processed_batches + + @OldAPIStack + def _concatenate_batches_and_pre_queue(self, batches: List[SampleBatch]) -> None: + """Concatenate batches that are being returned from rollout workers + + Args: + batches: List of batches of experiences from EnvRunners. + """ + + def aggregate_into_larger_batch(): + if ( + sum(b.count for b in self._batch_being_built) + >= self.config.total_train_batch_size + ): + batch_to_add = concat_samples(self._batch_being_built) + self.data_to_place_on_learner.append(batch_to_add) + self._batch_being_built = [] + + for batch in batches: + # TODO (sven): Strange bug after a RolloutWorker crash and proper + # restart. The bug is related to (old, non-V2) connectors being used and + # seems to happen inside the AgentCollector's `add_action_reward_next_obs` + # method, at the end of which the number of vf_preds (and all other + # extra action outs) in the batch is one smaller than the number of obs/ + # actions/rewards, which then leads to a malformed train batch. + # IMPALA/APPO crash inside the loss function (during v-trace operations) + # b/c of the resulting shape mismatch. The following if-block prevents + # this from happening and it can be removed once we are on the new API + # stack for good (and use the new connectors and also no longer + # AgentCollectors, RolloutWorkers, Policies, TrajectoryView API, etc..): + if ( + self.config.batch_mode == "truncate_episodes" + and self.config.restart_failed_env_runners + ): + if any( + SampleBatch.VF_PREDS in pb + and ( + pb[SampleBatch.VF_PREDS].shape[0] + != pb[SampleBatch.REWARDS].shape[0] + ) + for pb in batch.policy_batches.values() + ): + continue + + self._batch_being_built.append(batch) + aggregate_into_larger_batch() + + @OldAPIStack + def _place_processed_samples_on_learner_thread_queue(self) -> None: + """Place processed samples on the learner queue for training.""" + for i, batch in enumerate(self.data_to_place_on_learner): + try: + self._learner_thread.inqueue.put( + batch, + # Setting block = True for the very last item in our list prevents + # the learner thread, this main thread, and the GPU loader threads + # from thrashing when there are more samples than the learner can + # reasonably process. + # see https://github.com/ray-project/ray/pull/26581#issuecomment-1187877674 # noqa + block=i == len(self.data_to_place_on_learner) - 1, + ) + self._counters["num_samples_added_to_queue"] += ( + batch.agent_steps() + if self.config.count_steps_by == "agent_steps" + else batch.count + ) + except queue.Full: + self._counters["num_times_learner_queue_full"] += 1 + + self.data_to_place_on_learner.clear() + + @OldAPIStack + def _process_trained_results(self) -> ResultDict: + """Process training results that are outputed by the learner thread. + + Returns: + Aggregated results from the learner thread after an update is completed. + + """ + # Get learner outputs/stats from output queue. + num_env_steps_trained = 0 + num_agent_steps_trained = 0 + learner_infos = [] + # Loop through output queue and update our counts. + for _ in range(self._learner_thread.outqueue.qsize()): + ( + env_steps, + agent_steps, + learner_results, + ) = self._learner_thread.outqueue.get(timeout=0.001) + num_env_steps_trained += env_steps + num_agent_steps_trained += agent_steps + if learner_results: + learner_infos.append(learner_results) + # Nothing new happened since last time, use the same learner stats. + if not learner_infos: + final_learner_info = copy.deepcopy(self._learner_thread.learner_info) + # Accumulate learner stats using the `LearnerInfoBuilder` utility. + else: + builder = LearnerInfoBuilder() + for info in learner_infos: + builder.add_learn_on_batch_results_multi_agent(info) + final_learner_info = builder.finalize() + + # Update the steps trained counters. + self._counters[NUM_ENV_STEPS_TRAINED] += num_env_steps_trained + self._counters[NUM_AGENT_STEPS_TRAINED] += num_agent_steps_trained + + return final_learner_info + + @OldAPIStack + def _update_workers_old_api_stack( + self, + workers_that_need_updates: Set[int], + policy_ids: Optional[List[PolicyID]] = None, + ) -> None: + """Updates all RolloutWorkers that require updating. + + Updates only if NUM_TRAINING_STEP_CALLS_SINCE_LAST_SYNCH_WORKER_WEIGHTS has been + reached and the worker has sent samples in this iteration. Also only updates + those policies, whose IDs are given via `policies` (if None, update all + policies). + + Args: + workers_that_need_updates: Set of worker IDs that need to be updated. + policy_ids: Optional list of Policy IDs to update. If None, will update all + policies on the to-be-updated workers. + """ + # Update global vars of the local worker. + if self.config.policy_states_are_swappable: + self.env_runner.lock() + global_vars = { + "timestep": self._counters[NUM_AGENT_STEPS_TRAINED], + "num_grad_updates_per_policy": { + pid: self.env_runner.policy_map[pid].num_grad_updates + for pid in policy_ids or [] + }, + } + self.env_runner.set_global_vars(global_vars, policy_ids=policy_ids) + if self.config.policy_states_are_swappable: + self.env_runner.unlock() + + # Only need to update workers if there are remote workers. + self._counters[NUM_TRAINING_STEP_CALLS_SINCE_LAST_SYNCH_WORKER_WEIGHTS] += 1 + if ( + self.env_runner_group.num_remote_workers() > 0 + and self._counters[NUM_TRAINING_STEP_CALLS_SINCE_LAST_SYNCH_WORKER_WEIGHTS] + >= self.config.broadcast_interval + and workers_that_need_updates + ): + if self.config.policy_states_are_swappable: + self.env_runner.lock() + weights = self.env_runner.get_weights(policy_ids) + if self.config.policy_states_are_swappable: + self.env_runner.unlock() + weights_ref = ray.put(weights) + + self._learner_thread.policy_ids_updated.clear() + self._counters[NUM_TRAINING_STEP_CALLS_SINCE_LAST_SYNCH_WORKER_WEIGHTS] = 0 + self._counters[NUM_SYNCH_WORKER_WEIGHTS] += 1 + self.env_runner_group.foreach_env_runner( + func=lambda w: w.set_weights(ray.get(weights_ref), global_vars), + local_env_runner=False, + remote_worker_ids=list(workers_that_need_updates), + timeout_seconds=0, # Don't wait for the workers to finish. + ) + + @override(Algorithm) + def _compile_iteration_results_old_api_stack(self, *args, **kwargs): + result = super()._compile_iteration_results_old_api_stack(*args, **kwargs) + if not self.config.enable_rl_module_and_learner: + result = self._learner_thread.add_learner_metrics( + result, overwrite_learner_info=False + ) + return result + + +Impala = IMPALA + + +@OldAPIStack +def make_learner_thread(local_worker, config): + if not config["simple_optimizer"]: + logger.info( + "Enabling multi-GPU mode, {} GPUs, {} parallel tower-stacks".format( + config["num_gpus"], config["num_multi_gpu_tower_stacks"] + ) + ) + num_stacks = config["num_multi_gpu_tower_stacks"] + buffer_size = config["minibatch_buffer_size"] + if num_stacks < buffer_size: + logger.warning( + "In multi-GPU mode you should have at least as many " + "multi-GPU tower stacks (to load data into on one device) as " + "you have stack-index slots in the buffer! You have " + f"configured {num_stacks} stacks and a buffer of size " + f"{buffer_size}. Setting " + f"`minibatch_buffer_size={num_stacks}`." + ) + config["minibatch_buffer_size"] = num_stacks + + learner_thread = MultiGPULearnerThread( + local_worker, + num_gpus=config["num_gpus"], + lr=config["lr"], + train_batch_size=config["train_batch_size"], + num_multi_gpu_tower_stacks=config["num_multi_gpu_tower_stacks"], + num_sgd_iter=config["num_epochs"], + learner_queue_size=config["learner_queue_size"], + learner_queue_timeout=config["learner_queue_timeout"], + num_data_load_threads=config["num_gpu_loader_threads"], + ) + else: + learner_thread = LearnerThread( + local_worker, + minibatch_buffer_size=config["minibatch_buffer_size"], + num_sgd_iter=config["num_epochs"], + learner_queue_size=config["learner_queue_size"], + learner_queue_timeout=config["learner_queue_timeout"], + ) + return learner_thread diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/impala_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/impala_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..95ef5a9476235a9c460d49447b7c333b2949f79b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/impala_learner.py @@ -0,0 +1,382 @@ +from collections import deque +import queue +import threading +import time +from typing import Any, Dict, Union + +import ray +from ray.rllib.algorithms.appo.utils import CircularBuffer +from ray.rllib.algorithms.impala.impala import LEARNER_RESULTS_CURR_ENTROPY_COEFF_KEY +from ray.rllib.core import COMPONENT_RL_MODULE +from ray.rllib.core.learner.learner import Learner +from ray.rllib.core.learner.training_data import TrainingData +from ray.rllib.core.rl_module.apis import ValueFunctionAPI +from ray.rllib.utils.annotations import ( + override, + OverrideToImplementCustomLogic_CallToSuperRecommended, +) +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.lambda_defaultdict import LambdaDefaultDict +from ray.rllib.utils.metrics import ( + ALL_MODULES, + NUM_ENV_STEPS_SAMPLED_LIFETIME, +) +from ray.rllib.utils.metrics.metrics_logger import MetricsLogger +from ray.rllib.utils.schedules.scheduler import Scheduler +from ray.rllib.utils.typing import ModuleID, ResultDict + +torch, _ = try_import_torch() + +GPU_LOADER_QUEUE_WAIT_TIMER = "gpu_loader_queue_wait_timer" +GPU_LOADER_LOAD_TO_GPU_TIMER = "gpu_loader_load_to_gpu_timer" +LEARNER_THREAD_IN_QUEUE_WAIT_TIMER = "learner_thread_in_queue_wait_timer" +LEARNER_THREAD_ENV_STEPS_DROPPED = "learner_thread_env_steps_dropped" +LEARNER_THREAD_UPDATE_TIMER = "learner_thread_update_timer" +RAY_GET_EPISODES_TIMER = "ray_get_episodes_timer" + +QUEUE_SIZE_GPU_LOADER_QUEUE = "queue_size_gpu_loader_queue" +QUEUE_SIZE_LEARNER_THREAD_QUEUE = "queue_size_learner_thread_queue" +QUEUE_SIZE_RESULTS_QUEUE = "queue_size_results_queue" + +_CURRENT_GLOBAL_TIMESTEPS = None + + +class IMPALALearner(Learner): + @override(Learner) + def build(self) -> None: + super().build() + + # TODO (sven): We replace the dummy RLock here for APPO/IMPALA, b/c these algos + # require this for thread safety reasons. + # An RLock breaks our current OfflineData and OfflinePreLearner logic, in which + # the Learner (which contains a MetricsLogger) is serialized and deserialized. + # We will have to fix this offline RL logic first, then can remove this hack + # here and return to always using the RLock. + self.metrics._threading_lock = threading.RLock() + self._num_updates = 0 + self._num_updates_lock = threading.Lock() + + # Dict mapping module IDs to the respective entropy Scheduler instance. + self.entropy_coeff_schedulers_per_module: Dict[ + ModuleID, Scheduler + ] = LambdaDefaultDict( + lambda module_id: Scheduler( + fixed_value_or_schedule=( + self.config.get_config_for_module(module_id).entropy_coeff + ), + framework=self.framework, + device=self._device, + ) + ) + + # Create and start the GPU-loader thread. It picks up train-ready batches from + # the "GPU-loader queue" and loads them to the GPU, then places the GPU batches + # on the "update queue" for the actual RLModule forward pass and loss + # computations. + self._gpu_loader_in_queue = queue.Queue() + + # Default is to have a learner thread. + if not hasattr(self, "_learner_thread_in_queue"): + self._learner_thread_in_queue = deque(maxlen=self.config.learner_queue_size) + + # TODO (sven): Figure out a way to use a results queue instaad of the "reduce + # metrics each 20 updates" logic right now. + # # Results queue for reduced Learner metrics. + # # self._learner_thread_out_queue = deque(maxlen=1) + + # Create and start the GPU loader thread(s). + if self.config.num_gpus_per_learner > 0: + self._gpu_loader_threads = [ + _GPULoaderThread( + in_queue=self._gpu_loader_in_queue, + out_queue=self._learner_thread_in_queue, + device=self._device, + metrics_logger=self.metrics, + ) + for _ in range(self.config.num_gpu_loader_threads) + ] + for t in self._gpu_loader_threads: + t.start() + + # Create and start the Learner thread. + self._learner_thread = _LearnerThread( + update_method=Learner.update, + in_queue=self._learner_thread_in_queue, + # TODO (sven): Figure out a way to use a results queue instaad of the "reduce + # metrics each 20 updates" logic right now. + # out_queue=self._learner_thread_out_queue, + learner=self, + ) + self._learner_thread.start() + + @override(Learner) + def update( + self, + training_data: TrainingData, + *, + timesteps: Dict[str, Any], + return_state: bool = False, + **kwargs, + ) -> ResultDict: + """ + + Args: + batch: + timesteps: + return_state: Whether to include one of the Learner worker's state from + after the update step in the returned results dict (under the + `_rl_module_state_after_update` key). Note that after an update, all + Learner workers' states should be identical, so we use the first + Learner's state here. Useful for avoiding an extra `get_weights()` call, + e.g. for synchronizing EnvRunner weights. + **kwargs: + + Returns: + + """ + global _CURRENT_GLOBAL_TIMESTEPS + _CURRENT_GLOBAL_TIMESTEPS = timesteps or {} + + # Get the train batch from the object store. + training_data.solve_refs() + + batch = self._make_batch_if_necessary(training_data=training_data) + assert batch is not None + + if self.config.num_gpus_per_learner > 0: + self._gpu_loader_in_queue.put(batch) + self.metrics.log_value( + (ALL_MODULES, QUEUE_SIZE_GPU_LOADER_QUEUE), + self._gpu_loader_in_queue.qsize(), + ) + else: + if isinstance(self._learner_thread_in_queue, CircularBuffer): + ts_dropped = self._learner_thread_in_queue.add(batch) + self.metrics.log_value( + (ALL_MODULES, LEARNER_THREAD_ENV_STEPS_DROPPED), + ts_dropped, + reduce="sum", + ) + else: + # Enqueue to Learner thread's in-queue. + _LearnerThread.enqueue( + self._learner_thread_in_queue, batch, self.metrics + ) + + # TODO (sven): Find a better way to limit the number of (mostly) unnecessary + # metrics reduces. + with self._num_updates_lock: + count = self._num_updates + result = {} + if count >= 20: + with self._num_updates_lock: + self._num_updates = 0 + result = self.metrics.reduce() + + if return_state: + learner_state = self.get_state( + # Only return the state of those RLModules that are trainable. + components=[ + COMPONENT_RL_MODULE + "/" + mid + for mid in self.module.keys() + if self.should_module_be_updated(mid) + ], + inference_only=True, + ) + learner_state[COMPONENT_RL_MODULE] = ray.put( + learner_state[COMPONENT_RL_MODULE] + ) + result["_rl_module_state_after_update"] = learner_state + + return result + + # TODO (sven): Figure out a way to use a results queue instaad of the "reduce + # metrics each 20 updates" logic right now. + # try: + # result = self._learner_thread_out_queue.popleft() + # except IndexError: + # result = {} + + # if return_state: + # learner_state = self.get_state( + # # Only return the state of those RLModules that are trainable. + # components=[ + # COMPONENT_RL_MODULE + "/" + mid + # for mid in self.module.keys() + # if self.should_module_be_updated(mid) + # ], + # inference_only=True, + # ) + # learner_state[COMPONENT_RL_MODULE] = ray.put( + # learner_state[COMPONENT_RL_MODULE] + # ) + # result["_rl_module_state_after_update"] = learner_state + + # return result + + @OverrideToImplementCustomLogic_CallToSuperRecommended + def before_gradient_based_update(self, *, timesteps: Dict[str, Any]) -> None: + super().before_gradient_based_update(timesteps=timesteps) + + for module_id in self.module.keys(): + # Update entropy coefficient via our Scheduler. + new_entropy_coeff = self.entropy_coeff_schedulers_per_module[ + module_id + ].update(timestep=timesteps.get(NUM_ENV_STEPS_SAMPLED_LIFETIME, 0)) + self.metrics.log_value( + (module_id, LEARNER_RESULTS_CURR_ENTROPY_COEFF_KEY), + new_entropy_coeff, + window=1, + ) + + @override(Learner) + def remove_module(self, module_id: str): + super().remove_module(module_id) + self.entropy_coeff_schedulers_per_module.pop(module_id) + + @classmethod + @override(Learner) + def rl_module_required_apis(cls) -> list[type]: + # In order for a PPOLearner to update an RLModule, it must implement the + # following APIs: + return [ValueFunctionAPI] + + +ImpalaLearner = IMPALALearner + + +class _GPULoaderThread(threading.Thread): + def __init__( + self, + *, + in_queue: queue.Queue, + out_queue: deque, + device: torch.device, + metrics_logger: MetricsLogger, + ): + super().__init__(name="_GPULoaderThread") + self.daemon = True + + self._in_queue = in_queue + self._out_queue = out_queue + self._ts_dropped = 0 + self._device = device + self.metrics = metrics_logger + + def run(self) -> None: + while True: + self._step() + + def _step(self) -> None: + # Get a new batch from the data (inqueue). + with self.metrics.log_time((ALL_MODULES, GPU_LOADER_QUEUE_WAIT_TIMER)): + ma_batch_on_cpu = self._in_queue.get() + + # Load the batch onto the GPU device. + with self.metrics.log_time((ALL_MODULES, GPU_LOADER_LOAD_TO_GPU_TIMER)): + ma_batch_on_gpu = ma_batch_on_cpu.to_device(self._device, pin_memory=False) + + if isinstance(self._out_queue, CircularBuffer): + ts_dropped = self._out_queue.add(ma_batch_on_gpu) + self.metrics.log_value( + (ALL_MODULES, LEARNER_THREAD_ENV_STEPS_DROPPED), + ts_dropped, + reduce="sum", + ) + else: + # Enqueue to Learner thread's in-queue. + _LearnerThread.enqueue(self._out_queue, ma_batch_on_gpu, self.metrics) + + +class _LearnerThread(threading.Thread): + def __init__( + self, + *, + update_method, + in_queue: Union[deque, CircularBuffer], + # TODO (sven): Figure out a way to use a results queue instaad of the "reduce + # metrics each 20 updates" logic right now. + # out_queue: deque, + learner, + ): + super().__init__(name="_LearnerThread") + self.daemon = True + self.learner = learner + self.stopped = False + + self._update_method = update_method + self._in_queue: Union[deque, CircularBuffer] = in_queue + # TODO (sven): Figure out a way to use a results queue instaad of the "reduce + # metrics each 20 updates" logic right now. + # self._out_queue: deque = out_queue + + def run(self) -> None: + while not self.stopped: + self.step() + + def step(self): + global _CURRENT_GLOBAL_TIMESTEPS + + # Get a new batch from the GPU-data (deque.pop -> newest item first). + with self.learner.metrics.log_time( + (ALL_MODULES, LEARNER_THREAD_IN_QUEUE_WAIT_TIMER) + ): + # Get a new batch from the GPU-data (learner queue OR circular buffer). + if isinstance(self._in_queue, CircularBuffer): + ma_batch_on_gpu = self._in_queue.sample() + else: + # Queue is empty: Sleep a tiny bit to avoid CPU-thrashing. + while not self._in_queue: + time.sleep(0.0001) + # Consume from the left (oldest batches first). + # If we consumed from the right, we would run into the danger of + # learning from newer batches (left side) most times, BUT sometimes + # grabbing older batches (right area of deque). + ma_batch_on_gpu = self._in_queue.popleft() + + # Add this check here in case thread has been stopped while we were waiting for + # a batch from the queue/buffer. + if self.stopped: + return + + # Call the update method on the batch. + with self.learner.metrics.log_time((ALL_MODULES, LEARNER_THREAD_UPDATE_TIMER)): + # TODO (sven): For multi-agent AND SGD iter > 1, we need to make sure + # this thread has the information about the min minibatches necessary + # (due to different agents taking different steps in the env, e.g. + # MA-CartPole). + self._update_method( + self=self.learner, + training_data=TrainingData(batch=ma_batch_on_gpu), + timesteps=_CURRENT_GLOBAL_TIMESTEPS, + _no_metrics_reduce=True, + ) + # TODO (sven): Figure out a way to use a results queue instaad of the "reduce + # metrics each 20 updates" logic right now. + # self._out_queue.append(results) + with self.learner._num_updates_lock: + self.learner._num_updates += 1 + + @staticmethod + def enqueue(learner_queue: deque, batch, metrics): + # Right-append to learner queue (a deque). If full, drops the leftmost + # (oldest) item in the deque. + # Note that we consume from the left (oldest first), which is why the queue size + # should probably always be small'ish (<< 10), otherwise we run into the danger + # of training with very old samples. + # If we consumed from the right, we would run into the danger of learning + # from newer batches (left side) most times, BUT sometimes grabbing a + # really old batches (right area of deque). + if len(learner_queue) == learner_queue.maxlen: + metrics.log_value( + (ALL_MODULES, LEARNER_THREAD_ENV_STEPS_DROPPED), + learner_queue.popleft().env_steps(), + reduce="sum", + ) + learner_queue.append(batch) + + # Log current queue size. + metrics.log_value( + (ALL_MODULES, QUEUE_SIZE_LEARNER_THREAD_QUEUE), + len(learner_queue), + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/impala_tf_policy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/impala_tf_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..a1f74f48f8ced1d00d9657c6e60736b1dadd8d58 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/impala_tf_policy.py @@ -0,0 +1,444 @@ +"""Adapted from A3CTFPolicy to add V-trace. + +Keep in sync with changes to A3CTFPolicy and VtraceSurrogatePolicy.""" + +import numpy as np +import logging +import gymnasium as gym +from typing import Dict, List, Optional, Type, Union + +from ray.rllib.algorithms.impala import vtrace_tf as vtrace +from ray.rllib.evaluation.postprocessing import compute_bootstrap_value +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.tf.tf_action_dist import Categorical, TFActionDistribution +from ray.rllib.policy.dynamic_tf_policy_v2 import DynamicTFPolicyV2 +from ray.rllib.policy.eager_tf_policy_v2 import EagerTFPolicyV2 +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy.tf_mixins import LearningRateSchedule, EntropyCoeffSchedule +from ray.rllib.utils import force_list +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.tf_utils import explained_variance +from ray.rllib.policy.tf_mixins import GradStatsMixin, ValueNetworkMixin +from ray.rllib.utils.typing import ( + LocalOptimizer, + ModelGradients, + TensorType, + TFPolicyV2Type, +) + +tf1, tf, tfv = try_import_tf() + +logger = logging.getLogger(__name__) + + +class VTraceLoss: + def __init__( + self, + actions, + actions_logp, + actions_entropy, + dones, + behaviour_action_logp, + behaviour_logits, + target_logits, + discount, + rewards, + values, + bootstrap_value, + dist_class, + model, + valid_mask, + config, + vf_loss_coeff=0.5, + entropy_coeff=0.01, + clip_rho_threshold=1.0, + clip_pg_rho_threshold=1.0, + ): + """Policy gradient loss with vtrace importance weighting. + + VTraceLoss takes tensors of shape [T, B, ...], where `B` is the + batch_size. The reason we need to know `B` is for V-trace to properly + handle episode cut boundaries. + + Args: + actions: An int|float32 tensor of shape [T, B, ACTION_SPACE]. + actions_logp: A float32 tensor of shape [T, B]. + actions_entropy: A float32 tensor of shape [T, B]. + dones: A bool tensor of shape [T, B]. + behaviour_action_logp: Tensor of shape [T, B]. + behaviour_logits: A list with length of ACTION_SPACE of float32 + tensors of shapes + [T, B, ACTION_SPACE[0]], + ..., + [T, B, ACTION_SPACE[-1]] + target_logits: A list with length of ACTION_SPACE of float32 + tensors of shapes + [T, B, ACTION_SPACE[0]], + ..., + [T, B, ACTION_SPACE[-1]] + discount: A float32 scalar. + rewards: A float32 tensor of shape [T, B]. + values: A float32 tensor of shape [T, B]. + bootstrap_value: A float32 tensor of shape [B]. + dist_class: action distribution class for logits. + valid_mask: A bool tensor of valid RNN input elements (#2992). + config: Algorithm config dict. + """ + + # Compute vtrace on the CPU for better performance. + with tf.device("/cpu:0"): + self.vtrace_returns = vtrace.multi_from_logits( + behaviour_action_log_probs=behaviour_action_logp, + behaviour_policy_logits=behaviour_logits, + target_policy_logits=target_logits, + actions=tf.unstack(actions, axis=2), + discounts=tf.cast(~tf.cast(dones, tf.bool), tf.float32) * discount, + rewards=rewards, + values=values, + bootstrap_value=bootstrap_value, + dist_class=dist_class, + model=model, + clip_rho_threshold=tf.cast(clip_rho_threshold, tf.float32), + clip_pg_rho_threshold=tf.cast(clip_pg_rho_threshold, tf.float32), + ) + self.value_targets = self.vtrace_returns.vs + + # The policy gradients loss. + masked_pi_loss = tf.boolean_mask( + actions_logp * self.vtrace_returns.pg_advantages, valid_mask + ) + self.pi_loss = -tf.reduce_sum(masked_pi_loss) + self.mean_pi_loss = -tf.reduce_mean(masked_pi_loss) + + # The baseline loss. + delta = tf.boolean_mask(values - self.vtrace_returns.vs, valid_mask) + delta_squarred = tf.math.square(delta) + self.vf_loss = 0.5 * tf.reduce_sum(delta_squarred) + self.mean_vf_loss = 0.5 * tf.reduce_mean(delta_squarred) + + # The entropy loss. + masked_entropy = tf.boolean_mask(actions_entropy, valid_mask) + self.entropy = tf.reduce_sum(masked_entropy) + self.mean_entropy = tf.reduce_mean(masked_entropy) + + # The summed weighted loss. + self.total_loss = self.pi_loss - self.entropy * entropy_coeff + + # Optional vf loss (or in a separate term due to separate + # optimizers/networks). + self.loss_wo_vf = self.total_loss + if not config["_separate_vf_optimizer"]: + self.total_loss += self.vf_loss * vf_loss_coeff + + +def _make_time_major(policy, seq_lens, tensor): + """Swaps batch and trajectory axis. + + Args: + policy: Policy reference + seq_lens: Sequence lengths if recurrent or None + tensor: A tensor or list of tensors to reshape. + trajectory item. + + Returns: + res: A tensor with swapped axes or a list of tensors with + swapped axes. + """ + if isinstance(tensor, list): + return [_make_time_major(policy, seq_lens, t) for t in tensor] + + if policy.is_recurrent(): + B = tf.shape(seq_lens)[0] + T = tf.shape(tensor)[0] // B + else: + # Important: chop the tensor into batches at known episode cut + # boundaries. + # TODO: (sven) this is kind of a hack and won't work for + # batch_mode=complete_episodes. + T = policy.config["rollout_fragment_length"] + B = tf.shape(tensor)[0] // T + rs = tf.reshape(tensor, tf.concat([[B, T], tf.shape(tensor)[1:]], axis=0)) + + # swap B and T axes + res = tf.transpose(rs, [1, 0] + list(range(2, 1 + int(tf.shape(tensor).shape[0])))) + + return res + + +class VTraceClipGradients: + """VTrace version of gradient computation logic.""" + + def __init__(self): + """No special initialization required.""" + pass + + def compute_gradients_fn( + self, optimizer: LocalOptimizer, loss: TensorType + ) -> ModelGradients: + # Supporting more than one loss/optimizer. + trainable_variables = self.model.trainable_variables() + if self.config["_tf_policy_handles_more_than_one_loss"]: + optimizers = force_list(optimizer) + losses = force_list(loss) + assert len(optimizers) == len(losses) + clipped_grads_and_vars = [] + for optim, loss_ in zip(optimizers, losses): + grads_and_vars = optim.compute_gradients(loss_, trainable_variables) + clipped_g_and_v = [] + for g, v in grads_and_vars: + if g is not None: + clipped_g, _ = tf.clip_by_global_norm( + [g], self.config["grad_clip"] + ) + clipped_g_and_v.append((clipped_g[0], v)) + clipped_grads_and_vars.append(clipped_g_and_v) + + self.grads = [g for g_and_v in clipped_grads_and_vars for (g, v) in g_and_v] + # Only one optimizer and and loss term. + else: + grads_and_vars = optimizer.compute_gradients( + loss, self.model.trainable_variables() + ) + grads = [g for (g, v) in grads_and_vars] + self.grads, _ = tf.clip_by_global_norm(grads, self.config["grad_clip"]) + clipped_grads_and_vars = list(zip(self.grads, trainable_variables)) + + return clipped_grads_and_vars + + +class VTraceOptimizer: + """Optimizer function for VTrace policies.""" + + def __init__(self): + pass + + # TODO: maybe standardize this function, so the choice of optimizers are more + # predictable for common algorithms. + def optimizer( + self, + ) -> Union["tf.keras.optimizers.Optimizer", List["tf.keras.optimizers.Optimizer"]]: + config = self.config + if config["opt_type"] == "adam": + if config["framework"] == "tf2": + optim = tf.keras.optimizers.Adam(self.cur_lr) + if config["_separate_vf_optimizer"]: + return optim, tf.keras.optimizers.Adam(config["_lr_vf"]) + else: + optim = tf1.train.AdamOptimizer(self.cur_lr) + if config["_separate_vf_optimizer"]: + return optim, tf1.train.AdamOptimizer(config["_lr_vf"]) + else: + if config["_separate_vf_optimizer"]: + raise ValueError( + "RMSProp optimizer not supported for separate" + "vf- and policy losses yet! Set `opt_type=adam`" + ) + + if tfv == 2: + optim = tf.keras.optimizers.RMSprop( + self.cur_lr, config["decay"], config["momentum"], config["epsilon"] + ) + else: + optim = tf1.train.RMSPropOptimizer( + self.cur_lr, config["decay"], config["momentum"], config["epsilon"] + ) + + return optim + + +# We need this builder function because we want to share the same +# custom logics between TF1 dynamic and TF2 eager policies. +def get_impala_tf_policy(name: str, base: TFPolicyV2Type) -> TFPolicyV2Type: + """Construct an ImpalaTFPolicy inheriting either dynamic or eager base policies. + + Args: + base: Base class for this policy. DynamicTFPolicyV2 or EagerTFPolicyV2. + + Returns: + A TF Policy to be used with Impala. + """ + + # VTrace mixins are placed in front of more general mixins to make sure + # their functions like optimizer() overrides all the other implementations + # (e.g., LearningRateSchedule.optimizer()) + class ImpalaTFPolicy( + VTraceClipGradients, + VTraceOptimizer, + LearningRateSchedule, + EntropyCoeffSchedule, + GradStatsMixin, + ValueNetworkMixin, + base, + ): + def __init__( + self, + observation_space, + action_space, + config, + existing_model=None, + existing_inputs=None, + ): + # First thing first, enable eager execution if necessary. + base.enable_eager_execution_if_necessary() + + # Initialize base class. + base.__init__( + self, + observation_space, + action_space, + config, + existing_inputs=existing_inputs, + existing_model=existing_model, + ) + ValueNetworkMixin.__init__(self, config) + + # If Learner API is used, we don't need any loss-specific mixins. + # However, we also would like to avoid creating special Policy-subclasses + # for this as the entire Policy concept will soon not be used anymore with + # the new Learner- and RLModule APIs. + GradStatsMixin.__init__(self) + VTraceClipGradients.__init__(self) + VTraceOptimizer.__init__(self) + LearningRateSchedule.__init__(self, config["lr"], config["lr_schedule"]) + EntropyCoeffSchedule.__init__( + self, config["entropy_coeff"], config["entropy_coeff_schedule"] + ) + + # Note: this is a bit ugly, but loss and optimizer initialization must + # happen after all the MixIns are initialized. + self.maybe_initialize_optimizer_and_loss() + + @override(base) + def loss( + self, + model: Union[ModelV2, "tf.keras.Model"], + dist_class: Type[TFActionDistribution], + train_batch: SampleBatch, + ) -> Union[TensorType, List[TensorType]]: + model_out, _ = model(train_batch) + action_dist = dist_class(model_out, model) + + if isinstance(self.action_space, gym.spaces.Discrete): + is_multidiscrete = False + output_hidden_shape = [self.action_space.n] + elif isinstance(self.action_space, gym.spaces.MultiDiscrete): + is_multidiscrete = True + output_hidden_shape = self.action_space.nvec.astype(np.int32) + else: + is_multidiscrete = False + output_hidden_shape = 1 + + def make_time_major(*args, **kw): + return _make_time_major( + self, train_batch.get(SampleBatch.SEQ_LENS), *args, **kw + ) + + actions = train_batch[SampleBatch.ACTIONS] + dones = train_batch[SampleBatch.TERMINATEDS] + rewards = train_batch[SampleBatch.REWARDS] + behaviour_action_logp = train_batch[SampleBatch.ACTION_LOGP] + behaviour_logits = train_batch[SampleBatch.ACTION_DIST_INPUTS] + unpacked_behaviour_logits = tf.split( + behaviour_logits, output_hidden_shape, axis=1 + ) + unpacked_outputs = tf.split(model_out, output_hidden_shape, axis=1) + values = model.value_function() + values_time_major = make_time_major(values) + bootstrap_values_time_major = make_time_major( + train_batch[SampleBatch.VALUES_BOOTSTRAPPED] + ) + bootstrap_value = bootstrap_values_time_major[-1] + + if self.is_recurrent(): + max_seq_len = tf.reduce_max(train_batch[SampleBatch.SEQ_LENS]) + mask = tf.sequence_mask(train_batch[SampleBatch.SEQ_LENS], max_seq_len) + mask = tf.reshape(mask, [-1]) + else: + mask = tf.ones_like(rewards) + + # Prepare actions for loss + loss_actions = ( + actions if is_multidiscrete else tf.expand_dims(actions, axis=1) + ) + + # Inputs are reshaped from [B * T] => [(T|T-1), B] for V-trace calc. + self.vtrace_loss = VTraceLoss( + actions=make_time_major(loss_actions), + actions_logp=make_time_major(action_dist.logp(actions)), + actions_entropy=make_time_major(action_dist.multi_entropy()), + dones=make_time_major(dones), + behaviour_action_logp=make_time_major(behaviour_action_logp), + behaviour_logits=make_time_major(unpacked_behaviour_logits), + target_logits=make_time_major(unpacked_outputs), + discount=self.config["gamma"], + rewards=make_time_major(rewards), + values=values_time_major, + bootstrap_value=bootstrap_value, + dist_class=Categorical if is_multidiscrete else dist_class, + model=model, + valid_mask=make_time_major(mask), + config=self.config, + vf_loss_coeff=self.config["vf_loss_coeff"], + entropy_coeff=self.entropy_coeff, + clip_rho_threshold=self.config["vtrace_clip_rho_threshold"], + clip_pg_rho_threshold=self.config["vtrace_clip_pg_rho_threshold"], + ) + + if self.config.get("_separate_vf_optimizer"): + return self.vtrace_loss.loss_wo_vf, self.vtrace_loss.vf_loss + else: + return self.vtrace_loss.total_loss + + @override(base) + def stats_fn(self, train_batch: SampleBatch) -> Dict[str, TensorType]: + values_batched = _make_time_major( + self, + train_batch.get(SampleBatch.SEQ_LENS), + self.model.value_function(), + ) + + return { + "cur_lr": tf.cast(self.cur_lr, tf.float64), + "policy_loss": self.vtrace_loss.mean_pi_loss, + "entropy": self.vtrace_loss.mean_entropy, + "entropy_coeff": tf.cast(self.entropy_coeff, tf.float64), + "var_gnorm": tf.linalg.global_norm(self.model.trainable_variables()), + "vf_loss": self.vtrace_loss.mean_vf_loss, + "vf_explained_var": explained_variance( + tf.reshape(self.vtrace_loss.value_targets, [-1]), + tf.reshape(values_batched, [-1]), + ), + } + + @override(base) + def postprocess_trajectory( + self, + sample_batch: SampleBatch, + other_agent_batches: Optional[SampleBatch] = None, + episode=None, + ): + # Call super's postprocess_trajectory first. + # sample_batch = super().postprocess_trajectory( + # sample_batch, other_agent_batches, episode + # ) + + if self.config["vtrace"]: + # Add the SampleBatch.VALUES_BOOTSTRAPPED column, which we'll need + # inside the loss for vtrace calculations. + sample_batch = compute_bootstrap_value(sample_batch, self) + + return sample_batch + + @override(base) + def get_batch_divisibility_req(self) -> int: + return self.config["rollout_fragment_length"] + + ImpalaTFPolicy.__name__ = name + ImpalaTFPolicy.__qualname__ = name + + return ImpalaTFPolicy + + +ImpalaTF1Policy = get_impala_tf_policy("ImpalaTF1Policy", DynamicTFPolicyV2) +ImpalaTF2Policy = get_impala_tf_policy("ImpalaTF2Policy", EagerTFPolicyV2) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/impala_torch_policy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/impala_torch_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c174149f7c6042c6bf7b7984cde06359dba718f7 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/impala_torch_policy.py @@ -0,0 +1,424 @@ +import gymnasium as gym +import logging +import numpy as np +from typing import Dict, List, Optional, Type, Union + +import ray +from ray.rllib.evaluation.postprocessing import compute_bootstrap_value +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.action_dist import ActionDistribution +from ray.rllib.models.torch.torch_action_dist import TorchCategorical +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy.torch_mixins import ( + EntropyCoeffSchedule, + LearningRateSchedule, + ValueNetworkMixin, +) +from ray.rllib.policy.torch_policy_v2 import TorchPolicyV2 +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.torch_utils import ( + apply_grad_clipping, + explained_variance, + global_norm, + sequence_mask, +) +from ray.rllib.utils.typing import TensorType + +torch, nn = try_import_torch() + +logger = logging.getLogger(__name__) + + +class VTraceLoss: + def __init__( + self, + actions, + actions_logp, + actions_entropy, + dones, + behaviour_action_logp, + behaviour_logits, + target_logits, + discount, + rewards, + values, + bootstrap_value, + dist_class, + model, + valid_mask, + config, + vf_loss_coeff=0.5, + entropy_coeff=0.01, + clip_rho_threshold=1.0, + clip_pg_rho_threshold=1.0, + ): + """Policy gradient loss with vtrace importance weighting. + + VTraceLoss takes tensors of shape [T, B, ...], where `B` is the + batch_size. The reason we need to know `B` is for V-trace to properly + handle episode cut boundaries. + + Args: + actions: An int|float32 tensor of shape [T, B, ACTION_SPACE]. + actions_logp: A float32 tensor of shape [T, B]. + actions_entropy: A float32 tensor of shape [T, B]. + dones: A bool tensor of shape [T, B]. + behaviour_action_logp: Tensor of shape [T, B]. + behaviour_logits: A list with length of ACTION_SPACE of float32 + tensors of shapes + [T, B, ACTION_SPACE[0]], + ..., + [T, B, ACTION_SPACE[-1]] + target_logits: A list with length of ACTION_SPACE of float32 + tensors of shapes + [T, B, ACTION_SPACE[0]], + ..., + [T, B, ACTION_SPACE[-1]] + discount: A float32 scalar. + rewards: A float32 tensor of shape [T, B]. + values: A float32 tensor of shape [T, B]. + bootstrap_value: A float32 tensor of shape [B]. + dist_class: action distribution class for logits. + valid_mask: A bool tensor of valid RNN input elements (#2992). + config: Algorithm config dict. + """ + import ray.rllib.algorithms.impala.vtrace_torch as vtrace + + if valid_mask is None: + valid_mask = torch.ones_like(actions_logp) + + # Compute vtrace on the CPU for better perf + # (devices handled inside `vtrace.multi_from_logits`). + device = behaviour_action_logp[0].device + self.vtrace_returns = vtrace.multi_from_logits( + behaviour_action_log_probs=behaviour_action_logp, + behaviour_policy_logits=behaviour_logits, + target_policy_logits=target_logits, + actions=torch.unbind(actions, dim=2), + discounts=(1.0 - dones.float()) * discount, + rewards=rewards, + values=values, + bootstrap_value=bootstrap_value, + dist_class=dist_class, + model=model, + clip_rho_threshold=clip_rho_threshold, + clip_pg_rho_threshold=clip_pg_rho_threshold, + ) + # Move v-trace results back to GPU for actual loss computing. + self.value_targets = self.vtrace_returns.vs.to(device) + + # The policy gradients loss. + self.pi_loss = -torch.sum( + actions_logp * self.vtrace_returns.pg_advantages.to(device) * valid_mask + ) + + # The baseline loss. + delta = (values - self.value_targets) * valid_mask + self.vf_loss = 0.5 * torch.sum(torch.pow(delta, 2.0)) + + # The entropy loss. + self.entropy = torch.sum(actions_entropy * valid_mask) + self.mean_entropy = self.entropy / torch.sum(valid_mask) + + # The summed weighted loss. + self.total_loss = self.pi_loss - self.entropy * entropy_coeff + + # Optional vf loss (or in a separate term due to separate + # optimizers/networks). + self.loss_wo_vf = self.total_loss + if not config["_separate_vf_optimizer"]: + self.total_loss += self.vf_loss * vf_loss_coeff + + +def make_time_major(policy, seq_lens, tensor): + """Swaps batch and trajectory axis. + + Args: + policy: Policy reference + seq_lens: Sequence lengths if recurrent or None + tensor: A tensor or list of tensors to reshape. + + Returns: + res: A tensor with swapped axes or a list of tensors with + swapped axes. + """ + if isinstance(tensor, (list, tuple)): + return [make_time_major(policy, seq_lens, t) for t in tensor] + + if policy.is_recurrent(): + B = seq_lens.shape[0] + T = tensor.shape[0] // B + else: + # Important: chop the tensor into batches at known episode cut + # boundaries. + # TODO: (sven) this is kind of a hack and won't work for + # batch_mode=complete_episodes. + T = policy.config["rollout_fragment_length"] + B = tensor.shape[0] // T + rs = torch.reshape(tensor, [B, T] + list(tensor.shape[1:])) + + # Swap B and T axes. + res = torch.transpose(rs, 1, 0) + + return res + + +class VTraceOptimizer: + """Optimizer function for VTrace torch policies.""" + + def __init__(self): + pass + + def optimizer( + self, + ) -> Union[List["torch.optim.Optimizer"], "torch.optim.Optimizer"]: + + if self.config["_separate_vf_optimizer"]: + # Figure out, which parameters of the model belong to the value + # function (and which to the policy net). + dummy_batch = self._lazy_tensor_dict( + self._get_dummy_batch_from_view_requirements() + ) + # Zero out all gradients (set to None) + for param in self.model.parameters(): + param.grad = None + # Perform a dummy forward pass (through the policy net, which should be + # separated from the value function in this particular user setup). + out = self.model(dummy_batch) + # Perform a (dummy) backward pass to be able to see, which params have + # gradients and are therefore used for the policy computations (vs vf + # computations). + torch.sum(out[0]).backward() # [0] -> Model returns out and state-outs. + # Collect policy vs value function params separately. + policy_params = [] + value_params = [] + for param in self.model.parameters(): + if param.grad is None: + value_params.append(param) + else: + policy_params.append(param) + if self.config["opt_type"] == "adam": + return ( + torch.optim.Adam(params=policy_params, lr=self.cur_lr), + torch.optim.Adam(params=value_params, lr=self.cur_lr2), + ) + else: + raise NotImplementedError + + if self.config["opt_type"] == "adam": + return torch.optim.Adam(params=self.model.parameters(), lr=self.cur_lr) + else: + return torch.optim.RMSprop( + params=self.model.parameters(), + lr=self.cur_lr, + weight_decay=self.config["decay"], + momentum=self.config["momentum"], + eps=self.config["epsilon"], + ) + + +# VTrace mixins are placed in front of more general mixins to make sure +# their functions like optimizer() overrides all the other implementations +# (e.g., LearningRateSchedule.optimizer()) +class ImpalaTorchPolicy( + VTraceOptimizer, + LearningRateSchedule, + EntropyCoeffSchedule, + ValueNetworkMixin, + TorchPolicyV2, +): + """PyTorch policy class used with IMPALA.""" + + def __init__(self, observation_space, action_space, config): + config = dict( + ray.rllib.algorithms.impala.impala.IMPALAConfig().to_dict(), **config + ) + config["enable_rl_module_and_learner"] = False + config["enable_env_runner_and_connector_v2"] = False + + # If Learner API is used, we don't need any loss-specific mixins. + # However, we also would like to avoid creating special Policy-subclasses + # for this as the entire Policy concept will soon not be used anymore with + # the new Learner- and RLModule APIs. + VTraceOptimizer.__init__(self) + # Need to initialize learning rate variable before calling + # TorchPolicyV2.__init__. + lr_schedule_additional_args = [] + if config.get("_separate_vf_optimizer"): + lr_schedule_additional_args = ( + [config["_lr_vf"][0][1], config["_lr_vf"]] + if isinstance(config["_lr_vf"], (list, tuple)) + else [config["_lr_vf"], None] + ) + LearningRateSchedule.__init__( + self, config["lr"], config["lr_schedule"], *lr_schedule_additional_args + ) + EntropyCoeffSchedule.__init__( + self, config["entropy_coeff"], config["entropy_coeff_schedule"] + ) + + TorchPolicyV2.__init__( + self, + observation_space, + action_space, + config, + max_seq_len=config["model"]["max_seq_len"], + ) + + ValueNetworkMixin.__init__(self, config) + + self._initialize_loss_from_dummy_batch() + + @override(TorchPolicyV2) + def loss( + self, + model: ModelV2, + dist_class: Type[ActionDistribution], + train_batch: SampleBatch, + ) -> Union[TensorType, List[TensorType]]: + model_out, _ = model(train_batch) + action_dist = dist_class(model_out, model) + + if isinstance(self.action_space, gym.spaces.Discrete): + is_multidiscrete = False + output_hidden_shape = [self.action_space.n] + elif isinstance(self.action_space, gym.spaces.MultiDiscrete): + is_multidiscrete = True + output_hidden_shape = self.action_space.nvec.astype(np.int32) + else: + is_multidiscrete = False + output_hidden_shape = 1 + + def _make_time_major(*args, **kw): + return make_time_major( + self, train_batch.get(SampleBatch.SEQ_LENS), *args, **kw + ) + + actions = train_batch[SampleBatch.ACTIONS] + dones = train_batch[SampleBatch.TERMINATEDS] + rewards = train_batch[SampleBatch.REWARDS] + behaviour_action_logp = train_batch[SampleBatch.ACTION_LOGP] + behaviour_logits = train_batch[SampleBatch.ACTION_DIST_INPUTS] + if isinstance(output_hidden_shape, (list, tuple, np.ndarray)): + unpacked_behaviour_logits = torch.split( + behaviour_logits, list(output_hidden_shape), dim=1 + ) + unpacked_outputs = torch.split(model_out, list(output_hidden_shape), dim=1) + else: + unpacked_behaviour_logits = torch.chunk( + behaviour_logits, output_hidden_shape, dim=1 + ) + unpacked_outputs = torch.chunk(model_out, output_hidden_shape, dim=1) + values = model.value_function() + values_time_major = _make_time_major(values) + bootstrap_values_time_major = _make_time_major( + train_batch[SampleBatch.VALUES_BOOTSTRAPPED] + ) + bootstrap_value = bootstrap_values_time_major[-1] + + if self.is_recurrent(): + max_seq_len = torch.max(train_batch[SampleBatch.SEQ_LENS]) + mask_orig = sequence_mask(train_batch[SampleBatch.SEQ_LENS], max_seq_len) + mask = torch.reshape(mask_orig, [-1]) + else: + mask = torch.ones_like(rewards) + + # Prepare actions for loss. + loss_actions = actions if is_multidiscrete else torch.unsqueeze(actions, dim=1) + + # Inputs are reshaped from [B * T] => [(T|T-1), B] for V-trace calc. + loss = VTraceLoss( + actions=_make_time_major(loss_actions), + actions_logp=_make_time_major(action_dist.logp(actions)), + actions_entropy=_make_time_major(action_dist.entropy()), + dones=_make_time_major(dones), + behaviour_action_logp=_make_time_major(behaviour_action_logp), + behaviour_logits=_make_time_major(unpacked_behaviour_logits), + target_logits=_make_time_major(unpacked_outputs), + discount=self.config["gamma"], + rewards=_make_time_major(rewards), + values=values_time_major, + bootstrap_value=bootstrap_value, + dist_class=TorchCategorical if is_multidiscrete else dist_class, + model=model, + valid_mask=_make_time_major(mask), + config=self.config, + vf_loss_coeff=self.config["vf_loss_coeff"], + entropy_coeff=self.entropy_coeff, + clip_rho_threshold=self.config["vtrace_clip_rho_threshold"], + clip_pg_rho_threshold=self.config["vtrace_clip_pg_rho_threshold"], + ) + + # Store values for stats function in model (tower), such that for + # multi-GPU, we do not override them during the parallel loss phase. + model.tower_stats["pi_loss"] = loss.pi_loss + model.tower_stats["vf_loss"] = loss.vf_loss + model.tower_stats["entropy"] = loss.entropy + model.tower_stats["mean_entropy"] = loss.mean_entropy + model.tower_stats["total_loss"] = loss.total_loss + + values_batched = make_time_major( + self, + train_batch.get(SampleBatch.SEQ_LENS), + values, + ) + model.tower_stats["vf_explained_var"] = explained_variance( + torch.reshape(loss.value_targets, [-1]), torch.reshape(values_batched, [-1]) + ) + + if self.config.get("_separate_vf_optimizer"): + return loss.loss_wo_vf, loss.vf_loss + else: + return loss.total_loss + + @override(TorchPolicyV2) + def stats_fn(self, train_batch: SampleBatch) -> Dict[str, TensorType]: + return convert_to_numpy( + { + "cur_lr": self.cur_lr, + "total_loss": torch.mean( + torch.stack(self.get_tower_stats("total_loss")) + ), + "policy_loss": torch.mean(torch.stack(self.get_tower_stats("pi_loss"))), + "entropy": torch.mean( + torch.stack(self.get_tower_stats("mean_entropy")) + ), + "entropy_coeff": self.entropy_coeff, + "var_gnorm": global_norm(self.model.trainable_variables()), + "vf_loss": torch.mean(torch.stack(self.get_tower_stats("vf_loss"))), + "vf_explained_var": torch.mean( + torch.stack(self.get_tower_stats("vf_explained_var")) + ), + } + ) + + @override(TorchPolicyV2) + def postprocess_trajectory( + self, + sample_batch: SampleBatch, + other_agent_batches: Optional[SampleBatch] = None, + episode=None, + ): + # Call super's postprocess_trajectory first. + # sample_batch = super().postprocess_trajectory( + # sample_batch, other_agent_batches, episode + # ) + + if self.config["vtrace"]: + # Add the SampleBatch.VALUES_BOOTSTRAPPED column, which we'll need + # inside the loss for vtrace calculations. + sample_batch = compute_bootstrap_value(sample_batch, self) + + return sample_batch + + @override(TorchPolicyV2) + def extra_grad_process( + self, optimizer: "torch.optim.Optimizer", loss: TensorType + ) -> Dict[str, TensorType]: + return apply_grad_clipping(self, optimizer, loss) + + @override(TorchPolicyV2) + def get_batch_divisibility_req(self) -> int: + return self.config["rollout_fragment_length"] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/torch/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/torch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/torch/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/torch/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fac11af837e5caa01205f9bc3d1380276802391f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/torch/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/torch/__pycache__/impala_torch_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/torch/__pycache__/impala_torch_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d635fe02452917968f45fd539315d3dc2a2fe75e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/torch/__pycache__/impala_torch_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/torch/__pycache__/vtrace_torch_v2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/torch/__pycache__/vtrace_torch_v2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4557422d059cde82344f338261213d119eb4c93 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/torch/__pycache__/vtrace_torch_v2.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/torch/impala_torch_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/torch/impala_torch_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..256e3b48fb79f217ec66a9a9fdf7ec7a9a0ca6ae --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/torch/impala_torch_learner.py @@ -0,0 +1,164 @@ +from typing import Dict + +from ray.rllib.algorithms.impala.impala import IMPALAConfig +from ray.rllib.algorithms.impala.impala_learner import IMPALALearner +from ray.rllib.algorithms.impala.torch.vtrace_torch_v2 import ( + vtrace_torch, + make_time_major, +) +from ray.rllib.core.columns import Columns +from ray.rllib.core.learner.learner import ENTROPY_KEY +from ray.rllib.core.learner.torch.torch_learner import TorchLearner +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.typing import ModuleID, TensorType + +torch, nn = try_import_torch() + + +class IMPALATorchLearner(IMPALALearner, TorchLearner): + """Implements the IMPALA loss function in torch.""" + + @override(TorchLearner) + def compute_loss_for_module( + self, + *, + module_id: ModuleID, + config: IMPALAConfig, + batch: Dict, + fwd_out: Dict[str, TensorType], + ) -> TensorType: + module = self.module[module_id].unwrapped() + + # TODO (sven): Now that we do the +1ts trick to be less vulnerable about + # bootstrap values at the end of rollouts in the new stack, we might make + # this a more flexible, configurable parameter for users, e.g. + # `v_trace_seq_len` (independent of `rollout_fragment_length`). Separation + # of concerns (sampling vs learning). + rollout_frag_or_episode_len = config.get_rollout_fragment_length() + recurrent_seq_len = batch.get("seq_lens") + + loss_mask = batch[Columns.LOSS_MASK].float() + loss_mask_time_major = make_time_major( + loss_mask, + trajectory_len=rollout_frag_or_episode_len, + recurrent_seq_len=recurrent_seq_len, + ) + size_loss_mask = torch.sum(loss_mask) + + # Behavior actions logp and target actions logp. + behaviour_actions_logp = batch[Columns.ACTION_LOGP] + target_policy_dist = module.get_train_action_dist_cls().from_logits( + fwd_out[Columns.ACTION_DIST_INPUTS] + ) + target_actions_logp = target_policy_dist.logp(batch[Columns.ACTIONS]) + + # Values and bootstrap values. + values = module.compute_values( + batch, embeddings=fwd_out.get(Columns.EMBEDDINGS) + ) + values_time_major = make_time_major( + values, + trajectory_len=rollout_frag_or_episode_len, + recurrent_seq_len=recurrent_seq_len, + ) + assert Columns.VALUES_BOOTSTRAPPED not in batch + # Use as bootstrap values the vf-preds in the next "batch row", except + # for the very last row (which doesn't have a next row), for which the + # bootstrap value does not matter b/c it has a +1ts value at its end + # anyways. So we chose an arbitrary item (for simplicity of not having to + # move new data to the device). + bootstrap_values = torch.cat( + [ + values_time_major[0][1:], # 0th ts values from "next row" + values_time_major[0][0:1], # <- can use any arbitrary value here + ], + dim=0, + ) + + # TODO(Artur): In the old impala code, actions were unsqueezed if they were + # multi_discrete. Find out why and if we need to do the same here. + # actions = actions if is_multidiscrete else torch.unsqueeze(actions, dim=1) + target_actions_logp_time_major = make_time_major( + target_actions_logp, + trajectory_len=rollout_frag_or_episode_len, + recurrent_seq_len=recurrent_seq_len, + ) + behaviour_actions_logp_time_major = make_time_major( + behaviour_actions_logp, + trajectory_len=rollout_frag_or_episode_len, + recurrent_seq_len=recurrent_seq_len, + ) + rewards_time_major = make_time_major( + batch[Columns.REWARDS], + trajectory_len=rollout_frag_or_episode_len, + recurrent_seq_len=recurrent_seq_len, + ) + + # the discount factor that is used should be gamma except for timesteps where + # the episode is terminated. In that case, the discount factor should be 0. + discounts_time_major = ( + 1.0 + - make_time_major( + batch[Columns.TERMINATEDS], + trajectory_len=rollout_frag_or_episode_len, + recurrent_seq_len=recurrent_seq_len, + ).type(dtype=torch.float32) + ) * config.gamma + + # Note that vtrace will compute the main loop on the CPU for better performance. + vtrace_adjusted_target_values, pg_advantages = vtrace_torch( + target_action_log_probs=target_actions_logp_time_major, + behaviour_action_log_probs=behaviour_actions_logp_time_major, + discounts=discounts_time_major, + rewards=rewards_time_major, + values=values_time_major, + bootstrap_values=bootstrap_values, + clip_rho_threshold=config.vtrace_clip_rho_threshold, + clip_pg_rho_threshold=config.vtrace_clip_pg_rho_threshold, + ) + + # The policy gradients loss. + pi_loss = -torch.sum( + target_actions_logp_time_major * pg_advantages * loss_mask_time_major + ) + mean_pi_loss = pi_loss / size_loss_mask + + # The baseline loss. + delta = values_time_major - vtrace_adjusted_target_values + vf_loss = 0.5 * torch.sum(torch.pow(delta, 2.0) * loss_mask_time_major) + mean_vf_loss = vf_loss / size_loss_mask + + # The entropy loss. + entropy_loss = -torch.sum(target_policy_dist.entropy() * loss_mask) + mean_entropy_loss = entropy_loss / size_loss_mask + + # The summed weighted loss. + total_loss = ( + mean_pi_loss + + mean_vf_loss * config.vf_loss_coeff + + ( + mean_entropy_loss + * self.entropy_coeff_schedulers_per_module[ + module_id + ].get_current_value() + ) + ) + + # Log important loss stats. + self.metrics.log_dict( + { + "pi_loss": pi_loss, + "mean_pi_loss": mean_pi_loss, + "vf_loss": vf_loss, + "mean_vf_loss": mean_vf_loss, + ENTROPY_KEY: -mean_entropy_loss, + }, + key=module_id, + window=1, # <- single items (should not be mean/ema-reduced over time). + ) + # Return the total loss. + return total_loss + + +ImpalaTorchLearner = IMPALATorchLearner diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/torch/vtrace_torch_v2.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/torch/vtrace_torch_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..48231be9d7d5b9095c73384c6341d2318d543f98 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/torch/vtrace_torch_v2.py @@ -0,0 +1,168 @@ +from typing import List, Union +from ray.rllib.utils.framework import try_import_torch + +torch, nn = try_import_torch() + + +def make_time_major( + tensor: Union["torch.Tensor", List["torch.Tensor"]], + *, + trajectory_len: int = None, + recurrent_seq_len: int = None, +): + """Swaps batch and trajectory axis. + + Args: + tensor: A tensor or list of tensors to swap the axis of. + NOTE: Each tensor must have the shape [B * T] where B is the batch size and + T is the trajectory length. + trajectory_len: The length of each trajectory being transformed. + If None then `recurrent_seq_len` must be set. + recurrent_seq_len: Sequence lengths if recurrent. + If None then `trajectory_len` must be set. + + Returns: + res: A tensor with swapped axes or a list of tensors with + swapped axes. + """ + if isinstance(tensor, (list, tuple)): + return [ + make_time_major(_tensor, trajectory_len, recurrent_seq_len) + for _tensor in tensor + ] + + assert ( + trajectory_len is not None or recurrent_seq_len is not None + ), "Either trajectory_len or recurrent_seq_len must be set." + + # Figure out the sizes of the final B and T axes. + if recurrent_seq_len is not None: + assert len(tensor.shape) == 2 + # Swap B and T axes. + tensor = torch.transpose(tensor, 1, 0) + return tensor + else: + T = trajectory_len + # Zero-pad, if necessary. + tensor_0 = tensor.shape[0] + B = tensor_0 // T + if B != (tensor_0 / T): + assert len(tensor.shape) == 1 + tensor = torch.cat( + [ + tensor, + torch.zeros( + trajectory_len - tensor_0 % T, + dtype=tensor.dtype, + device=tensor.device, + ), + ] + ) + B += 1 + + # Reshape tensor (break up B axis into 2 axes: B and T). + tensor = torch.reshape(tensor, [B, T] + list(tensor.shape[1:])) + + # Swap B and T axes. + tensor = torch.transpose(tensor, 1, 0) + + return tensor + + +def vtrace_torch( + *, + target_action_log_probs: "torch.Tensor", + behaviour_action_log_probs: "torch.Tensor", + discounts: "torch.Tensor", + rewards: "torch.Tensor", + values: "torch.Tensor", + bootstrap_values: "torch.Tensor", + clip_rho_threshold: Union[float, "torch.Tensor"] = 1.0, + clip_pg_rho_threshold: Union[float, "torch.Tensor"] = 1.0, +): + r"""V-trace for softmax policies implemented with torch. + + Calculates V-trace actor critic targets for softmax polices as described in + "IMPALA: Scalable Distributed Deep-RL with Importance Weighted Actor-Learner + Architectures" by Espeholt, Soyer, Munos et al. (https://arxiv.org/abs/1802.01561) + + The V-trace implementation used here closely resembles the one found in the + scalable-agent repository by Google DeepMind, available at + https://github.com/deepmind/scalable_agent. This version has been optimized to + minimize the number of floating-point operations required per V-Trace + calculation, achieved through the use of dynamic programming techniques. It's + important to note that the mathematical expressions used in this implementation + may appear quite different from those presented in the IMPALA paper. + + The following terminology applies: + - `target policy` refers to the policy we are interested in improving. + - `behaviour policy` refers to the policy that generated the given + rewards and actions. + - `T` refers to the time dimension. This is usually either the length of the + trajectory or the length of the sequence if recurrent. + - `B` refers to the batch size. + + Args: + target_action_log_probs: Action log probs from the target policy. A float32 + tensor of shape [T, B]. + behaviour_action_log_probs: Action log probs from the behaviour policy. A + float32 tensor of shape [T, B]. + discounts: A float32 tensor of shape [T, B] with the discount encountered when + following the behaviour policy. This will be 0 for terminal timesteps + (done=True) and gamma (the discount factor) otherwise. + rewards: A float32 tensor of shape [T, B] with the rewards generated by + following the behaviour policy. + values: A float32 tensor of shape [T, B] with the value function estimates + wrt. the target policy. + bootstrap_values: A float32 of shape [B] with the value function estimate at + time T. + clip_rho_threshold: A scalar float32 tensor with the clipping threshold for + importance weights (rho) when calculating the baseline targets (vs). + rho^bar in the paper. + clip_pg_rho_threshold: A scalar float32 tensor with the clipping threshold + on rho_s in \rho_s \delta log \pi(a|x) (r + \gamma v_{s+1} - V(x_s)). + """ + log_rhos = target_action_log_probs - behaviour_action_log_probs + + rhos = torch.exp(log_rhos) + if clip_rho_threshold is not None: + clipped_rhos = torch.clamp(rhos, max=clip_rho_threshold) + else: + clipped_rhos = rhos + + cs = torch.clamp(rhos, max=1.0) + # Append bootstrapped value to get [v1, ..., v_t+1] + values_t_plus_1 = torch.cat( + [values[1:], torch.unsqueeze(bootstrap_values, 0)], axis=0 + ) + + deltas = clipped_rhos * (rewards + discounts * values_t_plus_1 - values) + + # Note: The original IMPALA code (and paper) suggested to perform the following + # v-trace for-loop on the CPU, due to its sequential nature. However, modern GPUs + # are quite optimized for these shorted for-loops, which is why it should be faster + # nowadays to leave these operations on the GPU to avoid the GPU<>CPU transfer + # penalty. This penalty can actually be quite massive on the LEarner actors, given + # all other code is already well optimized. + vs_minus_v_xs = [torch.zeros_like(bootstrap_values, device=deltas.device)] + for i in reversed(range(len(discounts))): + discount_t, c_t, delta_t = discounts[i], cs[i], deltas[i] + vs_minus_v_xs.append(delta_t + discount_t * c_t * vs_minus_v_xs[-1]) + vs_minus_v_xs = torch.stack(vs_minus_v_xs[1:]) + + # Reverse the results back to original order. + vs_minus_v_xs = torch.flip(vs_minus_v_xs, dims=[0]) + + # Add V(x_s) to get v_s. + vs = torch.add(vs_minus_v_xs, values) + + # Advantage for policy gradient. + vs_t_plus_1 = torch.cat([vs[1:], torch.unsqueeze(bootstrap_values, 0)], axis=0) + if clip_pg_rho_threshold is not None: + clipped_pg_rhos = torch.clamp(rhos, max=clip_pg_rho_threshold) + else: + clipped_pg_rhos = rhos + pg_advantages = clipped_pg_rhos * (rewards + discounts * vs_t_plus_1 - values) + + # Make sure no gradients backpropagated through the returned values. + return torch.detach(vs), torch.detach(pg_advantages) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f65b76a7f53de6fb3f436b8063341c057529f25b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/utils.py @@ -0,0 +1,96 @@ +from collections import defaultdict, deque + +import numpy as np + + +class _SleepTimeController: + def __init__(self): + self.L = 0.0 + self.H = 0.4 + + self._recompute_candidates() + + # Defaultdict mapping. + self.results = defaultdict(lambda: deque(maxlen=3)) + + self.iteration = 0 + + def _recompute_candidates(self): + self.center = (self.L + self.H) / 2 + self.low = (self.L + self.center) / 2 + self.high = (self.H + self.center) / 2 + + # Expand a little if range becomes too narrow to avoid + # overoptimization. + if self.H - self.L < 0.00001: + self.L = max(self.center - 0.1, 0.0) + self.H = min(self.center + 0.1, 1.0) + self._recompute_candidates() + # Reduce results, just in case it has grown too much. + c, l, h = ( + self.results[self.center], + self.results[self.low], + self.results[self.high], + ) + self.results = defaultdict(lambda: deque(maxlen=3)) + self.results[self.center] = c + self.results[self.low] = l + self.results[self.high] = h + + @property + def current(self): + if len(self.results[self.center]) < 3: + return self.center + elif len(self.results[self.low]) < 3: + return self.low + else: + return self.high + + def log_result(self, performance): + self.iteration += 1 + + # Skip first 2 iterations for ignoring warm-up effect. + if self.iteration < 2: + return + + self.results[self.current].append(performance) + + # If all candidates have at least 3 results logged, re-evaluate + # and compute new L and H. + center, low, high = self.center, self.low, self.high + if ( + len(self.results[center]) == 3 + and len(self.results[low]) == 3 + and len(self.results[high]) == 3 + ): + perf_center = np.mean(self.results[center]) + perf_low = np.mean(self.results[low]) + perf_high = np.mean(self.results[high]) + # Case: `center` is best. + if perf_center > perf_low and perf_center > perf_high: + self.L = low + self.H = high + # Erase low/high results: We'll not use these again. + self.results.pop(low, None) + self.results.pop(high, None) + # Case: `low` is best. + elif perf_low > perf_center and perf_low > perf_high: + self.H = center + # Erase center/high results: We'll not use these again. + self.results.pop(center, None) + self.results.pop(high, None) + # Case: `high` is best. + else: + self.L = center + # Erase center/low results: We'll not use these again. + self.results.pop(center, None) + self.results.pop(low, None) + + self._recompute_candidates() + + +if __name__ == "__main__": + controller = _SleepTimeController() + for _ in range(1000): + performance = np.random.random() + controller.log_result(performance) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/vtrace_tf.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/vtrace_tf.py new file mode 100644 index 0000000000000000000000000000000000000000..61c6a7e366d52e20a0d2c225749461c81c51b04d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/vtrace_tf.py @@ -0,0 +1,425 @@ +# Copyright 2018 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Functions to compute V-trace off-policy actor critic targets. + +For details and theory see: + +"IMPALA: Scalable Distributed Deep-RL with +Importance Weighted Actor-Learner Architectures" +by Espeholt, Soyer, Munos et al. + +See https://arxiv.org/abs/1802.01561 for the full paper. + +In addition to the original paper's code, changes have been made +to support MultiDiscrete action spaces. behaviour_policy_logits, +target_policy_logits and actions parameters in the entry point +multi_from_logits method accepts lists of tensors instead of just +tensors. +""" + +import collections + +from ray.rllib.models.tf.tf_action_dist import Categorical +from ray.rllib.utils.framework import try_import_tf + +tf1, tf, tfv = try_import_tf() + +VTraceFromLogitsReturns = collections.namedtuple( + "VTraceFromLogitsReturns", + [ + "vs", + "pg_advantages", + "log_rhos", + "behaviour_action_log_probs", + "target_action_log_probs", + ], +) + +VTraceReturns = collections.namedtuple("VTraceReturns", "vs pg_advantages") + + +def log_probs_from_logits_and_actions( + policy_logits, actions, dist_class=Categorical, model=None +): + return multi_log_probs_from_logits_and_actions( + [policy_logits], [actions], dist_class, model + )[0] + + +def multi_log_probs_from_logits_and_actions(policy_logits, actions, dist_class, model): + """Computes action log-probs from policy logits and actions. + + In the notation used throughout documentation and comments, T refers to the + time dimension ranging from 0 to T-1. B refers to the batch size and + ACTION_SPACE refers to the list of numbers each representing a number of + actions. + + Args: + policy_logits: A list with length of ACTION_SPACE of float32 + tensors of shapes [T, B, ACTION_SPACE[0]], ..., + [T, B, ACTION_SPACE[-1]] with un-normalized log-probabilities + parameterizing a softmax policy. + actions: A list with length of ACTION_SPACE of tensors of shapes + [T, B, ...], ..., [T, B, ...] + with actions. + dist_class: Python class of the action distribution. + + Returns: + A list with length of ACTION_SPACE of float32 tensors of shapes + [T, B], ..., [T, B] corresponding to the sampling log probability + of the chosen action w.r.t. the policy. + """ + log_probs = [] + for i in range(len(policy_logits)): + p_shape = tf.shape(policy_logits[i]) + a_shape = tf.shape(actions[i]) + policy_logits_flat = tf.reshape( + policy_logits[i], tf.concat([[-1], p_shape[2:]], axis=0) + ) + actions_flat = tf.reshape(actions[i], tf.concat([[-1], a_shape[2:]], axis=0)) + log_probs.append( + tf.reshape( + dist_class(policy_logits_flat, model).logp(actions_flat), a_shape[:2] + ) + ) + + return log_probs + + +def from_logits( + behaviour_policy_logits, + target_policy_logits, + actions, + discounts, + rewards, + values, + bootstrap_value, + dist_class=Categorical, + model=None, + clip_rho_threshold=1.0, + clip_pg_rho_threshold=1.0, + name="vtrace_from_logits", +): + """multi_from_logits wrapper used only for tests""" + + res = multi_from_logits( + [behaviour_policy_logits], + [target_policy_logits], + [actions], + discounts, + rewards, + values, + bootstrap_value, + dist_class, + model, + clip_rho_threshold=clip_rho_threshold, + clip_pg_rho_threshold=clip_pg_rho_threshold, + name=name, + ) + + return VTraceFromLogitsReturns( + vs=res.vs, + pg_advantages=res.pg_advantages, + log_rhos=res.log_rhos, + behaviour_action_log_probs=tf.squeeze(res.behaviour_action_log_probs, axis=0), + target_action_log_probs=tf.squeeze(res.target_action_log_probs, axis=0), + ) + + +def multi_from_logits( + behaviour_policy_logits, + target_policy_logits, + actions, + discounts, + rewards, + values, + bootstrap_value, + dist_class, + model, + behaviour_action_log_probs=None, + clip_rho_threshold=1.0, + clip_pg_rho_threshold=1.0, + name="vtrace_from_logits", +): + r"""V-trace for softmax policies. + + Calculates V-trace actor critic targets for softmax polices as described in + + "IMPALA: Scalable Distributed Deep-RL with + Importance Weighted Actor-Learner Architectures" + by Espeholt, Soyer, Munos et al. + + Target policy refers to the policy we are interested in improving and + behaviour policy refers to the policy that generated the given + rewards and actions. + + In the notation used throughout documentation and comments, T refers to the + time dimension ranging from 0 to T-1. B refers to the batch size and + ACTION_SPACE refers to the list of numbers each representing a number of + actions. + + Args: + behaviour_policy_logits: A list with length of ACTION_SPACE of float32 + tensors of shapes + [T, B, ACTION_SPACE[0]], + ..., + [T, B, ACTION_SPACE[-1]] + with un-normalized log-probabilities parameterizing the softmax behaviour + policy. + target_policy_logits: A list with length of ACTION_SPACE of float32 + tensors of shapes + [T, B, ACTION_SPACE[0]], + ..., + [T, B, ACTION_SPACE[-1]] + with un-normalized log-probabilities parameterizing the softmax target + policy. + actions: A list with length of ACTION_SPACE of + tensors of shapes + [T, B, ...], + ..., + [T, B, ...] + with actions sampled from the behaviour policy. + discounts: A float32 tensor of shape [T, B] with the discount encountered + when following the behaviour policy. + rewards: A float32 tensor of shape [T, B] with the rewards generated by + following the behaviour policy. + values: A float32 tensor of shape [T, B] with the value function estimates + wrt. the target policy. + bootstrap_value: A float32 of shape [B] with the value function estimate at + time T. + dist_class: action distribution class for the logits. + model: backing ModelV2 instance + behaviour_action_log_probs: precalculated values of the behaviour actions + clip_rho_threshold: A scalar float32 tensor with the clipping threshold for + importance weights (rho) when calculating the baseline targets (vs). + rho^bar in the paper. + clip_pg_rho_threshold: A scalar float32 tensor with the clipping threshold + on rho_s in \rho_s \delta log \pi(a|x) (r + \gamma v_{s+1} - V(x_s)). + name: The name scope that all V-trace operations will be created in. + + Returns: + A `VTraceFromLogitsReturns` namedtuple with the following fields: + vs: A float32 tensor of shape [T, B]. Can be used as target to train a + baseline (V(x_t) - vs_t)^2. + pg_advantages: A float 32 tensor of shape [T, B]. Can be used as an + estimate of the advantage in the calculation of policy gradients. + log_rhos: A float32 tensor of shape [T, B] containing the log importance + sampling weights (log rhos). + behaviour_action_log_probs: A float32 tensor of shape [T, B] containing + behaviour policy action log probabilities (log \mu(a_t)). + target_action_log_probs: A float32 tensor of shape [T, B] containing + target policy action probabilities (log \pi(a_t)). + """ + + for i in range(len(behaviour_policy_logits)): + behaviour_policy_logits[i] = tf.convert_to_tensor( + behaviour_policy_logits[i], dtype=tf.float32 + ) + target_policy_logits[i] = tf.convert_to_tensor( + target_policy_logits[i], dtype=tf.float32 + ) + + # Make sure tensor ranks are as expected. + # The rest will be checked by from_action_log_probs. + behaviour_policy_logits[i].shape.assert_has_rank(3) + target_policy_logits[i].shape.assert_has_rank(3) + + with tf1.name_scope( + name, + values=[ + behaviour_policy_logits, + target_policy_logits, + actions, + discounts, + rewards, + values, + bootstrap_value, + ], + ): + target_action_log_probs = multi_log_probs_from_logits_and_actions( + target_policy_logits, actions, dist_class, model + ) + + if len(behaviour_policy_logits) > 1 or behaviour_action_log_probs is None: + # can't use precalculated values, recompute them. Note that + # recomputing won't work well for autoregressive action dists + # which may have variables not captured by 'logits' + behaviour_action_log_probs = multi_log_probs_from_logits_and_actions( + behaviour_policy_logits, actions, dist_class, model + ) + + log_rhos = get_log_rhos(target_action_log_probs, behaviour_action_log_probs) + + vtrace_returns = from_importance_weights( + log_rhos=log_rhos, + discounts=discounts, + rewards=rewards, + values=values, + bootstrap_value=bootstrap_value, + clip_rho_threshold=clip_rho_threshold, + clip_pg_rho_threshold=clip_pg_rho_threshold, + ) + + return VTraceFromLogitsReturns( + log_rhos=log_rhos, + behaviour_action_log_probs=behaviour_action_log_probs, + target_action_log_probs=target_action_log_probs, + **vtrace_returns._asdict() + ) + + +def from_importance_weights( + log_rhos, + discounts, + rewards, + values, + bootstrap_value, + clip_rho_threshold=1.0, + clip_pg_rho_threshold=1.0, + name="vtrace_from_importance_weights", +): + r"""V-trace from log importance weights. + + Calculates V-trace actor critic targets as described in + + "IMPALA: Scalable Distributed Deep-RL with + Importance Weighted Actor-Learner Architectures" + by Espeholt, Soyer, Munos et al. + + In the notation used throughout documentation and comments, T refers to the + time dimension ranging from 0 to T-1. B refers to the batch size. This code + also supports the case where all tensors have the same number of additional + dimensions, e.g., `rewards` is [T, B, C], `values` is [T, B, C], + `bootstrap_value` is [B, C]. + + Args: + log_rhos: A float32 tensor of shape [T, B] representing the + log importance sampling weights, i.e. + log(target_policy(a) / behaviour_policy(a)). V-trace performs operations + on rhos in log-space for numerical stability. + discounts: A float32 tensor of shape [T, B] with discounts encountered when + following the behaviour policy. + rewards: A float32 tensor of shape [T, B] containing rewards generated by + following the behaviour policy. + values: A float32 tensor of shape [T, B] with the value function estimates + wrt. the target policy. + bootstrap_value: A float32 of shape [B] with the value function estimate at + time T. + clip_rho_threshold: A scalar float32 tensor with the clipping threshold for + importance weights (rho) when calculating the baseline targets (vs). + rho^bar in the paper. If None, no clipping is applied. + clip_pg_rho_threshold: A scalar float32 tensor with the clipping threshold + on rho_s in \rho_s \delta log \pi(a|x) (r + \gamma v_{s+1} - V(x_s)). If + None, no clipping is applied. + name: The name scope that all V-trace operations will be created in. + + Returns: + A VTraceReturns namedtuple (vs, pg_advantages) where: + vs: A float32 tensor of shape [T, B]. Can be used as target to + train a baseline (V(x_t) - vs_t)^2. + pg_advantages: A float32 tensor of shape [T, B]. Can be used as the + advantage in the calculation of policy gradients. + """ + log_rhos = tf.convert_to_tensor(log_rhos, dtype=tf.float32) + discounts = tf.convert_to_tensor(discounts, dtype=tf.float32) + rewards = tf.convert_to_tensor(rewards, dtype=tf.float32) + values = tf.convert_to_tensor(values, dtype=tf.float32) + bootstrap_value = tf.convert_to_tensor(bootstrap_value, dtype=tf.float32) + if clip_rho_threshold is not None: + clip_rho_threshold = tf.convert_to_tensor(clip_rho_threshold, dtype=tf.float32) + if clip_pg_rho_threshold is not None: + clip_pg_rho_threshold = tf.convert_to_tensor( + clip_pg_rho_threshold, dtype=tf.float32 + ) + + # Make sure tensor ranks are consistent. + rho_rank = log_rhos.shape.ndims # Usually 2. + values.shape.assert_has_rank(rho_rank) + bootstrap_value.shape.assert_has_rank(rho_rank - 1) + discounts.shape.assert_has_rank(rho_rank) + rewards.shape.assert_has_rank(rho_rank) + if clip_rho_threshold is not None: + clip_rho_threshold.shape.assert_has_rank(0) + if clip_pg_rho_threshold is not None: + clip_pg_rho_threshold.shape.assert_has_rank(0) + + with tf1.name_scope( + name, values=[log_rhos, discounts, rewards, values, bootstrap_value] + ): + rhos = tf.math.exp(log_rhos) + if clip_rho_threshold is not None: + clipped_rhos = tf.minimum(clip_rho_threshold, rhos, name="clipped_rhos") + else: + clipped_rhos = rhos + + cs = tf.minimum(1.0, rhos, name="cs") + # Append bootstrapped value to get [v1, ..., v_t+1] + values_t_plus_1 = tf.concat( + [values[1:], tf.expand_dims(bootstrap_value, 0)], axis=0 + ) + deltas = clipped_rhos * (rewards + discounts * values_t_plus_1 - values) + + # All sequences are reversed, computation starts from the back. + sequences = ( + tf.reverse(discounts, axis=[0]), + tf.reverse(cs, axis=[0]), + tf.reverse(deltas, axis=[0]), + ) + + # V-trace vs are calculated through a scan from the back to the + # beginning of the given trajectory. + def scanfunc(acc, sequence_item): + discount_t, c_t, delta_t = sequence_item + return delta_t + discount_t * c_t * acc + + initial_values = tf.zeros_like(bootstrap_value) + vs_minus_v_xs = tf.nest.map_structure( + tf.stop_gradient, + tf.scan( + fn=scanfunc, + elems=sequences, + initializer=initial_values, + parallel_iterations=1, + name="scan", + ), + ) + # Reverse the results back to original order. + vs_minus_v_xs = tf.reverse(vs_minus_v_xs, [0], name="vs_minus_v_xs") + + # Add V(x_s) to get v_s. + vs = tf.add(vs_minus_v_xs, values, name="vs") + + # Advantage for policy gradient. + vs_t_plus_1 = tf.concat([vs[1:], tf.expand_dims(bootstrap_value, 0)], axis=0) + if clip_pg_rho_threshold is not None: + clipped_pg_rhos = tf.minimum( + clip_pg_rho_threshold, rhos, name="clipped_pg_rhos" + ) + else: + clipped_pg_rhos = rhos + pg_advantages = clipped_pg_rhos * (rewards + discounts * vs_t_plus_1 - values) + + # Make sure no gradients backpropagated through the returned values. + return VTraceReturns( + vs=tf.stop_gradient(vs), pg_advantages=tf.stop_gradient(pg_advantages) + ) + + +def get_log_rhos(target_action_log_probs, behaviour_action_log_probs): + """With the selected log_probs for multi-discrete actions of behaviour + and target policies we compute the log_rhos for calculating the vtrace.""" + t = tf.stack(target_action_log_probs) + b = tf.stack(behaviour_action_log_probs) + log_rhos = tf.reduce_sum(t - b, axis=0) + return log_rhos diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/vtrace_torch.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/vtrace_torch.py new file mode 100644 index 0000000000000000000000000000000000000000..b63a5181c7ac81e3ccd10477f7b6728a66cfe72b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/impala/vtrace_torch.py @@ -0,0 +1,359 @@ +# Copyright 2018 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""PyTorch version of the functions to compute V-trace off-policy actor critic +targets. + +For details and theory see: + +"IMPALA: Scalable Distributed Deep-RL with +Importance Weighted Actor-Learner Architectures" +by Espeholt, Soyer, Munos et al. + +See https://arxiv.org/abs/1802.01561 for the full paper. + +In addition to the original paper's code, changes have been made +to support MultiDiscrete action spaces. behaviour_policy_logits, +target_policy_logits and actions parameters in the entry point +multi_from_logits method accepts lists of tensors instead of just +tensors. +""" + +from ray.rllib.algorithms.impala.vtrace_tf import VTraceFromLogitsReturns, VTraceReturns +from ray.rllib.models.torch.torch_action_dist import TorchCategorical +from ray.rllib.utils import force_list +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.torch_utils import convert_to_torch_tensor + +torch, nn = try_import_torch() + + +def log_probs_from_logits_and_actions( + policy_logits, actions, dist_class=TorchCategorical, model=None +): + return multi_log_probs_from_logits_and_actions( + [policy_logits], [actions], dist_class, model + )[0] + + +def multi_log_probs_from_logits_and_actions(policy_logits, actions, dist_class, model): + """Computes action log-probs from policy logits and actions. + + In the notation used throughout documentation and comments, T refers to the + time dimension ranging from 0 to T-1. B refers to the batch size and + ACTION_SPACE refers to the list of numbers each representing a number of + actions. + + Args: + policy_logits: A list with length of ACTION_SPACE of float32 + tensors of shapes [T, B, ACTION_SPACE[0]], ..., + [T, B, ACTION_SPACE[-1]] with un-normalized log-probabilities + parameterizing a softmax policy. + actions: A list with length of ACTION_SPACE of tensors of shapes + [T, B, ...], ..., [T, B, ...] + with actions. + dist_class: Python class of the action distribution. + + Returns: + A list with length of ACTION_SPACE of float32 tensors of shapes + [T, B], ..., [T, B] corresponding to the sampling log probability + of the chosen action w.r.t. the policy. + """ + log_probs = [] + for i in range(len(policy_logits)): + p_shape = policy_logits[i].shape + a_shape = actions[i].shape + policy_logits_flat = torch.reshape(policy_logits[i], (-1,) + tuple(p_shape[2:])) + actions_flat = torch.reshape(actions[i], (-1,) + tuple(a_shape[2:])) + log_probs.append( + torch.reshape( + dist_class(policy_logits_flat, model).logp(actions_flat), a_shape[:2] + ) + ) + + return log_probs + + +def from_logits( + behaviour_policy_logits, + target_policy_logits, + actions, + discounts, + rewards, + values, + bootstrap_value, + dist_class=TorchCategorical, + model=None, + clip_rho_threshold=1.0, + clip_pg_rho_threshold=1.0, +): + """multi_from_logits wrapper used only for tests""" + + res = multi_from_logits( + [behaviour_policy_logits], + [target_policy_logits], + [actions], + discounts, + rewards, + values, + bootstrap_value, + dist_class, + model, + clip_rho_threshold=clip_rho_threshold, + clip_pg_rho_threshold=clip_pg_rho_threshold, + ) + + assert len(res.behaviour_action_log_probs) == 1 + assert len(res.target_action_log_probs) == 1 + return VTraceFromLogitsReturns( + vs=res.vs, + pg_advantages=res.pg_advantages, + log_rhos=res.log_rhos, + behaviour_action_log_probs=res.behaviour_action_log_probs[0], + target_action_log_probs=res.target_action_log_probs[0], + ) + + +def multi_from_logits( + behaviour_policy_logits, + target_policy_logits, + actions, + discounts, + rewards, + values, + bootstrap_value, + dist_class, + model, + behaviour_action_log_probs=None, + clip_rho_threshold=1.0, + clip_pg_rho_threshold=1.0, +): + r"""V-trace for softmax policies. + + Calculates V-trace actor critic targets for softmax polices as described in + + "IMPALA: Scalable Distributed Deep-RL with + Importance Weighted Actor-Learner Architectures" + by Espeholt, Soyer, Munos et al. + + Target policy refers to the policy we are interested in improving and + behaviour policy refers to the policy that generated the given + rewards and actions. + + In the notation used throughout documentation and comments, T refers to the + time dimension ranging from 0 to T-1. B refers to the batch size and + ACTION_SPACE refers to the list of numbers each representing a number of + actions. + + Args: + behaviour_policy_logits: A list with length of ACTION_SPACE of float32 + tensors of shapes [T, B, ACTION_SPACE[0]], ..., + [T, B, ACTION_SPACE[-1]] with un-normalized log-probabilities + parameterizing the softmax behavior policy. + target_policy_logits: A list with length of ACTION_SPACE of float32 + tensors of shapes [T, B, ACTION_SPACE[0]], ..., + [T, B, ACTION_SPACE[-1]] with un-normalized log-probabilities + parameterizing the softmax target policy. + actions: A list with length of ACTION_SPACE of tensors of shapes + [T, B, ...], ..., [T, B, ...] + with actions sampled from the behavior policy. + discounts: A float32 tensor of shape [T, B] with the discount + encountered when following the behavior policy. + rewards: A float32 tensor of shape [T, B] with the rewards generated by + following the behavior policy. + values: A float32 tensor of shape [T, B] with the value function + estimates wrt. the target policy. + bootstrap_value: A float32 of shape [B] with the value function + estimate at time T. + dist_class: action distribution class for the logits. + model: backing ModelV2 instance + behaviour_action_log_probs: Precalculated values of the behavior + actions. + clip_rho_threshold: A scalar float32 tensor with the clipping threshold + for importance weights (rho) when calculating the baseline targets + (vs). rho^bar in the paper. + clip_pg_rho_threshold: A scalar float32 tensor with the clipping + threshold on rho_s in: + \rho_s \delta log \pi(a|x) (r + \gamma v_{s+1} - V(x_s)). + + Returns: + A `VTraceFromLogitsReturns` namedtuple with the following fields: + vs: A float32 tensor of shape [T, B]. Can be used as target to train a + baseline (V(x_t) - vs_t)^2. + pg_advantages: A float 32 tensor of shape [T, B]. Can be used as an + estimate of the advantage in the calculation of policy gradients. + log_rhos: A float32 tensor of shape [T, B] containing the log + importance sampling weights (log rhos). + behaviour_action_log_probs: A float32 tensor of shape [T, B] containing + behaviour policy action log probabilities (log \mu(a_t)). + target_action_log_probs: A float32 tensor of shape [T, B] containing + target policy action probabilities (log \pi(a_t)). + """ + + behaviour_policy_logits = convert_to_torch_tensor( + behaviour_policy_logits, device="cpu" + ) + target_policy_logits = convert_to_torch_tensor(target_policy_logits, device="cpu") + actions = convert_to_torch_tensor(actions, device="cpu") + + # Make sure tensor ranks are as expected. + # The rest will be checked by from_action_log_probs. + for i in range(len(behaviour_policy_logits)): + assert len(behaviour_policy_logits[i].size()) == 3 + assert len(target_policy_logits[i].size()) == 3 + + target_action_log_probs = multi_log_probs_from_logits_and_actions( + target_policy_logits, actions, dist_class, model + ) + + if len(behaviour_policy_logits) > 1 or behaviour_action_log_probs is None: + # can't use precalculated values, recompute them. Note that + # recomputing won't work well for autoregressive action dists + # which may have variables not captured by 'logits' + behaviour_action_log_probs = multi_log_probs_from_logits_and_actions( + behaviour_policy_logits, actions, dist_class, model + ) + + behaviour_action_log_probs = convert_to_torch_tensor( + behaviour_action_log_probs, device="cpu" + ) + behaviour_action_log_probs = force_list(behaviour_action_log_probs) + # log_rhos = target_logp - behavior_logp + log_rhos = get_log_rhos(target_action_log_probs, behaviour_action_log_probs) + + vtrace_returns = from_importance_weights( + log_rhos=log_rhos, + discounts=discounts, + rewards=rewards, + values=values, + bootstrap_value=bootstrap_value, + clip_rho_threshold=clip_rho_threshold, + clip_pg_rho_threshold=clip_pg_rho_threshold, + ) + + return VTraceFromLogitsReturns( + log_rhos=log_rhos, + behaviour_action_log_probs=behaviour_action_log_probs, + target_action_log_probs=target_action_log_probs, + **vtrace_returns._asdict() + ) + + +def from_importance_weights( + log_rhos, + discounts, + rewards, + values, + bootstrap_value, + clip_rho_threshold=1.0, + clip_pg_rho_threshold=1.0, +): + r"""V-trace from log importance weights. + + Calculates V-trace actor critic targets as described in + + "IMPALA: Scalable Distributed Deep-RL with + Importance Weighted Actor-Learner Architectures" + by Espeholt, Soyer, Munos et al. + + In the notation used throughout documentation and comments, T refers to the + time dimension ranging from 0 to T-1. B refers to the batch size. This code + also supports the case where all tensors have the same number of additional + dimensions, e.g., `rewards` is [T, B, C], `values` is [T, B, C], + `bootstrap_value` is [B, C]. + + Args: + log_rhos: A float32 tensor of shape [T, B] representing the log + importance sampling weights, i.e. + log(target_policy(a) / behaviour_policy(a)). V-trace performs + operations on rhos in log-space for numerical stability. + discounts: A float32 tensor of shape [T, B] with discounts encountered + when following the behaviour policy. + rewards: A float32 tensor of shape [T, B] containing rewards generated + by following the behaviour policy. + values: A float32 tensor of shape [T, B] with the value function + estimates wrt. the target policy. + bootstrap_value: A float32 of shape [B] with the value function + estimate at time T. + clip_rho_threshold: A scalar float32 tensor with the clipping threshold + for importance weights (rho) when calculating the baseline targets + (vs). rho^bar in the paper. If None, no clipping is applied. + clip_pg_rho_threshold: A scalar float32 tensor with the clipping + threshold on rho_s in + \rho_s \delta log \pi(a|x) (r + \gamma v_{s+1} - V(x_s)). + If None, no clipping is applied. + + Returns: + A VTraceReturns namedtuple (vs, pg_advantages) where: + vs: A float32 tensor of shape [T, B]. Can be used as target to + train a baseline (V(x_t) - vs_t)^2. + pg_advantages: A float32 tensor of shape [T, B]. Can be used as the + advantage in the calculation of policy gradients. + """ + log_rhos = convert_to_torch_tensor(log_rhos, device="cpu") + discounts = convert_to_torch_tensor(discounts, device="cpu") + rewards = convert_to_torch_tensor(rewards, device="cpu") + values = convert_to_torch_tensor(values, device="cpu") + bootstrap_value = convert_to_torch_tensor(bootstrap_value, device="cpu") + + # Make sure tensor ranks are consistent. + rho_rank = len(log_rhos.size()) # Usually 2. + assert rho_rank == len(values.size()) + assert rho_rank - 1 == len(bootstrap_value.size()), "must have rank {}".format( + rho_rank - 1 + ) + assert rho_rank == len(discounts.size()) + assert rho_rank == len(rewards.size()) + + rhos = torch.exp(log_rhos) + if clip_rho_threshold is not None: + clipped_rhos = torch.clamp_max(rhos, clip_rho_threshold) + else: + clipped_rhos = rhos + + cs = torch.clamp_max(rhos, 1.0) + # Append bootstrapped value to get [v1, ..., v_t+1] + values_t_plus_1 = torch.cat( + [values[1:], torch.unsqueeze(bootstrap_value, 0)], dim=0 + ) + deltas = clipped_rhos * (rewards + discounts * values_t_plus_1 - values) + + vs_minus_v_xs = [torch.zeros_like(bootstrap_value)] + for i in reversed(range(len(discounts))): + discount_t, c_t, delta_t = discounts[i], cs[i], deltas[i] + vs_minus_v_xs.append(delta_t + discount_t * c_t * vs_minus_v_xs[-1]) + vs_minus_v_xs = torch.stack(vs_minus_v_xs[1:]) + # Reverse the results back to original order. + vs_minus_v_xs = torch.flip(vs_minus_v_xs, dims=[0]) + # Add V(x_s) to get v_s. + vs = vs_minus_v_xs + values + + # Advantage for policy gradient. + vs_t_plus_1 = torch.cat([vs[1:], torch.unsqueeze(bootstrap_value, 0)], dim=0) + if clip_pg_rho_threshold is not None: + clipped_pg_rhos = torch.clamp_max(rhos, clip_pg_rho_threshold) + else: + clipped_pg_rhos = rhos + pg_advantages = clipped_pg_rhos * (rewards + discounts * vs_t_plus_1 - values) + + # Make sure no gradients backpropagated through the returned values. + return VTraceReturns(vs=vs.detach(), pg_advantages=pg_advantages.detach()) + + +def get_log_rhos(target_action_log_probs, behaviour_action_log_probs): + """With the selected log_probs for multi-discrete actions of behavior + and target policies we compute the log_rhos for calculating the vtrace.""" + t = torch.stack(target_action_log_probs) + b = torch.stack(behaviour_action_log_probs) + log_rhos = torch.sum(t - b, dim=0) + return log_rhos diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..404fb83b6aac79414874cc32c7ee0bb5c13ab7fe --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/__init__.py @@ -0,0 +1,6 @@ +from ray.rllib.algorithms.iql.iql import IQL, IQLConfig + +__all__ = [ + "IQL", + "IQLConfig", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9d6fa897e5720343e08ee9462311f9787c77685 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/__pycache__/default_iql_rl_module.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/__pycache__/default_iql_rl_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..569558186bdd38383c1cab5094e9248b147e37e2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/__pycache__/default_iql_rl_module.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/__pycache__/iql.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/__pycache__/iql.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5333470390a8f4cf8be0a03617fe4721a15b60f6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/__pycache__/iql.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/__pycache__/iql_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/__pycache__/iql_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6195a95c37fc96469908bd9dbfbcaf7ce6530770 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/__pycache__/iql_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/default_iql_rl_module.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/default_iql_rl_module.py new file mode 100644 index 0000000000000000000000000000000000000000..e6e3b2279ac5b8be0b10b93627c00335aac3a0fb --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/default_iql_rl_module.py @@ -0,0 +1,35 @@ +from ray.rllib.algorithms.sac.default_sac_rl_module import DefaultSACRLModule +from ray.rllib.core.models.configs import MLPHeadConfig +from ray.rllib.core.rl_module.apis.value_function_api import ValueFunctionAPI +from ray.rllib.utils.annotations import ( + override, + OverrideToImplementCustomLogic_CallToSuperRecommended, +) + + +class DefaultIQLRLModule(DefaultSACRLModule, ValueFunctionAPI): + @override(DefaultSACRLModule) + def setup(self): + # Setup the `DefaultSACRLModule` to get the catalog. + super().setup() + + # Only, if the `RLModule` is used on a `Learner` we build the value network. + if not self.inference_only: + # Build the encoder for the value function. + self.vf_encoder = self.catalog.build_encoder(framework=self.framework) + + # Build the vf head. + self.vf = MLPHeadConfig( + input_dims=self.catalog.latent_dims, + # Note, we use the same layers as for the policy and Q-network. + hidden_layer_dims=self.catalog.pi_and_qf_head_hiddens, + hidden_layer_activation=self.catalog.pi_and_qf_head_activation, + output_layer_activation="linear", + output_layer_dim=1, + ).build(framework=self.framework) + + @override(DefaultSACRLModule) + @OverrideToImplementCustomLogic_CallToSuperRecommended + def get_non_inference_attributes(self): + # Use all of `super`'s attributes and add the value function attributes. + return super().get_non_inference_attributes() + ["vf_encoder", "vf"] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/iql.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/iql.py new file mode 100644 index 0000000000000000000000000000000000000000..8935550027084e6b243e75c7798e4812e28c0661 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/iql.py @@ -0,0 +1,228 @@ +from typing import Optional, Type, Union + +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig, NotProvided +from ray.rllib.algorithms.marwil.marwil import MARWIL, MARWILConfig +from ray.rllib.connectors.common.add_observations_from_episodes_to_batch import ( + AddObservationsFromEpisodesToBatch, +) +from ray.rllib.connectors.learner.add_next_observations_from_episodes_to_train_batch import ( # noqa + AddNextObservationsFromEpisodesToTrainBatch, +) +from ray.rllib.core.learner.learner import Learner +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import LearningRateOrSchedule, RLModuleSpecType + + +class IQLConfig(MARWILConfig): + """Defines a configuration class from which a new IQL Algorithm can be built + + .. testcode:: + :skipif: True + + from ray.rllib.algorithms.iql import IQLConfig + # Run this from the ray directory root. + config = IQLConfig().training(actor_lr=0.00001, gamma=0.99) + config = config.offline_data( + input_="./rllib/tests/data/pendulum/pendulum-v1_enormous") + + # Build an Algorithm object from the config and run 1 training iteration. + algo = config.build() + algo.train() + + .. testcode:: + :skipif: True + + from ray.rllib.algorithms.iql import IQLConfig + from ray import tune + config = IQLConfig() + # Print out some default values. + print(config.beta) + # Update the config object. + config.training( + lr=tune.grid_search([0.001, 0.0001]), beta=0.75 + ) + # Set the config object's data path. + # Run this from the ray directory root. + config.offline_data( + input_="./rllib/tests/data/pendulum-v1_enormous" + ) + # Set the config object's env, used for evaluation. + config.environment(env="Pendulum-v1") + # Use to_dict() to get the old-style python config dict + # when running with tune. + tune.Tuner( + "IQL", + param_space=config.to_dict(), + ).fit() + """ + + def __init__(self, algo_class=None): + super().__init__(algo_class=algo_class or IQL) + + # fmt: off + # __sphinx_doc_begin__ + # The temperature for the actor loss. + self.beta = 0.1 + + # The expectile to use in expectile regression. + self.expectile = 0.8 + + # The learning rates for the actor, critic and value network(s). + self.actor_lr = 3e-4 + self.critic_lr = 3e-4 + self.value_lr = 3e-4 + # Set `lr` parameter to `None` and ensure it is not used. + self.lr = None + + # If a twin-Q architecture should be used (advisable). + self.twin_q = True + + # How often the target network should be updated. + self.target_network_update_freq = 0 + # The weight for Polyak averaging. + self.tau = 1.0 + + # __sphinx_doc_end__ + # fmt: on + + @override(MARWILConfig) + def training( + self, + *, + twin_q: Optional[bool] = NotProvided, + expectile: Optional[float] = NotProvided, + actor_lr: Optional[LearningRateOrSchedule] = NotProvided, + critic_lr: Optional[LearningRateOrSchedule] = NotProvided, + value_lr: Optional[LearningRateOrSchedule] = NotProvided, + target_network_update_freq: Optional[int] = NotProvided, + tau: Optional[float] = NotProvided, + **kwargs, + ) -> "IQLConfig": + """Sets the training related configuration. + + Args: + beta: The temperature to scaling advantages in exponential terms. + Must be >> 0.0. The higher this parameter the less greedy + (exploitative) the policy becomes. It also means that the policy + is fitting less to the best actions in the dataset. + twin_q: If a twin-Q architecture should be used (advisable). + expectile: The expectile to use in expectile regression for the value + function. For high expectiles the value function tries to match + the upper tail of the Q-value distribution. + actor_lr: The learning rate for the actor network. Actor learning rates + greater than critic learning rates work well in experiments. + critic_lr: The learning rate for the Q-network. Critic learning rates + greater than value function learning rates work well in experiments. + value_lr: The learning rate for the value function network. + target_network_update_freq: The number of timesteps in between the target + Q-network is fixed. Note, too high values here could harm convergence. + The target network is updated via Polyak-averaging. + tau: The update parameter for Polyak-averaging of the target Q-network. + The higher this value the faster the weights move towards the actual + Q-network. + + Return: + This updated `AlgorithmConfig` object. + """ + super().training(**kwargs) + + if twin_q is not NotProvided: + self.twin_q = twin_q + if expectile is not NotProvided: + self.expectile = expectile + if actor_lr is not NotProvided: + self.actor_lr = actor_lr + if critic_lr is not NotProvided: + self.critic_lr = critic_lr + if value_lr is not NotProvided: + self.value_lr = value_lr + if target_network_update_freq is not NotProvided: + self.target_network_update_freq = target_network_update_freq + if tau is not NotProvided: + self.tau = tau + + return self + + @override(MARWILConfig) + def get_default_learner_class(self) -> Union[Type["Learner"], str]: + if self.framework_str == "torch": + from ray.rllib.algorithms.iql.torch.iql_torch_learner import IQLTorchLearner + + return IQLTorchLearner + else: + raise ValueError( + f"The framework {self.framework_str} is not supported. " + "Use `'torch'` instead." + ) + + @override(MARWILConfig) + def get_default_rl_module_spec(self) -> RLModuleSpecType: + if self.framework_str == "torch": + from ray.rllib.algorithms.iql.torch.default_iql_torch_rl_module import ( + DefaultIQLTorchRLModule, + ) + + return RLModuleSpec(module_class=DefaultIQLTorchRLModule) + else: + raise ValueError( + f"The framework {self.framework_str} is not supported. " + "Use `torch` instead." + ) + + @override(MARWILConfig) + def build_learner_connector( + self, + input_observation_space, + input_action_space, + device=None, + ): + pipeline = super().build_learner_connector( + input_observation_space=input_observation_space, + input_action_space=input_action_space, + device=device, + ) + + # Remove unneeded connectors from the MARWIL connector pipeline. + pipeline.remove("AddOneTsToEpisodesAndTruncate") + pipeline.remove("GeneralAdvantageEstimation") + + # Prepend the "add-NEXT_OBS-from-episodes-to-train-batch" connector piece (right + # after the corresponding "add-OBS-..." default piece). + pipeline.insert_after( + AddObservationsFromEpisodesToBatch, + AddNextObservationsFromEpisodesToTrainBatch(), + ) + + return pipeline + + @override(MARWILConfig) + def validate(self) -> None: + # Call super's validation method. + super().validate() + + # Ensure hyperparameters are meaningful. + if self.beta <= 0.0: + self._value_error( + "For meaningful results, `beta` (temperature) parameter must be >> 0.0!" + ) + if not 0.0 < self.expectile < 1.0: + self._value_error( + "For meaningful results, `expectile` parameter must be in (0, 1)." + ) + + @property + def _model_config_auto_includes(self): + return super()._model_config_auto_includes | {"twin_q": self.twin_q} + + +class IQL(MARWIL): + """Implicit Q-learning (derived from MARWIL). + + Uses MARWIL training step. + """ + + @classmethod + @override(MARWIL) + def get_default_config(cls) -> AlgorithmConfig: + return IQLConfig() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/iql_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/iql_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..5821f2ccb5e0bddd9596d366695750acef542e24 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/iql_learner.py @@ -0,0 +1,84 @@ +from typing import Dict + +from ray.rllib.algorithms.dqn.dqn_learner import DQNLearner +from ray.rllib.utils.annotations import ( + override, + OverrideToImplementCustomLogic_CallToSuperRecommended, +) +from ray.rllib.utils.lambda_defaultdict import LambdaDefaultDict +from ray.rllib.utils.typing import ModuleID, TensorType + +QF_TARGET_PREDS = "qf_target_preds" +VF_PREDS_NEXT = "vf_preds_next" +VF_LOSS = "value_loss" + + +class IQLLearner(DQNLearner): + @OverrideToImplementCustomLogic_CallToSuperRecommended + @override(DQNLearner) + def build(self) -> None: + # Build the `DQNLearner` (builds the target network). + super().build() + + # Define the expectile parameter(s). + self.expectile: Dict[ModuleID, TensorType] = LambdaDefaultDict( + lambda module_id: self._get_tensor_variable( + # Note, we want to train with a certain expectile. + [self.config.get_config_for_module(module_id).expectile], + trainable=False, + ) + ) + + # Define the temperature for the actor advantage loss. + self.temperature: Dict[ModuleID, TensorType] = LambdaDefaultDict( + lambda module_id: self._get_tensor_variable( + # Note, we want to train with a certain expectile. + [self.config.get_config_for_module(module_id).beta], + trainable=False, + ) + ) + + # Store loss tensors here temporarily inside the loss function for (exact) + # consumption later by the compute gradients function. + # Keys=(module_id, optimizer_name), values=loss tensors (in-graph). + self._temp_losses = {} + + @override(DQNLearner) + def remove_module(self, module_id: ModuleID) -> None: + """Removes the expectile and temperature for removed modules.""" + # First call `super`'s `remove_module` method. + super().remove_module(module_id) + # Remove the expectile from the mapping. + self.expectile.pop(module_id, None) + # Remove the temperature from the mapping. + self.temperature.pop(module_id, None) + + @override(DQNLearner) + def add_module( + self, + *, + module_id, + module_spec, + config_overrides=None, + new_should_module_be_updated=None + ): + """Adds the expectile and temperature for new modules.""" + # First call `super`'s `add_module` method. + super().add_module( + module_id=module_id, + module_spec=module_spec, + config_overrides=config_overrides, + new_should_module_be_updated=new_should_module_be_updated, + ) + # Add the expectile to the mapping. + self.expectile[module_id] = self._get_tensor_variable( + # Note, we want to train with a certain expectile. + [self.config.get_config_for_module(module_id).beta], + trainable=False, + ) + # Add the temperature to the mapping. + self.temperature[module_id] = self._get_tensor_variable( + # Note, we want to train with a certain expectile. + [self.config.get_config_for_module(module_id).beta], + trainable=False, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/torch/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/torch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/torch/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/torch/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..890971581d15c8d8749a953ca813d1c710081ae0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/torch/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/torch/__pycache__/default_iql_torch_rl_module.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/torch/__pycache__/default_iql_torch_rl_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..084a62494a8629c55f1889b040da4d490a00c9f5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/torch/__pycache__/default_iql_torch_rl_module.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/torch/__pycache__/iql_torch_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/torch/__pycache__/iql_torch_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3990d855a9202fb1caef85cfa2747953ef41b91f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/torch/__pycache__/iql_torch_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/torch/default_iql_torch_rl_module.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/torch/default_iql_torch_rl_module.py new file mode 100644 index 0000000000000000000000000000000000000000..00d7fc821e4932f8f6ff5a08511806ceb763cb4a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/torch/default_iql_torch_rl_module.py @@ -0,0 +1,78 @@ +import gymnasium as gym +from typing import Any, Dict, Optional + +from ray.rllib.algorithms.iql.default_iql_rl_module import DefaultIQLRLModule +from ray.rllib.algorithms.iql.iql_learner import VF_PREDS_NEXT, QF_TARGET_PREDS +from ray.rllib.algorithms.sac.torch.default_sac_torch_rl_module import ( + DefaultSACTorchRLModule, +) +from ray.rllib.core.columns import Columns +from ray.rllib.core.models.base import ENCODER_OUT +from ray.rllib.core.rl_module.apis.value_function_api import ValueFunctionAPI +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.typing import TensorType + +torch, nn = try_import_torch() + + +class DefaultIQLTorchRLModule(DefaultSACTorchRLModule, DefaultIQLRLModule): + + framework: str = "torch" + + @override(DefaultSACTorchRLModule) + def _forward_train(self, batch: Dict, **kwargs) -> Dict[str, Any]: + + # Right now, IQL runs only with continuous action spaces. + # TODO (simon): Implement it also for discrete action spaces. + if not isinstance(self.action_space, gym.spaces.Box): + raise ValueError( + f"Unsupported action space type: {type(self.action_space)}. " + "Only continuous action spaces are supported." + ) + + # Call the forward pass of the SAC module. + output = super()._forward_train(batch, **kwargs) + + # Create batches for the forward passes of the target Q-networks and the + # value function. + batch_curr = { + Columns.OBS: batch[Columns.OBS], + Columns.ACTIONS: batch[Columns.ACTIONS], + } + batch_next = {Columns.OBS: batch[Columns.NEXT_OBS]} + + # These target q-values are needed for the value loss and actor loss. + output[QF_TARGET_PREDS] = self._qf_forward_train_helper( + batch_curr, encoder=self.target_qf_encoder, head=self.target_qf + ) + # If a twin-Q architecture is used run its target Q-network. + if self.twin_q: + output[QF_TARGET_PREDS] = torch.min( + output[QF_TARGET_PREDS], + self._qf_forward_train_helper( + batch_curr, encoder=self.target_qf_twin_encoder, head=self.qf_twin + ), + ) + + # Compute values for the current observations. + output[Columns.VF_PREDS] = self.compute_values(batch_curr) + # The values of the next observations are needed for the critic loss. + output[VF_PREDS_NEXT] = self.compute_values(batch_next) + + return output + + @override(ValueFunctionAPI) + def compute_values( + self, + batch: Dict[str, Any], + embeddings: Optional[Any] = None, + ) -> TensorType: + # If no embeddings are provided make a forward pass on the encoder. + if embeddings is None: + embeddings = self.vf_encoder(batch)[ENCODER_OUT] + + # Value head. + vf_out = self.vf(embeddings) + # Squeeze out last dimension (single node value head). + return vf_out.squeeze(-1) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/torch/iql_torch_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/torch/iql_torch_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..85dc68e86fb2242d70036b2a70f4d825cc52b836 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/iql/torch/iql_torch_learner.py @@ -0,0 +1,245 @@ +from typing import Dict + +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig +from ray.rllib.algorithms.dqn.dqn_learner import QF_PREDS, QF_LOSS_KEY +from ray.rllib.algorithms.iql.iql_learner import ( + IQLLearner, + QF_TARGET_PREDS, + VF_PREDS_NEXT, + VF_LOSS, +) +from ray.rllib.algorithms.sac.sac_learner import QF_TWIN_PREDS, QF_TWIN_LOSS_KEY +from ray.rllib.core import ALL_MODULES +from ray.rllib.core.columns import Columns +from ray.rllib.core.learner.learner import ( + POLICY_LOSS_KEY, +) +from ray.rllib.core.learner.torch.torch_learner import TorchLearner +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.typing import ModuleID, ParamDict, TensorType + +torch, nn = try_import_torch() + + +class IQLTorchLearner(TorchLearner, IQLLearner): + """Implements the IQL loss on top of `IQLLearner`. + + This Learner implements configure_optimizers_for_module to define + separate optimizers for the policy, Q-, and value networks. When + using a twin-Q network architecture, each Q-network is assigned its + own optimizer—consistent with the SAC algorithm. + + The IQL loss is defined in compute_loss_for_module and consists of + three components: value loss, Q-loss (TD error), and actor (policy) + loss. + + Note that the original IQL implementation performs separate backward + passes for each network. However, due to RLlib's reliance on TorchDDP, + all backward passes must be executed within a single update step. This + constraint can lead to parameter lag and cyclical loss behavior, though + it does not hinder convergence. + """ + + @override(TorchLearner) + def configure_optimizers_for_module( + self, module_id: ModuleID, config: AlgorithmConfig = None + ) -> None: + + # Note, we could have derived directly from SACTorchLearner to + # inherit the setup of optimizers, but that learner comes with + # additional parameters which we do not need. + # Receive the module. + module = self._module[module_id] + + # Define the optimizer for the critic. + # TODO (sven): Maybe we change here naming to `qf` for unification. + params_critic = self.get_parameters(module.qf_encoder) + self.get_parameters( + module.qf + ) + optim_critic = torch.optim.Adam(params_critic, eps=1e-7) + self.register_optimizer( + module_id=module_id, + optimizer_name="qf", + optimizer=optim_critic, + params=params_critic, + lr_or_lr_schedule=config.critic_lr, + ) + # If necessary register also an optimizer for a twin Q network. + if config.twin_q: + params_twin_critic = self.get_parameters( + module.qf_twin_encoder + ) + self.get_parameters(module.qf_twin) + optim_twin_critic = torch.optim.Adam(params_twin_critic, eps=1e-7) + self.register_optimizer( + module_id=module_id, + optimizer_name="qf_twin", + optimizer=optim_twin_critic, + params=params_twin_critic, + lr_or_lr_schedule=config.critic_lr, + ) + + # Define the optimizer for the actor. + params_actor = self.get_parameters(module.pi_encoder) + self.get_parameters( + module.pi + ) + optim_actor = torch.optim.Adam(params_actor, eps=1e-7) + self.register_optimizer( + module_id=module_id, + optimizer_name="policy", + optimizer=optim_actor, + params=params_actor, + lr_or_lr_schedule=config.actor_lr, + ) + + # Define the optimizer for the value function. + params_value = self.get_parameters(module.vf_encoder) + self.get_parameters( + module.vf + ) + optim_value = torch.optim.Adam(params_value, eps=1e-7) + self.register_optimizer( + module_id=module_id, + optimizer_name="value", + optimizer=optim_value, + params=params_value, + lr_or_lr_schedule=config.value_lr, + ) + + @override(TorchLearner) + def compute_loss_for_module( + self, + *, + module_id: ModuleID, + config: AlgorithmConfig, + batch: Dict, + fwd_out: Dict + ): + + # Get the module and hyperparameters. + module = self._module[module_id] + expectile = self.expectile[module_id] + temperature = self.temperature[module_id] + + # Get the action distribution for the actor loss. + action_train_dist_class = module.get_train_action_dist_cls() + action_train_dist = action_train_dist_class.from_logits( + fwd_out[Columns.ACTION_DIST_INPUTS] + ) + + # First, compute the value loss via the target Q-network and current observations. + value_loss = torch.mean( + self._expectile_loss( + fwd_out[QF_TARGET_PREDS] - fwd_out[Columns.VF_PREDS], expectile + ) + ) + + # Second, compute the actor loss using the target-Q network and values. + exp_advantages = torch.minimum( + torch.exp( + temperature * (fwd_out[QF_TARGET_PREDS] - fwd_out[Columns.VF_PREDS]) + ), + torch.Tensor([100.0]).to(self.device), + ) + # Note, we are using here the actions from the data sample. + action_logps = action_train_dist.logp(batch[Columns.ACTIONS]) + # Compute the actor loss. + actor_loss = -torch.mean(exp_advantages.detach() * action_logps) + + # Third, compute the critic loss. + target_critic = ( + batch[Columns.REWARDS] + + config.gamma + * (1 - batch[Columns.TERMINATEDS].float()) + * fwd_out[VF_PREDS_NEXT].detach() + ) + + critic_loss = torch.mean( + torch.nn.MSELoss(reduction="none")(target_critic, fwd_out[QF_PREDS]) + ) + + # If we have a twin-Q architecture, calculate the its loss, too. + if config.twin_q: + critic_twin_loss = ( + torch.mean( + torch.nn.MSELoss(reduction="none")( + target_critic, fwd_out[QF_TWIN_PREDS] + ) + ) + * 0.5 + ) + critic_loss *= 0.5 + + # Compute the total loss. + total_loss = value_loss + actor_loss + critic_loss + + # If we have a twin-Q architecture, add its loss. + if config.twin_q: + total_loss += critic_twin_loss + + # Log metrics. + self.metrics.log_dict( + { + POLICY_LOSS_KEY: actor_loss, + QF_LOSS_KEY: critic_loss, + }, + key=module_id, + window=1, # <- single items (should not be mean/ema-reduced over time). + ) + + # Log the losses also in the temporary containers for gradient computation. + self._temp_losses[(module_id, POLICY_LOSS_KEY)] = actor_loss + self._temp_losses[(module_id, QF_LOSS_KEY)] = critic_loss + self._temp_losses[(module_id, VF_LOSS)] = value_loss + + # If a twin-Q architecture is used add metrics and loss. + if config.twin_q: + self.metrics.log_value( + key=(module_id, QF_TWIN_LOSS_KEY), + value=critic_twin_loss, + window=1, # <- single items (should not be mean/ema-reduced over time). + ) + self._temp_losses[(module_id, QF_TWIN_LOSS_KEY)] = critic_twin_loss + + return total_loss + + @override(TorchLearner) + def compute_gradients( + self, loss_per_module: Dict[ModuleID, TensorType], **kwargs + ) -> ParamDict: + grads = {} + for module_id in set(loss_per_module.keys()) - {ALL_MODULES}: + # Loop through optimizers registered for this module. + for optim_name, optim in self.get_optimizers_for_module(module_id): + # Zero the gradients. Note, we need to reset the gradients b/c + # each component for a module operates on the same graph. + optim.zero_grad(set_to_none=True) + + # Compute the gradients for the component and module. + loss_tensor = self._temp_losses.pop((module_id, optim_name + "_loss")) + loss_tensor.backward(retain_graph=True) + # Store the gradients for the component and module. + grads.update( + { + pid: p.grad + for pid, p in self.filter_param_dict_for_optimizer( + self._params, optim + ).items() + } + ) + + # Make sure we updated on all loss terms. + assert not self._temp_losses + return grads + + def _expectile_loss(self, diff: TensorType, expectile: TensorType) -> TensorType: + """Computes the expectile loss. + + Args: + diff: A tensor containing a difference loss. + expectile: The expectile to use for the expectile loss. + + Returns: + The expectile loss of `diff` using `expectile`. + """ + weight = torch.where(diff > 0, expectile, 1 - expectile) + return weight * torch.pow(diff, 2) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e132e3a8ae8baa2eb5d4787315ae3c30dff8d2e5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/__init__.py @@ -0,0 +1,18 @@ +from ray.rllib.algorithms.marwil.marwil import ( + MARWIL, + MARWILConfig, +) +from ray.rllib.algorithms.marwil.marwil_tf_policy import ( + MARWILTF1Policy, + MARWILTF2Policy, +) +from ray.rllib.algorithms.marwil.marwil_torch_policy import MARWILTorchPolicy + +__all__ = [ + "MARWIL", + "MARWILConfig", + # @OldAPIStack + "MARWILTF1Policy", + "MARWILTF2Policy", + "MARWILTorchPolicy", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aecfc972056034c8c7ba9e21da30d815915128b2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/__pycache__/marwil.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/__pycache__/marwil.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0bef69c72114d8ead73cd9988788bed48bb4a45 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/__pycache__/marwil.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/__pycache__/marwil_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/__pycache__/marwil_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d70e73d5f11883f28dfc23086b3dbc0b8c244dc Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/__pycache__/marwil_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/__pycache__/marwil_tf_policy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/__pycache__/marwil_tf_policy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e169645ab4f44296a2445bffdd7877b2ee7951a4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/__pycache__/marwil_tf_policy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/__pycache__/marwil_torch_policy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/__pycache__/marwil_torch_policy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e577a520b324b4a0edc12ed06e77d1a2a745dbe Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/__pycache__/marwil_torch_policy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/marwil.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/marwil.py new file mode 100644 index 0000000000000000000000000000000000000000..4ebf1d9333a449955c12922e9a6e8ac053efc336 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/marwil.py @@ -0,0 +1,534 @@ +from typing import Callable, Optional, Type, Union + +from ray.rllib.algorithms.algorithm import Algorithm +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig, NotProvided +from ray.rllib.connectors.learner import ( + AddObservationsFromEpisodesToBatch, + AddOneTsToEpisodesAndTruncate, + AddNextObservationsFromEpisodesToTrainBatch, + GeneralAdvantageEstimation, +) +from ray.rllib.core.learner.learner import Learner +from ray.rllib.core.learner.training_data import TrainingData +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.execution.rollout_ops import ( + synchronous_parallel_sample, +) +from ray.rllib.execution.train_ops import ( + multi_gpu_train_one_step, + train_one_step, +) +from ray.rllib.policy.policy import Policy +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.deprecation import deprecation_warning +from ray.rllib.utils.metrics import ( + LEARNER_RESULTS, + LEARNER_UPDATE_TIMER, + NUM_AGENT_STEPS_SAMPLED, + NUM_ENV_STEPS_SAMPLED, + OFFLINE_SAMPLING_TIMER, + SAMPLE_TIMER, + SYNCH_WORKER_WEIGHTS_TIMER, + TIMERS, +) +from ray.rllib.utils.typing import ( + EnvType, + ResultDict, + RLModuleSpecType, +) +from ray.tune.logger import Logger + + +class MARWILConfig(AlgorithmConfig): + """Defines a configuration class from which a MARWIL Algorithm can be built. + + .. testcode:: + + import gymnasium as gym + import numpy as np + + from pathlib import Path + from ray.rllib.algorithms.marwil import MARWILConfig + + # Get the base path (to ray/rllib) + base_path = Path(__file__).parents[2] + # Get the path to the data in rllib folder. + data_path = base_path / "tests/data/cartpole/cartpole-v1_large" + + config = MARWILConfig() + # Enable the new API stack. + config.api_stack( + enable_rl_module_and_learner=True, + enable_env_runner_and_connector_v2=True, + ) + # Define the environment for which to learn a policy + # from offline data. + config.environment( + observation_space=gym.spaces.Box( + np.array([-4.8, -np.inf, -0.41887903, -np.inf]), + np.array([4.8, np.inf, 0.41887903, np.inf]), + shape=(4,), + dtype=np.float32, + ), + action_space=gym.spaces.Discrete(2), + ) + # Set the training parameters. + config.training( + beta=1.0, + lr=1e-5, + gamma=0.99, + # We must define a train batch size for each + # learner (here 1 local learner). + train_batch_size_per_learner=2000, + ) + # Define the data source for offline data. + config.offline_data( + input_=[data_path.as_posix()], + # Run exactly one update per training iteration. + dataset_num_iters_per_learner=1, + ) + + # Build an `Algorithm` object from the config and run 1 training + # iteration. + algo = config.build() + algo.train() + + .. testcode:: + + import gymnasium as gym + import numpy as np + + from pathlib import Path + from ray.rllib.algorithms.marwil import MARWILConfig + from ray import tune + + # Get the base path (to ray/rllib) + base_path = Path(__file__).parents[2] + # Get the path to the data in rllib folder. + data_path = base_path / "tests/data/cartpole/cartpole-v1_large" + + config = MARWILConfig() + # Enable the new API stack. + config.api_stack( + enable_rl_module_and_learner=True, + enable_env_runner_and_connector_v2=True, + ) + # Print out some default values + print(f"beta: {config.beta}") + # Update the config object. + config.training( + lr=tune.grid_search([1e-3, 1e-4]), + beta=0.75, + # We must define a train batch size for each + # learner (here 1 local learner). + train_batch_size_per_learner=2000, + ) + # Set the config's data path. + config.offline_data( + input_=[data_path.as_posix()], + # Set the number of updates to be run per learner + # per training step. + dataset_num_iters_per_learner=1, + ) + # Set the config's environment for evalaution. + config.environment( + observation_space=gym.spaces.Box( + np.array([-4.8, -np.inf, -0.41887903, -np.inf]), + np.array([4.8, np.inf, 0.41887903, np.inf]), + shape=(4,), + dtype=np.float32, + ), + action_space=gym.spaces.Discrete(2), + ) + # Set up a tuner to run the experiment. + tuner = tune.Tuner( + "MARWIL", + param_space=config, + run_config=tune.RunConfig( + stop={"training_iteration": 1}, + ), + ) + # Run the experiment. + tuner.fit() + """ + + def __init__(self, algo_class=None): + """Initializes a MARWILConfig instance.""" + self.exploration_config = { + # The Exploration class to use. In the simplest case, this is the name + # (str) of any class present in the `rllib.utils.exploration` package. + # You can also provide the python class directly or the full location + # of your class (e.g. "ray.rllib.utils.exploration.epsilon_greedy. + # EpsilonGreedy"). + "type": "StochasticSampling", + # Add constructor kwargs here (if any). + } + + super().__init__(algo_class=algo_class or MARWIL) + self._is_online = False + # fmt: off + # __sphinx_doc_begin__ + # MARWIL specific settings: + self.beta = 1.0 + self.bc_logstd_coeff = 0.0 + self.moving_average_sqd_adv_norm_update_rate = 1e-8 + self.moving_average_sqd_adv_norm_start = 100.0 + self.vf_coeff = 1.0 + self.model["vf_share_layers"] = False + self.grad_clip = None + + # Override some of AlgorithmConfig's default values with MARWIL-specific values. + + # You should override input_ to point to an offline dataset + # (see algorithm.py and algorithm_config.py). + # The dataset may have an arbitrary number of timesteps + # (and even episodes) per line. + # However, each line must only contain consecutive timesteps in + # order for MARWIL to be able to calculate accumulated + # discounted returns. It is ok, though, to have multiple episodes in + # the same line. + self.input_ = "sampler" + self.postprocess_inputs = True + self.lr = 1e-4 + self.lambda_ = 1.0 + self.train_batch_size = 2000 + + # Materialize only the data in raw format, but not the mapped data b/c + # MARWIL uses a connector to calculate values and therefore the module + # needs to be updated frequently. This updating would not work if we + # map the data once at the beginning. + # TODO (simon, sven): The module is only updated when the OfflinePreLearner + # gets reinitiated, i.e. when the iterator gets reinitiated. This happens + # frequently enough with a small dataset, but with a big one this does not + # update often enough. We might need to put model weigths every couple of + # iterations into the object storage (maybe also connector states). + self.materialize_data = True + self.materialize_mapped_data = False + # __sphinx_doc_end__ + # fmt: on + self._set_off_policy_estimation_methods = False + + @override(AlgorithmConfig) + def training( + self, + *, + beta: Optional[float] = NotProvided, + bc_logstd_coeff: Optional[float] = NotProvided, + moving_average_sqd_adv_norm_update_rate: Optional[float] = NotProvided, + moving_average_sqd_adv_norm_start: Optional[float] = NotProvided, + vf_coeff: Optional[float] = NotProvided, + grad_clip: Optional[float] = NotProvided, + **kwargs, + ) -> "MARWILConfig": + """Sets the training related configuration. + + Args: + beta: Scaling of advantages in exponential terms. When beta is 0.0, + MARWIL is reduced to behavior cloning (imitation learning); + see bc.py algorithm in this same directory. + bc_logstd_coeff: A coefficient to encourage higher action distribution + entropy for exploration. + moving_average_sqd_adv_norm_update_rate: The rate for updating the + squared moving average advantage norm (c^2). A higher rate leads + to faster updates of this moving avergage. + moving_average_sqd_adv_norm_start: Starting value for the + squared moving average advantage norm (c^2). + vf_coeff: Balancing value estimation loss and policy optimization loss. + grad_clip: If specified, clip the global norm of gradients by this amount. + + Returns: + This updated AlgorithmConfig object. + """ + # Pass kwargs onto super's `training()` method. + super().training(**kwargs) + if beta is not NotProvided: + self.beta = beta + if bc_logstd_coeff is not NotProvided: + self.bc_logstd_coeff = bc_logstd_coeff + if moving_average_sqd_adv_norm_update_rate is not NotProvided: + self.moving_average_sqd_adv_norm_update_rate = ( + moving_average_sqd_adv_norm_update_rate + ) + if moving_average_sqd_adv_norm_start is not NotProvided: + self.moving_average_sqd_adv_norm_start = moving_average_sqd_adv_norm_start + if vf_coeff is not NotProvided: + self.vf_coeff = vf_coeff + if grad_clip is not NotProvided: + self.grad_clip = grad_clip + return self + + @override(AlgorithmConfig) + def get_default_rl_module_spec(self) -> RLModuleSpecType: + if self.framework_str == "torch": + from ray.rllib.algorithms.ppo.torch.default_ppo_torch_rl_module import ( + DefaultPPOTorchRLModule, + ) + + return RLModuleSpec(module_class=DefaultPPOTorchRLModule) + else: + raise ValueError( + f"The framework {self.framework_str} is not supported. " + "Use 'torch' instead." + ) + + @override(AlgorithmConfig) + def get_default_learner_class(self) -> Union[Type["Learner"], str]: + if self.framework_str == "torch": + from ray.rllib.algorithms.marwil.torch.marwil_torch_learner import ( + MARWILTorchLearner, + ) + + return MARWILTorchLearner + else: + raise ValueError( + f"The framework {self.framework_str} is not supported. " + "Use 'torch' instead." + ) + + @override(AlgorithmConfig) + def evaluation( + self, + **kwargs, + ) -> "MARWILConfig": + """Sets the evaluation related configuration. + Returns: + This updated AlgorithmConfig object. + """ + # Pass kwargs onto super's `evaluation()` method. + super().evaluation(**kwargs) + + if "off_policy_estimation_methods" in kwargs: + # User specified their OPE methods. + self._set_off_policy_estimation_methods = True + + return self + + @override(AlgorithmConfig) + def offline_data(self, **kwargs) -> "MARWILConfig": + + super().offline_data(**kwargs) + + # Check, if the passed in class incorporates the `OfflinePreLearner` + # interface. + if "prelearner_class" in kwargs: + from ray.rllib.offline.offline_data import OfflinePreLearner + + if not issubclass(kwargs.get("prelearner_class"), OfflinePreLearner): + raise ValueError( + f"`prelearner_class` {kwargs.get('prelearner_class')} is not a " + "subclass of `OfflinePreLearner`. Any class passed to " + "`prelearner_class` needs to implement the interface given by " + "`OfflinePreLearner`." + ) + + return self + + @override(AlgorithmConfig) + def build( + self, + env: Optional[Union[str, EnvType]] = None, + logger_creator: Optional[Callable[[], Logger]] = None, + ) -> "Algorithm": + if not self._set_off_policy_estimation_methods: + deprecation_warning( + old=r"MARWIL used to have off_policy_estimation_methods " + "is and wis by default. This has" + r"changed to off_policy_estimation_methods: \{\}." + "If you want to use an off-policy estimator, specify it in" + ".evaluation(off_policy_estimation_methods=...)", + error=False, + ) + return super().build(env, logger_creator) + + @override(AlgorithmConfig) + def build_learner_connector( + self, + input_observation_space, + input_action_space, + device=None, + ): + pipeline = super().build_learner_connector( + input_observation_space=input_observation_space, + input_action_space=input_action_space, + device=device, + ) + + # Before anything, add one ts to each episode (and record this in the loss + # mask, so that the computations at this extra ts are not used to compute + # the loss). + pipeline.prepend(AddOneTsToEpisodesAndTruncate()) + + # Prepend the "add-NEXT_OBS-from-episodes-to-train-batch" connector piece (right + # after the corresponding "add-OBS-..." default piece). + pipeline.insert_after( + AddObservationsFromEpisodesToBatch, + AddNextObservationsFromEpisodesToTrainBatch(), + ) + + # At the end of the pipeline (when the batch is already completed), add the + # GAE connector, which performs a vf forward pass, then computes the GAE + # computations, and puts the results of this (advantages, value targets) + # directly back in the batch. This is then the batch used for + # `forward_train` and `compute_losses`. + pipeline.append( + GeneralAdvantageEstimation(gamma=self.gamma, lambda_=self.lambda_) + ) + + return pipeline + + @override(AlgorithmConfig) + def validate(self) -> None: + # Call super's validation method. + super().validate() + + if self.beta < 0.0 or self.beta > 1.0: + self._value_error("`beta` must be within 0.0 and 1.0!") + + if self.postprocess_inputs is False and self.beta > 0.0: + self._value_error( + "`postprocess_inputs` must be True for MARWIL (to " + "calculate accum., discounted returns)! Try setting " + "`config.offline_data(postprocess_inputs=True)`." + ) + + # Assert that for a local learner the number of iterations is 1. Note, + # this is needed because we have no iterators, but instead a single + # batch returned directly from the `OfflineData.sample` method. + if ( + self.num_learners == 0 + and not self.dataset_num_iters_per_learner + and self.enable_rl_module_and_learner + ): + self._value_error( + "When using a local Learner (`config.num_learners=0`), the number of " + "iterations per learner (`dataset_num_iters_per_learner`) has to be " + "defined! Set this hyperparameter through `config.offline_data(" + "dataset_num_iters_per_learner=...)`." + ) + + @property + def _model_auto_keys(self): + return super()._model_auto_keys | {"beta": self.beta, "vf_share_layers": False} + + +class MARWIL(Algorithm): + @classmethod + @override(Algorithm) + def get_default_config(cls) -> AlgorithmConfig: + return MARWILConfig() + + @classmethod + @override(Algorithm) + def get_default_policy_class( + cls, config: AlgorithmConfig + ) -> Optional[Type[Policy]]: + if config["framework"] == "torch": + from ray.rllib.algorithms.marwil.marwil_torch_policy import ( + MARWILTorchPolicy, + ) + + return MARWILTorchPolicy + elif config["framework"] == "tf": + from ray.rllib.algorithms.marwil.marwil_tf_policy import ( + MARWILTF1Policy, + ) + + return MARWILTF1Policy + else: + from ray.rllib.algorithms.marwil.marwil_tf_policy import MARWILTF2Policy + + return MARWILTF2Policy + + @override(Algorithm) + def training_step(self) -> None: + """Implements training logic for the new stack + + Note, this includes so far training with the `OfflineData` + class (multi-/single-learner setup) and evaluation on + `EnvRunner`s. Note further, evaluation on the dataset itself + using estimators is not implemented, yet. + """ + # Old API stack (Policy, RolloutWorker, Connector). + if not self.config.enable_env_runner_and_connector_v2: + return self._training_step_old_api_stack() + + # TODO (simon): Take care of sampler metrics: right + # now all rewards are `nan`, which possibly confuses + # the user that sth. is not right, although it is as + # we do not step the env. + with self.metrics.log_time((TIMERS, OFFLINE_SAMPLING_TIMER)): + # If we should use an iterator in the learner(s). Note, in case of + # multiple learners we must always return a list of iterators. + return_iterator = ( + self.config.num_learners > 0 + or self.config.dataset_num_iters_per_learner != 1 + ) + + # Sampling from offline data. + batch_or_iterator = self.offline_data.sample( + num_samples=self.config.train_batch_size_per_learner, + num_shards=self.config.num_learners, + # Return an iterator, if a `Learner` should update + # multiple times per RLlib iteration. + return_iterator=return_iterator, + ) + if return_iterator: + training_data = TrainingData(data_iterators=batch_or_iterator) + else: + training_data = TrainingData(batch=batch_or_iterator) + + with self.metrics.log_time((TIMERS, LEARNER_UPDATE_TIMER)): + # Updating the policy. + learner_results = self.learner_group.update( + training_data=training_data, + minibatch_size=self.config.train_batch_size_per_learner, + num_iters=self.config.dataset_num_iters_per_learner, + **self.offline_data.iter_batches_kwargs, + ) + + # Log training results. + self.metrics.aggregate(learner_results, key=LEARNER_RESULTS) + + @OldAPIStack + def _training_step_old_api_stack(self) -> ResultDict: + """Implements training step for the old stack. + + Note, there is no hybrid stack anymore. If you need to use `RLModule`s, + use the new api stack. + """ + # Collect SampleBatches from sample workers. + with self._timers[SAMPLE_TIMER]: + train_batch = synchronous_parallel_sample(worker_set=self.env_runner_group) + train_batch = train_batch.as_multi_agent( + module_id=list(self.config.policies)[0] + ) + self._counters[NUM_AGENT_STEPS_SAMPLED] += train_batch.agent_steps() + self._counters[NUM_ENV_STEPS_SAMPLED] += train_batch.env_steps() + + # Train. + if self.config.simple_optimizer: + train_results = train_one_step(self, train_batch) + else: + train_results = multi_gpu_train_one_step(self, train_batch) + + # TODO: Move training steps counter update outside of `train_one_step()` method. + # # Update train step counters. + # self._counters[NUM_ENV_STEPS_TRAINED] += train_batch.env_steps() + # self._counters[NUM_AGENT_STEPS_TRAINED] += train_batch.agent_steps() + + global_vars = { + "timestep": self._counters[NUM_AGENT_STEPS_SAMPLED], + } + + # Update weights - after learning on the local worker - on all remote + # workers (only those policies that were actually trained). + if self.env_runner_group.num_remote_env_runners() > 0: + with self._timers[SYNCH_WORKER_WEIGHTS_TIMER]: + self.env_runner_group.sync_weights( + policies=list(train_results.keys()), global_vars=global_vars + ) + + # Update global vars on local worker as well. + self.env_runner.set_global_vars(global_vars) + + return train_results diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/marwil_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/marwil_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..363e6a84a30995a7866fa0605372262ef82b67e5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/marwil_learner.py @@ -0,0 +1,51 @@ +from typing import Dict, Optional + +from ray.rllib.core.rl_module.apis import ValueFunctionAPI +from ray.rllib.core.learner.learner import Learner +from ray.rllib.utils.annotations import override +from ray.rllib.utils.lambda_defaultdict import LambdaDefaultDict +from ray.rllib.utils.typing import ModuleID, ShouldModuleBeUpdatedFn, TensorType + +LEARNER_RESULTS_MOVING_AVG_SQD_ADV_NORM_KEY = "moving_avg_sqd_adv_norm" +LEARNER_RESULTS_VF_EXPLAINED_VAR_KEY = "vf_explained_variance" + + +# TODO (simon): Check, if the norm update should be done inside +# the Learner. +class MARWILLearner(Learner): + @override(Learner) + def build(self) -> None: + super().build() + + # Dict mapping module IDs to the respective moving averages of squared + # advantages. + self.moving_avg_sqd_adv_norms_per_module: Dict[ + ModuleID, TensorType + ] = LambdaDefaultDict( + lambda module_id: self._get_tensor_variable( + self.config.get_config_for_module( + module_id + ).moving_average_sqd_adv_norm_start + ) + ) + + @override(Learner) + def remove_module( + self, + module_id: ModuleID, + *, + new_should_module_be_updated: Optional[ShouldModuleBeUpdatedFn] = None, + ) -> None: + super().remove_module( + module_id, + new_should_module_be_updated=new_should_module_be_updated, + ) + # In case of BC (beta==0.0 and this property never being used), + self.moving_avg_sqd_adv_norms_per_module.pop(module_id, None) + + @classmethod + @override(Learner) + def rl_module_required_apis(cls) -> list[type]: + # In order for a PPOLearner to update an RLModule, it must implement the + # following APIs: + return [ValueFunctionAPI] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/marwil_tf_policy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/marwil_tf_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..5f75a8424c76690266d674bce1cdc0e60447e1fb --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/marwil_tf_policy.py @@ -0,0 +1,251 @@ +import logging +from typing import Any, Dict, List, Optional, Type, Union + +from ray.rllib.evaluation.postprocessing import compute_advantages, Postprocessing +from ray.rllib.models.action_dist import ActionDistribution +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.tf.tf_action_dist import TFActionDistribution +from ray.rllib.policy.dynamic_tf_policy_v2 import DynamicTFPolicyV2 +from ray.rllib.policy.eager_tf_policy_v2 import EagerTFPolicyV2 +from ray.rllib.policy.policy import Policy +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy.tf_mixins import ( + ValueNetworkMixin, + compute_gradients, +) +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_tf, get_variable +from ray.rllib.utils.tf_utils import explained_variance +from ray.rllib.utils.typing import ( + LocalOptimizer, + ModelGradients, + TensorType, +) + +tf1, tf, tfv = try_import_tf() + +logger = logging.getLogger(__name__) + + +class PostprocessAdvantages: + """Marwil's custom trajectory post-processing mixin.""" + + def __init__(self): + pass + + def postprocess_trajectory( + self, + sample_batch: SampleBatch, + other_agent_batches: Optional[Dict[Any, SampleBatch]] = None, + episode=None, + ): + sample_batch = super().postprocess_trajectory( + sample_batch, other_agent_batches, episode + ) + + # Trajectory is actually complete -> last r=0.0. + if sample_batch[SampleBatch.TERMINATEDS][-1]: + last_r = 0.0 + # Trajectory has been truncated -> last r=VF estimate of last obs. + else: + # Input dict is provided to us automatically via the Model's + # requirements. It's a single-timestep (last one in trajectory) + # input_dict. + # Create an input dict according to the Model's requirements. + index = "last" if SampleBatch.NEXT_OBS in sample_batch else -1 + input_dict = sample_batch.get_single_step_input_dict( + self.view_requirements, index=index + ) + last_r = self._value(**input_dict) + + # Adds the "advantages" (which in the case of MARWIL are simply the + # discounted cumulative rewards) to the SampleBatch. + return compute_advantages( + sample_batch, + last_r, + self.config["gamma"], + # We just want the discounted cumulative rewards, so we won't need + # GAE nor critic (use_critic=True: Subtract vf-estimates from returns). + use_gae=False, + use_critic=False, + ) + + +class MARWILLoss: + def __init__( + self, + policy: Policy, + value_estimates: TensorType, + action_dist: ActionDistribution, + train_batch: SampleBatch, + vf_loss_coeff: float, + beta: float, + ): + # L = - A * log\pi_\theta(a|s) + logprobs = action_dist.logp(train_batch[SampleBatch.ACTIONS]) + if beta != 0.0: + cumulative_rewards = train_batch[Postprocessing.ADVANTAGES] + # Advantage Estimation. + adv = cumulative_rewards - value_estimates + adv_squared = tf.reduce_mean(tf.math.square(adv)) + # Value function's loss term (MSE). + self.v_loss = 0.5 * adv_squared + + # Perform moving averaging of advantage^2. + rate = policy.config["moving_average_sqd_adv_norm_update_rate"] + + # Update averaged advantage norm. + # Eager. + if policy.config["framework"] == "tf2": + update_term = adv_squared - policy._moving_average_sqd_adv_norm + policy._moving_average_sqd_adv_norm.assign_add(rate * update_term) + + # Exponentially weighted advantages. + c = tf.math.sqrt(policy._moving_average_sqd_adv_norm) + exp_advs = tf.math.exp(beta * (adv / (1e-8 + c))) + # Static graph. + else: + update_adv_norm = tf1.assign_add( + ref=policy._moving_average_sqd_adv_norm, + value=rate * (adv_squared - policy._moving_average_sqd_adv_norm), + ) + + # Exponentially weighted advantages. + with tf1.control_dependencies([update_adv_norm]): + exp_advs = tf.math.exp( + beta + * tf.math.divide( + adv, + 1e-8 + tf.math.sqrt(policy._moving_average_sqd_adv_norm), + ) + ) + exp_advs = tf.stop_gradient(exp_advs) + + self.explained_variance = tf.reduce_mean( + explained_variance(cumulative_rewards, value_estimates) + ) + + else: + # Value function's loss term (MSE). + self.v_loss = tf.constant(0.0) + exp_advs = 1.0 + + # logprob loss alone tends to push action distributions to + # have very low entropy, resulting in worse performance for + # unfamiliar situations. + # A scaled logstd loss term encourages stochasticity, thus + # alleviate the problem to some extent. + logstd_coeff = policy.config["bc_logstd_coeff"] + if logstd_coeff > 0.0: + logstds = tf.reduce_sum(action_dist.log_std, axis=1) + else: + logstds = 0.0 + + self.p_loss = -1.0 * tf.reduce_mean( + exp_advs * (logprobs + logstd_coeff * logstds) + ) + + self.total_loss = self.p_loss + vf_loss_coeff * self.v_loss + + +# We need this builder function because we want to share the same +# custom logics between TF1 dynamic and TF2 eager policies. +def get_marwil_tf_policy(name: str, base: type) -> type: + """Construct a MARWILTFPolicy inheriting either dynamic or eager base policies. + + Args: + base: Base class for this policy. DynamicTFPolicyV2 or EagerTFPolicyV2. + + Returns: + A TF Policy to be used with MAML. + """ + + class MARWILTFPolicy(ValueNetworkMixin, PostprocessAdvantages, base): + def __init__( + self, + observation_space, + action_space, + config, + existing_model=None, + existing_inputs=None, + ): + # First thing first, enable eager execution if necessary. + base.enable_eager_execution_if_necessary() + + # Initialize base class. + base.__init__( + self, + observation_space, + action_space, + config, + existing_inputs=existing_inputs, + existing_model=existing_model, + ) + + ValueNetworkMixin.__init__(self, config) + PostprocessAdvantages.__init__(self) + + # Not needed for pure BC. + if config["beta"] != 0.0: + # Set up a tf-var for the moving avg (do this here to make it work + # with eager mode); "c^2" in the paper. + self._moving_average_sqd_adv_norm = get_variable( + config["moving_average_sqd_adv_norm_start"], + framework="tf", + tf_name="moving_average_of_advantage_norm", + trainable=False, + ) + + # Note: this is a bit ugly, but loss and optimizer initialization must + # happen after all the MixIns are initialized. + self.maybe_initialize_optimizer_and_loss() + + @override(base) + def loss( + self, + model: Union[ModelV2, "tf.keras.Model"], + dist_class: Type[TFActionDistribution], + train_batch: SampleBatch, + ) -> Union[TensorType, List[TensorType]]: + model_out, _ = model(train_batch) + action_dist = dist_class(model_out, model) + value_estimates = model.value_function() + + self._marwil_loss = MARWILLoss( + self, + value_estimates, + action_dist, + train_batch, + self.config["vf_coeff"], + self.config["beta"], + ) + + return self._marwil_loss.total_loss + + @override(base) + def stats_fn(self, train_batch: SampleBatch) -> Dict[str, TensorType]: + stats = { + "policy_loss": self._marwil_loss.p_loss, + "total_loss": self._marwil_loss.total_loss, + } + if self.config["beta"] != 0.0: + stats["moving_average_sqd_adv_norm"] = self._moving_average_sqd_adv_norm + stats["vf_explained_var"] = self._marwil_loss.explained_variance + stats["vf_loss"] = self._marwil_loss.v_loss + + return stats + + @override(base) + def compute_gradients_fn( + self, optimizer: LocalOptimizer, loss: TensorType + ) -> ModelGradients: + return compute_gradients(self, optimizer, loss) + + MARWILTFPolicy.__name__ = name + MARWILTFPolicy.__qualname__ = name + + return MARWILTFPolicy + + +MARWILTF1Policy = get_marwil_tf_policy("MARWILTF1Policy", DynamicTFPolicyV2) +MARWILTF2Policy = get_marwil_tf_policy("MARWILTF2Policy", EagerTFPolicyV2) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/marwil_torch_policy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/marwil_torch_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..219a0b176d918fd34a123ef1ea66d921660a19e4 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/marwil_torch_policy.py @@ -0,0 +1,132 @@ +from typing import Dict, List, Type, Union + +from ray.rllib.algorithms.marwil.marwil_tf_policy import PostprocessAdvantages +from ray.rllib.evaluation.postprocessing import Postprocessing +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.torch.torch_action_dist import TorchDistributionWrapper +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy.torch_mixins import ValueNetworkMixin +from ray.rllib.policy.torch_policy_v2 import TorchPolicyV2 +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.torch_utils import apply_grad_clipping, explained_variance +from ray.rllib.utils.typing import TensorType + +torch, _ = try_import_torch() + + +class MARWILTorchPolicy(ValueNetworkMixin, PostprocessAdvantages, TorchPolicyV2): + """PyTorch policy class used with Marwil.""" + + def __init__(self, observation_space, action_space, config): + TorchPolicyV2.__init__( + self, + observation_space, + action_space, + config, + max_seq_len=config["model"]["max_seq_len"], + ) + + ValueNetworkMixin.__init__(self, config) + PostprocessAdvantages.__init__(self) + + # Not needed for pure BC. + if config["beta"] != 0.0: + # Set up a torch-var for the squared moving avg. advantage norm. + self._moving_average_sqd_adv_norm = torch.tensor( + [config["moving_average_sqd_adv_norm_start"]], + dtype=torch.float32, + requires_grad=False, + ).to(self.device) + + # TODO: Don't require users to call this manually. + self._initialize_loss_from_dummy_batch() + + @override(TorchPolicyV2) + def loss( + self, + model: ModelV2, + dist_class: Type[TorchDistributionWrapper], + train_batch: SampleBatch, + ) -> Union[TensorType, List[TensorType]]: + model_out, _ = model(train_batch) + action_dist = dist_class(model_out, model) + actions = train_batch[SampleBatch.ACTIONS] + # log\pi_\theta(a|s) + logprobs = action_dist.logp(actions) + + # Advantage estimation. + if self.config["beta"] != 0.0: + cumulative_rewards = train_batch[Postprocessing.ADVANTAGES] + state_values = model.value_function() + adv = cumulative_rewards - state_values + adv_squared_mean = torch.mean(torch.pow(adv, 2.0)) + + explained_var = explained_variance(cumulative_rewards, state_values) + ev = torch.mean(explained_var) + model.tower_stats["explained_variance"] = ev + + # Policy loss. + # Update averaged advantage norm. + rate = self.config["moving_average_sqd_adv_norm_update_rate"] + self._moving_average_sqd_adv_norm = ( + rate * (adv_squared_mean.detach() - self._moving_average_sqd_adv_norm) + + self._moving_average_sqd_adv_norm + ) + model.tower_stats[ + "_moving_average_sqd_adv_norm" + ] = self._moving_average_sqd_adv_norm + # Exponentially weighted advantages. + exp_advs = torch.exp( + self.config["beta"] + * (adv / (1e-8 + torch.pow(self._moving_average_sqd_adv_norm, 0.5))) + ).detach() + # Value loss. + v_loss = 0.5 * adv_squared_mean + else: + # Policy loss (simple BC loss term). + exp_advs = 1.0 + # Value loss. + v_loss = 0.0 + model.tower_stats["v_loss"] = v_loss + # logprob loss alone tends to push action distributions to + # have very low entropy, resulting in worse performance for + # unfamiliar situations. + # A scaled logstd loss term encourages stochasticity, thus + # alleviate the problem to some extent. + logstd_coeff = self.config["bc_logstd_coeff"] + if logstd_coeff > 0.0: + logstds = torch.mean(action_dist.log_std, dim=1) + else: + logstds = 0.0 + + p_loss = -torch.mean(exp_advs * (logprobs + logstd_coeff * logstds)) + model.tower_stats["p_loss"] = p_loss + # Combine both losses. + self.v_loss = v_loss + self.p_loss = p_loss + total_loss = p_loss + self.config["vf_coeff"] * v_loss + model.tower_stats["total_loss"] = total_loss + return total_loss + + @override(TorchPolicyV2) + def stats_fn(self, train_batch: SampleBatch) -> Dict[str, TensorType]: + stats = { + "policy_loss": self.get_tower_stats("p_loss")[0].item(), + "total_loss": self.get_tower_stats("total_loss")[0].item(), + } + if self.config["beta"] != 0.0: + stats["moving_average_sqd_adv_norm"] = self.get_tower_stats( + "_moving_average_sqd_adv_norm" + )[0].item() + stats["vf_explained_var"] = self.get_tower_stats("explained_variance")[ + 0 + ].item() + stats["vf_loss"] = self.get_tower_stats("v_loss")[0].item() + return convert_to_numpy(stats) + + def extra_grad_process( + self, optimizer: "torch.optim.Optimizer", loss: TensorType + ) -> Dict[str, TensorType]: + return apply_grad_clipping(self, optimizer, loss) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/torch/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/torch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/torch/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/torch/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e859b5983a87903185381d1490bef1ead9cba38f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/torch/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/torch/__pycache__/marwil_torch_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/torch/__pycache__/marwil_torch_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b1bc30c95d0af88b303b3457fce053b9d1163c6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/torch/__pycache__/marwil_torch_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/torch/marwil_torch_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/torch/marwil_torch_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..a61eb3bde13596b515497aac396383b4cbb08068 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/marwil/torch/marwil_torch_learner.py @@ -0,0 +1,138 @@ +from typing import Any, Dict, Optional + +from ray.rllib.algorithms.marwil.marwil import MARWILConfig +from ray.rllib.algorithms.marwil.marwil_learner import ( + LEARNER_RESULTS_MOVING_AVG_SQD_ADV_NORM_KEY, + LEARNER_RESULTS_VF_EXPLAINED_VAR_KEY, + MARWILLearner, +) +from ray.rllib.core.columns import Columns +from ray.rllib.core.learner.learner import POLICY_LOSS_KEY, VF_LOSS_KEY +from ray.rllib.core.learner.torch.torch_learner import TorchLearner +from ray.rllib.evaluation.postprocessing import Postprocessing +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.torch_utils import explained_variance +from ray.rllib.utils.typing import TensorType + +torch, nn = try_import_torch() + + +class MARWILTorchLearner(MARWILLearner, TorchLearner): + """Implements torch-specific MARWIL loss on top of MARWILLearner. + + This class implements the MARWIL loss under `self.compute_loss_for_module()`. + """ + + def compute_loss_for_module( + self, + *, + module_id: str, + config: Optional[MARWILConfig] = None, + batch: Dict[str, Any], + fwd_out: Dict[str, TensorType] + ) -> TensorType: + module = self.module[module_id].unwrapped() + + # Possibly apply masking to some sub loss terms and to the total loss term + # at the end. Masking could be used for RNN-based model (zero padded `batch`) + # and for PPO's batched value function (and bootstrap value) computations, + # for which we add an additional (artificial) timestep to each episode to + # simplify the actual computation. + if Columns.LOSS_MASK in batch: + num_valid = torch.sum(batch[Columns.LOSS_MASK]) + + def possibly_masked_mean(data_): + return torch.sum(data_[batch[Columns.LOSS_MASK]]) / num_valid + + else: + possibly_masked_mean = torch.mean + + action_dist_class_train = module.get_train_action_dist_cls() + curr_action_dist = action_dist_class_train.from_logits( + fwd_out[Columns.ACTION_DIST_INPUTS] + ) + + log_probs = curr_action_dist.logp(batch[Columns.ACTIONS]) + + # If beta is zero, we fall back to BC. + if config.beta == 0.0: + # Value function's loss term. + mean_vf_loss = 0.0 + # Policy's loss term. + exp_weighted_advantages = 1.0 + # Otherwise, compute advantages. + else: + # cumulative_rewards = batch[Columns.ADVANTAGES] + value_fn_out = module.compute_values( + batch, embeddings=fwd_out.get(Columns.EMBEDDINGS) + ) + advantages = batch[Columns.VALUE_TARGETS] - value_fn_out + advantages_squared_mean = possibly_masked_mean(torch.pow(advantages, 2.0)) + + # Compute the value loss. + mean_vf_loss = 0.5 * advantages_squared_mean + + # Compute the policy loss. + self.moving_avg_sqd_adv_norms_per_module[module_id] = ( + config.moving_average_sqd_adv_norm_update_rate + * ( + advantages_squared_mean.detach() + - self.moving_avg_sqd_adv_norms_per_module[module_id] + ) + + self.moving_avg_sqd_adv_norms_per_module[module_id] + ) + # Exponentially weighted advantages. + # TODO (simon): Check, if we need the mask here. + exp_weighted_advantages = torch.exp( + config.beta + * ( + advantages + / ( + 1e-8 + + torch.pow( + self.moving_avg_sqd_adv_norms_per_module[module_id], 0.5 + ) + ) + ) + ).detach() + + # Note, using solely a log-probability loss term tends to push the action + # distributions to have very low entropy, which results in worse performance + # specifically in unknown situations. + # Scaling the loss term with the logarithm of the action distribution's + # standard deviation encourages stochasticity in the policy. + if config.bc_logstd_coeff > 0.0: + log_stds = possibly_masked_mean(curr_action_dist.log_std, dim=1) + else: + log_stds = 0.0 + + # Compute the policy loss. + policy_loss = -possibly_masked_mean( + exp_weighted_advantages * (log_probs + config.bc_logstd_coeff * log_stds) + ) + + # Compute the total loss. + total_loss = policy_loss + config.vf_coeff * mean_vf_loss + + # Log import loss stats. In case of the BC loss this is simply + # the policy loss. + if config.beta == 0.0: + self.metrics.log_value((module_id, POLICY_LOSS_KEY), policy_loss, window=1) + # Log more stats, if using the MARWIL loss. + else: + ma_sqd_adv_norms = self.moving_avg_sqd_adv_norms_per_module[module_id] + self.metrics.log_dict( + { + POLICY_LOSS_KEY: policy_loss, + VF_LOSS_KEY: mean_vf_loss, + LEARNER_RESULTS_VF_EXPLAINED_VAR_KEY: explained_variance( + batch[Postprocessing.VALUE_TARGETS], value_fn_out + ), + LEARNER_RESULTS_MOVING_AVG_SQD_ADV_NORM_KEY: ma_sqd_adv_norms, + }, + key=module_id, + window=1, # <- single items (should not be mean/ema-reduced over time). + ) + + # Return the total loss. + return total_loss diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/mock.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/mock.py new file mode 100644 index 0000000000000000000000000000000000000000..25707cf1677bde58226f56b1879da6b69c1a73d3 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/mock.py @@ -0,0 +1,154 @@ +import os +import pickle +import time + +import numpy as np + +from ray.tune import result as tune_result +from ray.rllib.algorithms.algorithm import Algorithm, AlgorithmConfig +from ray.rllib.utils.annotations import override + + +class _MockTrainer(Algorithm): + """Mock Algorithm for use in tests.""" + + @classmethod + @override(Algorithm) + def get_default_config(cls) -> AlgorithmConfig: + return ( + AlgorithmConfig() + .framework("tf") + .update_from_dict( + { + "mock_error": False, + "persistent_error": False, + "test_variable": 1, + "user_checkpoint_freq": 0, + "sleep": 0, + } + ) + ) + + @classmethod + def default_resource_request(cls, config: AlgorithmConfig): + return None + + @override(Algorithm) + def setup(self, config): + self.callbacks = self.config.callbacks_class() + + # Add needed properties. + self.info = None + self.restored = False + + @override(Algorithm) + def step(self): + if ( + self.config.mock_error + and self.iteration == 1 + and (self.config.persistent_error or not self.restored) + ): + raise Exception("mock error") + if self.config.sleep: + time.sleep(self.config.sleep) + result = dict( + episode_reward_mean=10, episode_len_mean=10, timesteps_this_iter=10, info={} + ) + if self.config.user_checkpoint_freq > 0 and self.iteration > 0: + if self.iteration % self.config.user_checkpoint_freq == 0: + result.update({tune_result.SHOULD_CHECKPOINT: True}) + return result + + @override(Algorithm) + def save_checkpoint(self, checkpoint_dir): + path = os.path.join(checkpoint_dir, "mock_agent.pkl") + with open(path, "wb") as f: + pickle.dump(self.info, f) + + @override(Algorithm) + def load_checkpoint(self, checkpoint_dir): + path = os.path.join(checkpoint_dir, "mock_agent.pkl") + with open(path, "rb") as f: + info = pickle.load(f) + self.info = info + self.restored = True + + @staticmethod + @override(Algorithm) + def _get_env_id_and_creator(env_specifier, config): + # No env to register. + return None, None + + def set_info(self, info): + self.info = info + return info + + def get_info(self, sess=None): + return self.info + + +class _SigmoidFakeData(_MockTrainer): + """Algorithm that returns sigmoid learning curves. + + This can be helpful for evaluating early stopping algorithms.""" + + @classmethod + @override(Algorithm) + def get_default_config(cls) -> AlgorithmConfig: + return AlgorithmConfig().update_from_dict( + { + "width": 100, + "height": 100, + "offset": 0, + "iter_time": 10, + "iter_timesteps": 1, + } + ) + + def step(self): + i = max(0, self.iteration - self.config.offset) + v = np.tanh(float(i) / self.config.width) + v *= self.config.height + return dict( + episode_reward_mean=v, + episode_len_mean=v, + timesteps_this_iter=self.config.iter_timesteps, + time_this_iter_s=self.config.iter_time, + info={}, + ) + + +class _ParameterTuningTrainer(_MockTrainer): + @classmethod + @override(Algorithm) + def get_default_config(cls) -> AlgorithmConfig: + return AlgorithmConfig().update_from_dict( + { + "reward_amt": 10, + "dummy_param": 10, + "dummy_param2": 15, + "iter_time": 10, + "iter_timesteps": 1, + } + ) + + def step(self): + return dict( + episode_reward_mean=self.config.reward_amt * self.iteration, + episode_len_mean=self.config.reward_amt, + timesteps_this_iter=self.config.iter_timesteps, + time_this_iter_s=self.config.iter_time, + info={}, + ) + + +def _algorithm_import_failed(trace): + """Returns dummy Algorithm class for if PyTorch etc. is not installed.""" + + class _AlgorithmImportFailed(Algorithm): + _name = "AlgorithmImportFailed" + + def setup(self, config): + raise ImportError(trace) + + return _AlgorithmImportFailed diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a02982e64a5363a585a0f125ab3eaa8ff2481fda --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/__init__.py @@ -0,0 +1,12 @@ +from ray.rllib.algorithms.ppo.ppo import PPOConfig, PPO +from ray.rllib.algorithms.ppo.ppo_tf_policy import PPOTF1Policy, PPOTF2Policy +from ray.rllib.algorithms.ppo.ppo_torch_policy import PPOTorchPolicy + +__all__ = [ + "PPO", + "PPOConfig", + # @OldAPIStack + "PPOTF1Policy", + "PPOTF2Policy", + "PPOTorchPolicy", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11413db4fabf4795a638ea7e6837aed35da59c29 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/__pycache__/default_ppo_rl_module.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/__pycache__/default_ppo_rl_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..918a47f6c24354a627ae28e61d1fea45f1a451ad Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/__pycache__/default_ppo_rl_module.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/__pycache__/ppo.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/__pycache__/ppo.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57a1d33419f1227bc4d40d38efbe42876fd0e658 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/__pycache__/ppo.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/__pycache__/ppo_catalog.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/__pycache__/ppo_catalog.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba4b7dbe5c3b4da9fb2ba96fa650ebd5f55658d7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/__pycache__/ppo_catalog.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/__pycache__/ppo_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/__pycache__/ppo_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..beb2f2be4a3e877d08ed31dad2e8ec6b31923a82 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/__pycache__/ppo_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/__pycache__/ppo_rl_module.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/__pycache__/ppo_rl_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..575cf49061c187fae7b11967f7c8d12a628e1e91 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/__pycache__/ppo_rl_module.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/__pycache__/ppo_tf_policy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/__pycache__/ppo_tf_policy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d68cdaf89f527dc5859b2931a23b946799ca7d3a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/__pycache__/ppo_tf_policy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/__pycache__/ppo_torch_policy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/__pycache__/ppo_torch_policy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15ef01ef6a8c54ab23a735dc91e376b442f83ed1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/__pycache__/ppo_torch_policy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/default_ppo_rl_module.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/default_ppo_rl_module.py new file mode 100644 index 0000000000000000000000000000000000000000..1216eeef0d75fd5e00cf3b9e2321a9dc7c962fc5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/default_ppo_rl_module.py @@ -0,0 +1,62 @@ +import abc +from typing import List + +from ray.rllib.core.models.configs import RecurrentEncoderConfig +from ray.rllib.core.rl_module.apis import InferenceOnlyAPI, ValueFunctionAPI +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import ( + override, + OverrideToImplementCustomLogic_CallToSuperRecommended, +) +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +class DefaultPPORLModule(RLModule, InferenceOnlyAPI, ValueFunctionAPI, abc.ABC): + """Default RLModule used by PPO, if user does not specify a custom RLModule. + + Users who want to train their RLModules with PPO may implement any RLModule + (or TorchRLModule) subclass as long as the custom class also implements the + `ValueFunctionAPI` (see ray.rllib.core.rl_module.apis.value_function_api.py) + """ + + @override(RLModule) + def setup(self): + # __sphinx_doc_begin__ + # If we have a stateful model, states for the critic need to be collected + # during sampling and `inference-only` needs to be `False`. Note, at this + # point the encoder is not built, yet and therefore `is_stateful()` does + # not work. + is_stateful = isinstance( + self.catalog.actor_critic_encoder_config.base_encoder_config, + RecurrentEncoderConfig, + ) + if is_stateful: + self.inference_only = False + # If this is an `inference_only` Module, we'll have to pass this information + # to the encoder config as well. + if self.inference_only and self.framework == "torch": + self.catalog.actor_critic_encoder_config.inference_only = True + + # Build models from catalog. + self.encoder = self.catalog.build_actor_critic_encoder(framework=self.framework) + self.pi = self.catalog.build_pi_head(framework=self.framework) + self.vf = self.catalog.build_vf_head(framework=self.framework) + # __sphinx_doc_end__ + + @override(RLModule) + def get_initial_state(self) -> dict: + if hasattr(self.encoder, "get_initial_state"): + return self.encoder.get_initial_state() + else: + return {} + + @OverrideToImplementCustomLogic_CallToSuperRecommended + @override(InferenceOnlyAPI) + def get_non_inference_attributes(self) -> List[str]: + """Return attributes, which are NOT inference-only (only used for training).""" + return ["vf"] + ( + [] + if self.model_config.get("vf_share_layers") + else ["encoder.critic_encoder"] + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/ppo.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/ppo.py new file mode 100644 index 0000000000000000000000000000000000000000..2b28c5bd91c81ec2abd9bb77c750f2ed200f431a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/ppo.py @@ -0,0 +1,557 @@ +""" +Proximal Policy Optimization (PPO) +================================== + +This file defines the distributed Algorithm class for proximal policy +optimization. +See `ppo_[tf|torch]_policy.py` for the definition of the policy loss. + +Detailed documentation: https://docs.ray.io/en/master/rllib-algorithms.html#ppo +""" + +import logging +from typing import Any, Dict, List, Optional, Type, Union, TYPE_CHECKING + +from ray.rllib.algorithms.algorithm import Algorithm +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig, NotProvided +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.execution.rollout_ops import ( + standardize_fields, + synchronous_parallel_sample, +) +from ray.rllib.execution.train_ops import ( + train_one_step, + multi_gpu_train_one_step, +) +from ray.rllib.policy.policy import Policy +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.deprecation import DEPRECATED_VALUE +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + ENV_RUNNER_SAMPLING_TIMER, + LEARNER_RESULTS, + LEARNER_UPDATE_TIMER, + NUM_AGENT_STEPS_SAMPLED, + NUM_ENV_STEPS_SAMPLED, + NUM_ENV_STEPS_SAMPLED_LIFETIME, + SYNCH_WORKER_WEIGHTS_TIMER, + SAMPLE_TIMER, + TIMERS, + ALL_MODULES, +) +from ray.rllib.utils.metrics.learner_info import LEARNER_STATS_KEY +from ray.rllib.utils.schedules.scheduler import Scheduler +from ray.rllib.utils.typing import ResultDict +from ray.util.debug import log_once + +if TYPE_CHECKING: + from ray.rllib.core.learner.learner import Learner + + +logger = logging.getLogger(__name__) + +LEARNER_RESULTS_VF_LOSS_UNCLIPPED_KEY = "vf_loss_unclipped" +LEARNER_RESULTS_VF_EXPLAINED_VAR_KEY = "vf_explained_var" +LEARNER_RESULTS_KL_KEY = "mean_kl_loss" +LEARNER_RESULTS_CURR_KL_COEFF_KEY = "curr_kl_coeff" +LEARNER_RESULTS_CURR_ENTROPY_COEFF_KEY = "curr_entropy_coeff" + + +class PPOConfig(AlgorithmConfig): + """Defines a configuration class from which a PPO Algorithm can be built. + + .. testcode:: + + from ray.rllib.algorithms.ppo import PPOConfig + + config = PPOConfig() + config.environment("CartPole-v1") + config.env_runners(num_env_runners=1) + config.training( + gamma=0.9, lr=0.01, kl_coeff=0.3, train_batch_size_per_learner=256 + ) + + # Build a Algorithm object from the config and run 1 training iteration. + algo = config.build() + algo.train() + + .. testcode:: + + from ray.rllib.algorithms.ppo import PPOConfig + from ray import tune + + config = ( + PPOConfig() + # Set the config object's env. + .environment(env="CartPole-v1") + # Update the config object's training parameters. + .training( + lr=0.001, clip_param=0.2 + ) + ) + + tune.Tuner( + "PPO", + run_config=tune.RunConfig(stop={"training_iteration": 1}), + param_space=config, + ).fit() + + .. testoutput:: + :hide: + + ... + """ + + def __init__(self, algo_class=None): + """Initializes a PPOConfig instance.""" + self.exploration_config = { + # The Exploration class to use. In the simplest case, this is the name + # (str) of any class present in the `rllib.utils.exploration` package. + # You can also provide the python class directly or the full location + # of your class (e.g. "ray.rllib.utils.exploration.epsilon_greedy. + # EpsilonGreedy"). + "type": "StochasticSampling", + # Add constructor kwargs here (if any). + } + + super().__init__(algo_class=algo_class or PPO) + + # fmt: off + # __sphinx_doc_begin__ + self.lr = 5e-5 + self.rollout_fragment_length = "auto" + self.train_batch_size = 4000 + + # PPO specific settings: + self.use_critic = True + self.use_gae = True + self.num_epochs = 30 + self.minibatch_size = 128 + self.shuffle_batch_per_epoch = True + self.lambda_ = 1.0 + self.use_kl_loss = True + self.kl_coeff = 0.2 + self.kl_target = 0.01 + self.vf_loss_coeff = 1.0 + self.entropy_coeff = 0.0 + self.clip_param = 0.3 + self.vf_clip_param = 10.0 + self.grad_clip = None + + # Override some of AlgorithmConfig's default values with PPO-specific values. + self.num_env_runners = 2 + # __sphinx_doc_end__ + # fmt: on + + self.model["vf_share_layers"] = False # @OldAPIStack + self.entropy_coeff_schedule = None # @OldAPIStack + self.lr_schedule = None # @OldAPIStack + + # Deprecated keys. + self.sgd_minibatch_size = DEPRECATED_VALUE + self.vf_share_layers = DEPRECATED_VALUE + + @override(AlgorithmConfig) + def get_default_rl_module_spec(self) -> RLModuleSpec: + if self.framework_str == "torch": + from ray.rllib.algorithms.ppo.torch.default_ppo_torch_rl_module import ( + DefaultPPOTorchRLModule, + ) + + return RLModuleSpec(module_class=DefaultPPOTorchRLModule) + else: + raise ValueError( + f"The framework {self.framework_str} is not supported. " + "Use either 'torch' or 'tf2'." + ) + + @override(AlgorithmConfig) + def get_default_learner_class(self) -> Union[Type["Learner"], str]: + if self.framework_str == "torch": + from ray.rllib.algorithms.ppo.torch.ppo_torch_learner import ( + PPOTorchLearner, + ) + + return PPOTorchLearner + elif self.framework_str in ["tf2", "tf"]: + raise ValueError( + "TensorFlow is no longer supported on the new API stack! " + "Use `framework='torch'`." + ) + else: + raise ValueError( + f"The framework {self.framework_str} is not supported. " + "Use `framework='torch'`." + ) + + @override(AlgorithmConfig) + def training( + self, + *, + use_critic: Optional[bool] = NotProvided, + use_gae: Optional[bool] = NotProvided, + lambda_: Optional[float] = NotProvided, + use_kl_loss: Optional[bool] = NotProvided, + kl_coeff: Optional[float] = NotProvided, + kl_target: Optional[float] = NotProvided, + vf_loss_coeff: Optional[float] = NotProvided, + entropy_coeff: Optional[float] = NotProvided, + entropy_coeff_schedule: Optional[List[List[Union[int, float]]]] = NotProvided, + clip_param: Optional[float] = NotProvided, + vf_clip_param: Optional[float] = NotProvided, + grad_clip: Optional[float] = NotProvided, + # @OldAPIStack + lr_schedule: Optional[List[List[Union[int, float]]]] = NotProvided, + # Deprecated. + vf_share_layers=DEPRECATED_VALUE, + **kwargs, + ) -> "PPOConfig": + """Sets the training related configuration. + + Args: + use_critic: Should use a critic as a baseline (otherwise don't use value + baseline; required for using GAE). + use_gae: If true, use the Generalized Advantage Estimator (GAE) + with a value function, see https://arxiv.org/pdf/1506.02438.pdf. + lambda_: The lambda parameter for General Advantage Estimation (GAE). + Defines the exponential weight used between actually measured rewards + vs value function estimates over multiple time steps. Specifically, + `lambda_` balances short-term, low-variance estimates against long-term, + high-variance returns. A `lambda_` of 0.0 makes the GAE rely only on + immediate rewards (and vf predictions from there on, reducing variance, + but increasing bias), while a `lambda_` of 1.0 only incorporates vf + predictions at the truncation points of the given episodes or episode + chunks (reducing bias but increasing variance). + use_kl_loss: Whether to use the KL-term in the loss function. + kl_coeff: Initial coefficient for KL divergence. + kl_target: Target value for KL divergence. + vf_loss_coeff: Coefficient of the value function loss. IMPORTANT: you must + tune this if you set vf_share_layers=True inside your model's config. + entropy_coeff: The entropy coefficient (float) or entropy coefficient + schedule in the format of + [[timestep, coeff-value], [timestep, coeff-value], ...] + In case of a schedule, intermediary timesteps will be assigned to + linearly interpolated coefficient values. A schedule config's first + entry must start with timestep 0, i.e.: [[0, initial_value], [...]]. + clip_param: The PPO clip parameter. + vf_clip_param: Clip param for the value function. Note that this is + sensitive to the scale of the rewards. If your expected V is large, + increase this. + grad_clip: If specified, clip the global norm of gradients by this amount. + + Returns: + This updated AlgorithmConfig object. + """ + # Pass kwargs onto super's `training()` method. + super().training(**kwargs) + + if use_critic is not NotProvided: + self.use_critic = use_critic + # TODO (Kourosh) This is experimental. + # Don't forget to remove .use_critic from algorithm config. + if use_gae is not NotProvided: + self.use_gae = use_gae + if lambda_ is not NotProvided: + self.lambda_ = lambda_ + if use_kl_loss is not NotProvided: + self.use_kl_loss = use_kl_loss + if kl_coeff is not NotProvided: + self.kl_coeff = kl_coeff + if kl_target is not NotProvided: + self.kl_target = kl_target + if vf_loss_coeff is not NotProvided: + self.vf_loss_coeff = vf_loss_coeff + if entropy_coeff is not NotProvided: + self.entropy_coeff = entropy_coeff + if clip_param is not NotProvided: + self.clip_param = clip_param + if vf_clip_param is not NotProvided: + self.vf_clip_param = vf_clip_param + if grad_clip is not NotProvided: + self.grad_clip = grad_clip + + # TODO (sven): Remove these once new API stack is only option for PPO. + if lr_schedule is not NotProvided: + self.lr_schedule = lr_schedule + if entropy_coeff_schedule is not NotProvided: + self.entropy_coeff_schedule = entropy_coeff_schedule + + return self + + @override(AlgorithmConfig) + def validate(self) -> None: + # Call super's validation method. + super().validate() + + # Synchronous sampling, on-policy/PPO algos -> Check mismatches between + # `rollout_fragment_length` and `train_batch_size_per_learner` to avoid user + # confusion. + # TODO (sven): Make rollout_fragment_length a property and create a private + # attribute to store (possibly) user provided value (or "auto") in. Deprecate + # `self.get_rollout_fragment_length()`. + self.validate_train_batch_size_vs_rollout_fragment_length() + + # SGD minibatch size must be smaller than train_batch_size (b/c + # we subsample a batch of `minibatch_size` from the train-batch for + # each `num_epochs`). + if ( + not self.enable_rl_module_and_learner + and self.minibatch_size > self.train_batch_size + ): + self._value_error( + f"`minibatch_size` ({self.minibatch_size}) must be <= " + f"`train_batch_size` ({self.train_batch_size}). In PPO, the train batch" + f" will be split into {self.minibatch_size} chunks, each of which " + f"is iterated over (used for updating the policy) {self.num_epochs} " + "times." + ) + elif self.enable_rl_module_and_learner: + mbs = self.minibatch_size + tbs = self.train_batch_size_per_learner or self.train_batch_size + if isinstance(mbs, int) and isinstance(tbs, int) and mbs > tbs: + self._value_error( + f"`minibatch_size` ({mbs}) must be <= " + f"`train_batch_size_per_learner` ({tbs}). In PPO, the train batch" + f" will be split into {mbs} chunks, each of which is iterated over " + f"(used for updating the policy) {self.num_epochs} times." + ) + + # Episodes may only be truncated (and passed into PPO's + # `postprocessing_fn`), iff generalized advantage estimation is used + # (value function estimate at end of truncated episode to estimate + # remaining value). + if ( + not self.in_evaluation + and self.batch_mode == "truncate_episodes" + and not self.use_gae + ): + self._value_error( + "Episode truncation is not supported without a value " + "function (to estimate the return at the end of the truncated" + " trajectory). Consider setting " + "batch_mode=complete_episodes." + ) + + # New API stack checks. + if self.enable_rl_module_and_learner: + # `lr_schedule` checking. + if self.lr_schedule is not None: + self._value_error( + "`lr_schedule` is deprecated and must be None! Use the " + "`lr` setting to setup a schedule." + ) + if self.entropy_coeff_schedule is not None: + self._value_error( + "`entropy_coeff_schedule` is deprecated and must be None! Use the " + "`entropy_coeff` setting to setup a schedule." + ) + Scheduler.validate( + fixed_value_or_schedule=self.entropy_coeff, + setting_name="entropy_coeff", + description="entropy coefficient", + ) + if isinstance(self.entropy_coeff, float) and self.entropy_coeff < 0.0: + self._value_error("`entropy_coeff` must be >= 0.0") + + @property + @override(AlgorithmConfig) + def _model_config_auto_includes(self) -> Dict[str, Any]: + return super()._model_config_auto_includes | {"vf_share_layers": False} + + +class PPO(Algorithm): + @classmethod + @override(Algorithm) + def get_default_config(cls) -> AlgorithmConfig: + return PPOConfig() + + @classmethod + @override(Algorithm) + def get_default_policy_class( + cls, config: AlgorithmConfig + ) -> Optional[Type[Policy]]: + if config["framework"] == "torch": + + from ray.rllib.algorithms.ppo.ppo_torch_policy import PPOTorchPolicy + + return PPOTorchPolicy + elif config["framework"] == "tf": + from ray.rllib.algorithms.ppo.ppo_tf_policy import PPOTF1Policy + + return PPOTF1Policy + else: + from ray.rllib.algorithms.ppo.ppo_tf_policy import PPOTF2Policy + + return PPOTF2Policy + + @override(Algorithm) + def training_step(self) -> None: + # Old API stack (Policy, RolloutWorker, Connector). + if not self.config.enable_env_runner_and_connector_v2: + return self._training_step_old_api_stack() + + # Collect batches from sample workers until we have a full batch. + with self.metrics.log_time((TIMERS, ENV_RUNNER_SAMPLING_TIMER)): + # Sample in parallel from the workers. + if self.config.count_steps_by == "agent_steps": + episodes, env_runner_results = synchronous_parallel_sample( + worker_set=self.env_runner_group, + max_agent_steps=self.config.total_train_batch_size, + sample_timeout_s=self.config.sample_timeout_s, + _uses_new_env_runners=( + self.config.enable_env_runner_and_connector_v2 + ), + _return_metrics=True, + ) + else: + episodes, env_runner_results = synchronous_parallel_sample( + worker_set=self.env_runner_group, + max_env_steps=self.config.total_train_batch_size, + sample_timeout_s=self.config.sample_timeout_s, + _uses_new_env_runners=( + self.config.enable_env_runner_and_connector_v2 + ), + _return_metrics=True, + ) + # Return early if all our workers failed. + if not episodes: + return + + # Reduce EnvRunner metrics over the n EnvRunners. + self.metrics.aggregate(env_runner_results, key=ENV_RUNNER_RESULTS) + + # Perform a learner update step on the collected episodes. + with self.metrics.log_time((TIMERS, LEARNER_UPDATE_TIMER)): + learner_results = self.learner_group.update( + episodes=episodes, + timesteps={ + NUM_ENV_STEPS_SAMPLED_LIFETIME: ( + self.metrics.peek( + (ENV_RUNNER_RESULTS, NUM_ENV_STEPS_SAMPLED_LIFETIME) + ) + ), + }, + num_epochs=self.config.num_epochs, + minibatch_size=self.config.minibatch_size, + shuffle_batch_per_epoch=self.config.shuffle_batch_per_epoch, + ) + self.metrics.aggregate(learner_results, key=LEARNER_RESULTS) + + # Update weights - after learning on the local worker - on all remote + # workers. + with self.metrics.log_time((TIMERS, SYNCH_WORKER_WEIGHTS_TIMER)): + # The train results's loss keys are ModuleIDs to their loss values. + # But we also return a total_loss key at the same level as the ModuleID + # keys. So we need to subtract that to get the correct set of ModuleIDs to + # update. + # TODO (sven): We should not be using `learner_results` as a messenger + # to infer which modules to update. `policies_to_train` might also NOT work + # as it might be a very large set (100s of Modules) vs a smaller Modules + # set that's present in the current train batch. + modules_to_update = set(learner_results[0].keys()) - {ALL_MODULES} + self.env_runner_group.sync_weights( + # Sync weights from learner_group to all EnvRunners. + from_worker_or_learner_group=self.learner_group, + policies=modules_to_update, + inference_only=True, + ) + + @OldAPIStack + def _training_step_old_api_stack(self) -> ResultDict: + # Collect batches from sample workers until we have a full batch. + with self._timers[SAMPLE_TIMER]: + if self.config.count_steps_by == "agent_steps": + train_batch = synchronous_parallel_sample( + worker_set=self.env_runner_group, + max_agent_steps=self.config.total_train_batch_size, + sample_timeout_s=self.config.sample_timeout_s, + ) + else: + train_batch = synchronous_parallel_sample( + worker_set=self.env_runner_group, + max_env_steps=self.config.total_train_batch_size, + sample_timeout_s=self.config.sample_timeout_s, + ) + # Return early if all our workers failed. + if not train_batch: + return {} + train_batch = train_batch.as_multi_agent() + self._counters[NUM_AGENT_STEPS_SAMPLED] += train_batch.agent_steps() + self._counters[NUM_ENV_STEPS_SAMPLED] += train_batch.env_steps() + # Standardize advantages. + train_batch = standardize_fields(train_batch, ["advantages"]) + + if self.config.simple_optimizer: + train_results = train_one_step(self, train_batch) + else: + train_results = multi_gpu_train_one_step(self, train_batch) + + policies_to_update = list(train_results.keys()) + + global_vars = { + "timestep": self._counters[NUM_AGENT_STEPS_SAMPLED], + # TODO (sven): num_grad_updates per each policy should be + # accessible via `train_results` (and get rid of global_vars). + "num_grad_updates_per_policy": { + pid: self.env_runner.policy_map[pid].num_grad_updates + for pid in policies_to_update + }, + } + + # Update weights - after learning on the local worker - on all remote + # workers. + with self._timers[SYNCH_WORKER_WEIGHTS_TIMER]: + if self.env_runner_group.num_remote_workers() > 0: + from_worker_or_learner_group = None + self.env_runner_group.sync_weights( + from_worker_or_learner_group=from_worker_or_learner_group, + policies=policies_to_update, + global_vars=global_vars, + ) + + # For each policy: Update KL scale and warn about possible issues + for policy_id, policy_info in train_results.items(): + # Update KL loss with dynamic scaling + # for each (possibly multiagent) policy we are training + kl_divergence = policy_info[LEARNER_STATS_KEY].get("kl") + self.get_policy(policy_id).update_kl(kl_divergence) + + # Warn about excessively high value function loss + scaled_vf_loss = ( + self.config.vf_loss_coeff * policy_info[LEARNER_STATS_KEY]["vf_loss"] + ) + policy_loss = policy_info[LEARNER_STATS_KEY]["policy_loss"] + if ( + log_once("ppo_warned_lr_ratio") + and self.config.get("model", {}).get("vf_share_layers") + and scaled_vf_loss > 100 + ): + logger.warning( + "The magnitude of your value function loss for policy: {} is " + "extremely large ({}) compared to the policy loss ({}). This " + "can prevent the policy from learning. Consider scaling down " + "the VF loss by reducing vf_loss_coeff, or disabling " + "vf_share_layers.".format(policy_id, scaled_vf_loss, policy_loss) + ) + # Warn about bad clipping configs. + train_batch.policy_batches[policy_id].set_get_interceptor(None) + mean_reward = train_batch.policy_batches[policy_id]["rewards"].mean() + if ( + log_once("ppo_warned_vf_clip") + and mean_reward > self.config.vf_clip_param + ): + self.warned_vf_clip = True + logger.warning( + f"The mean reward returned from the environment is {mean_reward}" + f" but the vf_clip_param is set to {self.config['vf_clip_param']}." + f" Consider increasing it for policy: {policy_id} to improve" + " value function convergence." + ) + + # Update global vars on local worker as well. + # TODO (simon): At least in RolloutWorker obsolete I guess as called in + # `sync_weights()` called above if remote workers. Can we call this + # where `set_weights()` is called on the local_worker? + self.env_runner.set_global_vars(global_vars) + + return train_results diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/ppo_catalog.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/ppo_catalog.py new file mode 100644 index 0000000000000000000000000000000000000000..fb11efea17ba7cd2949b46254c8971e463d8fb1e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/ppo_catalog.py @@ -0,0 +1,195 @@ +# __sphinx_doc_begin__ +import gymnasium as gym + +from ray.rllib.core.models.catalog import Catalog +from ray.rllib.core.models.configs import ( + ActorCriticEncoderConfig, + MLPHeadConfig, + FreeLogStdMLPHeadConfig, +) +from ray.rllib.core.models.base import Encoder, ActorCriticEncoder, Model +from ray.rllib.utils import override +from ray.rllib.utils.annotations import OverrideToImplementCustomLogic + + +def _check_if_diag_gaussian(action_distribution_cls, framework, no_error=False): + if framework == "torch": + from ray.rllib.core.distribution.torch.torch_distribution import ( + TorchDiagGaussian, + ) + + is_diag_gaussian = issubclass(action_distribution_cls, TorchDiagGaussian) + if no_error: + return is_diag_gaussian + else: + assert is_diag_gaussian, ( + f"free_log_std is only supported for DiagGaussian action " + f"distributions. Found action distribution: {action_distribution_cls}." + ) + else: + raise ValueError(f"Framework {framework} not supported for free_log_std.") + + +class PPOCatalog(Catalog): + """The Catalog class used to build models for PPO. + + PPOCatalog provides the following models: + - ActorCriticEncoder: The encoder used to encode the observations. + - Pi Head: The head used to compute the policy logits. + - Value Function Head: The head used to compute the value function. + + The ActorCriticEncoder is a wrapper around Encoders to produce separate outputs + for the policy and value function. See implementations of DefaultPPORLModule for + more details. + + Any custom ActorCriticEncoder can be built by overriding the + build_actor_critic_encoder() method. Alternatively, the ActorCriticEncoderConfig + at PPOCatalog.actor_critic_encoder_config can be overridden to build a custom + ActorCriticEncoder during RLModule runtime. + + Any custom head can be built by overriding the build_pi_head() and build_vf_head() + methods. Alternatively, the PiHeadConfig and VfHeadConfig can be overridden to + build custom heads during RLModule runtime. + + Any module built for exploration or inference is built with the flag + `ìnference_only=True` and does not contain a value network. This flag can be set + in the `SingleAgentModuleSpec` through the `inference_only` boolean flag. + In case that the actor-critic-encoder is not shared between the policy and value + function, the inference-only module will contain only the actor encoder network. + """ + + def __init__( + self, + observation_space: gym.Space, + action_space: gym.Space, + model_config_dict: dict, + ): + """Initializes the PPOCatalog. + + Args: + observation_space: The observation space of the Encoder. + action_space: The action space for the Pi Head. + model_config_dict: The model config to use. + """ + super().__init__( + observation_space=observation_space, + action_space=action_space, + model_config_dict=model_config_dict, + ) + # Replace EncoderConfig by ActorCriticEncoderConfig + self.actor_critic_encoder_config = ActorCriticEncoderConfig( + base_encoder_config=self._encoder_config, + shared=self._model_config_dict["vf_share_layers"], + ) + + self.pi_and_vf_head_hiddens = self._model_config_dict["head_fcnet_hiddens"] + self.pi_and_vf_head_activation = self._model_config_dict[ + "head_fcnet_activation" + ] + + # We don't have the exact (framework specific) action dist class yet and thus + # cannot determine the exact number of output nodes (action space) required. + # -> Build pi config only in the `self.build_pi_head` method. + self.pi_head_config = None + + self.vf_head_config = MLPHeadConfig( + input_dims=self.latent_dims, + hidden_layer_dims=self.pi_and_vf_head_hiddens, + hidden_layer_activation=self.pi_and_vf_head_activation, + output_layer_activation="linear", + output_layer_dim=1, + ) + + @OverrideToImplementCustomLogic + def build_actor_critic_encoder(self, framework: str) -> ActorCriticEncoder: + """Builds the ActorCriticEncoder. + + The default behavior is to build the encoder from the encoder_config. + This can be overridden to build a custom ActorCriticEncoder as a means of + configuring the behavior of a PPORLModule implementation. + + Args: + framework: The framework to use. Either "torch" or "tf2". + + Returns: + The ActorCriticEncoder. + """ + return self.actor_critic_encoder_config.build(framework=framework) + + @override(Catalog) + def build_encoder(self, framework: str) -> Encoder: + """Builds the encoder. + + Since PPO uses an ActorCriticEncoder, this method should not be implemented. + """ + raise NotImplementedError( + "Use PPOCatalog.build_actor_critic_encoder() instead for PPO." + ) + + @OverrideToImplementCustomLogic + def build_pi_head(self, framework: str) -> Model: + """Builds the policy head. + + The default behavior is to build the head from the pi_head_config. + This can be overridden to build a custom policy head as a means of configuring + the behavior of a PPORLModule implementation. + + Args: + framework: The framework to use. Either "torch" or "tf2". + + Returns: + The policy head. + """ + # Get action_distribution_cls to find out about the output dimension for pi_head + action_distribution_cls = self.get_action_dist_cls(framework=framework) + if self._model_config_dict["free_log_std"]: + _check_if_diag_gaussian( + action_distribution_cls=action_distribution_cls, framework=framework + ) + is_diag_gaussian = True + else: + is_diag_gaussian = _check_if_diag_gaussian( + action_distribution_cls=action_distribution_cls, + framework=framework, + no_error=True, + ) + required_output_dim = action_distribution_cls.required_input_dim( + space=self.action_space, model_config=self._model_config_dict + ) + # Now that we have the action dist class and number of outputs, we can define + # our pi-config and build the pi head. + pi_head_config_class = ( + FreeLogStdMLPHeadConfig + if self._model_config_dict["free_log_std"] + else MLPHeadConfig + ) + self.pi_head_config = pi_head_config_class( + input_dims=self.latent_dims, + hidden_layer_dims=self.pi_and_vf_head_hiddens, + hidden_layer_activation=self.pi_and_vf_head_activation, + output_layer_dim=required_output_dim, + output_layer_activation="linear", + clip_log_std=is_diag_gaussian, + log_std_clip_param=self._model_config_dict.get("log_std_clip_param", 20), + ) + + return self.pi_head_config.build(framework=framework) + + @OverrideToImplementCustomLogic + def build_vf_head(self, framework: str) -> Model: + """Builds the value function head. + + The default behavior is to build the head from the vf_head_config. + This can be overridden to build a custom value function head as a means of + configuring the behavior of a PPORLModule implementation. + + Args: + framework: The framework to use. Either "torch" or "tf2". + + Returns: + The value function head. + """ + return self.vf_head_config.build(framework=framework) + + +# __sphinx_doc_end__ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/ppo_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/ppo_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..b6d3953a8a457ec3e675ffb34c0586661db192c2 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/ppo_learner.py @@ -0,0 +1,149 @@ +import abc +from typing import Any, Dict + +from ray.rllib.algorithms.ppo.ppo import ( + LEARNER_RESULTS_CURR_ENTROPY_COEFF_KEY, + LEARNER_RESULTS_KL_KEY, + PPOConfig, +) +from ray.rllib.connectors.learner import ( + AddOneTsToEpisodesAndTruncate, + GeneralAdvantageEstimation, +) +from ray.rllib.core.learner.learner import Learner +from ray.rllib.core.rl_module.apis.value_function_api import ValueFunctionAPI +from ray.rllib.utils.annotations import ( + override, + OverrideToImplementCustomLogic_CallToSuperRecommended, +) +from ray.rllib.utils.lambda_defaultdict import LambdaDefaultDict +from ray.rllib.utils.metrics import ( + NUM_ENV_STEPS_SAMPLED_LIFETIME, + NUM_MODULE_STEPS_TRAINED, +) +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.schedules.scheduler import Scheduler +from ray.rllib.utils.typing import ModuleID, TensorType + + +class PPOLearner(Learner): + @override(Learner) + def build(self) -> None: + super().build() + + # Dict mapping module IDs to the respective entropy Scheduler instance. + self.entropy_coeff_schedulers_per_module: Dict[ + ModuleID, Scheduler + ] = LambdaDefaultDict( + lambda module_id: Scheduler( + fixed_value_or_schedule=( + self.config.get_config_for_module(module_id).entropy_coeff + ), + framework=self.framework, + device=self._device, + ) + ) + + # Set up KL coefficient variables (per module). + # Note that the KL coeff is not controlled by a Scheduler, but seeks + # to stay close to a given kl_target value. + self.curr_kl_coeffs_per_module: Dict[ModuleID, TensorType] = LambdaDefaultDict( + lambda module_id: self._get_tensor_variable( + self.config.get_config_for_module(module_id).kl_coeff + ) + ) + + # Extend all episodes by one artificial timestep to allow the value function net + # to compute the bootstrap values (and add a mask to the batch to know, which + # slots to mask out). + if ( + self._learner_connector is not None + and self.config.add_default_connectors_to_learner_pipeline + ): + # Before anything, add one ts to each episode (and record this in the loss + # mask, so that the computations at this extra ts are not used to compute + # the loss). + self._learner_connector.prepend(AddOneTsToEpisodesAndTruncate()) + # At the end of the pipeline (when the batch is already completed), add the + # GAE connector, which performs a vf forward pass, then computes the GAE + # computations, and puts the results of this (advantages, value targets) + # directly back in the batch. This is then the batch used for + # `forward_train` and `compute_losses`. + self._learner_connector.append( + GeneralAdvantageEstimation( + gamma=self.config.gamma, lambda_=self.config.lambda_ + ) + ) + + @override(Learner) + def remove_module(self, module_id: ModuleID, **kwargs): + marl_spec = super().remove_module(module_id, **kwargs) + + self.entropy_coeff_schedulers_per_module.pop(module_id, None) + self.curr_kl_coeffs_per_module.pop(module_id, None) + + return marl_spec + + @OverrideToImplementCustomLogic_CallToSuperRecommended + @override(Learner) + def after_gradient_based_update( + self, + *, + timesteps: Dict[str, Any], + ) -> None: + super().after_gradient_based_update(timesteps=timesteps) + + for module_id, module in self.module._rl_modules.items(): + config = self.config.get_config_for_module(module_id) + + # Update entropy coefficient via our Scheduler. + new_entropy_coeff = self.entropy_coeff_schedulers_per_module[ + module_id + ].update(timestep=timesteps.get(NUM_ENV_STEPS_SAMPLED_LIFETIME, 0)) + self.metrics.log_value( + (module_id, LEARNER_RESULTS_CURR_ENTROPY_COEFF_KEY), + new_entropy_coeff, + window=1, + ) + if ( + config.use_kl_loss + and self.metrics.peek((module_id, NUM_MODULE_STEPS_TRAINED), default=0) + > 0 + and (module_id, LEARNER_RESULTS_KL_KEY) in self.metrics + ): + kl_loss = convert_to_numpy( + self.metrics.peek((module_id, LEARNER_RESULTS_KL_KEY)) + ) + self._update_module_kl_coeff( + module_id=module_id, + config=config, + kl_loss=kl_loss, + ) + + @classmethod + @override(Learner) + def rl_module_required_apis(cls) -> list[type]: + # In order for a PPOLearner to update an RLModule, it must implement the + # following APIs: + return [ValueFunctionAPI] + + @abc.abstractmethod + def _update_module_kl_coeff( + self, + *, + module_id: ModuleID, + config: PPOConfig, + kl_loss: float, + ) -> None: + """Dynamically update the KL loss coefficients of each module. + + The update is completed using the mean KL divergence between the action + distributions current policy and old policy of each module. That action + distribution is computed during the most recent update/call to `compute_loss`. + + Args: + module_id: The module whose KL loss coefficient to update. + config: The AlgorithmConfig specific to the given `module_id`. + kl_loss: The mean KL loss of the module, computed inside + `compute_loss_for_module()`. + """ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/ppo_rl_module.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/ppo_rl_module.py new file mode 100644 index 0000000000000000000000000000000000000000..78f1ccef9fbd3e5124325426cbb7e249a184a054 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/ppo_rl_module.py @@ -0,0 +1,11 @@ +# Backward compat import. +from ray.rllib.algorithms.ppo.default_ppo_rl_module import ( # noqa + DefaultPPORLModule as PPORLModule, +) +from ray.rllib.utils.deprecation import deprecation_warning + +deprecation_warning( + old="ray.rllib.algorithms.ppo.ppo_rl_module.PPORLModule", + new="ray.rllib.algorithms.ppo.default_ppo_rl_module.DefaultPPORLModule", + error=False, +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/ppo_tf_policy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/ppo_tf_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..76e8d0161689a4e79fb9673cfce65dff8743354c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/ppo_tf_policy.py @@ -0,0 +1,235 @@ +""" +TensorFlow policy class used for PPO. +""" + +import logging +from typing import Dict, List, Type, Union + +from ray.rllib.evaluation.postprocessing import ( + Postprocessing, + compute_gae_for_sample_batch, +) +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.tf.tf_action_dist import TFActionDistribution +from ray.rllib.policy.dynamic_tf_policy_v2 import DynamicTFPolicyV2 +from ray.rllib.policy.eager_tf_policy_v2 import EagerTFPolicyV2 +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy.tf_mixins import ( + EntropyCoeffSchedule, + KLCoeffMixin, + LearningRateSchedule, + ValueNetworkMixin, +) +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.tf_utils import explained_variance, warn_if_infinite_kl_divergence +from ray.rllib.utils.typing import AlgorithmConfigDict, TensorType, TFPolicyV2Type + +tf1, tf, tfv = try_import_tf() + +logger = logging.getLogger(__name__) + + +def validate_config(config: AlgorithmConfigDict) -> None: + """Executed before Policy is "initialized" (at beginning of constructor). + Args: + config: The Policy's config. + """ + # If vf_share_layers is True, inform about the need to tune vf_loss_coeff. + if config.get("model", {}).get("vf_share_layers") is True: + logger.info( + "`vf_share_layers=True` in your model. " + "Therefore, remember to tune the value of `vf_loss_coeff`!" + ) + + +# We need this builder function because we want to share the same +# custom logics between TF1 dynamic and TF2 eager policies. +def get_ppo_tf_policy(name: str, base: TFPolicyV2Type) -> TFPolicyV2Type: + """Construct a PPOTFPolicy inheriting either dynamic or eager base policies. + + Args: + base: Base class for this policy. DynamicTFPolicyV2 or EagerTFPolicyV2. + + Returns: + A TF Policy to be used with PPO. + """ + + class PPOTFPolicy( + EntropyCoeffSchedule, + LearningRateSchedule, + KLCoeffMixin, + ValueNetworkMixin, + base, + ): + def __init__( + self, + observation_space, + action_space, + config, + existing_model=None, + existing_inputs=None, + ): + # First thing first, enable eager execution if necessary. + base.enable_eager_execution_if_necessary() + + # TODO: Move into Policy API, if needed at all here. Why not move this into + # `PPOConfig`?. + validate_config(config) + + # Initialize base class. + base.__init__( + self, + observation_space, + action_space, + config, + existing_inputs=existing_inputs, + existing_model=existing_model, + ) + + # Initialize MixIns. + ValueNetworkMixin.__init__(self, config) + EntropyCoeffSchedule.__init__( + self, config["entropy_coeff"], config["entropy_coeff_schedule"] + ) + LearningRateSchedule.__init__(self, config["lr"], config["lr_schedule"]) + KLCoeffMixin.__init__(self, config) + + # Note: this is a bit ugly, but loss and optimizer initialization must + # happen after all the MixIns are initialized. + self.maybe_initialize_optimizer_and_loss() + + @override(base) + def loss( + self, + model: Union[ModelV2, "tf.keras.Model"], + dist_class: Type[TFActionDistribution], + train_batch: SampleBatch, + ) -> Union[TensorType, List[TensorType]]: + if isinstance(model, tf.keras.Model): + logits, state, extra_outs = model(train_batch) + value_fn_out = extra_outs[SampleBatch.VF_PREDS] + else: + logits, state = model(train_batch) + value_fn_out = model.value_function() + + curr_action_dist = dist_class(logits, model) + + # RNN case: Mask away 0-padded chunks at end of time axis. + if state: + # Derive max_seq_len from the data itself, not from the seq_lens + # tensor. This is in case e.g. seq_lens=[2, 3], but the data is still + # 0-padded up to T=5 (as it's the case for attention nets). + B = tf.shape(train_batch[SampleBatch.SEQ_LENS])[0] + max_seq_len = tf.shape(logits)[0] // B + + mask = tf.sequence_mask(train_batch[SampleBatch.SEQ_LENS], max_seq_len) + mask = tf.reshape(mask, [-1]) + + def reduce_mean_valid(t): + return tf.reduce_mean(tf.boolean_mask(t, mask)) + + # non-RNN case: No masking. + else: + mask = None + reduce_mean_valid = tf.reduce_mean + + prev_action_dist = dist_class( + train_batch[SampleBatch.ACTION_DIST_INPUTS], model + ) + + logp_ratio = tf.exp( + curr_action_dist.logp(train_batch[SampleBatch.ACTIONS]) + - train_batch[SampleBatch.ACTION_LOGP] + ) + + # Only calculate kl loss if necessary (kl-coeff > 0.0). + if self.config["kl_coeff"] > 0.0: + action_kl = prev_action_dist.kl(curr_action_dist) + mean_kl_loss = reduce_mean_valid(action_kl) + warn_if_infinite_kl_divergence(self, mean_kl_loss) + else: + mean_kl_loss = tf.constant(0.0) + + curr_entropy = curr_action_dist.entropy() + mean_entropy = reduce_mean_valid(curr_entropy) + + surrogate_loss = tf.minimum( + train_batch[Postprocessing.ADVANTAGES] * logp_ratio, + train_batch[Postprocessing.ADVANTAGES] + * tf.clip_by_value( + logp_ratio, + 1 - self.config["clip_param"], + 1 + self.config["clip_param"], + ), + ) + + # Compute a value function loss. + if self.config["use_critic"]: + vf_loss = tf.math.square( + value_fn_out - train_batch[Postprocessing.VALUE_TARGETS] + ) + vf_loss_clipped = tf.clip_by_value( + vf_loss, + 0, + self.config["vf_clip_param"], + ) + mean_vf_loss = reduce_mean_valid(vf_loss_clipped) + # Ignore the value function. + else: + vf_loss_clipped = mean_vf_loss = tf.constant(0.0) + + total_loss = reduce_mean_valid( + -surrogate_loss + + self.config["vf_loss_coeff"] * vf_loss_clipped + - self.entropy_coeff * curr_entropy + ) + # Add mean_kl_loss (already processed through `reduce_mean_valid`), + # if necessary. + if self.config["kl_coeff"] > 0.0: + total_loss += self.kl_coeff * mean_kl_loss + + # Store stats in policy for stats_fn. + self._total_loss = total_loss + self._mean_policy_loss = reduce_mean_valid(-surrogate_loss) + self._mean_vf_loss = mean_vf_loss + self._mean_entropy = mean_entropy + # Backward compatibility: Deprecate self._mean_kl. + self._mean_kl_loss = self._mean_kl = mean_kl_loss + self._value_fn_out = value_fn_out + + return total_loss + + @override(base) + def stats_fn(self, train_batch: SampleBatch) -> Dict[str, TensorType]: + return { + "cur_kl_coeff": tf.cast(self.kl_coeff, tf.float64), + "cur_lr": tf.cast(self.cur_lr, tf.float64), + "total_loss": self._total_loss, + "policy_loss": self._mean_policy_loss, + "vf_loss": self._mean_vf_loss, + "vf_explained_var": explained_variance( + train_batch[Postprocessing.VALUE_TARGETS], self._value_fn_out + ), + "kl": self._mean_kl_loss, + "entropy": self._mean_entropy, + "entropy_coeff": tf.cast(self.entropy_coeff, tf.float64), + } + + @override(base) + def postprocess_trajectory( + self, sample_batch, other_agent_batches=None, episode=None + ): + sample_batch = super().postprocess_trajectory(sample_batch) + return compute_gae_for_sample_batch( + self, sample_batch, other_agent_batches, episode + ) + + PPOTFPolicy.__name__ = name + PPOTFPolicy.__qualname__ = name + + return PPOTFPolicy + + +PPOTF1Policy = get_ppo_tf_policy("PPOTF1Policy", DynamicTFPolicyV2) +PPOTF2Policy = get_ppo_tf_policy("PPOTF2Policy", EagerTFPolicyV2) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/ppo_torch_policy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/ppo_torch_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..26a52dbe4d2b1bcd6f66b501bff9d3c410cc5923 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/ppo_torch_policy.py @@ -0,0 +1,217 @@ +import logging +from typing import Dict, List, Type, Union + +import ray +from ray.rllib.algorithms.ppo.ppo_tf_policy import validate_config +from ray.rllib.evaluation.postprocessing import ( + Postprocessing, + compute_gae_for_sample_batch, +) +from ray.rllib.models.action_dist import ActionDistribution +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy.torch_mixins import ( + EntropyCoeffSchedule, + KLCoeffMixin, + LearningRateSchedule, + ValueNetworkMixin, +) +from ray.rllib.policy.torch_policy_v2 import TorchPolicyV2 +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.torch_utils import ( + apply_grad_clipping, + explained_variance, + sequence_mask, + warn_if_infinite_kl_divergence, +) +from ray.rllib.utils.typing import TensorType + +torch, nn = try_import_torch() + +logger = logging.getLogger(__name__) + + +class PPOTorchPolicy( + ValueNetworkMixin, + LearningRateSchedule, + EntropyCoeffSchedule, + KLCoeffMixin, + TorchPolicyV2, +): + """PyTorch policy class used with PPO.""" + + def __init__(self, observation_space, action_space, config): + config = dict(ray.rllib.algorithms.ppo.ppo.PPOConfig().to_dict(), **config) + validate_config(config) + + TorchPolicyV2.__init__( + self, + observation_space, + action_space, + config, + max_seq_len=config["model"]["max_seq_len"], + ) + + ValueNetworkMixin.__init__(self, config) + LearningRateSchedule.__init__(self, config["lr"], config["lr_schedule"]) + EntropyCoeffSchedule.__init__( + self, config["entropy_coeff"], config["entropy_coeff_schedule"] + ) + KLCoeffMixin.__init__(self, config) + + self._initialize_loss_from_dummy_batch() + + @override(TorchPolicyV2) + def loss( + self, + model: ModelV2, + dist_class: Type[ActionDistribution], + train_batch: SampleBatch, + ) -> Union[TensorType, List[TensorType]]: + """Compute loss for Proximal Policy Objective. + + Args: + model: The Model to calculate the loss for. + dist_class: The action distr. class. + train_batch: The training data. + + Returns: + The PPO loss tensor given the input batch. + """ + + logits, state = model(train_batch) + curr_action_dist = dist_class(logits, model) + + # RNN case: Mask away 0-padded chunks at end of time axis. + if state: + B = len(train_batch[SampleBatch.SEQ_LENS]) + max_seq_len = logits.shape[0] // B + mask = sequence_mask( + train_batch[SampleBatch.SEQ_LENS], + max_seq_len, + time_major=model.is_time_major(), + ) + mask = torch.reshape(mask, [-1]) + num_valid = torch.sum(mask) + + def reduce_mean_valid(t): + return torch.sum(t[mask]) / num_valid + + # non-RNN case: No masking. + else: + mask = None + reduce_mean_valid = torch.mean + + prev_action_dist = dist_class( + train_batch[SampleBatch.ACTION_DIST_INPUTS], model + ) + + logp_ratio = torch.exp( + curr_action_dist.logp(train_batch[SampleBatch.ACTIONS]) + - train_batch[SampleBatch.ACTION_LOGP] + ) + + # Only calculate kl loss if necessary (kl-coeff > 0.0). + if self.config["kl_coeff"] > 0.0: + action_kl = prev_action_dist.kl(curr_action_dist) + mean_kl_loss = reduce_mean_valid(action_kl) + # TODO smorad: should we do anything besides warn? Could discard KL term + # for this update + warn_if_infinite_kl_divergence(self, mean_kl_loss) + else: + mean_kl_loss = torch.tensor(0.0, device=logp_ratio.device) + + curr_entropy = curr_action_dist.entropy() + mean_entropy = reduce_mean_valid(curr_entropy) + + surrogate_loss = torch.min( + train_batch[Postprocessing.ADVANTAGES] * logp_ratio, + train_batch[Postprocessing.ADVANTAGES] + * torch.clamp( + logp_ratio, 1 - self.config["clip_param"], 1 + self.config["clip_param"] + ), + ) + + # Compute a value function loss. + if self.config["use_critic"]: + value_fn_out = model.value_function() + vf_loss = torch.pow( + value_fn_out - train_batch[Postprocessing.VALUE_TARGETS], 2.0 + ) + vf_loss_clipped = torch.clamp(vf_loss, 0, self.config["vf_clip_param"]) + mean_vf_loss = reduce_mean_valid(vf_loss_clipped) + # Ignore the value function. + else: + value_fn_out = torch.tensor(0.0).to(surrogate_loss.device) + vf_loss_clipped = mean_vf_loss = torch.tensor(0.0).to(surrogate_loss.device) + + total_loss = reduce_mean_valid( + -surrogate_loss + + self.config["vf_loss_coeff"] * vf_loss_clipped + - self.entropy_coeff * curr_entropy + ) + + # Add mean_kl_loss (already processed through `reduce_mean_valid`), + # if necessary. + if self.config["kl_coeff"] > 0.0: + total_loss += self.kl_coeff * mean_kl_loss + + # Store values for stats function in model (tower), such that for + # multi-GPU, we do not override them during the parallel loss phase. + model.tower_stats["total_loss"] = total_loss + model.tower_stats["mean_policy_loss"] = reduce_mean_valid(-surrogate_loss) + model.tower_stats["mean_vf_loss"] = mean_vf_loss + model.tower_stats["vf_explained_var"] = explained_variance( + train_batch[Postprocessing.VALUE_TARGETS], value_fn_out + ) + model.tower_stats["mean_entropy"] = mean_entropy + model.tower_stats["mean_kl_loss"] = mean_kl_loss + + return total_loss + + # TODO: Make this an event-style subscription (e.g.: + # "after_gradients_computed"). + @override(TorchPolicyV2) + def extra_grad_process(self, local_optimizer, loss): + return apply_grad_clipping(self, local_optimizer, loss) + + @override(TorchPolicyV2) + def stats_fn(self, train_batch: SampleBatch) -> Dict[str, TensorType]: + return convert_to_numpy( + { + "cur_kl_coeff": self.kl_coeff, + "cur_lr": self.cur_lr, + "total_loss": torch.mean( + torch.stack(self.get_tower_stats("total_loss")) + ), + "policy_loss": torch.mean( + torch.stack(self.get_tower_stats("mean_policy_loss")) + ), + "vf_loss": torch.mean( + torch.stack(self.get_tower_stats("mean_vf_loss")) + ), + "vf_explained_var": torch.mean( + torch.stack(self.get_tower_stats("vf_explained_var")) + ), + "kl": torch.mean(torch.stack(self.get_tower_stats("mean_kl_loss"))), + "entropy": torch.mean( + torch.stack(self.get_tower_stats("mean_entropy")) + ), + "entropy_coeff": self.entropy_coeff, + } + ) + + @override(TorchPolicyV2) + def postprocess_trajectory( + self, sample_batch, other_agent_batches=None, episode=None + ): + # Do all post-processing always with no_grad(). + # Not using this here will introduce a memory leak + # in torch (issue #6962). + # TODO: no_grad still necessary? + with torch.no_grad(): + return compute_gae_for_sample_batch( + self, sample_batch, other_agent_batches, episode + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/torch/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/torch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/torch/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/torch/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c05ad71fda383e326d373b760f061f13125be7c7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/torch/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/torch/__pycache__/default_ppo_torch_rl_module.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/torch/__pycache__/default_ppo_torch_rl_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d20ae276ff7480ca4a65330e7fc49f7055ba4dc Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/torch/__pycache__/default_ppo_torch_rl_module.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/torch/__pycache__/ppo_torch_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/torch/__pycache__/ppo_torch_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0693db6048605a016205d69ddfe8f3cc480eb30 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/torch/__pycache__/ppo_torch_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/torch/__pycache__/ppo_torch_rl_module.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/torch/__pycache__/ppo_torch_rl_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7911831e2346415ac1cae414dc753ddff149092d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/torch/__pycache__/ppo_torch_rl_module.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/torch/default_ppo_torch_rl_module.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/torch/default_ppo_torch_rl_module.py new file mode 100644 index 0000000000000000000000000000000000000000..0ca3093887e62562f7a9697db8b77f3ba1d6d44b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/torch/default_ppo_torch_rl_module.py @@ -0,0 +1,73 @@ +from typing import Any, Dict, Optional + +from ray.rllib.algorithms.ppo.default_ppo_rl_module import DefaultPPORLModule +from ray.rllib.algorithms.ppo.ppo_catalog import PPOCatalog +from ray.rllib.core.columns import Columns +from ray.rllib.core.models.base import ACTOR, CRITIC, ENCODER_OUT +from ray.rllib.core.rl_module.apis.value_function_api import ValueFunctionAPI +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.core.rl_module.torch import TorchRLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.typing import TensorType +from ray.util.annotations import DeveloperAPI + +torch, nn = try_import_torch() + + +@DeveloperAPI +class DefaultPPOTorchRLModule(TorchRLModule, DefaultPPORLModule): + def __init__(self, *args, **kwargs): + catalog_class = kwargs.pop("catalog_class", None) + if catalog_class is None: + catalog_class = PPOCatalog + super().__init__(*args, **kwargs, catalog_class=catalog_class) + + @override(RLModule) + def _forward(self, batch: Dict[str, Any], **kwargs) -> Dict[str, Any]: + """Default forward pass (used for inference and exploration).""" + output = {} + # Encoder forward pass. + encoder_outs = self.encoder(batch) + # Stateful encoder? + if Columns.STATE_OUT in encoder_outs: + output[Columns.STATE_OUT] = encoder_outs[Columns.STATE_OUT] + # Pi head. + output[Columns.ACTION_DIST_INPUTS] = self.pi(encoder_outs[ENCODER_OUT][ACTOR]) + return output + + @override(RLModule) + def _forward_train(self, batch: Dict[str, Any], **kwargs) -> Dict[str, Any]: + """Train forward pass (keep embeddings for possible shared value func. call).""" + output = {} + encoder_outs = self.encoder(batch) + output[Columns.EMBEDDINGS] = encoder_outs[ENCODER_OUT][CRITIC] + if Columns.STATE_OUT in encoder_outs: + output[Columns.STATE_OUT] = encoder_outs[Columns.STATE_OUT] + output[Columns.ACTION_DIST_INPUTS] = self.pi(encoder_outs[ENCODER_OUT][ACTOR]) + return output + + @override(ValueFunctionAPI) + def compute_values( + self, + batch: Dict[str, Any], + embeddings: Optional[Any] = None, + ) -> TensorType: + if embeddings is None: + # Separate vf-encoder. + if hasattr(self.encoder, "critic_encoder"): + batch_ = batch + if self.is_stateful(): + # The recurrent encoders expect a `(state_in, h)` key in the + # input dict while the key returned is `(state_in, critic, h)`. + batch_ = batch.copy() + batch_[Columns.STATE_IN] = batch[Columns.STATE_IN][CRITIC] + embeddings = self.encoder.critic_encoder(batch_)[ENCODER_OUT] + # Shared encoder. + else: + embeddings = self.encoder(batch)[ENCODER_OUT][CRITIC] + + # Value head. + vf_out = self.vf(embeddings) + # Squeeze out last dimension (single node value head). + return vf_out.squeeze(-1) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/torch/ppo_torch_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/torch/ppo_torch_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..190ecbf106c142ab7046161dca80cc2ed5391e85 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/torch/ppo_torch_learner.py @@ -0,0 +1,173 @@ +import logging +from typing import Any, Dict + +import numpy as np + +from ray.rllib.algorithms.ppo.ppo import ( + LEARNER_RESULTS_KL_KEY, + LEARNER_RESULTS_CURR_KL_COEFF_KEY, + LEARNER_RESULTS_VF_EXPLAINED_VAR_KEY, + LEARNER_RESULTS_VF_LOSS_UNCLIPPED_KEY, + PPOConfig, +) +from ray.rllib.algorithms.ppo.ppo_learner import PPOLearner +from ray.rllib.core.columns import Columns +from ray.rllib.core.learner.learner import POLICY_LOSS_KEY, VF_LOSS_KEY, ENTROPY_KEY +from ray.rllib.core.learner.torch.torch_learner import TorchLearner +from ray.rllib.evaluation.postprocessing import Postprocessing +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.torch_utils import explained_variance +from ray.rllib.utils.typing import ModuleID, TensorType + +torch, nn = try_import_torch() + +logger = logging.getLogger(__name__) + + +class PPOTorchLearner(PPOLearner, TorchLearner): + """Implements torch-specific PPO loss logic on top of PPOLearner. + + This class implements the ppo loss under `self.compute_loss_for_module()`. + """ + + @override(TorchLearner) + def compute_loss_for_module( + self, + *, + module_id: ModuleID, + config: PPOConfig, + batch: Dict[str, Any], + fwd_out: Dict[str, TensorType], + ) -> TensorType: + module = self.module[module_id].unwrapped() + + # Possibly apply masking to some sub loss terms and to the total loss term + # at the end. Masking could be used for RNN-based model (zero padded `batch`) + # and for PPO's batched value function (and bootstrap value) computations, + # for which we add an (artificial) timestep to each episode to + # simplify the actual computation. + if Columns.LOSS_MASK in batch: + mask = batch[Columns.LOSS_MASK] + num_valid = torch.sum(mask) + + def possibly_masked_mean(data_): + return torch.sum(data_[mask]) / num_valid + + else: + possibly_masked_mean = torch.mean + + action_dist_class_train = module.get_train_action_dist_cls() + action_dist_class_exploration = module.get_exploration_action_dist_cls() + + curr_action_dist = action_dist_class_train.from_logits( + fwd_out[Columns.ACTION_DIST_INPUTS] + ) + # TODO (sven): We should ideally do this in the LearnerConnector (separation of + # concerns: Only do things on the EnvRunners that are required for computing + # actions, do NOT do anything on the EnvRunners that's only required for a + # training update). + prev_action_dist = action_dist_class_exploration.from_logits( + batch[Columns.ACTION_DIST_INPUTS] + ) + + logp_ratio = torch.exp( + curr_action_dist.logp(batch[Columns.ACTIONS]) - batch[Columns.ACTION_LOGP] + ) + + # Only calculate kl loss if necessary (kl-coeff > 0.0). + if config.use_kl_loss: + action_kl = prev_action_dist.kl(curr_action_dist) + mean_kl_loss = possibly_masked_mean(action_kl) + else: + mean_kl_loss = torch.tensor(0.0, device=logp_ratio.device) + + curr_entropy = curr_action_dist.entropy() + mean_entropy = possibly_masked_mean(curr_entropy) + + surrogate_loss = torch.min( + batch[Postprocessing.ADVANTAGES] * logp_ratio, + batch[Postprocessing.ADVANTAGES] + * torch.clamp(logp_ratio, 1 - config.clip_param, 1 + config.clip_param), + ) + + # Compute a value function loss. + if config.use_critic: + value_fn_out = module.compute_values( + batch, embeddings=fwd_out.get(Columns.EMBEDDINGS) + ) + vf_loss = torch.pow(value_fn_out - batch[Postprocessing.VALUE_TARGETS], 2.0) + vf_loss_clipped = torch.clamp(vf_loss, 0, config.vf_clip_param) + mean_vf_loss = possibly_masked_mean(vf_loss_clipped) + mean_vf_unclipped_loss = possibly_masked_mean(vf_loss) + # Ignore the value function -> Set all to 0.0. + else: + z = torch.tensor(0.0, device=surrogate_loss.device) + value_fn_out = mean_vf_unclipped_loss = vf_loss_clipped = mean_vf_loss = z + + total_loss = possibly_masked_mean( + -surrogate_loss + + config.vf_loss_coeff * vf_loss_clipped + - ( + self.entropy_coeff_schedulers_per_module[module_id].get_current_value() + * curr_entropy + ) + ) + + # Add mean_kl_loss (already processed through `possibly_masked_mean`), + # if necessary. + if config.use_kl_loss: + total_loss += self.curr_kl_coeffs_per_module[module_id] * mean_kl_loss + + # Log important loss stats. + self.metrics.log_dict( + { + POLICY_LOSS_KEY: -possibly_masked_mean(surrogate_loss), + VF_LOSS_KEY: mean_vf_loss, + LEARNER_RESULTS_VF_LOSS_UNCLIPPED_KEY: mean_vf_unclipped_loss, + LEARNER_RESULTS_VF_EXPLAINED_VAR_KEY: explained_variance( + batch[Postprocessing.VALUE_TARGETS], value_fn_out + ), + ENTROPY_KEY: mean_entropy, + LEARNER_RESULTS_KL_KEY: mean_kl_loss, + }, + key=module_id, + window=1, # <- single items (should not be mean/ema-reduced over time). + ) + # Return the total loss. + return total_loss + + @override(PPOLearner) + def _update_module_kl_coeff( + self, + *, + module_id: ModuleID, + config: PPOConfig, + kl_loss: float, + ) -> None: + if np.isnan(kl_loss): + logger.warning( + f"KL divergence for Module {module_id} is non-finite, this " + "will likely destabilize your model and the training " + "process. Action(s) in a specific state have near-zero " + "probability. This can happen naturally in deterministic " + "environments where the optimal policy has zero mass for a " + "specific action. To fix this issue, consider setting " + "`kl_coeff` to 0.0 or increasing `entropy_coeff` in your " + "config." + ) + + # Update the KL coefficient. + curr_var = self.curr_kl_coeffs_per_module[module_id] + if kl_loss > 2.0 * config.kl_target: + # TODO (Kourosh) why not 2? + curr_var.data *= 1.5 + elif kl_loss < 0.5 * config.kl_target: + curr_var.data *= 0.5 + + # Log the updated KL-coeff value. + self.metrics.log_value( + (module_id, LEARNER_RESULTS_CURR_KL_COEFF_KEY), + curr_var.item(), + window=1, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/torch/ppo_torch_rl_module.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/torch/ppo_torch_rl_module.py new file mode 100644 index 0000000000000000000000000000000000000000..60370a1504974599ef10a182b98a39f6d055f92e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/ppo/torch/ppo_torch_rl_module.py @@ -0,0 +1,13 @@ +# Backward compat import. +from ray.rllib.algorithms.ppo.torch.default_ppo_torch_rl_module import ( # noqa + DefaultPPOTorchRLModule as PPOTorchRLModule, +) +from ray.rllib.utils.deprecation import deprecation_warning + + +deprecation_warning( + old="ray.rllib.algorithms.ppo.torch.ppo_torch_rl_module.PPOTorchRLModule", + new="ray.rllib.algorithms.ppo.torch.default_ppo_torch_rl_module." + "DefaultPPOTorchRLModule", + error=False, +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/registry.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..c349489d165c27e920928bf8d6b5d4f70362300a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/registry.py @@ -0,0 +1,185 @@ +"""Registry of algorithm names for tune.Tuner(trainable=[..]).""" + +import importlib +import re + + +def _import_appo(): + import ray.rllib.algorithms.appo as appo + + return appo.APPO, appo.APPO.get_default_config() + + +def _import_bc(): + import ray.rllib.algorithms.bc as bc + + return bc.BC, bc.BC.get_default_config() + + +def _import_cql(): + import ray.rllib.algorithms.cql as cql + + return cql.CQL, cql.CQL.get_default_config() + + +def _import_dqn(): + import ray.rllib.algorithms.dqn as dqn + + return dqn.DQN, dqn.DQN.get_default_config() + + +def _import_dreamerv3(): + import ray.rllib.algorithms.dreamerv3 as dreamerv3 + + return dreamerv3.DreamerV3, dreamerv3.DreamerV3.get_default_config() + + +def _import_impala(): + import ray.rllib.algorithms.impala as impala + + return impala.IMPALA, impala.IMPALA.get_default_config() + + +def _import_iql(): + import ray.rllib.algorithms.iql as iql + + return iql.IQL, iql.IQL.get_default_config() + + +def _import_marwil(): + import ray.rllib.algorithms.marwil as marwil + + return marwil.MARWIL, marwil.MARWIL.get_default_config() + + +def _import_ppo(): + import ray.rllib.algorithms.ppo as ppo + + return ppo.PPO, ppo.PPO.get_default_config() + + +def _import_sac(): + import ray.rllib.algorithms.sac as sac + + return sac.SAC, sac.SAC.get_default_config() + + +ALGORITHMS = { + "APPO": _import_appo, + "BC": _import_bc, + "CQL": _import_cql, + "DQN": _import_dqn, + "DreamerV3": _import_dreamerv3, + "IMPALA": _import_impala, + "IQL": _import_iql, + "MARWIL": _import_marwil, + "PPO": _import_ppo, + "SAC": _import_sac, +} + + +ALGORITHMS_CLASS_TO_NAME = { + "APPO": "APPO", + "BC": "BC", + "CQL": "CQL", + "DQN": "DQN", + "DreamerV3": "DreamerV3", + "Impala": "IMPALA", + "IQL": "IQL", + "IMPALA": "IMPALA", + "MARWIL": "MARWIL", + "PPO": "PPO", + "SAC": "SAC", +} + + +def _get_algorithm_class(alg: str) -> type: + # This helps us get around a circular import (tune calls rllib._register_all when + # checking if a rllib Trainable is registered) + if alg in ALGORITHMS: + return ALGORITHMS[alg]()[0] + elif alg == "script": + from ray.tune import script_runner + + return script_runner.ScriptRunner + elif alg == "__fake": + from ray.rllib.algorithms.mock import _MockTrainer + + return _MockTrainer + elif alg == "__sigmoid_fake_data": + from ray.rllib.algorithms.mock import _SigmoidFakeData + + return _SigmoidFakeData + elif alg == "__parameter_tuning": + from ray.rllib.algorithms.mock import _ParameterTuningTrainer + + return _ParameterTuningTrainer + else: + raise Exception("Unknown algorithm {}.".format(alg)) + + +# Dict mapping policy names to where the class is located, relative to rllib.algorithms. +# TODO(jungong) : Finish migrating all the policies to PolicyV2, so we can list +# all the TF eager policies here. +POLICIES = { + "APPOTF1Policy": "appo.appo_tf_policy", + "APPOTF2Policy": "appo.appo_tf_policy", + "APPOTorchPolicy": "appo.appo_torch_policy", + "CQLTFPolicy": "cql.cql_tf_policy", + "CQLTorchPolicy": "cql.cql_torch_policy", + "DQNTFPolicy": "dqn.dqn_tf_policy", + "DQNTorchPolicy": "dqn.dqn_torch_policy", + "ImpalaTF1Policy": "impala.impala_tf_policy", + "ImpalaTF2Policy": "impala.impala_tf_policy", + "ImpalaTorchPolicy": "impala.impala_torch_policy", + "MARWILTF1Policy": "marwil.marwil_tf_policy", + "MARWILTF2Policy": "marwil.marwil_tf_policy", + "MARWILTorchPolicy": "marwil.marwil_torch_policy", + "SACTFPolicy": "sac.sac_tf_policy", + "SACTorchPolicy": "sac.sac_torch_policy", + "PPOTF1Policy": "ppo.ppo_tf_policy", + "PPOTF2Policy": "ppo.ppo_tf_policy", + "PPOTorchPolicy": "ppo.ppo_torch_policy", +} + + +def get_policy_class_name(policy_class: type): + """Returns a string name for the provided policy class. + + Args: + policy_class: RLlib policy class, e.g. A3CTorchPolicy, DQNTFPolicy, etc. + + Returns: + A string name uniquely mapped to the given policy class. + """ + # TF2 policy classes may get automatically converted into new class types + # that have eager tracing capability. + # These policy classes have the "_traced" postfix in their names. + # When checkpointing these policy classes, we should save the name of the + # original policy class instead. So that users have the choice of turning + # on eager tracing during inference time. + name = re.sub("_traced$", "", policy_class.__name__) + if name in POLICIES: + return name + return None + + +def get_policy_class(name: str): + """Return an actual policy class given the string name. + + Args: + name: string name of the policy class. + + Returns: + Actual policy class for the given name. + """ + if name not in POLICIES: + return None + + path = POLICIES[name] + module = importlib.import_module("ray.rllib.algorithms." + path) + + if not hasattr(module, name): + return None + + return getattr(module, name) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8170f353edd12a02ae10ea205b21520f78d97b27 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__init__.py @@ -0,0 +1,10 @@ +from ray.rllib.algorithms.sac.sac import SAC, SACConfig +from ray.rllib.algorithms.sac.sac_tf_policy import SACTFPolicy +from ray.rllib.algorithms.sac.sac_torch_policy import SACTorchPolicy + +__all__ = [ + "SAC", + "SACTFPolicy", + "SACTorchPolicy", + "SACConfig", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..078052b26dae504d6e72ad332223020a2244a191 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__pycache__/default_sac_rl_module.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__pycache__/default_sac_rl_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6beed9ed6ccf76ff094f739eb32a2bea3490b545 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__pycache__/default_sac_rl_module.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__pycache__/sac.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__pycache__/sac.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3503626b859921d44136c81417da444e808531b4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__pycache__/sac.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__pycache__/sac_catalog.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__pycache__/sac_catalog.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a18471daa06418e781cd1ef4c1b47553437f84c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__pycache__/sac_catalog.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__pycache__/sac_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__pycache__/sac_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0d1f7e23f693b1440d3fbf468be9b3b559ad455 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__pycache__/sac_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__pycache__/sac_tf_model.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__pycache__/sac_tf_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0cb4dd1bfa4cf0a62a9831d49a6c7b12f1f95b50 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__pycache__/sac_tf_model.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__pycache__/sac_tf_policy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__pycache__/sac_tf_policy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2bf452750d100dcfa5fae18aa67ce8f59df9517 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__pycache__/sac_tf_policy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__pycache__/sac_torch_model.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__pycache__/sac_torch_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c3c3d3d20696fe937e3cea4d5b46f903e293378 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__pycache__/sac_torch_model.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__pycache__/sac_torch_policy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__pycache__/sac_torch_policy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28d3275cfee4b6ce1dc57dea1bb67be7c5754af6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/__pycache__/sac_torch_policy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/default_sac_rl_module.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/default_sac_rl_module.py new file mode 100644 index 0000000000000000000000000000000000000000..3d01e5ed5ccca90856cb21c33bd5bd6de298bee3 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/default_sac_rl_module.py @@ -0,0 +1,141 @@ +from abc import abstractmethod +from typing import Any, Dict, List, Tuple + +from ray.rllib.core.learner.utils import make_target_network +from ray.rllib.core.models.base import Encoder, Model +from ray.rllib.core.rl_module.apis import InferenceOnlyAPI, QNetAPI, TargetNetworkAPI +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import ( + override, + OverrideToImplementCustomLogic, +) +from ray.rllib.utils.typing import NetworkType +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +class DefaultSACRLModule(RLModule, InferenceOnlyAPI, TargetNetworkAPI, QNetAPI): + """`RLModule` for the Soft-Actor-Critic (SAC) algorithm. + + It consists of several architectures, each in turn composed of + two networks: an encoder and a head. + + The policy (actor) contains a state encoder (`pi_encoder`) and + a head (`pi_head`) that feeds into an action distribution (a + squashed Gaussian, i.e. outputs define the location and the log + scale parameters). + + In addition, two (or four in case `twin_q=True`) Q networks are + defined, the second one (and fourth, if `twin_q=True`) of them the + Q target network(s). All of these in turn are - similar to the + policy network - composed of an encoder and a head network. Each of + the encoders forms a state-action encoding that feeds into the + corresponding value heads to result in an estimation of the soft + action-value of SAC. + + The following graphics show the forward passes through this module: + [obs] -> [pi_encoder] -> [pi_head] -> [action_dist_inputs] + [obs, action] -> [qf_encoder] -> [qf_head] -> [q-value] + [obs, action] -> [qf_target_encoder] -> [qf_target_head] + -> [q-target-value] + --- + If `twin_q=True`: + [obs, action] -> [qf_twin_encoder] -> [qf_twin_head] -> [q-twin-value] + [obs, action] -> [qf_target_twin_encoder] -> [qf_target_twin_head] + -> [q-target-twin-value] + """ + + @override(RLModule) + def setup(self): + # If a twin Q architecture should be used. + self.twin_q = self.model_config["twin_q"] + + # Build the encoder for the policy. + self.pi_encoder = self.catalog.build_encoder(framework=self.framework) + + if not self.inference_only or self.framework != "torch": + # SAC needs a separate Q network encoder (besides the pi network). + # This is because the Q network also takes the action as input + # (concatenated with the observations). + self.qf_encoder = self.catalog.build_qf_encoder(framework=self.framework) + + # If necessary, build also a twin Q encoders. + if self.twin_q: + self.qf_twin_encoder = self.catalog.build_qf_encoder( + framework=self.framework + ) + + # Build heads. + self.pi = self.catalog.build_pi_head(framework=self.framework) + + if not self.inference_only or self.framework != "torch": + self.qf = self.catalog.build_qf_head(framework=self.framework) + # If necessary build also a twin Q heads. + if self.twin_q: + self.qf_twin = self.catalog.build_qf_head(framework=self.framework) + + @override(TargetNetworkAPI) + def make_target_networks(self): + self.target_qf_encoder = make_target_network(self.qf_encoder) + self.target_qf = make_target_network(self.qf) + if self.twin_q: + self.target_qf_twin_encoder = make_target_network(self.qf_twin_encoder) + self.target_qf_twin = make_target_network(self.qf_twin) + + @override(InferenceOnlyAPI) + def get_non_inference_attributes(self) -> List[str]: + ret = ["qf", "target_qf", "qf_encoder", "target_qf_encoder"] + if self.twin_q: + ret += [ + "qf_twin", + "target_qf_twin", + "qf_twin_encoder", + "target_qf_twin_encoder", + ] + return ret + + @override(TargetNetworkAPI) + def get_target_network_pairs(self) -> List[Tuple[NetworkType, NetworkType]]: + """Returns target Q and Q network(s) to update the target network(s).""" + return [ + (self.qf_encoder, self.target_qf_encoder), + (self.qf, self.target_qf), + ] + ( + # If we have twin networks we need to update them, too. + [ + (self.qf_twin_encoder, self.target_qf_twin_encoder), + (self.qf_twin, self.target_qf_twin), + ] + if self.twin_q + else [] + ) + + # TODO (simon): SAC does not support RNNs, yet. + @override(RLModule) + def get_initial_state(self) -> dict: + # if hasattr(self.pi_encoder, "get_initial_state"): + # return { + # ACTOR: self.pi_encoder.get_initial_state(), + # CRITIC: self.qf_encoder.get_initial_state(), + # CRITIC_TARGET: self.qf_target_encoder.get_initial_state(), + # } + # else: + # return {} + return {} + + @abstractmethod + @OverrideToImplementCustomLogic + def _qf_forward_train_helper( + self, batch: Dict[str, Any], encoder: Encoder, head: Model + ) -> Dict[str, Any]: + """Executes the forward pass for Q networks. + + Args: + batch: Dict containing a concatenated tensor with observations + and actions under the key `SampleBatch.OBS`. + encoder: An `Encoder` model for the Q state-action encoder. + head: A `Model` for the Q head. + + Returns: + The estimated Q-value using the `encoder` and `head` networks. + """ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/sac.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/sac.py new file mode 100644 index 0000000000000000000000000000000000000000..581434e03ed94f75fd233a81d1996dd56fd950f3 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/sac.py @@ -0,0 +1,589 @@ +import logging +from typing import Any, Dict, Optional, Tuple, Type, Union + +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig, NotProvided +from ray.rllib.algorithms.dqn.dqn import DQN +from ray.rllib.algorithms.sac.sac_tf_policy import SACTFPolicy +from ray.rllib.connectors.common.add_observations_from_episodes_to_batch import ( + AddObservationsFromEpisodesToBatch, +) +from ray.rllib.connectors.learner.add_next_observations_from_episodes_to_train_batch import ( # noqa + AddNextObservationsFromEpisodesToTrainBatch, +) +from ray.rllib.core.learner import Learner +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.policy.policy import Policy +from ray.rllib.utils import deep_update +from ray.rllib.utils.annotations import override +from ray.rllib.utils.deprecation import DEPRECATED_VALUE, deprecation_warning +from ray.rllib.utils.framework import try_import_tf, try_import_tfp +from ray.rllib.utils.replay_buffers.episode_replay_buffer import EpisodeReplayBuffer +from ray.rllib.utils.typing import LearningRateOrSchedule, RLModuleSpecType + +tf1, tf, tfv = try_import_tf() +tfp = try_import_tfp() + +logger = logging.getLogger(__name__) + + +class SACConfig(AlgorithmConfig): + """Defines a configuration class from which an SAC Algorithm can be built. + + .. testcode:: + + config = ( + SACConfig() + .environment("Pendulum-v1") + .env_runners(num_env_runners=1) + .training( + gamma=0.9, + actor_lr=0.001, + critic_lr=0.002, + train_batch_size_per_learner=32, + ) + ) + # Build the SAC algo object from the config and run 1 training iteration. + algo = config.build() + algo.train() + """ + + def __init__(self, algo_class=None): + self.exploration_config = { + # The Exploration class to use. In the simplest case, this is the name + # (str) of any class present in the `rllib.utils.exploration` package. + # You can also provide the python class directly or the full location + # of your class (e.g. "ray.rllib.utils.exploration.epsilon_greedy. + # EpsilonGreedy"). + "type": "StochasticSampling", + # Add constructor kwargs here (if any). + } + + super().__init__(algo_class=algo_class or SAC) + + # fmt: off + # __sphinx_doc_begin__ + # SAC-specific config settings. + # `.training()` + self.twin_q = True + self.q_model_config = { + "fcnet_hiddens": [256, 256], + "fcnet_activation": "relu", + "post_fcnet_hiddens": [], + "post_fcnet_activation": None, + "custom_model": None, # Use this to define custom Q-model(s). + "custom_model_config": {}, + } + self.policy_model_config = { + "fcnet_hiddens": [256, 256], + "fcnet_activation": "relu", + "post_fcnet_hiddens": [], + "post_fcnet_activation": None, + "custom_model": None, # Use this to define a custom policy model. + "custom_model_config": {}, + } + self.clip_actions = False + self.tau = 5e-3 + self.initial_alpha = 1.0 + self.target_entropy = "auto" + self.n_step = 1 + + # Replay buffer configuration. + self.replay_buffer_config = { + "type": "PrioritizedEpisodeReplayBuffer", + # Size of the replay buffer. Note that if async_updates is set, + # then each worker will have a replay buffer of this size. + "capacity": int(1e6), + "alpha": 0.6, + # Beta parameter for sampling from prioritized replay buffer. + "beta": 0.4, + } + + self.store_buffer_in_checkpoints = False + self.training_intensity = None + self.optimization = { + "actor_learning_rate": 3e-4, + "critic_learning_rate": 3e-4, + "entropy_learning_rate": 3e-4, + } + self.actor_lr = 3e-5 + self.critic_lr = 3e-4 + self.alpha_lr = 3e-4 + # Set `lr` parameter to `None` and ensure it is not used. + self.lr = None + self.grad_clip = None + self.target_network_update_freq = 0 + + # .env_runners() + # Set to `self.n_step`, if 'auto'. + self.rollout_fragment_length = "auto" + + # .training() + self.train_batch_size_per_learner = 256 + self.train_batch_size = 256 # @OldAPIstack + self.num_steps_sampled_before_learning_starts = 1500 + + # .reporting() + self.min_time_s_per_iteration = 1 + self.min_sample_timesteps_per_iteration = 100 + # __sphinx_doc_end__ + # fmt: on + + self._deterministic_loss = False + self._use_beta_distribution = False + + self.use_state_preprocessor = DEPRECATED_VALUE + self.worker_side_prioritization = DEPRECATED_VALUE + + @override(AlgorithmConfig) + def training( + self, + *, + twin_q: Optional[bool] = NotProvided, + q_model_config: Optional[Dict[str, Any]] = NotProvided, + policy_model_config: Optional[Dict[str, Any]] = NotProvided, + tau: Optional[float] = NotProvided, + initial_alpha: Optional[float] = NotProvided, + target_entropy: Optional[Union[str, float]] = NotProvided, + n_step: Optional[Union[int, Tuple[int, int]]] = NotProvided, + store_buffer_in_checkpoints: Optional[bool] = NotProvided, + replay_buffer_config: Optional[Dict[str, Any]] = NotProvided, + training_intensity: Optional[float] = NotProvided, + clip_actions: Optional[bool] = NotProvided, + grad_clip: Optional[float] = NotProvided, + optimization_config: Optional[Dict[str, Any]] = NotProvided, + actor_lr: Optional[LearningRateOrSchedule] = NotProvided, + critic_lr: Optional[LearningRateOrSchedule] = NotProvided, + alpha_lr: Optional[LearningRateOrSchedule] = NotProvided, + target_network_update_freq: Optional[int] = NotProvided, + _deterministic_loss: Optional[bool] = NotProvided, + _use_beta_distribution: Optional[bool] = NotProvided, + num_steps_sampled_before_learning_starts: Optional[int] = NotProvided, + **kwargs, + ) -> "SACConfig": + """Sets the training related configuration. + + Args: + twin_q: Use two Q-networks (instead of one) for action-value estimation. + Note: Each Q-network will have its own target network. + q_model_config: Model configs for the Q network(s). These will override + MODEL_DEFAULTS. This is treated just as the top-level `model` dict in + setting up the Q-network(s) (2 if twin_q=True). + That means, you can do for different observation spaces: + `obs=Box(1D)` -> `Tuple(Box(1D) + Action)` -> `concat` -> `post_fcnet` + obs=Box(3D) -> Tuple(Box(3D) + Action) -> vision-net -> concat w/ action + -> post_fcnet + obs=Tuple(Box(1D), Box(3D)) -> Tuple(Box(1D), Box(3D), Action) + -> vision-net -> concat w/ Box(1D) and action -> post_fcnet + You can also have SAC use your custom_model as Q-model(s), by simply + specifying the `custom_model` sub-key in below dict (just like you would + do in the top-level `model` dict. + policy_model_config: Model options for the policy function (see + `q_model_config` above for details). The difference to `q_model_config` + above is that no action concat'ing is performed before the post_fcnet + stack. + tau: Update the target by \tau * policy + (1-\tau) * target_policy. + initial_alpha: Initial value to use for the entropy weight alpha. + target_entropy: Target entropy lower bound. If "auto", will be set + to `-|A|` (e.g. -2.0 for Discrete(2), -3.0 for Box(shape=(3,))). + This is the inverse of reward scale, and will be optimized + automatically. + n_step: N-step target updates. If >1, sars' tuples in trajectories will be + postprocessed to become sa[discounted sum of R][s t+n] tuples. An + integer will be interpreted as a fixed n-step value. If a tuple of 2 + ints is provided here, the n-step value will be drawn for each sample(!) + in the train batch from a uniform distribution over the closed interval + defined by `[n_step[0], n_step[1]]`. + store_buffer_in_checkpoints: Set this to True, if you want the contents of + your buffer(s) to be stored in any saved checkpoints as well. + Warnings will be created if: + - This is True AND restoring from a checkpoint that contains no buffer + data. + - This is False AND restoring from a checkpoint that does contain + buffer data. + replay_buffer_config: Replay buffer config. + Examples: + { + "_enable_replay_buffer_api": True, + "type": "MultiAgentReplayBuffer", + "capacity": 50000, + "replay_batch_size": 32, + "replay_sequence_length": 1, + } + - OR - + { + "_enable_replay_buffer_api": True, + "type": "MultiAgentPrioritizedReplayBuffer", + "capacity": 50000, + "prioritized_replay_alpha": 0.6, + "prioritized_replay_beta": 0.4, + "prioritized_replay_eps": 1e-6, + "replay_sequence_length": 1, + } + - Where - + prioritized_replay_alpha: Alpha parameter controls the degree of + prioritization in the buffer. In other words, when a buffer sample has + a higher temporal-difference error, with how much more probability + should it drawn to use to update the parametrized Q-network. 0.0 + corresponds to uniform probability. Setting much above 1.0 may quickly + result as the sampling distribution could become heavily “pointy” with + low entropy. + prioritized_replay_beta: Beta parameter controls the degree of + importance sampling which suppresses the influence of gradient updates + from samples that have higher probability of being sampled via alpha + parameter and the temporal-difference error. + prioritized_replay_eps: Epsilon parameter sets the baseline probability + for sampling so that when the temporal-difference error of a sample is + zero, there is still a chance of drawing the sample. + training_intensity: The intensity with which to update the model (vs + collecting samples from the env). + If None, uses "natural" values of: + `train_batch_size` / (`rollout_fragment_length` x `num_env_runners` x + `num_envs_per_env_runner`). + If not None, will make sure that the ratio between timesteps inserted + into and sampled from th buffer matches the given values. + Example: + training_intensity=1000.0 + train_batch_size=250 + rollout_fragment_length=1 + num_env_runners=1 (or 0) + num_envs_per_env_runner=1 + -> natural value = 250 / 1 = 250.0 + -> will make sure that replay+train op will be executed 4x asoften as + rollout+insert op (4 * 250 = 1000). + See: rllib/algorithms/dqn/dqn.py::calculate_rr_weights for further + details. + clip_actions: Whether to clip actions. If actions are already normalized, + this should be set to False. + grad_clip: If not None, clip gradients during optimization at this value. + optimization_config: Config dict for optimization. Set the supported keys + `actor_learning_rate`, `critic_learning_rate`, and + `entropy_learning_rate` in here. + actor_lr: The learning rate (float) or learning rate schedule for the + policy in the format of + [[timestep, lr-value], [timestep, lr-value], ...] In case of a + schedule, intermediary timesteps will be assigned to linearly + interpolated learning rate values. A schedule config's first entry + must start with timestep 0, i.e.: [[0, initial_value], [...]]. + Note: It is common practice (two-timescale approach) to use a smaller + learning rate for the policy than for the critic to ensure that the + critic gives adequate values for improving the policy. + Note: If you require a) more than one optimizer (per RLModule), + b) optimizer types that are not Adam, c) a learning rate schedule that + is not a linearly interpolated, piecewise schedule as described above, + or d) specifying c'tor arguments of the optimizer that are not the + learning rate (e.g. Adam's epsilon), then you must override your + Learner's `configure_optimizer_for_module()` method and handle + lr-scheduling yourself. + The default value is 3e-5, one decimal less than the respective + learning rate of the critic (see `critic_lr`). + critic_lr: The learning rate (float) or learning rate schedule for the + critic in the format of + [[timestep, lr-value], [timestep, lr-value], ...] In case of a + schedule, intermediary timesteps will be assigned to linearly + interpolated learning rate values. A schedule config's first entry + must start with timestep 0, i.e.: [[0, initial_value], [...]]. + Note: It is common practice (two-timescale approach) to use a smaller + learning rate for the policy than for the critic to ensure that the + critic gives adequate values for improving the policy. + Note: If you require a) more than one optimizer (per RLModule), + b) optimizer types that are not Adam, c) a learning rate schedule that + is not a linearly interpolated, piecewise schedule as described above, + or d) specifying c'tor arguments of the optimizer that are not the + learning rate (e.g. Adam's epsilon), then you must override your + Learner's `configure_optimizer_for_module()` method and handle + lr-scheduling yourself. + The default value is 3e-4, one decimal higher than the respective + learning rate of the actor (policy) (see `actor_lr`). + alpha_lr: The learning rate (float) or learning rate schedule for the + hyperparameter alpha in the format of + [[timestep, lr-value], [timestep, lr-value], ...] In case of a + schedule, intermediary timesteps will be assigned to linearly + interpolated learning rate values. A schedule config's first entry + must start with timestep 0, i.e.: [[0, initial_value], [...]]. + Note: If you require a) more than one optimizer (per RLModule), + b) optimizer types that are not Adam, c) a learning rate schedule that + is not a linearly interpolated, piecewise schedule as described above, + or d) specifying c'tor arguments of the optimizer that are not the + learning rate (e.g. Adam's epsilon), then you must override your + Learner's `configure_optimizer_for_module()` method and handle + lr-scheduling yourself. + The default value is 3e-4, identical to the critic learning rate (`lr`). + target_network_update_freq: Update the target network every + `target_network_update_freq` steps. + num_steps_sampled_before_learning_starts: Number of timesteps (int) + that we collect from the runners before we start sampling the + replay buffers for learning. Whether we count this in agent steps + or environment steps depends on the value of + `config.multi_agent(count_steps_by=...)`. + _deterministic_loss: Whether the loss should be calculated deterministically + (w/o the stochastic action sampling step). True only useful for + continuous actions and for debugging. + _use_beta_distribution: Use a Beta-distribution instead of a + `SquashedGaussian` for bounded, continuous action spaces (not + recommended; for debugging only). + + Returns: + This updated AlgorithmConfig object. + """ + # Pass kwargs onto super's `training()` method. + super().training(**kwargs) + + if twin_q is not NotProvided: + self.twin_q = twin_q + if q_model_config is not NotProvided: + self.q_model_config.update(q_model_config) + if policy_model_config is not NotProvided: + self.policy_model_config.update(policy_model_config) + if tau is not NotProvided: + self.tau = tau + if initial_alpha is not NotProvided: + self.initial_alpha = initial_alpha + if target_entropy is not NotProvided: + self.target_entropy = target_entropy + if n_step is not NotProvided: + self.n_step = n_step + if store_buffer_in_checkpoints is not NotProvided: + self.store_buffer_in_checkpoints = store_buffer_in_checkpoints + if replay_buffer_config is not NotProvided: + # Override entire `replay_buffer_config` if `type` key changes. + # Update, if `type` key remains the same or is not specified. + new_replay_buffer_config = deep_update( + {"replay_buffer_config": self.replay_buffer_config}, + {"replay_buffer_config": replay_buffer_config}, + False, + ["replay_buffer_config"], + ["replay_buffer_config"], + ) + self.replay_buffer_config = new_replay_buffer_config["replay_buffer_config"] + if training_intensity is not NotProvided: + self.training_intensity = training_intensity + if clip_actions is not NotProvided: + self.clip_actions = clip_actions + if grad_clip is not NotProvided: + self.grad_clip = grad_clip + if optimization_config is not NotProvided: + self.optimization = optimization_config + if actor_lr is not NotProvided: + self.actor_lr = actor_lr + if critic_lr is not NotProvided: + self.critic_lr = critic_lr + if alpha_lr is not NotProvided: + self.alpha_lr = alpha_lr + if target_network_update_freq is not NotProvided: + self.target_network_update_freq = target_network_update_freq + if _deterministic_loss is not NotProvided: + self._deterministic_loss = _deterministic_loss + if _use_beta_distribution is not NotProvided: + self._use_beta_distribution = _use_beta_distribution + if num_steps_sampled_before_learning_starts is not NotProvided: + self.num_steps_sampled_before_learning_starts = ( + num_steps_sampled_before_learning_starts + ) + + return self + + @override(AlgorithmConfig) + def validate(self) -> None: + # Call super's validation method. + super().validate() + + # Check rollout_fragment_length to be compatible with n_step. + if isinstance(self.n_step, tuple): + min_rollout_fragment_length = self.n_step[1] + else: + min_rollout_fragment_length = self.n_step + + if ( + not self.in_evaluation + and self.rollout_fragment_length != "auto" + and self.rollout_fragment_length + < min_rollout_fragment_length # (self.n_step or 1) + ): + raise ValueError( + f"Your `rollout_fragment_length` ({self.rollout_fragment_length}) is " + f"smaller than needed for `n_step` ({self.n_step})! If `n_step` is " + f"an integer try setting `rollout_fragment_length={self.n_step}`. If " + "`n_step` is a tuple, try setting " + f"`rollout_fragment_length={self.n_step[1]}`." + ) + + if self.use_state_preprocessor != DEPRECATED_VALUE: + deprecation_warning( + old="config['use_state_preprocessor']", + error=False, + ) + self.use_state_preprocessor = DEPRECATED_VALUE + + if self.grad_clip is not None and self.grad_clip <= 0.0: + raise ValueError("`grad_clip` value must be > 0.0!") + + if self.framework in ["tf", "tf2"] and tfp is None: + logger.warning( + "You need `tensorflow_probability` in order to run SAC! " + "Install it via `pip install tensorflow_probability`. Your " + f"tf.__version__={tf.__version__ if tf else None}." + "Trying to import tfp results in the following error:" + ) + try_import_tfp(error=True) + + # Validate that we use the corresponding `EpisodeReplayBuffer` when using + # episodes. + if ( + self.enable_env_runner_and_connector_v2 + and self.replay_buffer_config["type"] + not in [ + "EpisodeReplayBuffer", + "PrioritizedEpisodeReplayBuffer", + "MultiAgentEpisodeReplayBuffer", + "MultiAgentPrioritizedEpisodeReplayBuffer", + ] + and not ( + # TODO (simon): Set up an indicator `is_offline_new_stack` that + # includes all these variable checks. + self.input_ + and ( + isinstance(self.input_, str) + or ( + isinstance(self.input_, list) + and isinstance(self.input_[0], str) + ) + ) + and self.input_ != "sampler" + and self.enable_rl_module_and_learner + ) + ): + raise ValueError( + "When using the new `EnvRunner API` the replay buffer must be of type " + "`EpisodeReplayBuffer`." + ) + elif not self.enable_env_runner_and_connector_v2 and ( + ( + isinstance(self.replay_buffer_config["type"], str) + and "Episode" in self.replay_buffer_config["type"] + ) + or ( + isinstance(self.replay_buffer_config["type"], type) + and issubclass(self.replay_buffer_config["type"], EpisodeReplayBuffer) + ) + ): + raise ValueError( + "When using the old API stack the replay buffer must not be of type " + "`EpisodeReplayBuffer`! We suggest you use the following config to run " + "SAC on the old API stack: `config.training(replay_buffer_config={" + "'type': 'MultiAgentPrioritizedReplayBuffer', " + "'prioritized_replay_alpha': [alpha], " + "'prioritized_replay_beta': [beta], " + "'prioritized_replay_eps': [eps], " + "})`." + ) + + if self.enable_rl_module_and_learner: + if self.lr is not None: + raise ValueError( + "Basic learning rate parameter `lr` is not `None`. For SAC " + "use the specific learning rate parameters `actor_lr`, `critic_lr` " + "and `alpha_lr`, for the actor, critic, and the hyperparameter " + "`alpha`, respectively and set `config.lr` to None." + ) + # Warn about new API stack on by default. + logger.warning( + "You are running SAC on the new API stack! This is the new default " + "behavior for this algorithm. If you don't want to use the new API " + "stack, set `config.api_stack(enable_rl_module_and_learner=False, " + "enable_env_runner_and_connector_v2=False)`. For a detailed " + "migration guide, see here: https://docs.ray.io/en/master/rllib/new-api-stack-migration-guide.html" # noqa + ) + + @override(AlgorithmConfig) + def get_rollout_fragment_length(self, worker_index: int = 0) -> int: + if self.rollout_fragment_length == "auto": + return ( + self.n_step[1] + if isinstance(self.n_step, (tuple, list)) + else self.n_step + ) + else: + return self.rollout_fragment_length + + @override(AlgorithmConfig) + def get_default_rl_module_spec(self) -> RLModuleSpecType: + if self.framework_str == "torch": + from ray.rllib.algorithms.sac.torch.default_sac_torch_rl_module import ( + DefaultSACTorchRLModule, + ) + + return RLModuleSpec(module_class=DefaultSACTorchRLModule) + else: + raise ValueError( + f"The framework {self.framework_str} is not supported. Use `torch`." + ) + + @override(AlgorithmConfig) + def get_default_learner_class(self) -> Union[Type["Learner"], str]: + if self.framework_str == "torch": + from ray.rllib.algorithms.sac.torch.sac_torch_learner import SACTorchLearner + + return SACTorchLearner + else: + raise ValueError( + f"The framework {self.framework_str} is not supported. Use `torch`." + ) + + @override(AlgorithmConfig) + def build_learner_connector( + self, + input_observation_space, + input_action_space, + device=None, + ): + pipeline = super().build_learner_connector( + input_observation_space=input_observation_space, + input_action_space=input_action_space, + device=device, + ) + + # Prepend the "add-NEXT_OBS-from-episodes-to-train-batch" connector piece (right + # after the corresponding "add-OBS-..." default piece). + pipeline.insert_after( + AddObservationsFromEpisodesToBatch, + AddNextObservationsFromEpisodesToTrainBatch(), + ) + + return pipeline + + @property + def _model_config_auto_includes(self): + return super()._model_config_auto_includes | {"twin_q": self.twin_q} + + +class SAC(DQN): + """Soft Actor Critic (SAC) Algorithm class. + + This file defines the distributed Algorithm class for the soft actor critic + algorithm. + See `sac_[tf|torch]_policy.py` for the definition of the policy loss. + + Detailed documentation: + https://docs.ray.io/en/master/rllib-algorithms.html#sac + """ + + def __init__(self, *args, **kwargs): + self._allow_unknown_subkeys += ["policy_model_config", "q_model_config"] + super().__init__(*args, **kwargs) + + @classmethod + @override(DQN) + def get_default_config(cls) -> AlgorithmConfig: + return SACConfig() + + @classmethod + @override(DQN) + def get_default_policy_class( + cls, config: AlgorithmConfig + ) -> Optional[Type[Policy]]: + if config["framework"] == "torch": + from ray.rllib.algorithms.sac.sac_torch_policy import SACTorchPolicy + + return SACTorchPolicy + else: + return SACTFPolicy diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/sac_catalog.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/sac_catalog.py new file mode 100644 index 0000000000000000000000000000000000000000..c60bfd77992f0835356698c1cfbba0f0865afb84 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/sac_catalog.py @@ -0,0 +1,287 @@ +import gymnasium as gym +import numpy as np +from typing import Callable + +# TODO (simon): Store this function somewhere more central as many +# algorithms will use it. +from ray.rllib.algorithms.ppo.ppo_catalog import _check_if_diag_gaussian +from ray.rllib.core.models.catalog import Catalog +from ray.rllib.core.models.configs import ( + FreeLogStdMLPHeadConfig, + MLPEncoderConfig, + MLPHeadConfig, +) +from ray.rllib.core.models.base import Encoder, Model +from ray.rllib.core.distribution.torch.torch_distribution import ( + TorchSquashedGaussian, + TorchCategorical, +) +from ray.rllib.utils.annotations import override, OverrideToImplementCustomLogic +from ray.rllib.core.distribution.distribution import Distribution + + +# TODO (simon): Check, if we can directly derive from DQNCatalog. +# This should work as we need a qf and qf_target. +# TODO (simon): Add CNNEnocders for Image observations. +class SACCatalog(Catalog): + """The catalog class used to build models for SAC. + + SACCatalog provides the following models: + - Encoder: The encoder used to encode the observations for the actor + network (`pi`). For this we use the default encoder from the Catalog. + - Q-Function Encoder: The encoder used to encode the observations and + actions for the soft Q-function network. + - Target Q-Function Encoder: The encoder used to encode the observations + and actions for the target soft Q-function network. + - Pi Head: The head used to compute the policy logits. This network outputs + the mean and log-std for the action distribution (a Squashed Gaussian). + - Q-Function Head: The head used to compute the soft Q-values. + - Target Q-Function Head: The head used to compute the target soft Q-values. + + Any custom Encoder to be used for the policy network can be built by overriding + the build_encoder() method. Alternatively the `encoder_config` can be overridden + by using the `model_config_dict`. + + Any custom Q-Function Encoder can be built by overriding the build_qf_encoder(). + Important: The Q-Function Encoder must encode both the state and the action. The + same holds true for the target Q-Function Encoder. + + Any custom head can be built by overriding the build_pi_head() and build_qf_head(). + + Any module built for exploration or inference is built with the flag + `ìnference_only=True` and does not contain any Q-function. This flag can be set + in the `model_config_dict` with the key `ray.rllib.core.rl_module.INFERENCE_ONLY`. + """ + + def __init__( + self, + observation_space: gym.Space, + action_space: gym.Space, + model_config_dict: dict, + view_requirements: dict = None, + ): + """Initializes the SACCatalog. + + Args: + observation_space: The observation space of the Encoder. + action_space: The action space for the Pi Head. + model_config_dict: The model config to use. + """ + assert view_requirements is None, ( + "Instead, use the new ConnectorV2 API to pick whatever information " + "you need from the running episodes" + ) + + super().__init__( + observation_space=observation_space, + action_space=action_space, + model_config_dict=model_config_dict, + ) + if not isinstance(self.action_space, (gym.spaces.Box, gym.spaces.Discrete)): + self._raise_unsupported_action_space_error() + + # Define the heads. + self.pi_and_qf_head_hiddens = self._model_config_dict["head_fcnet_hiddens"] + self.pi_and_qf_head_activation = self._model_config_dict[ + "head_fcnet_activation" + ] + + # We don't have the exact (framework specific) action dist class yet and thus + # cannot determine the exact number of output nodes (action space) required. + # -> Build pi config only in the `self.build_pi_head` method. + self.pi_head_config = None + + # SAC-Discrete: The Q-function outputs q-values for each action + # SAC-Continuous: The Q-function outputs a single value (the Q-value for the + # action taken). + required_qf_output_dim = ( + self.action_space.n + if isinstance(self.action_space, gym.spaces.Discrete) + else 1 + ) + + # TODO (simon): Implement in a later step a q network with + # different `head_fcnet_hiddens` than pi. + # TODO (simon): These latent_dims could be different for the + # q function, value function, and pi head. + # Here we consider the simple case of identical encoders. + self.qf_head_config = MLPHeadConfig( + input_dims=self.latent_dims, + hidden_layer_dims=self.pi_and_qf_head_hiddens, + hidden_layer_activation=self.pi_and_qf_head_activation, + output_layer_activation="linear", + output_layer_dim=required_qf_output_dim, + ) + + @OverrideToImplementCustomLogic + def build_qf_encoder(self, framework: str) -> Encoder: + """Builds the Q-function encoder. + + In contrast to PPO, SAC needs a different encoder for Pi and + Q-function as the Q-function in the continuous case has to + encode actions, too. Therefore the Q-function uses its own + encoder config. + Note, the Pi network uses the base encoder from the `Catalog`. + + Args: + framework: The framework to use. Either `torch` or `tf2`. + + Returns: + The encoder for the Q-network. + """ + + # Compute the required dimension for the action space. + if isinstance(self.action_space, gym.spaces.Box): + required_action_dim = self.action_space.shape[0] + elif isinstance(self.action_space, gym.spaces.Discrete): + # for discrete action spaces, we don't need to encode the action + # because the Q-function will output a value for each action + required_action_dim = 0 + else: + self._raise_unsupported_action_space_error() + + # Encoder input for the Q-network contains state and action. We + # need to infer the shape for the input from the state and action + # spaces + if not ( + isinstance(self.observation_space, gym.spaces.Box) + and len(self.observation_space.shape) == 1 + ): + raise ValueError("The observation space is not supported by RLlib's SAC.") + + input_space = gym.spaces.Box( + -np.inf, + np.inf, + (self.observation_space.shape[0] + required_action_dim,), + dtype=np.float32, + ) + + self.qf_encoder_hiddens = self._model_config_dict["fcnet_hiddens"][:-1] + self.qf_encoder_activation = self._model_config_dict["fcnet_activation"] + + self.qf_encoder_config = MLPEncoderConfig( + input_dims=input_space.shape, + hidden_layer_dims=self.qf_encoder_hiddens, + hidden_layer_activation=self.qf_encoder_activation, + output_layer_dim=self.latent_dims[0], + output_layer_activation=self.qf_encoder_activation, + ) + + return self.qf_encoder_config.build(framework=framework) + + @OverrideToImplementCustomLogic + def build_pi_head(self, framework: str) -> Model: + """Builds the policy head. + + The default behavior is to build the head from the pi_head_config. + This can be overridden to build a custom policy head as a means of configuring + the behavior of the DefaultSACRLModule implementation. + + Args: + framework: The framework to use. Either "torch" or "tf2". + + Returns: + The policy head. + """ + # Get action_distribution_cls to find out about the output dimension for pi_head + action_distribution_cls = self.get_action_dist_cls(framework=framework) + BUILD_MAP: dict[ + type[gym.spaces.Space], Callable[[str, Distribution], Model] + ] = { + gym.spaces.Discrete: self._build_pi_head_discrete, + gym.spaces.Box: self._build_pi_head_continuous, + } + try: + # Try to get the build function for the action space type. + return BUILD_MAP[type(self.action_space)]( + framework, action_distribution_cls + ) + except KeyError: + # If the action space type is not supported, raise an error. + self._raise_unsupported_action_space_error() + + def _build_pi_head_continuous( + self, framework: str, action_distribution_cls: Distribution + ) -> Model: + """Builds the policy head for continuous action spaces.""" + # Get action_distribution_cls to find out about the output dimension for pi_head + # TODO (simon): CHeck, if this holds also for Squashed Gaussian. + if self._model_config_dict["free_log_std"]: + _check_if_diag_gaussian( + action_distribution_cls=action_distribution_cls, framework=framework + ) + is_diag_gaussian = True + else: + is_diag_gaussian = _check_if_diag_gaussian( + action_distribution_cls=action_distribution_cls, + framework=framework, + no_error=True, + ) + required_output_dim = action_distribution_cls.required_input_dim( + space=self.action_space, model_config=self._model_config_dict + ) + # Now that we have the action dist class and number of outputs, we can define + # our pi-config and build the pi head. + pi_head_config_class = ( + FreeLogStdMLPHeadConfig + if self._model_config_dict["free_log_std"] + else MLPHeadConfig + ) + self.pi_head_config = pi_head_config_class( + input_dims=self.latent_dims, + hidden_layer_dims=self.pi_and_qf_head_hiddens, + hidden_layer_activation=self.pi_and_qf_head_activation, + output_layer_dim=required_output_dim, + output_layer_activation="linear", + clip_log_std=is_diag_gaussian, + log_std_clip_param=self._model_config_dict.get("log_std_clip_param", 20), + ) + + return self.pi_head_config.build(framework=framework) + + def _build_pi_head_discrete( + self, framework: str, action_distribution_cls: Distribution + ) -> Model: + """Builds the policy head for discrete action spaces. The module outputs logits for Categorical + distribution. + """ + required_output_dim = action_distribution_cls.required_input_dim( + space=self.action_space, model_config=self._model_config_dict + ) + self.pi_head_config = MLPHeadConfig( + input_dims=self.latent_dims, + hidden_layer_dims=self.pi_and_qf_head_hiddens, + hidden_layer_activation=self.pi_and_qf_head_activation, + output_layer_dim=required_output_dim, + output_layer_activation="linear", + ) + return self.pi_head_config.build(framework=framework) + + @OverrideToImplementCustomLogic + def build_qf_head(self, framework: str) -> Model: + """Build the Q function head.""" + + return self.qf_head_config.build(framework=framework) + + @override(Catalog) + def get_action_dist_cls(self, framework: str) -> Distribution: + """Returns the action distribution class to use for the given framework. TorchSquashedGaussian + for continuous action spaces and TorchCategorical for discrete action spaces.""" + # TODO (KIY): Catalog.get_action_dist_cls should return a type[Distribution] instead of a Distribution instance. + assert framework == "torch" + + if isinstance(self.action_space, gym.spaces.Box): + # For continuous action spaces, we use a Squashed Gaussian. + return TorchSquashedGaussian + elif isinstance(self.action_space, gym.spaces.Discrete): + # For discrete action spaces, we use a Categorical distribution. + return TorchCategorical + else: + self._raise_unsupported_action_space_error() + + def _raise_unsupported_action_space_error(self): + """Raises an error if the action space is not supported.""" + raise ValueError( + f"SAC only supports Box and Discrete action spaces. " + f"Got: {type(self.action_space)}" + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/sac_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/sac_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..f4108943ad046339d51b50a5d395a9111228385e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/sac_learner.py @@ -0,0 +1,115 @@ +import numpy as np + +from typing import Dict + +from ray.rllib.algorithms.dqn.dqn_learner import DQNLearner +from ray.rllib.core.learner.learner import Learner +from ray.rllib.utils.annotations import override +from ray.rllib.utils.lambda_defaultdict import LambdaDefaultDict +from ray.rllib.utils.typing import ModuleID, TensorType + +# Now, this is double defined: In `DefaultSACRLModule` and here. I would keep it here +# or push it into the `Learner` as these are recurring keys in RL. +LOGPS_KEY = "logps" +QF_LOSS_KEY = "qf_loss" +QF_MEAN_KEY = "qf_mean" +QF_MAX_KEY = "qf_max" +QF_MIN_KEY = "qf_min" +QF_PREDS = "qf_preds" +QF_TWIN_LOSS_KEY = "qf_twin_loss" +QF_TWIN_PREDS = "qf_twin_preds" +TD_ERROR_MEAN_KEY = "td_error_mean" +CRITIC_TARGET = "critic_target" +ACTION_DIST_INPUTS_NEXT = "action_dist_inputs_next" +QF_TARGET_NEXT = "q_target_next" +ACTION_PROBS_NEXT = "action_probs_next" +ACTION_LOG_PROBS_NEXT = "action_log_probs_next" +ACTION_PROBS = "action_probs" +ACTION_LOG_PROBS = "action_log_probs" + + +class SACLearner(DQNLearner): + @override(Learner) + def build(self) -> None: + # Store the current alpha in log form. We need it during optimization + # in log form. + self.curr_log_alpha: Dict[ModuleID, TensorType] = LambdaDefaultDict( + lambda module_id: self._get_tensor_variable( + # Note, we want to train the temperature parameter. + [ + np.log( + self.config.get_config_for_module(module_id).initial_alpha + ).astype(np.float32) + ], + trainable=True, + ) + ) + + # We need to call the `super()`'s `build()` method here to have the variables + # for the alpha already defined. + super().build() + + self.target_entropy: Dict[ModuleID, TensorType] = LambdaDefaultDict( + lambda module_id: self._get_tensor_variable( + self._get_target_entropy(module_id) + ) + ) + + @override(Learner) + def remove_module(self, module_id: ModuleID) -> None: + """Removes the temperature and target entropy. + + Note, this means that we also need to remove the corresponding + temperature optimizer. + """ + super().remove_module(module_id) + self.curr_log_alpha.pop(module_id, None) + self.target_entropy.pop(module_id, None) + + @override(Learner) + def add_module( + self, + *, + module_id, + module_spec, + config_overrides=None, + new_should_module_be_updated=None + ): + # First call `super`'s `add_module` method. + super().add_module( + module_id=module_id, + module_spec=module_spec, + config_overrides=config_overrides, + new_should_module_be_updated=new_should_module_be_updated, + ) + # Now add the log alpha. + self.curr_log_alpha[module_id] = self._get_tensor_variable( + # Note, we want to train the temperature parameter. + [ + np.log( + self.config.get_config_for_module(module_id).initial_alpha + ).astype(np.float32) + ], + trainable=True, + ) + # Add also the target entropy for the new module. + self.target_entropy[module_id] = self._get_tensor_variable( + self._get_target_entropy(module_id) + ) + + def _get_target_entropy(self, module_id): + """Returns the target entropy to use for the loss. + + Args: + module_id: Module ID for which the target entropy should be + returned. + + Returns: + Target entropy. + """ + target_entropy = self.config.get_config_for_module(module_id).target_entropy + if target_entropy is None or target_entropy == "auto": + target_entropy = -np.prod( + self._module_spec.module_specs[module_id].action_space.shape + ) + return target_entropy diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/sac_tf_model.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/sac_tf_model.py new file mode 100644 index 0000000000000000000000000000000000000000..7302a25fcccf95a5ec262c0cf3574c62df328222 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/sac_tf_model.py @@ -0,0 +1,321 @@ +import gymnasium as gym +from gymnasium.spaces import Box, Discrete +import numpy as np +import tree # pip install dm_tree +from typing import Dict, List, Optional + +from ray.rllib.models.catalog import ModelCatalog +from ray.rllib.models.tf.tf_modelv2 import TFModelV2 +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.spaces.simplex import Simplex +from ray.rllib.utils.typing import ModelConfigDict, TensorType, TensorStructType + +tf1, tf, tfv = try_import_tf() + + +class SACTFModel(TFModelV2): + """Extension of the standard TFModelV2 for SAC. + + To customize, do one of the following: + - sub-class SACTFModel and override one or more of its methods. + - Use SAC's `q_model_config` and `policy_model` keys to tweak the default model + behaviors (e.g. fcnet_hiddens, conv_filters, etc..). + - Use SAC's `q_model_config->custom_model` and `policy_model->custom_model` keys + to specify your own custom Q-model(s) and policy-models, which will be + created within this SACTFModel (see `build_policy_model` and + `build_q_model`. + + Note: It is not recommended to override the `forward` method for SAC. This + would lead to shared weights (between policy and Q-nets), which will then + not be optimized by either of the critic- or actor-optimizers! + + Data flow: + `obs` -> forward() (should stay a noop method!) -> `model_out` + `model_out` -> get_policy_output() -> pi(actions|obs) + `model_out`, `actions` -> get_q_values() -> Q(s, a) + `model_out`, `actions` -> get_twin_q_values() -> Q_twin(s, a) + """ + + def __init__( + self, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + num_outputs: Optional[int], + model_config: ModelConfigDict, + name: str, + policy_model_config: ModelConfigDict = None, + q_model_config: ModelConfigDict = None, + twin_q: bool = False, + initial_alpha: float = 1.0, + target_entropy: Optional[float] = None, + ): + """Initialize a SACTFModel instance. + + Args: + policy_model_config: The config dict for the + policy network. + q_model_config: The config dict for the + Q-network(s) (2 if twin_q=True). + twin_q: Build twin Q networks (Q-net and target) for more + stable Q-learning. + initial_alpha: The initial value for the to-be-optimized + alpha parameter (default: 1.0). + target_entropy (Optional[float]): A target entropy value for + the to-be-optimized alpha parameter. If None, will use the + defaults described in the papers for SAC (and discrete SAC). + + Note that the core layers for forward() are not defined here, this + only defines the layers for the output heads. Those layers for + forward() should be defined in subclasses of SACModel. + """ + super(SACTFModel, self).__init__( + obs_space, action_space, num_outputs, model_config, name + ) + if isinstance(action_space, Discrete): + self.action_dim = action_space.n + self.discrete = True + action_outs = q_outs = self.action_dim + elif isinstance(action_space, Box): + self.action_dim = np.prod(action_space.shape) + self.discrete = False + action_outs = 2 * self.action_dim + q_outs = 1 + else: + assert isinstance(action_space, Simplex) + self.action_dim = np.prod(action_space.shape) + self.discrete = False + action_outs = self.action_dim + q_outs = 1 + + self.action_model = self.build_policy_model( + self.obs_space, action_outs, policy_model_config, "policy_model" + ) + + self.q_net = self.build_q_model( + self.obs_space, self.action_space, q_outs, q_model_config, "q" + ) + if twin_q: + self.twin_q_net = self.build_q_model( + self.obs_space, self.action_space, q_outs, q_model_config, "twin_q" + ) + else: + self.twin_q_net = None + + self.log_alpha = tf.Variable( + np.log(initial_alpha), dtype=tf.float32, name="log_alpha" + ) + self.alpha = tf.exp(self.log_alpha) + + # Auto-calculate the target entropy. + if target_entropy is None or target_entropy == "auto": + # See hyperparams in [2] (README.md). + if self.discrete: + target_entropy = 0.98 * np.array( + -np.log(1.0 / action_space.n), dtype=np.float32 + ) + # See [1] (README.md). + else: + target_entropy = -np.prod(action_space.shape) + self.target_entropy = target_entropy + + @override(TFModelV2) + def forward( + self, + input_dict: Dict[str, TensorType], + state: List[TensorType], + seq_lens: TensorType, + ) -> (TensorType, List[TensorType]): + """The common (Q-net and policy-net) forward pass. + + NOTE: It is not(!) recommended to override this method as it would + introduce a shared pre-network, which would be updated by both + actor- and critic optimizers. + """ + return input_dict["obs"], state + + def build_policy_model(self, obs_space, num_outputs, policy_model_config, name): + """Builds the policy model used by this SAC. + + Override this method in a sub-class of SACTFModel to implement your + own policy net. Alternatively, simply set `custom_model` within the + top level SAC `policy_model` config key to make this default + implementation of `build_policy_model` use your custom policy network. + + Returns: + TFModelV2: The TFModelV2 policy sub-model. + """ + model = ModelCatalog.get_model_v2( + obs_space, + self.action_space, + num_outputs, + policy_model_config, + framework="tf", + name=name, + ) + return model + + def build_q_model(self, obs_space, action_space, num_outputs, q_model_config, name): + """Builds one of the (twin) Q-nets used by this SAC. + + Override this method in a sub-class of SACTFModel to implement your + own Q-nets. Alternatively, simply set `custom_model` within the + top level SAC `q_model_config` config key to make this default implementation + of `build_q_model` use your custom Q-nets. + + Returns: + TFModelV2: The TFModelV2 Q-net sub-model. + """ + self.concat_obs_and_actions = False + if self.discrete: + input_space = obs_space + else: + orig_space = getattr(obs_space, "original_space", obs_space) + if isinstance(orig_space, Box) and len(orig_space.shape) == 1: + input_space = Box( + float("-inf"), + float("inf"), + shape=(orig_space.shape[0] + action_space.shape[0],), + ) + self.concat_obs_and_actions = True + else: + input_space = gym.spaces.Tuple([orig_space, action_space]) + + model = ModelCatalog.get_model_v2( + input_space, + action_space, + num_outputs, + q_model_config, + framework="tf", + name=name, + ) + return model + + def get_q_values( + self, model_out: TensorType, actions: Optional[TensorType] = None + ) -> TensorType: + """Returns Q-values, given the output of self.__call__(). + + This implements Q(s, a) -> [single Q-value] for the continuous case and + Q(s) -> [Q-values for all actions] for the discrete case. + + Args: + model_out: Feature outputs from the model layers + (result of doing `self.__call__(obs)`). + actions (Optional[TensorType]): Continuous action batch to return + Q-values for. Shape: [BATCH_SIZE, action_dim]. If None + (discrete action case), return Q-values for all actions. + + Returns: + TensorType: Q-values tensor of shape [BATCH_SIZE, 1]. + """ + return self._get_q_value(model_out, actions, self.q_net) + + def get_twin_q_values( + self, model_out: TensorType, actions: Optional[TensorType] = None + ) -> TensorType: + """Same as get_q_values but using the twin Q net. + + This implements the twin Q(s, a). + + Args: + model_out: Feature outputs from the model layers + (result of doing `self.__call__(obs)`). + actions (Optional[Tensor]): Actions to return the Q-values for. + Shape: [BATCH_SIZE, action_dim]. If None (discrete action + case), return Q-values for all actions. + + Returns: + TensorType: Q-values tensor of shape [BATCH_SIZE, 1]. + """ + return self._get_q_value(model_out, actions, self.twin_q_net) + + def _get_q_value(self, model_out, actions, net): + # Model outs may come as original Tuple/Dict observations, concat them + # here if this is the case. + if isinstance(net.obs_space, Box): + if isinstance(model_out, (list, tuple)): + model_out = tf.concat(model_out, axis=-1) + elif isinstance(model_out, dict): + model_out = tf.concat(list(model_out.values()), axis=-1) + + # Continuous case -> concat actions to model_out. + if actions is not None: + if self.concat_obs_and_actions: + input_dict = {"obs": tf.concat([model_out, actions], axis=-1)} + else: + # TODO(junogng) : SampleBatch doesn't support list columns yet. + # Use ModelInputDict. + input_dict = {"obs": (model_out, actions)} + # Discrete case -> return q-vals for all actions. + else: + input_dict = {"obs": model_out} + # Switch on training mode (when getting Q-values, we are usually in + # training). + input_dict["is_training"] = True + + return net(input_dict, [], None) + + def get_action_model_outputs( + self, + model_out: TensorType, + state_in: List[TensorType] = None, + seq_lens: TensorType = None, + ) -> (TensorType, List[TensorType]): + """Returns distribution inputs and states given the output of + policy.model(). + + For continuous action spaces, these will be the mean/stddev + distribution inputs for the (SquashedGaussian) action distribution. + For discrete action spaces, these will be the logits for a categorical + distribution. + + Args: + model_out: Feature outputs from the model layers + (result of doing `model(obs)`). + state_in List(TensorType): State input for recurrent cells + seq_lens: Sequence lengths of input- and state + sequences + + Returns: + TensorType: Distribution inputs for sampling actions. + """ + + def concat_obs_if_necessary(obs: TensorStructType): + """Concat model outs if they are original tuple observations.""" + if isinstance(obs, (list, tuple)): + obs = tf.concat(obs, axis=-1) + elif isinstance(obs, dict): + obs = tf.concat( + [ + tf.expand_dims(val, 1) if len(val.shape) == 1 else val + for val in tree.flatten(obs.values()) + ], + axis=-1, + ) + return obs + + if state_in is None: + state_in = [] + + if isinstance(model_out, dict) and "obs" in model_out: + # Model outs may come as original Tuple observations + if isinstance(self.action_model.obs_space, Box): + model_out["obs"] = concat_obs_if_necessary(model_out["obs"]) + return self.action_model(model_out, state_in, seq_lens) + else: + if isinstance(self.action_model.obs_space, Box): + model_out = concat_obs_if_necessary(model_out) + return self.action_model({"obs": model_out}, state_in, seq_lens) + + def policy_variables(self): + """Return the list of variables for the policy net.""" + + return self.action_model.variables() + + def q_variables(self): + """Return the list of variables for Q / twin Q nets.""" + + return self.q_net.variables() + ( + self.twin_q_net.variables() if self.twin_q_net else [] + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/sac_tf_policy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/sac_tf_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..2ce3184c70d9604cf62e2f423f183b6336f2e617 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/sac_tf_policy.py @@ -0,0 +1,792 @@ +""" +TensorFlow policy class used for SAC. +""" + +import copy +import gymnasium as gym +from gymnasium.spaces import Box, Discrete +from functools import partial +import logging +from typing import Dict, List, Optional, Tuple, Type, Union + +import ray +from ray.rllib.algorithms.dqn.dqn_tf_policy import ( + postprocess_nstep_and_prio, + PRIO_WEIGHTS, +) +from ray.rllib.algorithms.sac.sac_tf_model import SACTFModel +from ray.rllib.algorithms.sac.sac_torch_model import SACTorchModel +from ray.rllib.models import ModelCatalog +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.tf.tf_action_dist import ( + Beta, + Categorical, + DiagGaussian, + Dirichlet, + SquashedGaussian, + TFActionDistribution, +) +from ray.rllib.policy.policy import Policy +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy.tf_mixins import TargetNetworkMixin +from ray.rllib.policy.tf_policy_template import build_tf_policy +from ray.rllib.utils.error import UnsupportedSpaceException +from ray.rllib.utils.framework import get_variable, try_import_tf +from ray.rllib.utils.spaces.simplex import Simplex +from ray.rllib.utils.tf_utils import huber_loss, make_tf_callable +from ray.rllib.utils.typing import ( + AgentID, + LocalOptimizer, + ModelGradients, + TensorType, + AlgorithmConfigDict, +) + +tf1, tf, tfv = try_import_tf() + +logger = logging.getLogger(__name__) + + +def build_sac_model( + policy: Policy, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + config: AlgorithmConfigDict, +) -> ModelV2: + """Constructs the necessary ModelV2 for the Policy and returns it. + + Args: + policy: The TFPolicy that will use the models. + obs_space (gym.spaces.Space): The observation space. + action_space (gym.spaces.Space): The action space. + config: The SACConfig object. + + Returns: + ModelV2: The ModelV2 to be used by the Policy. Note: An additional + target model will be created in this function and assigned to + `policy.target_model`. + """ + # Force-ignore any additionally provided hidden layer sizes. + # Everything should be configured using SAC's `q_model_config` and + # `policy_model_config` config settings. + policy_model_config = copy.deepcopy(config["model"]) + policy_model_config.update(config["policy_model_config"]) + q_model_config = copy.deepcopy(config["model"]) + q_model_config.update(config["q_model_config"]) + + default_model_cls = SACTorchModel if config["framework"] == "torch" else SACTFModel + + model = ModelCatalog.get_model_v2( + obs_space=obs_space, + action_space=action_space, + num_outputs=None, + model_config=config["model"], + framework=config["framework"], + default_model=default_model_cls, + name="sac_model", + policy_model_config=policy_model_config, + q_model_config=q_model_config, + twin_q=config["twin_q"], + initial_alpha=config["initial_alpha"], + target_entropy=config["target_entropy"], + ) + + assert isinstance(model, default_model_cls) + + # Create an exact copy of the model and store it in `policy.target_model`. + # This will be used for tau-synched Q-target models that run behind the + # actual Q-networks and are used for target q-value calculations in the + # loss terms. + policy.target_model = ModelCatalog.get_model_v2( + obs_space=obs_space, + action_space=action_space, + num_outputs=None, + model_config=config["model"], + framework=config["framework"], + default_model=default_model_cls, + name="target_sac_model", + policy_model_config=policy_model_config, + q_model_config=q_model_config, + twin_q=config["twin_q"], + initial_alpha=config["initial_alpha"], + target_entropy=config["target_entropy"], + ) + + assert isinstance(policy.target_model, default_model_cls) + + return model + + +def postprocess_trajectory( + policy: Policy, + sample_batch: SampleBatch, + other_agent_batches: Optional[Dict[AgentID, SampleBatch]] = None, + episode=None, +) -> SampleBatch: + """Postprocesses a trajectory and returns the processed trajectory. + + The trajectory contains only data from one episode and from one agent. + - If `config.batch_mode=truncate_episodes` (default), sample_batch may + contain a truncated (at-the-end) episode, in case the + `config.rollout_fragment_length` was reached by the sampler. + - If `config.batch_mode=complete_episodes`, sample_batch will contain + exactly one episode (no matter how long). + New columns can be added to sample_batch and existing ones may be altered. + + Args: + policy: The Policy used to generate the trajectory + (`sample_batch`) + sample_batch: The SampleBatch to postprocess. + other_agent_batches (Optional[Dict[AgentID, SampleBatch]]): Optional + dict of AgentIDs mapping to other agents' trajectory data (from the + same episode). NOTE: The other agents use the same policy. + episode (Optional[Episode]): Optional multi-agent episode + object in which the agents operated. + + Returns: + SampleBatch: The postprocessed, modified SampleBatch (or a new one). + """ + return postprocess_nstep_and_prio(policy, sample_batch) + + +def _get_dist_class( + policy: Policy, config: AlgorithmConfigDict, action_space: gym.spaces.Space +) -> Type[TFActionDistribution]: + """Helper function to return a dist class based on config and action space. + + Args: + policy: The policy for which to return the action + dist class. + config: The Algorithm's config dict. + action_space (gym.spaces.Space): The action space used. + + Returns: + Type[TFActionDistribution]: A TF distribution class. + """ + if hasattr(policy, "dist_class") and policy.dist_class is not None: + return policy.dist_class + elif config["model"].get("custom_action_dist"): + action_dist_class, _ = ModelCatalog.get_action_dist( + action_space, config["model"], framework="tf" + ) + return action_dist_class + elif isinstance(action_space, Discrete): + return Categorical + elif isinstance(action_space, Simplex): + return Dirichlet + else: + assert isinstance(action_space, Box) + if config["normalize_actions"]: + return SquashedGaussian if not config["_use_beta_distribution"] else Beta + else: + return DiagGaussian + + +def get_distribution_inputs_and_class( + policy: Policy, + model: ModelV2, + obs_batch: TensorType, + *, + explore: bool = True, + **kwargs +) -> Tuple[TensorType, Type[TFActionDistribution], List[TensorType]]: + """The action distribution function to be used the algorithm. + + An action distribution function is used to customize the choice of action + distribution class and the resulting action distribution inputs (to + parameterize the distribution object). + After parameterizing the distribution, a `sample()` call + will be made on it to generate actions. + + Args: + policy: The Policy being queried for actions and calling this + function. + model: The SAC specific Model to use to generate the + distribution inputs (see sac_tf|torch_model.py). Must support the + `get_action_model_outputs` method. + obs_batch: The observations to be used as inputs to the + model. + explore: Whether to activate exploration or not. + + Returns: + Tuple[TensorType, Type[TFActionDistribution], List[TensorType]]: The + dist inputs, dist class, and a list of internal state outputs + (in the RNN case). + """ + # Get base-model (forward) output (this should be a noop call). + forward_out, state_out = model( + SampleBatch(obs=obs_batch, _is_training=policy._get_is_training_placeholder()), + [], + None, + ) + # Use the base output to get the policy outputs from the SAC model's + # policy components. + distribution_inputs, _ = model.get_action_model_outputs(forward_out) + # Get a distribution class to be used with the just calculated dist-inputs. + action_dist_class = _get_dist_class(policy, policy.config, policy.action_space) + + return distribution_inputs, action_dist_class, state_out + + +def sac_actor_critic_loss( + policy: Policy, + model: ModelV2, + dist_class: Type[TFActionDistribution], + train_batch: SampleBatch, +) -> Union[TensorType, List[TensorType]]: + """Constructs the loss for the Soft Actor Critic. + + Args: + policy: The Policy to calculate the loss for. + model (ModelV2): The Model to calculate the loss for. + dist_class (Type[ActionDistribution]: The action distr. class. + train_batch: The training data. + + Returns: + Union[TensorType, List[TensorType]]: A single loss tensor or a list + of loss tensors. + """ + # Should be True only for debugging purposes (e.g. test cases)! + deterministic = policy.config["_deterministic_loss"] + + _is_training = policy._get_is_training_placeholder() + # Get the base model output from the train batch. + model_out_t, _ = model( + SampleBatch(obs=train_batch[SampleBatch.CUR_OBS], _is_training=_is_training), + [], + None, + ) + + # Get the base model output from the next observations in the train batch. + model_out_tp1, _ = model( + SampleBatch(obs=train_batch[SampleBatch.NEXT_OBS], _is_training=_is_training), + [], + None, + ) + + # Get the target model's base outputs from the next observations in the + # train batch. + target_model_out_tp1, _ = policy.target_model( + SampleBatch(obs=train_batch[SampleBatch.NEXT_OBS], _is_training=_is_training), + [], + None, + ) + + # Discrete actions case. + if model.discrete: + # Get all action probs directly from pi and form their logp. + action_dist_inputs_t, _ = model.get_action_model_outputs(model_out_t) + log_pis_t = tf.nn.log_softmax(action_dist_inputs_t, -1) + policy_t = tf.math.exp(log_pis_t) + + action_dist_inputs_tp1, _ = model.get_action_model_outputs(model_out_tp1) + log_pis_tp1 = tf.nn.log_softmax(action_dist_inputs_tp1, -1) + policy_tp1 = tf.math.exp(log_pis_tp1) + + # Q-values. + q_t, _ = model.get_q_values(model_out_t) + # Target Q-values. + q_tp1, _ = policy.target_model.get_q_values(target_model_out_tp1) + if policy.config["twin_q"]: + twin_q_t, _ = model.get_twin_q_values(model_out_t) + twin_q_tp1, _ = policy.target_model.get_twin_q_values(target_model_out_tp1) + q_tp1 = tf.reduce_min((q_tp1, twin_q_tp1), axis=0) + q_tp1 -= model.alpha * log_pis_tp1 + + # Actually selected Q-values (from the actions batch). + one_hot = tf.one_hot( + train_batch[SampleBatch.ACTIONS], depth=q_t.shape.as_list()[-1] + ) + q_t_selected = tf.reduce_sum(q_t * one_hot, axis=-1) + if policy.config["twin_q"]: + twin_q_t_selected = tf.reduce_sum(twin_q_t * one_hot, axis=-1) + # Discrete case: "Best" means weighted by the policy (prob) outputs. + q_tp1_best = tf.reduce_sum(tf.multiply(policy_tp1, q_tp1), axis=-1) + q_tp1_best_masked = ( + 1.0 - tf.cast(train_batch[SampleBatch.TERMINATEDS], tf.float32) + ) * q_tp1_best + # Continuous actions case. + else: + # Sample simgle actions from distribution. + action_dist_class = _get_dist_class(policy, policy.config, policy.action_space) + action_dist_inputs_t, _ = model.get_action_model_outputs(model_out_t) + action_dist_t = action_dist_class(action_dist_inputs_t, policy.model) + policy_t = ( + action_dist_t.sample() + if not deterministic + else action_dist_t.deterministic_sample() + ) + log_pis_t = tf.expand_dims(action_dist_t.logp(policy_t), -1) + + action_dist_inputs_tp1, _ = model.get_action_model_outputs(model_out_tp1) + action_dist_tp1 = action_dist_class(action_dist_inputs_tp1, policy.model) + policy_tp1 = ( + action_dist_tp1.sample() + if not deterministic + else action_dist_tp1.deterministic_sample() + ) + log_pis_tp1 = tf.expand_dims(action_dist_tp1.logp(policy_tp1), -1) + + # Q-values for the actually selected actions. + q_t, _ = model.get_q_values( + model_out_t, tf.cast(train_batch[SampleBatch.ACTIONS], tf.float32) + ) + if policy.config["twin_q"]: + twin_q_t, _ = model.get_twin_q_values( + model_out_t, tf.cast(train_batch[SampleBatch.ACTIONS], tf.float32) + ) + + # Q-values for current policy in given current state. + q_t_det_policy, _ = model.get_q_values(model_out_t, policy_t) + if policy.config["twin_q"]: + twin_q_t_det_policy, _ = model.get_twin_q_values(model_out_t, policy_t) + q_t_det_policy = tf.reduce_min( + (q_t_det_policy, twin_q_t_det_policy), axis=0 + ) + + # target q network evaluation + q_tp1, _ = policy.target_model.get_q_values(target_model_out_tp1, policy_tp1) + if policy.config["twin_q"]: + twin_q_tp1, _ = policy.target_model.get_twin_q_values( + target_model_out_tp1, policy_tp1 + ) + # Take min over both twin-NNs. + q_tp1 = tf.reduce_min((q_tp1, twin_q_tp1), axis=0) + + q_t_selected = tf.squeeze(q_t, axis=len(q_t.shape) - 1) + if policy.config["twin_q"]: + twin_q_t_selected = tf.squeeze(twin_q_t, axis=len(q_t.shape) - 1) + q_tp1 -= model.alpha * log_pis_tp1 + + q_tp1_best = tf.squeeze(input=q_tp1, axis=len(q_tp1.shape) - 1) + q_tp1_best_masked = ( + 1.0 - tf.cast(train_batch[SampleBatch.TERMINATEDS], tf.float32) + ) * q_tp1_best + + # Compute RHS of bellman equation for the Q-loss (critic(s)). + q_t_selected_target = tf.stop_gradient( + tf.cast(train_batch[SampleBatch.REWARDS], tf.float32) + + policy.config["gamma"] ** policy.config["n_step"] * q_tp1_best_masked + ) + + # Compute the TD-error (potentially clipped). + base_td_error = tf.math.abs(q_t_selected - q_t_selected_target) + if policy.config["twin_q"]: + twin_td_error = tf.math.abs(twin_q_t_selected - q_t_selected_target) + td_error = 0.5 * (base_td_error + twin_td_error) + else: + td_error = base_td_error + + # Calculate one or two critic losses (2 in the twin_q case). + prio_weights = tf.cast(train_batch[PRIO_WEIGHTS], tf.float32) + critic_loss = [tf.reduce_mean(prio_weights * huber_loss(base_td_error))] + if policy.config["twin_q"]: + critic_loss.append(tf.reduce_mean(prio_weights * huber_loss(twin_td_error))) + + # Alpha- and actor losses. + # Note: In the papers, alpha is used directly, here we take the log. + # Discrete case: Multiply the action probs as weights with the original + # loss terms (no expectations needed). + if model.discrete: + alpha_loss = tf.reduce_mean( + tf.reduce_sum( + tf.multiply( + tf.stop_gradient(policy_t), + -model.log_alpha + * tf.stop_gradient(log_pis_t + model.target_entropy), + ), + axis=-1, + ) + ) + actor_loss = tf.reduce_mean( + tf.reduce_sum( + tf.multiply( + # NOTE: No stop_grad around policy output here + # (compare with q_t_det_policy for continuous case). + policy_t, + model.alpha * log_pis_t - tf.stop_gradient(q_t), + ), + axis=-1, + ) + ) + else: + alpha_loss = -tf.reduce_mean( + model.log_alpha * tf.stop_gradient(log_pis_t + model.target_entropy) + ) + actor_loss = tf.reduce_mean(model.alpha * log_pis_t - q_t_det_policy) + + # Save for stats function. + policy.policy_t = policy_t + policy.q_t = q_t + policy.td_error = td_error + policy.actor_loss = actor_loss + policy.critic_loss = critic_loss + policy.alpha_loss = alpha_loss + policy.alpha_value = model.alpha + policy.target_entropy = model.target_entropy + + # In a custom apply op we handle the losses separately, but return them + # combined in one loss here. + return actor_loss + tf.math.add_n(critic_loss) + alpha_loss + + +def compute_and_clip_gradients( + policy: Policy, optimizer: LocalOptimizer, loss: TensorType +) -> ModelGradients: + """Gradients computing function (from loss tensor, using local optimizer). + + Note: For SAC, optimizer and loss are ignored b/c we have 3 + losses and 3 local optimizers (all stored in policy). + `optimizer` will be used, though, in the tf-eager case b/c it is then a + fake optimizer (OptimizerWrapper) object with a `tape` property to + generate a GradientTape object for gradient recording. + + Args: + policy: The Policy object that generated the loss tensor and + that holds the given local optimizer. + optimizer: The tf (local) optimizer object to + calculate the gradients with. + loss: The loss tensor for which gradients should be + calculated. + + Returns: + ModelGradients: List of the possibly clipped gradients- and variable + tuples. + """ + # Eager: Use GradientTape (which is a property of the `optimizer` object + # (an OptimizerWrapper): see rllib/policy/eager_tf_policy.py). + if policy.config["framework"] == "tf2": + tape = optimizer.tape + pol_weights = policy.model.policy_variables() + actor_grads_and_vars = list( + zip(tape.gradient(policy.actor_loss, pol_weights), pol_weights) + ) + q_weights = policy.model.q_variables() + if policy.config["twin_q"]: + half_cutoff = len(q_weights) // 2 + grads_1 = tape.gradient(policy.critic_loss[0], q_weights[:half_cutoff]) + grads_2 = tape.gradient(policy.critic_loss[1], q_weights[half_cutoff:]) + critic_grads_and_vars = list(zip(grads_1, q_weights[:half_cutoff])) + list( + zip(grads_2, q_weights[half_cutoff:]) + ) + else: + critic_grads_and_vars = list( + zip(tape.gradient(policy.critic_loss[0], q_weights), q_weights) + ) + + alpha_vars = [policy.model.log_alpha] + alpha_grads_and_vars = list( + zip(tape.gradient(policy.alpha_loss, alpha_vars), alpha_vars) + ) + # Tf1.x: Use optimizer.compute_gradients() + else: + actor_grads_and_vars = policy._actor_optimizer.compute_gradients( + policy.actor_loss, var_list=policy.model.policy_variables() + ) + + q_weights = policy.model.q_variables() + if policy.config["twin_q"]: + half_cutoff = len(q_weights) // 2 + base_q_optimizer, twin_q_optimizer = policy._critic_optimizer + critic_grads_and_vars = base_q_optimizer.compute_gradients( + policy.critic_loss[0], var_list=q_weights[:half_cutoff] + ) + twin_q_optimizer.compute_gradients( + policy.critic_loss[1], var_list=q_weights[half_cutoff:] + ) + else: + critic_grads_and_vars = policy._critic_optimizer[0].compute_gradients( + policy.critic_loss[0], var_list=q_weights + ) + alpha_grads_and_vars = policy._alpha_optimizer.compute_gradients( + policy.alpha_loss, var_list=[policy.model.log_alpha] + ) + + # Clip if necessary. + if policy.config["grad_clip"]: + clip_func = partial(tf.clip_by_norm, clip_norm=policy.config["grad_clip"]) + else: + clip_func = tf.identity + + # Save grads and vars for later use in `build_apply_op`. + policy._actor_grads_and_vars = [ + (clip_func(g), v) for (g, v) in actor_grads_and_vars if g is not None + ] + policy._critic_grads_and_vars = [ + (clip_func(g), v) for (g, v) in critic_grads_and_vars if g is not None + ] + policy._alpha_grads_and_vars = [ + (clip_func(g), v) for (g, v) in alpha_grads_and_vars if g is not None + ] + + grads_and_vars = ( + policy._actor_grads_and_vars + + policy._critic_grads_and_vars + + policy._alpha_grads_and_vars + ) + return grads_and_vars + + +def apply_gradients( + policy: Policy, optimizer: LocalOptimizer, grads_and_vars: ModelGradients +) -> Union["tf.Operation", None]: + """Gradients applying function (from list of "grad_and_var" tuples). + + Note: For SAC, optimizer and grads_and_vars are ignored b/c we have 3 + losses and optimizers (stored in policy). + + Args: + policy: The Policy object whose Model(s) the given gradients + should be applied to. + optimizer: The tf (local) optimizer object through + which to apply the gradients. + grads_and_vars: The list of grad_and_var tuples to + apply via the given optimizer. + + Returns: + Union[tf.Operation, None]: The tf op to be used to run the apply + operation. None for eager mode. + """ + actor_apply_ops = policy._actor_optimizer.apply_gradients( + policy._actor_grads_and_vars + ) + + cgrads = policy._critic_grads_and_vars + half_cutoff = len(cgrads) // 2 + if policy.config["twin_q"]: + critic_apply_ops = [ + policy._critic_optimizer[0].apply_gradients(cgrads[:half_cutoff]), + policy._critic_optimizer[1].apply_gradients(cgrads[half_cutoff:]), + ] + else: + critic_apply_ops = [policy._critic_optimizer[0].apply_gradients(cgrads)] + + # Eager mode -> Just apply and return None. + if policy.config["framework"] == "tf2": + policy._alpha_optimizer.apply_gradients(policy._alpha_grads_and_vars) + return + # Tf static graph -> Return op. + else: + alpha_apply_ops = policy._alpha_optimizer.apply_gradients( + policy._alpha_grads_and_vars, + global_step=tf1.train.get_or_create_global_step(), + ) + return tf.group([actor_apply_ops, alpha_apply_ops] + critic_apply_ops) + + +def stats(policy: Policy, train_batch: SampleBatch) -> Dict[str, TensorType]: + """Stats function for SAC. Returns a dict with important loss stats. + + Args: + policy: The Policy to generate stats for. + train_batch: The SampleBatch (already) used for training. + + Returns: + Dict[str, TensorType]: The stats dict. + """ + return { + "mean_td_error": tf.reduce_mean(policy.td_error), + "actor_loss": tf.reduce_mean(policy.actor_loss), + "critic_loss": tf.reduce_mean(policy.critic_loss), + "alpha_loss": tf.reduce_mean(policy.alpha_loss), + "alpha_value": tf.reduce_mean(policy.alpha_value), + "target_entropy": tf.constant(policy.target_entropy), + "mean_q": tf.reduce_mean(policy.q_t), + "max_q": tf.reduce_max(policy.q_t), + "min_q": tf.reduce_min(policy.q_t), + } + + +class ActorCriticOptimizerMixin: + """Mixin class to generate the necessary optimizers for actor-critic algos. + + - Creates global step for counting the number of update operations. + - Creates separate optimizers for actor, critic, and alpha. + """ + + def __init__(self, config): + # Eager mode. + if config["framework"] == "tf2": + self.global_step = get_variable(0, tf_name="global_step") + self._actor_optimizer = tf.keras.optimizers.Adam( + learning_rate=config["optimization"]["actor_learning_rate"] + ) + self._critic_optimizer = [ + tf.keras.optimizers.Adam( + learning_rate=config["optimization"]["critic_learning_rate"] + ) + ] + if config["twin_q"]: + self._critic_optimizer.append( + tf.keras.optimizers.Adam( + learning_rate=config["optimization"]["critic_learning_rate"] + ) + ) + self._alpha_optimizer = tf.keras.optimizers.Adam( + learning_rate=config["optimization"]["entropy_learning_rate"] + ) + # Static graph mode. + else: + self.global_step = tf1.train.get_or_create_global_step() + self._actor_optimizer = tf1.train.AdamOptimizer( + learning_rate=config["optimization"]["actor_learning_rate"] + ) + self._critic_optimizer = [ + tf1.train.AdamOptimizer( + learning_rate=config["optimization"]["critic_learning_rate"] + ) + ] + if config["twin_q"]: + self._critic_optimizer.append( + tf1.train.AdamOptimizer( + learning_rate=config["optimization"]["critic_learning_rate"] + ) + ) + self._alpha_optimizer = tf1.train.AdamOptimizer( + learning_rate=config["optimization"]["entropy_learning_rate"] + ) + + +def setup_early_mixins( + policy: Policy, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + config: AlgorithmConfigDict, +) -> None: + """Call mixin classes' constructors before Policy's initialization. + + Adds the necessary optimizers to the given Policy. + + Args: + policy: The Policy object. + obs_space (gym.spaces.Space): The Policy's observation space. + action_space (gym.spaces.Space): The Policy's action space. + config: The Policy's config. + """ + ActorCriticOptimizerMixin.__init__(policy, config) + + +# TODO: Unify with DDPG's ComputeTDErrorMixin when SAC policy subclasses PolicyV2 +class ComputeTDErrorMixin: + def __init__(self, loss_fn): + @make_tf_callable(self.get_session(), dynamic_shape=True) + def compute_td_error( + obs_t, act_t, rew_t, obs_tp1, terminateds_mask, importance_weights + ): + # Do forward pass on loss to update td errors attribute + # (one TD-error value per item in batch to update PR weights). + loss_fn( + self, + self.model, + None, + { + SampleBatch.CUR_OBS: tf.convert_to_tensor(obs_t), + SampleBatch.ACTIONS: tf.convert_to_tensor(act_t), + SampleBatch.REWARDS: tf.convert_to_tensor(rew_t), + SampleBatch.NEXT_OBS: tf.convert_to_tensor(obs_tp1), + SampleBatch.TERMINATEDS: tf.convert_to_tensor(terminateds_mask), + PRIO_WEIGHTS: tf.convert_to_tensor(importance_weights), + }, + ) + # `self.td_error` is set in loss_fn. + return self.td_error + + self.compute_td_error = compute_td_error + + +def setup_mid_mixins( + policy: Policy, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + config: AlgorithmConfigDict, +) -> None: + """Call mixin classes' constructors before Policy's loss initialization. + + Adds the `compute_td_error` method to the given policy. + Calling `compute_td_error` with batch data will re-calculate the loss + on that batch AND return the per-batch-item TD-error for prioritized + replay buffer record weight updating (in case a prioritized replay buffer + is used). + + Args: + policy: The Policy object. + obs_space (gym.spaces.Space): The Policy's observation space. + action_space (gym.spaces.Space): The Policy's action space. + config: The Policy's config. + """ + ComputeTDErrorMixin.__init__(policy, sac_actor_critic_loss) + + +def setup_late_mixins( + policy: Policy, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + config: AlgorithmConfigDict, +) -> None: + """Call mixin classes' constructors after Policy initialization. + + Adds the `update_target` method to the given policy. + Calling `update_target` updates all target Q-networks' weights from their + respective "main" Q-metworks, based on tau (smooth, partial updating). + + Args: + policy: The Policy object. + obs_space (gym.spaces.Space): The Policy's observation space. + action_space (gym.spaces.Space): The Policy's action space. + config: The Policy's config. + """ + TargetNetworkMixin.__init__(policy) + + +def validate_spaces( + policy: Policy, + observation_space: gym.spaces.Space, + action_space: gym.spaces.Space, + config: AlgorithmConfigDict, +) -> None: + """Validates the observation- and action spaces used for the Policy. + + Args: + policy: The policy, whose spaces are being validated. + observation_space (gym.spaces.Space): The observation space to + validate. + action_space (gym.spaces.Space): The action space to validate. + config: The Policy's config dict. + + Raises: + UnsupportedSpaceException: If one of the spaces is not supported. + """ + # Only support single Box or single Discrete spaces. + if not isinstance(action_space, (Box, Discrete, Simplex)): + raise UnsupportedSpaceException( + "Action space ({}) of {} is not supported for " + "SAC. Must be [Box|Discrete|Simplex].".format(action_space, policy) + ) + # If Box, make sure it's a 1D vector space. + elif isinstance(action_space, (Box, Simplex)) and len(action_space.shape) > 1: + raise UnsupportedSpaceException( + "Action space ({}) of {} has multiple dimensions " + "{}. ".format(action_space, policy, action_space.shape) + + "Consider reshaping this into a single dimension, " + "using a Tuple action space, or the multi-agent API." + ) + + +# Build a child class of `DynamicTFPolicy`, given the custom functions defined +# above. +SACTFPolicy = build_tf_policy( + name="SACTFPolicy", + get_default_config=lambda: ray.rllib.algorithms.sac.sac.SACConfig(), + make_model=build_sac_model, + postprocess_fn=postprocess_trajectory, + action_distribution_fn=get_distribution_inputs_and_class, + loss_fn=sac_actor_critic_loss, + stats_fn=stats, + compute_gradients_fn=compute_and_clip_gradients, + apply_gradients_fn=apply_gradients, + extra_learn_fetches_fn=lambda policy: {"td_error": policy.td_error}, + mixins=[TargetNetworkMixin, ActorCriticOptimizerMixin, ComputeTDErrorMixin], + validate_spaces=validate_spaces, + before_init=setup_early_mixins, + before_loss_init=setup_mid_mixins, + after_init=setup_late_mixins, +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/sac_torch_model.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/sac_torch_model.py new file mode 100644 index 0000000000000000000000000000000000000000..00219fd95b8af80fe76f47079ba1f3af79482fc2 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/sac_torch_model.py @@ -0,0 +1,329 @@ +import gymnasium as gym +from gymnasium.spaces import Box, Discrete +import numpy as np +import tree # pip install dm_tree +from typing import Dict, List, Optional + +from ray.rllib.models.catalog import ModelCatalog +from ray.rllib.models.torch.torch_modelv2 import TorchModelV2 +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.spaces.simplex import Simplex +from ray.rllib.utils.typing import ModelConfigDict, TensorType, TensorStructType + +torch, nn = try_import_torch() + + +class SACTorchModel(TorchModelV2, nn.Module): + """Extension of the standard TorchModelV2 for SAC. + + To customize, do one of the following: + - sub-class SACTorchModel and override one or more of its methods. + - Use SAC's `q_model_config` and `policy_model` keys to tweak the default model + behaviors (e.g. fcnet_hiddens, conv_filters, etc..). + - Use SAC's `q_model_config->custom_model` and `policy_model->custom_model` keys + to specify your own custom Q-model(s) and policy-models, which will be + created within this SACTFModel (see `build_policy_model` and + `build_q_model`. + + Note: It is not recommended to override the `forward` method for SAC. This + would lead to shared weights (between policy and Q-nets), which will then + not be optimized by either of the critic- or actor-optimizers! + + Data flow: + `obs` -> forward() (should stay a noop method!) -> `model_out` + `model_out` -> get_policy_output() -> pi(actions|obs) + `model_out`, `actions` -> get_q_values() -> Q(s, a) + `model_out`, `actions` -> get_twin_q_values() -> Q_twin(s, a) + """ + + def __init__( + self, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + num_outputs: Optional[int], + model_config: ModelConfigDict, + name: str, + policy_model_config: ModelConfigDict = None, + q_model_config: ModelConfigDict = None, + twin_q: bool = False, + initial_alpha: float = 1.0, + target_entropy: Optional[float] = None, + ): + """Initializes a SACTorchModel instance. + 7 + Args: + policy_model_config: The config dict for the + policy network. + q_model_config: The config dict for the + Q-network(s) (2 if twin_q=True). + twin_q: Build twin Q networks (Q-net and target) for more + stable Q-learning. + initial_alpha: The initial value for the to-be-optimized + alpha parameter (default: 1.0). + target_entropy (Optional[float]): A target entropy value for + the to-be-optimized alpha parameter. If None, will use the + defaults described in the papers for SAC (and discrete SAC). + + Note that the core layers for forward() are not defined here, this + only defines the layers for the output heads. Those layers for + forward() should be defined in subclasses of SACModel. + """ + nn.Module.__init__(self) + super(SACTorchModel, self).__init__( + obs_space, action_space, num_outputs, model_config, name + ) + + if isinstance(action_space, Discrete): + self.action_dim = action_space.n + self.discrete = True + action_outs = q_outs = self.action_dim + elif isinstance(action_space, Box): + self.action_dim = np.prod(action_space.shape) + self.discrete = False + action_outs = 2 * self.action_dim + q_outs = 1 + else: + assert isinstance(action_space, Simplex) + self.action_dim = np.prod(action_space.shape) + self.discrete = False + action_outs = self.action_dim + q_outs = 1 + + # Build the policy network. + self.action_model = self.build_policy_model( + self.obs_space, action_outs, policy_model_config, "policy_model" + ) + + # Build the Q-network(s). + self.q_net = self.build_q_model( + self.obs_space, self.action_space, q_outs, q_model_config, "q" + ) + if twin_q: + self.twin_q_net = self.build_q_model( + self.obs_space, self.action_space, q_outs, q_model_config, "twin_q" + ) + else: + self.twin_q_net = None + + log_alpha = nn.Parameter( + torch.from_numpy(np.array([np.log(initial_alpha)])).float() + ) + self.register_parameter("log_alpha", log_alpha) + + # Auto-calculate the target entropy. + if target_entropy is None or target_entropy == "auto": + # See hyperparams in [2] (README.md). + if self.discrete: + target_entropy = 0.98 * np.array( + -np.log(1.0 / action_space.n), dtype=np.float32 + ) + # See [1] (README.md). + else: + target_entropy = -np.prod(action_space.shape) + + target_entropy = nn.Parameter( + torch.from_numpy(np.array([target_entropy])).float(), requires_grad=False + ) + self.register_parameter("target_entropy", target_entropy) + + @override(TorchModelV2) + def forward( + self, + input_dict: Dict[str, TensorType], + state: List[TensorType], + seq_lens: TensorType, + ) -> (TensorType, List[TensorType]): + """The common (Q-net and policy-net) forward pass. + + NOTE: It is not(!) recommended to override this method as it would + introduce a shared pre-network, which would be updated by both + actor- and critic optimizers. + """ + return input_dict["obs"], state + + def build_policy_model(self, obs_space, num_outputs, policy_model_config, name): + """Builds the policy model used by this SAC. + + Override this method in a sub-class of SACTFModel to implement your + own policy net. Alternatively, simply set `custom_model` within the + top level SAC `policy_model` config key to make this default + implementation of `build_policy_model` use your custom policy network. + + Returns: + TorchModelV2: The TorchModelV2 policy sub-model. + """ + model = ModelCatalog.get_model_v2( + obs_space, + self.action_space, + num_outputs, + policy_model_config, + framework="torch", + name=name, + ) + return model + + def build_q_model(self, obs_space, action_space, num_outputs, q_model_config, name): + """Builds one of the (twin) Q-nets used by this SAC. + + Override this method in a sub-class of SACTFModel to implement your + own Q-nets. Alternatively, simply set `custom_model` within the + top level SAC `q_model_config` config key to make this default implementation + of `build_q_model` use your custom Q-nets. + + Returns: + TorchModelV2: The TorchModelV2 Q-net sub-model. + """ + self.concat_obs_and_actions = False + if self.discrete: + input_space = obs_space + else: + orig_space = getattr(obs_space, "original_space", obs_space) + if isinstance(orig_space, Box) and len(orig_space.shape) == 1: + input_space = Box( + float("-inf"), + float("inf"), + shape=(orig_space.shape[0] + action_space.shape[0],), + ) + self.concat_obs_and_actions = True + else: + input_space = gym.spaces.Tuple([orig_space, action_space]) + + model = ModelCatalog.get_model_v2( + input_space, + action_space, + num_outputs, + q_model_config, + framework="torch", + name=name, + ) + return model + + def get_q_values( + self, model_out: TensorType, actions: Optional[TensorType] = None + ) -> TensorType: + """Returns Q-values, given the output of self.__call__(). + + This implements Q(s, a) -> [single Q-value] for the continuous case and + Q(s) -> [Q-values for all actions] for the discrete case. + + Args: + model_out: Feature outputs from the model layers + (result of doing `self.__call__(obs)`). + actions (Optional[TensorType]): Continuous action batch to return + Q-values for. Shape: [BATCH_SIZE, action_dim]. If None + (discrete action case), return Q-values for all actions. + + Returns: + TensorType: Q-values tensor of shape [BATCH_SIZE, 1]. + """ + return self._get_q_value(model_out, actions, self.q_net) + + def get_twin_q_values( + self, model_out: TensorType, actions: Optional[TensorType] = None + ) -> TensorType: + """Same as get_q_values but using the twin Q net. + + This implements the twin Q(s, a). + + Args: + model_out: Feature outputs from the model layers + (result of doing `self.__call__(obs)`). + actions (Optional[Tensor]): Actions to return the Q-values for. + Shape: [BATCH_SIZE, action_dim]. If None (discrete action + case), return Q-values for all actions. + + Returns: + TensorType: Q-values tensor of shape [BATCH_SIZE, 1]. + """ + return self._get_q_value(model_out, actions, self.twin_q_net) + + def _get_q_value(self, model_out, actions, net): + # Model outs may come as original Tuple observations, concat them + # here if this is the case. + if isinstance(net.obs_space, Box): + if isinstance(model_out, (list, tuple)): + model_out = torch.cat(model_out, dim=-1) + elif isinstance(model_out, dict): + model_out = torch.cat(list(model_out.values()), dim=-1) + + # Continuous case -> concat actions to model_out. + if actions is not None: + if self.concat_obs_and_actions: + input_dict = {"obs": torch.cat([model_out, actions], dim=-1)} + else: + # TODO(junogng) : SampleBatch doesn't support list columns yet. + # Use ModelInputDict. + input_dict = {"obs": (model_out, actions)} + # Discrete case -> return q-vals for all actions. + else: + input_dict = {"obs": model_out} + # Switch on training mode (when getting Q-values, we are usually in + # training). + input_dict["is_training"] = True + + return net(input_dict, [], None) + + def get_action_model_outputs( + self, + model_out: TensorType, + state_in: List[TensorType] = None, + seq_lens: TensorType = None, + ) -> (TensorType, List[TensorType]): + """Returns distribution inputs and states given the output of + policy.model(). + + For continuous action spaces, these will be the mean/stddev + distribution inputs for the (SquashedGaussian) action distribution. + For discrete action spaces, these will be the logits for a categorical + distribution. + + Args: + model_out: Feature outputs from the model layers + (result of doing `model(obs)`). + state_in List(TensorType): State input for recurrent cells + seq_lens: Sequence lengths of input- and state + sequences + + Returns: + TensorType: Distribution inputs for sampling actions. + """ + + def concat_obs_if_necessary(obs: TensorStructType): + """Concat model outs if they come as original tuple observations.""" + if isinstance(obs, (list, tuple)): + obs = torch.cat(obs, dim=-1) + elif isinstance(obs, dict): + obs = torch.cat( + [ + torch.unsqueeze(val, 1) if len(val.shape) == 1 else val + for val in tree.flatten(obs.values()) + ], + dim=-1, + ) + return obs + + if state_in is None: + state_in = [] + + if isinstance(model_out, dict) and "obs" in model_out: + # Model outs may come as original Tuple observations + if isinstance(self.action_model.obs_space, Box): + model_out["obs"] = concat_obs_if_necessary(model_out["obs"]) + return self.action_model(model_out, state_in, seq_lens) + else: + if isinstance(self.action_model.obs_space, Box): + model_out = concat_obs_if_necessary(model_out) + return self.action_model({"obs": model_out}, state_in, seq_lens) + + def policy_variables(self): + """Return the list of variables for the policy net.""" + + return self.action_model.variables() + + def q_variables(self): + """Return the list of variables for Q / twin Q nets.""" + + return self.q_net.variables() + ( + self.twin_q_net.variables() if self.twin_q_net else [] + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/sac_torch_policy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/sac_torch_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..cef30f465f5d7c5050e12bef244d8655f7a2fa8f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/sac_torch_policy.py @@ -0,0 +1,516 @@ +""" +PyTorch policy class used for SAC. +""" + +import gymnasium as gym +from gymnasium.spaces import Box, Discrete +import logging +import tree # pip install dm_tree +from typing import Dict, List, Optional, Tuple, Type, Union + +import ray +from ray.rllib.algorithms.sac.sac_tf_policy import ( + build_sac_model, + postprocess_trajectory, + validate_spaces, +) +from ray.rllib.algorithms.dqn.dqn_tf_policy import PRIO_WEIGHTS +from ray.rllib.models.catalog import ModelCatalog +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.torch.torch_action_dist import ( + TorchCategorical, + TorchDistributionWrapper, + TorchDirichlet, + TorchSquashedGaussian, + TorchDiagGaussian, + TorchBeta, +) +from ray.rllib.policy.policy import Policy +from ray.rllib.policy.policy_template import build_policy_class +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.spaces.simplex import Simplex +from ray.rllib.policy.torch_mixins import TargetNetworkMixin +from ray.rllib.utils.torch_utils import ( + apply_grad_clipping, + concat_multi_gpu_td_errors, + huber_loss, +) +from ray.rllib.utils.typing import ( + LocalOptimizer, + ModelInputDict, + TensorType, + AlgorithmConfigDict, +) + +torch, nn = try_import_torch() +F = nn.functional + +logger = logging.getLogger(__name__) + + +def _get_dist_class( + policy: Policy, config: AlgorithmConfigDict, action_space: gym.spaces.Space +) -> Type[TorchDistributionWrapper]: + """Helper function to return a dist class based on config and action space. + + Args: + policy: The policy for which to return the action + dist class. + config: The Algorithm's config dict. + action_space (gym.spaces.Space): The action space used. + + Returns: + Type[TFActionDistribution]: A TF distribution class. + """ + if hasattr(policy, "dist_class") and policy.dist_class is not None: + return policy.dist_class + elif config["model"].get("custom_action_dist"): + action_dist_class, _ = ModelCatalog.get_action_dist( + action_space, config["model"], framework="torch" + ) + return action_dist_class + elif isinstance(action_space, Discrete): + return TorchCategorical + elif isinstance(action_space, Simplex): + return TorchDirichlet + else: + assert isinstance(action_space, Box) + if config["normalize_actions"]: + return ( + TorchSquashedGaussian + if not config["_use_beta_distribution"] + else TorchBeta + ) + else: + return TorchDiagGaussian + + +def build_sac_model_and_action_dist( + policy: Policy, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + config: AlgorithmConfigDict, +) -> Tuple[ModelV2, Type[TorchDistributionWrapper]]: + """Constructs the necessary ModelV2 and action dist class for the Policy. + + Args: + policy: The TFPolicy that will use the models. + obs_space (gym.spaces.Space): The observation space. + action_space (gym.spaces.Space): The action space. + config: The SACConfig object. + + Returns: + ModelV2: The ModelV2 to be used by the Policy. Note: An additional + target model will be created in this function and assigned to + `policy.target_model`. + """ + model = build_sac_model(policy, obs_space, action_space, config) + action_dist_class = _get_dist_class(policy, config, action_space) + return model, action_dist_class + + +def action_distribution_fn( + policy: Policy, + model: ModelV2, + input_dict: ModelInputDict, + *, + state_batches: Optional[List[TensorType]] = None, + seq_lens: Optional[TensorType] = None, + prev_action_batch: Optional[TensorType] = None, + prev_reward_batch=None, + explore: Optional[bool] = None, + timestep: Optional[int] = None, + is_training: Optional[bool] = None +) -> Tuple[TensorType, Type[TorchDistributionWrapper], List[TensorType]]: + """The action distribution function to be used the algorithm. + + An action distribution function is used to customize the choice of action + distribution class and the resulting action distribution inputs (to + parameterize the distribution object). + After parameterizing the distribution, a `sample()` call + will be made on it to generate actions. + + Args: + policy: The Policy being queried for actions and calling this + function. + model (TorchModelV2): The SAC specific model to use to generate the + distribution inputs (see sac_tf|torch_model.py). Must support the + `get_action_model_outputs` method. + input_dict: The input-dict to be used for the model + call. + state_batches (Optional[List[TensorType]]): The list of internal state + tensor batches. + seq_lens (Optional[TensorType]): The tensor of sequence lengths used + in RNNs. + prev_action_batch (Optional[TensorType]): Optional batch of prev + actions used by the model. + prev_reward_batch (Optional[TensorType]): Optional batch of prev + rewards used by the model. + explore (Optional[bool]): Whether to activate exploration or not. If + None, use value of `config.explore`. + timestep (Optional[int]): An optional timestep. + is_training (Optional[bool]): An optional is-training flag. + + Returns: + Tuple[TensorType, Type[TorchDistributionWrapper], List[TensorType]]: + The dist inputs, dist class, and a list of internal state outputs + (in the RNN case). + """ + # Get base-model output (w/o the SAC specific parts of the network). + model_out, _ = model(input_dict, [], None) + # Use the base output to get the policy outputs from the SAC model's + # policy components. + action_dist_inputs, _ = model.get_action_model_outputs(model_out) + # Get a distribution class to be used with the just calculated dist-inputs. + action_dist_class = _get_dist_class(policy, policy.config, policy.action_space) + + return action_dist_inputs, action_dist_class, [] + + +def actor_critic_loss( + policy: Policy, + model: ModelV2, + dist_class: Type[TorchDistributionWrapper], + train_batch: SampleBatch, +) -> Union[TensorType, List[TensorType]]: + """Constructs the loss for the Soft Actor Critic. + + Args: + policy: The Policy to calculate the loss for. + model (ModelV2): The Model to calculate the loss for. + dist_class (Type[TorchDistributionWrapper]: The action distr. class. + train_batch: The training data. + + Returns: + Union[TensorType, List[TensorType]]: A single loss tensor or a list + of loss tensors. + """ + # Look up the target model (tower) using the model tower. + target_model = policy.target_models[model] + + # Should be True only for debugging purposes (e.g. test cases)! + deterministic = policy.config["_deterministic_loss"] + + model_out_t, _ = model( + SampleBatch(obs=train_batch[SampleBatch.CUR_OBS], _is_training=True), [], None + ) + + model_out_tp1, _ = model( + SampleBatch(obs=train_batch[SampleBatch.NEXT_OBS], _is_training=True), [], None + ) + + target_model_out_tp1, _ = target_model( + SampleBatch(obs=train_batch[SampleBatch.NEXT_OBS], _is_training=True), [], None + ) + + alpha = torch.exp(model.log_alpha) + + # Discrete case. + if model.discrete: + # Get all action probs directly from pi and form their logp. + action_dist_inputs_t, _ = model.get_action_model_outputs(model_out_t) + log_pis_t = F.log_softmax(action_dist_inputs_t, dim=-1) + policy_t = torch.exp(log_pis_t) + action_dist_inputs_tp1, _ = model.get_action_model_outputs(model_out_tp1) + log_pis_tp1 = F.log_softmax(action_dist_inputs_tp1, -1) + policy_tp1 = torch.exp(log_pis_tp1) + # Q-values. + q_t, _ = model.get_q_values(model_out_t) + # Target Q-values. + q_tp1, _ = target_model.get_q_values(target_model_out_tp1) + if policy.config["twin_q"]: + twin_q_t, _ = model.get_twin_q_values(model_out_t) + twin_q_tp1, _ = target_model.get_twin_q_values(target_model_out_tp1) + q_tp1 = torch.min(q_tp1, twin_q_tp1) + q_tp1 -= alpha * log_pis_tp1 + + # Actually selected Q-values (from the actions batch). + one_hot = F.one_hot( + train_batch[SampleBatch.ACTIONS].long(), num_classes=q_t.size()[-1] + ) + q_t_selected = torch.sum(q_t * one_hot, dim=-1) + if policy.config["twin_q"]: + twin_q_t_selected = torch.sum(twin_q_t * one_hot, dim=-1) + # Discrete case: "Best" means weighted by the policy (prob) outputs. + q_tp1_best = torch.sum(torch.mul(policy_tp1, q_tp1), dim=-1) + q_tp1_best_masked = ( + 1.0 - train_batch[SampleBatch.TERMINATEDS].float() + ) * q_tp1_best + # Continuous actions case. + else: + # Sample single actions from distribution. + action_dist_class = _get_dist_class(policy, policy.config, policy.action_space) + action_dist_inputs_t, _ = model.get_action_model_outputs(model_out_t) + action_dist_t = action_dist_class(action_dist_inputs_t, model) + policy_t = ( + action_dist_t.sample() + if not deterministic + else action_dist_t.deterministic_sample() + ) + log_pis_t = torch.unsqueeze(action_dist_t.logp(policy_t), -1) + action_dist_inputs_tp1, _ = model.get_action_model_outputs(model_out_tp1) + action_dist_tp1 = action_dist_class(action_dist_inputs_tp1, model) + policy_tp1 = ( + action_dist_tp1.sample() + if not deterministic + else action_dist_tp1.deterministic_sample() + ) + log_pis_tp1 = torch.unsqueeze(action_dist_tp1.logp(policy_tp1), -1) + + # Q-values for the actually selected actions. + q_t, _ = model.get_q_values(model_out_t, train_batch[SampleBatch.ACTIONS]) + if policy.config["twin_q"]: + twin_q_t, _ = model.get_twin_q_values( + model_out_t, train_batch[SampleBatch.ACTIONS] + ) + + # Q-values for current policy in given current state. + q_t_det_policy, _ = model.get_q_values(model_out_t, policy_t) + if policy.config["twin_q"]: + twin_q_t_det_policy, _ = model.get_twin_q_values(model_out_t, policy_t) + q_t_det_policy = torch.min(q_t_det_policy, twin_q_t_det_policy) + + # Target q network evaluation. + q_tp1, _ = target_model.get_q_values(target_model_out_tp1, policy_tp1) + if policy.config["twin_q"]: + twin_q_tp1, _ = target_model.get_twin_q_values( + target_model_out_tp1, policy_tp1 + ) + # Take min over both twin-NNs. + q_tp1 = torch.min(q_tp1, twin_q_tp1) + + q_t_selected = torch.squeeze(q_t, dim=-1) + if policy.config["twin_q"]: + twin_q_t_selected = torch.squeeze(twin_q_t, dim=-1) + q_tp1 -= alpha * log_pis_tp1 + + q_tp1_best = torch.squeeze(input=q_tp1, dim=-1) + q_tp1_best_masked = ( + 1.0 - train_batch[SampleBatch.TERMINATEDS].float() + ) * q_tp1_best + + # compute RHS of bellman equation + q_t_selected_target = ( + train_batch[SampleBatch.REWARDS] + + (policy.config["gamma"] ** policy.config["n_step"]) * q_tp1_best_masked + ).detach() + + # Compute the TD-error (potentially clipped). + base_td_error = torch.abs(q_t_selected - q_t_selected_target) + if policy.config["twin_q"]: + twin_td_error = torch.abs(twin_q_t_selected - q_t_selected_target) + td_error = 0.5 * (base_td_error + twin_td_error) + else: + td_error = base_td_error + + critic_loss = [torch.mean(train_batch[PRIO_WEIGHTS] * huber_loss(base_td_error))] + if policy.config["twin_q"]: + critic_loss.append( + torch.mean(train_batch[PRIO_WEIGHTS] * huber_loss(twin_td_error)) + ) + + # Alpha- and actor losses. + # Note: In the papers, alpha is used directly, here we take the log. + # Discrete case: Multiply the action probs as weights with the original + # loss terms (no expectations needed). + if model.discrete: + weighted_log_alpha_loss = policy_t.detach() * ( + -model.log_alpha * (log_pis_t + model.target_entropy).detach() + ) + # Sum up weighted terms and mean over all batch items. + alpha_loss = torch.mean(torch.sum(weighted_log_alpha_loss, dim=-1)) + # Actor loss. + actor_loss = torch.mean( + torch.sum( + torch.mul( + # NOTE: No stop_grad around policy output here + # (compare with q_t_det_policy for continuous case). + policy_t, + alpha.detach() * log_pis_t - q_t.detach(), + ), + dim=-1, + ) + ) + else: + alpha_loss = -torch.mean( + model.log_alpha * (log_pis_t + model.target_entropy).detach() + ) + # Note: Do not detach q_t_det_policy here b/c is depends partly + # on the policy vars (policy sample pushed through Q-net). + # However, we must make sure `actor_loss` is not used to update + # the Q-net(s)' variables. + actor_loss = torch.mean(alpha.detach() * log_pis_t - q_t_det_policy) + + # Store values for stats function in model (tower), such that for + # multi-GPU, we do not override them during the parallel loss phase. + model.tower_stats["q_t"] = q_t + model.tower_stats["policy_t"] = policy_t + model.tower_stats["log_pis_t"] = log_pis_t + model.tower_stats["actor_loss"] = actor_loss + model.tower_stats["critic_loss"] = critic_loss + model.tower_stats["alpha_loss"] = alpha_loss + + # TD-error tensor in final stats + # will be concatenated and retrieved for each individual batch item. + model.tower_stats["td_error"] = td_error + + # Return all loss terms corresponding to our optimizers. + return tuple([actor_loss] + critic_loss + [alpha_loss]) + + +def stats(policy: Policy, train_batch: SampleBatch) -> Dict[str, TensorType]: + """Stats function for SAC. Returns a dict with important loss stats. + + Args: + policy: The Policy to generate stats for. + train_batch: The SampleBatch (already) used for training. + + Returns: + Dict[str, TensorType]: The stats dict. + """ + q_t = torch.stack(policy.get_tower_stats("q_t")) + + return { + "actor_loss": torch.mean(torch.stack(policy.get_tower_stats("actor_loss"))), + "critic_loss": torch.mean( + torch.stack(tree.flatten(policy.get_tower_stats("critic_loss"))) + ), + "alpha_loss": torch.mean(torch.stack(policy.get_tower_stats("alpha_loss"))), + "alpha_value": torch.exp(policy.model.log_alpha), + "log_alpha_value": policy.model.log_alpha, + "target_entropy": policy.model.target_entropy, + "policy_t": torch.mean(torch.stack(policy.get_tower_stats("policy_t"))), + "mean_q": torch.mean(q_t), + "max_q": torch.max(q_t), + "min_q": torch.min(q_t), + } + + +def optimizer_fn(policy: Policy, config: AlgorithmConfigDict) -> Tuple[LocalOptimizer]: + """Creates all necessary optimizers for SAC learning. + + The 3 or 4 (twin_q=True) optimizers returned here correspond to the + number of loss terms returned by the loss function. + + Args: + policy: The policy object to be trained. + config: The Algorithm's config dict. + + Returns: + Tuple[LocalOptimizer]: The local optimizers to use for policy training. + """ + policy.actor_optim = torch.optim.Adam( + params=policy.model.policy_variables(), + lr=config["optimization"]["actor_learning_rate"], + eps=1e-7, # to match tf.keras.optimizers.Adam's epsilon default + ) + + critic_split = len(policy.model.q_variables()) + if config["twin_q"]: + critic_split //= 2 + + policy.critic_optims = [ + torch.optim.Adam( + params=policy.model.q_variables()[:critic_split], + lr=config["optimization"]["critic_learning_rate"], + eps=1e-7, # to match tf.keras.optimizers.Adam's epsilon default + ) + ] + if config["twin_q"]: + policy.critic_optims.append( + torch.optim.Adam( + params=policy.model.q_variables()[critic_split:], + lr=config["optimization"]["critic_learning_rate"], + eps=1e-7, # to match tf.keras.optimizers.Adam's eps default + ) + ) + policy.alpha_optim = torch.optim.Adam( + params=[policy.model.log_alpha], + lr=config["optimization"]["entropy_learning_rate"], + eps=1e-7, # to match tf.keras.optimizers.Adam's epsilon default + ) + + return tuple([policy.actor_optim] + policy.critic_optims + [policy.alpha_optim]) + + +# TODO: Unify with DDPG's ComputeTDErrorMixin when SAC policy subclasses PolicyV2 +class ComputeTDErrorMixin: + """Mixin class calculating TD-error (part of critic loss) per batch item. + + - Adds `policy.compute_td_error()` method for TD-error calculation from a + batch of observations/actions/rewards/etc.. + """ + + def __init__(self): + def compute_td_error( + obs_t, act_t, rew_t, obs_tp1, terminateds_mask, importance_weights + ): + input_dict = self._lazy_tensor_dict( + { + SampleBatch.CUR_OBS: obs_t, + SampleBatch.ACTIONS: act_t, + SampleBatch.REWARDS: rew_t, + SampleBatch.NEXT_OBS: obs_tp1, + SampleBatch.TERMINATEDS: terminateds_mask, + PRIO_WEIGHTS: importance_weights, + } + ) + # Do forward pass on loss to update td errors attribute + # (one TD-error value per item in batch to update PR weights). + actor_critic_loss(self, self.model, None, input_dict) + + # `self.model.td_error` is set within actor_critic_loss call. + # Return its updated value here. + return self.model.tower_stats["td_error"] + + # Assign the method to policy (self) for later usage. + self.compute_td_error = compute_td_error + + +def setup_late_mixins( + policy: Policy, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + config: AlgorithmConfigDict, +) -> None: + """Call mixin classes' constructors after Policy initialization. + + - Moves the target model(s) to the GPU, if necessary. + - Adds the `compute_td_error` method to the given policy. + Calling `compute_td_error` with batch data will re-calculate the loss + on that batch AND return the per-batch-item TD-error for prioritized + replay buffer record weight updating (in case a prioritized replay buffer + is used). + - Also adds the `update_target` method to the given policy. + Calling `update_target` updates all target Q-networks' weights from their + respective "main" Q-metworks, based on tau (smooth, partial updating). + + Args: + policy: The Policy object. + obs_space (gym.spaces.Space): The Policy's observation space. + action_space (gym.spaces.Space): The Policy's action space. + config: The Policy's config. + """ + ComputeTDErrorMixin.__init__(policy) + TargetNetworkMixin.__init__(policy) + + +# Build a child class of `TorchPolicy`, given the custom functions defined +# above. +SACTorchPolicy = build_policy_class( + name="SACTorchPolicy", + framework="torch", + loss_fn=actor_critic_loss, + get_default_config=lambda: ray.rllib.algorithms.sac.sac.SACConfig(), + stats_fn=stats, + postprocess_fn=postprocess_trajectory, + extra_grad_process_fn=apply_grad_clipping, + optimizer_fn=optimizer_fn, + validate_spaces=validate_spaces, + before_loss_init=setup_late_mixins, + make_model_and_action_dist=build_sac_model_and_action_dist, + extra_learn_fetches_fn=concat_multi_gpu_td_errors, + mixins=[TargetNetworkMixin, ComputeTDErrorMixin], + action_distribution_fn=action_distribution_fn, +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/torch/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/torch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/torch/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/torch/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3dfe783d16e8ab1759ad341e201e00a9cea7f15b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/torch/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/torch/__pycache__/default_sac_torch_rl_module.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/torch/__pycache__/default_sac_torch_rl_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c787988f8e19d0572eeddce194a4518de925f2c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/torch/__pycache__/default_sac_torch_rl_module.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/torch/__pycache__/sac_torch_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/torch/__pycache__/sac_torch_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ffc3bab3ae5f68e687cdddf95a99c96434738ac1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/torch/__pycache__/sac_torch_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/torch/default_sac_torch_rl_module.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/torch/default_sac_torch_rl_module.py new file mode 100644 index 0000000000000000000000000000000000000000..0612dce7c391b2966941455c428392f0e5939d08 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/torch/default_sac_torch_rl_module.py @@ -0,0 +1,279 @@ +import gymnasium as gym +from typing import Any, Dict + +from ray.rllib.algorithms.sac.default_sac_rl_module import DefaultSACRLModule +from ray.rllib.algorithms.sac.sac_catalog import SACCatalog +from ray.rllib.algorithms.sac.sac_learner import ( + ACTION_DIST_INPUTS_NEXT, + QF_PREDS, + QF_TWIN_PREDS, + QF_TARGET_NEXT, + ACTION_LOG_PROBS_NEXT, + ACTION_PROBS_NEXT, + ACTION_PROBS, + ACTION_LOG_PROBS, +) +from ray.rllib.core.columns import Columns +from ray.rllib.core.models.base import ENCODER_OUT, Encoder, Model +from ray.rllib.core.rl_module.apis import QNetAPI, TargetNetworkAPI +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.core.rl_module.torch.torch_rl_module import TorchRLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.util.annotations import DeveloperAPI + +torch, nn = try_import_torch() + + +@DeveloperAPI +class DefaultSACTorchRLModule(TorchRLModule, DefaultSACRLModule): + framework: str = "torch" + + def __init__(self, *args, **kwargs): + catalog_class = kwargs.pop("catalog_class", None) + if catalog_class is None: + catalog_class = SACCatalog + super().__init__(*args, **kwargs, catalog_class=catalog_class) + + @override(RLModule) + def _forward_inference(self, batch: Dict) -> Dict[str, Any]: + output = {} + + # Pi encoder forward pass. + pi_encoder_outs = self.pi_encoder(batch) + + # Pi head. + # assume action space is either discrete or continuous. + output[Columns.ACTION_DIST_INPUTS] = self.pi(pi_encoder_outs[ENCODER_OUT]) + + return output + + @override(RLModule) + def _forward_exploration(self, batch: Dict, **kwargs) -> Dict[str, Any]: + return self._forward_inference(batch) + + @override(RLModule) + def _forward_train(self, batch: Dict) -> Dict[str, Any]: + # Call the `super`'s `forward_train` + super()._forward_train(batch) + if isinstance(self.action_space, gym.spaces.Discrete): + return self._forward_train_discrete(batch) + elif isinstance(self.action_space, gym.spaces.Box): + return self._forward_train_continuous(batch) + else: + raise ValueError( + f"Unsupported action space type: {type(self.action_space)}. " + "Only discrete and continuous action spaces are supported." + ) + + def _forward_train_discrete(self, batch: Dict[str, Any]) -> Dict[str, Any]: + output = {} + + # SAC needs also Q function values and action logits for next observations. + batch_curr = {Columns.OBS: batch[Columns.OBS]} + batch_next = {Columns.OBS: batch[Columns.NEXT_OBS]} + + ## calculate values for the Q target ## + # Also encode the next observations (and next actions for the Q net). + pi_encoder_next_outs = self.pi_encoder(batch_next) + action_logits_next = self.pi(pi_encoder_next_outs[ENCODER_OUT]) + # TODO(inyoung): get the action dist class and use that. But currently TorchCategorical + # does not get the prob value of the actual torch distribution. So we use softmax directly + # for now. + action_probs_next = torch.nn.functional.softmax(action_logits_next, dim=-1) + + output[ACTION_PROBS_NEXT] = action_probs_next + output[ACTION_LOG_PROBS_NEXT] = action_probs_next.log() + + # (B, action_dim) + qf_target_next = self.forward_target(batch_next, squeeze=False) + output[QF_TARGET_NEXT] = qf_target_next + + qf_preds = self._qf_forward_train_helper( + batch_curr, self.qf_encoder, self.qf, squeeze=False + ) + # we don't need straight-through gradient here + output[QF_PREDS] = qf_preds + if self.twin_q: + qf_twin_preds = self._qf_forward_train_helper( + batch_curr, self.qf_twin_encoder, self.qf_twin, squeeze=False + ) + output[QF_TWIN_PREDS] = qf_twin_preds + + ## calculate values for gradient ## + pi_encoder_outs = self.pi_encoder(batch_curr) + action_logits = self.pi(pi_encoder_outs[ENCODER_OUT]) + action_probs = torch.nn.functional.softmax(action_logits, dim=-1) + output[ACTION_PROBS] = action_probs + output[ACTION_LOG_PROBS] = action_probs.log() + + return output + + def _forward_train_continuous(self, batch: Dict[str, Any]) -> Dict[str, Any]: + output = {} + + # SAC needs also Q function values and action logits for next observations. + batch_curr = {Columns.OBS: batch[Columns.OBS]} + batch_next = {Columns.OBS: batch[Columns.NEXT_OBS]} + + # Encoder forward passes. + pi_encoder_outs = self.pi_encoder(batch_curr) + + # Also encode the next observations (and next actions for the Q net). + pi_encoder_next_outs = self.pi_encoder(batch_next) + + # Q-network(s) forward passes. + batch_curr.update({Columns.ACTIONS: batch[Columns.ACTIONS]}) + output[QF_PREDS] = self._qf_forward_train_helper( + batch_curr, self.qf_encoder, self.qf + ) # self._qf_forward_train(batch_curr)[QF_PREDS] + # If necessary make a forward pass through the twin Q network. + if self.twin_q: + output[QF_TWIN_PREDS] = self._qf_forward_train_helper( + batch_curr, self.qf_twin_encoder, self.qf_twin + ) + + # Policy head. + action_logits = self.pi(pi_encoder_outs[ENCODER_OUT]) + # Also get the action logits for the next observations. + action_logits_next = self.pi(pi_encoder_next_outs[ENCODER_OUT]) + output[Columns.ACTION_DIST_INPUTS] = action_logits + output[ACTION_DIST_INPUTS_NEXT] = action_logits_next + + # Get the train action distribution for the current policy and current state. + # This is needed for the policy (actor) loss in SAC. + action_dist_class = self.get_train_action_dist_cls() + action_dist_curr = action_dist_class.from_logits(action_logits) + # Get the train action distribution for the current policy and next state. + # For the Q (critic) loss in SAC, we need to sample from the current policy at + # the next state. + action_dist_next = action_dist_class.from_logits(action_logits_next) + + # Sample actions for the current state. Note that we need to apply the + # reparameterization trick (`rsample()` instead of `sample()`) to avoid the + # expectation over actions. + actions_resampled = action_dist_curr.rsample() + # Compute the log probabilities for the current state (for the critic loss). + output["logp_resampled"] = action_dist_curr.logp(actions_resampled) + + # Sample actions for the next state. + actions_next_resampled = action_dist_next.sample().detach() + # Compute the log probabilities for the next state. + output["logp_next_resampled"] = ( + action_dist_next.logp(actions_next_resampled) + ).detach() + + # Compute Q-values for the current policy in the current state with + # the sampled actions. + q_batch_curr = { + Columns.OBS: batch[Columns.OBS], + Columns.ACTIONS: actions_resampled, + } + # Make sure we perform a "straight-through gradient" pass here, + # ignoring the gradients of the q-net, however, still recording + # the gradients of the policy net (which was used to rsample the actions used + # here). This is different from doing `.detach()` or `with torch.no_grads()`, + # as these two methds would fully block all gradient recordings, including + # the needed policy ones. + all_params = list(self.qf.parameters()) + list(self.qf_encoder.parameters()) + if self.twin_q: + all_params += list(self.qf_twin.parameters()) + list( + self.qf_twin_encoder.parameters() + ) + + for param in all_params: + param.requires_grad = False + output["q_curr"] = self.compute_q_values(q_batch_curr) + for param in all_params: + param.requires_grad = True + + # Compute Q-values from the target Q network for the next state with the + # sampled actions for the next state. + q_batch_next = { + Columns.OBS: batch[Columns.NEXT_OBS], + Columns.ACTIONS: actions_next_resampled, + } + output["q_target_next"] = self.forward_target(q_batch_next).detach() + + # Return the network outputs. + return output + + @override(TargetNetworkAPI) + def forward_target( + self, batch: Dict[str, Any], squeeze: bool = True + ) -> Dict[str, Any]: + target_qvs = self._qf_forward_train_helper( + batch, self.target_qf_encoder, self.target_qf, squeeze=squeeze + ) + + # If a twin Q network should be used, calculate twin Q-values and use the + # minimum. + if self.twin_q: + target_qvs = torch.min( + target_qvs, + self._qf_forward_train_helper( + batch, + self.target_qf_twin_encoder, + self.target_qf_twin, + squeeze=squeeze, + ), + ) + + return target_qvs + + @override(QNetAPI) + def compute_q_values( + self, batch: Dict[str, Any], squeeze: bool = True + ) -> Dict[str, Any]: + qvs = self._qf_forward_train_helper( + batch, self.qf_encoder, self.qf, squeeze=squeeze + ) + # If a twin Q network should be used, calculate twin Q-values and use the + # minimum. + if self.twin_q: + qvs = torch.min( + qvs, + self._qf_forward_train_helper( + batch, self.qf_twin_encoder, self.qf_twin, squeeze=squeeze + ), + ) + return qvs + + @override(DefaultSACRLModule) + def _qf_forward_train_helper( + self, batch: Dict[str, Any], encoder: Encoder, head: Model, squeeze: bool = True + ) -> Dict[str, Any]: + """Executes the forward pass for Q networks. + + Args: + batch: Dict containing a concatenated tensor with observations + and actions under the key `Columns.OBS`. + encoder: An `Encoder` model for the Q state-action encoder. + head: A `Model` for the Q head. + squeeze: If True, squeezes the last dimension of the output if it is 1. Used for continuous action spaces. + + Returns: + The estimated Q-value for the input action for continuous action spaces. + Or the Q-values for all actions for discrete action spaces. + """ + # Construct batch. Note, we need to feed observations and actions. + if isinstance(self.action_space, gym.spaces.Box): + actions = batch[Columns.ACTIONS] + qf_batch = { + Columns.OBS: torch.concat((batch[Columns.OBS], actions), dim=-1) + } + else: + # For discrete action spaces, we don't need to include the actions + # in the batch, as the Q function outputs the Q-values for each action + qf_batch = {Columns.OBS: batch[Columns.OBS]} + + # Encoder forward pass. + qf_encoder_outs = encoder(qf_batch) + + # Q head forward pass. + # (B,latent_size) -> (B, 1|action_dim) + qf_out = head(qf_encoder_outs[ENCODER_OUT]) + if squeeze: + # Squeeze the last dimension if it is 1. + qf_out = qf_out.squeeze(-1) + return qf_out diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/torch/sac_torch_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/torch/sac_torch_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..8d96f22f4730e1bbcfbaa5ccf7124aafec3f7b00 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/sac/torch/sac_torch_learner.py @@ -0,0 +1,429 @@ +import gymnasium as gym +from typing import Any, Dict + +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig +from ray.rllib.algorithms.dqn.torch.dqn_torch_learner import DQNTorchLearner +from ray.rllib.algorithms.sac.sac import SACConfig +from ray.rllib.algorithms.sac.sac_learner import ( + LOGPS_KEY, + QF_LOSS_KEY, + QF_MEAN_KEY, + QF_MAX_KEY, + QF_MIN_KEY, + QF_PREDS, + QF_TWIN_LOSS_KEY, + QF_TWIN_PREDS, + TD_ERROR_MEAN_KEY, + ACTION_LOG_PROBS, + ACTION_LOG_PROBS_NEXT, + ACTION_PROBS, + ACTION_PROBS_NEXT, + QF_TARGET_NEXT, + SACLearner, +) +from ray.rllib.core.columns import Columns +from ray.rllib.core.learner.learner import ( + POLICY_LOSS_KEY, +) +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.metrics import ALL_MODULES, TD_ERROR_KEY +from ray.rllib.utils.typing import ModuleID, ParamDict, TensorType + +torch, nn = try_import_torch() + + +class SACTorchLearner(DQNTorchLearner, SACLearner): + """Implements `torch`-specific SAC loss logic on top of `SACLearner` + + This ' Learner' class implements the loss in its + `self.compute_loss_for_module()` method. In addition, it updates + the target networks of the RLModule(s). + """ + + def build(self) -> None: + super().build() + + # Store loss tensors here temporarily inside the loss function for (exact) + # consumption later by the compute gradients function. + # Keys=(module_id, optimizer_name), values=loss tensors (in-graph). + self._temp_losses = {} + + # TODO (simon): Set different learning rates for optimizers. + @override(DQNTorchLearner) + def configure_optimizers_for_module( + self, module_id: ModuleID, config: AlgorithmConfig = None + ) -> None: + # Receive the module. + module = self._module[module_id] + + # Define the optimizer for the critic. + # TODO (sven): Maybe we change here naming to `qf` for unification. + params_critic = self.get_parameters(module.qf_encoder) + self.get_parameters( + module.qf + ) + optim_critic = torch.optim.Adam(params_critic, eps=1e-7) + + self.register_optimizer( + module_id=module_id, + optimizer_name="qf", + optimizer=optim_critic, + params=params_critic, + lr_or_lr_schedule=config.critic_lr, + ) + # If necessary register also an optimizer for a twin Q network. + if config.twin_q: + params_twin_critic = self.get_parameters( + module.qf_twin_encoder + ) + self.get_parameters(module.qf_twin) + optim_twin_critic = torch.optim.Adam(params_twin_critic, eps=1e-7) + + self.register_optimizer( + module_id=module_id, + optimizer_name="qf_twin", + optimizer=optim_twin_critic, + params=params_twin_critic, + lr_or_lr_schedule=config.critic_lr, + ) + + # Define the optimizer for the actor. + params_actor = self.get_parameters(module.pi_encoder) + self.get_parameters( + module.pi + ) + optim_actor = torch.optim.Adam(params_actor, eps=1e-7) + + self.register_optimizer( + module_id=module_id, + optimizer_name="policy", + optimizer=optim_actor, + params=params_actor, + lr_or_lr_schedule=config.actor_lr, + ) + + # Define the optimizer for the temperature. + temperature = self.curr_log_alpha[module_id] + optim_temperature = torch.optim.Adam([temperature], eps=1e-7) + self.register_optimizer( + module_id=module_id, + optimizer_name="alpha", + optimizer=optim_temperature, + params=[temperature], + lr_or_lr_schedule=config.alpha_lr, + ) + + @override(DQNTorchLearner) + def compute_loss_for_module( + self, + *, + module_id: ModuleID, + config: SACConfig, + batch: Dict[str, Any], + fwd_out: Dict[str, TensorType], + ) -> TensorType: + + module = self._module[module_id] + if isinstance(module.action_space, gym.spaces.Discrete): + # Discrete action space: Use the discrete loss function. + return self._compute_loss_for_module_discrete( + module_id=module_id, + config=config, + batch=batch, + fwd_out=fwd_out, + ) + elif isinstance(module.action_space, gym.spaces.Box): + # Continuous action space: Use the continuous loss function. + return self._compute_loss_for_module_continuous( + module_id=module_id, + config=config, + batch=batch, + fwd_out=fwd_out, + ) + else: + raise ValueError( + f"Unsupported action space type: {type(module.action_space)}. " + "Only Discrete and Box action spaces are supported." + ) + + def _compute_loss_for_module_discrete( + self, + *, + module_id: ModuleID, + config: SACConfig, + batch: Dict[str, Any], + fwd_out: Dict[str, TensorType], + ) -> TensorType: + # Receive the current alpha hyperparameter. + alpha = torch.exp(self.curr_log_alpha[module_id]) + + ## Calculate Q value targets + action_probs_next = fwd_out[ACTION_PROBS_NEXT] + action_log_probs_next = fwd_out[ACTION_LOG_PROBS_NEXT] + next_q = fwd_out[QF_TARGET_NEXT] + next_v = ( + (action_probs_next * (next_q - alpha.detach() * action_log_probs_next)) + .sum(-1) + .squeeze(-1) + ) + next_v_masked = (1.0 - batch[Columns.TERMINATEDS].float()) * next_v + target_q = ( + batch[Columns.REWARDS] + (config.gamma ** batch["n_step"]) * next_v_masked + ).detach() + + # Get Q-values for the actually selected actions during rollout. + actions = batch[Columns.ACTIONS].to(dtype=torch.int64).unsqueeze(-1) + qf_pred = fwd_out[QF_PREDS].gather(dim=-1, index=actions).squeeze(-1) + if config.twin_q: + qf_twin_pred = ( + fwd_out[QF_TWIN_PREDS].gather(dim=-1, index=actions).squeeze(-1) + ) + + # Calculate the TD-error. Note, this is needed for the priority weights in + # the replay buffer. + td_error = torch.abs(qf_pred - target_q) + # If a twin Q network should be used, add the TD error of the twin Q network. + if config.twin_q: + td_error += torch.abs(qf_twin_pred - target_q) + # Rescale the TD error. + td_error *= 0.5 + + # MSBE loss for the critic(s) (i.e. Q, see eqs. (7-8) Haarnoja et al. (2018)). + # Note, this needs a sample from the current policy given the next state. + # Note further, we use here the Huber loss instead of the mean squared error + # as it improves training performance. + critic_loss = torch.mean( + batch["weights"] + * torch.nn.HuberLoss(reduction="none", delta=1.0)(qf_pred, target_q) + ) + # If a twin Q network should be used, add the critic loss of the twin Q network. + if config.twin_q: + critic_twin_loss = torch.mean( + batch["weights"] + * torch.nn.HuberLoss(reduction="none", delta=1.0)( + qf_twin_pred, target_q + ) + ) + + ## Calculate the actor loss ## + action_probs = fwd_out[ACTION_PROBS] + action_log_probs = fwd_out[ACTION_LOG_PROBS] + qf = torch.min(fwd_out[QF_PREDS], fwd_out[QF_TWIN_PREDS]).detach() + policy_loss = ( + (action_probs * (alpha.detach() * action_log_probs - qf)).sum(-1).mean() + ) + + ## Calculate the alpha loss ## + entropy = (action_log_probs * action_probs).sum(-1) + alpha_loss = -torch.mean( + self.curr_log_alpha[module_id] + * (entropy.detach() + self.target_entropy[module_id]) + ) + + total_loss = policy_loss + critic_loss + alpha_loss + if config.twin_q: + total_loss += critic_twin_loss + + # Log the TD-error with reduce=None, such that - in case we have n parallel + # Learners - we will re-concatenate the produced TD-error tensors to yield + # a 1:1 representation of the original batch. + self.metrics.log_value( + key=(module_id, TD_ERROR_KEY), + value=td_error, + reduce=None, + clear_on_reduce=True, + ) + # Log other important loss stats (reduce=mean (default), but with window=1 + # in order to keep them history free). + self.metrics.log_dict( + { + POLICY_LOSS_KEY: policy_loss, + QF_LOSS_KEY: critic_loss, + "alpha_loss": alpha_loss, + "alpha_value": alpha[0], + "log_alpha_value": torch.log(alpha)[0], + "target_entropy": self.target_entropy[module_id], + LOGPS_KEY: torch.mean(fwd_out[ACTION_LOG_PROBS]), + QF_MEAN_KEY: torch.mean(fwd_out[QF_PREDS]), + QF_MAX_KEY: torch.max(fwd_out[QF_PREDS]), + QF_MIN_KEY: torch.min(fwd_out[QF_PREDS]), + TD_ERROR_MEAN_KEY: torch.mean(td_error), + }, + key=module_id, + window=1, # <- single items (should not be mean/ema-reduced over time). + ) + + self._temp_losses[(module_id, POLICY_LOSS_KEY)] = policy_loss + self._temp_losses[(module_id, QF_LOSS_KEY)] = critic_loss + self._temp_losses[(module_id, "alpha_loss")] = alpha_loss + + # If twin Q networks should be used add a critic loss for the twin Q network. + # Note, we need this in the `self.compute_gradients()` to optimize. + if config.twin_q: + self.metrics.log_value( + key=(module_id, QF_TWIN_LOSS_KEY), + value=critic_twin_loss, + window=1, # <- single items (should not be mean/ema-reduced over time). + ) + self._temp_losses[(module_id, QF_TWIN_LOSS_KEY)] = critic_twin_loss + + return total_loss + + def _compute_loss_for_module_continuous( + self, + *, + module_id: ModuleID, + config: SACConfig, + batch: Dict[str, Any], + fwd_out: Dict[str, TensorType], + ) -> TensorType: + # Receive the current alpha hyperparameter. + alpha = torch.exp(self.curr_log_alpha[module_id]) + + # Get Q-values for the actually selected actions during rollout. + # In the critic loss we use these as predictions. + q_selected = fwd_out[QF_PREDS] + if config.twin_q: + q_twin_selected = fwd_out[QF_TWIN_PREDS] + + # Compute value function for next state (see eq. (3) in Haarnoja et al. (2018)). + # Note, we use here the sampled actions in the log probabilities. + q_target_next = ( + fwd_out["q_target_next"] - alpha.detach() * fwd_out["logp_next_resampled"] + ) + # Now mask all Q-values with terminated next states in the targets. + q_next_masked = (1.0 - batch[Columns.TERMINATEDS].float()) * q_target_next + + # Compute the right hand side of the Bellman equation. + # Detach this node from the computation graph as we do not want to + # backpropagate through the target network when optimizing the Q loss. + q_selected_target = ( + batch[Columns.REWARDS] + (config.gamma ** batch["n_step"]) * q_next_masked + ).detach() + + # Calculate the TD-error. Note, this is needed for the priority weights in + # the replay buffer. + td_error = torch.abs(q_selected - q_selected_target) + # If a twin Q network should be used, add the TD error of the twin Q network. + if config.twin_q: + td_error += torch.abs(q_twin_selected - q_selected_target) + # Rescale the TD error. + td_error *= 0.5 + + # MSBE loss for the critic(s) (i.e. Q, see eqs. (7-8) Haarnoja et al. (2018)). + # Note, this needs a sample from the current policy given the next state. + # Note further, we use here the Huber loss instead of the mean squared error + # as it improves training performance. + critic_loss = torch.mean( + batch["weights"] + * torch.nn.HuberLoss(reduction="none", delta=1.0)( + q_selected, q_selected_target + ) + ) + # If a twin Q network should be used, add the critic loss of the twin Q network. + if config.twin_q: + critic_twin_loss = torch.mean( + batch["weights"] + * torch.nn.HuberLoss(reduction="none", delta=1.0)( + q_twin_selected, q_selected_target + ) + ) + + # For the actor (policy) loss we need sampled actions from the current policy + # evaluated at the current observations. + # Note that the `q_curr` tensor below has the q-net's gradients ignored, while + # having the policy's gradients registered. The policy net was used to rsample + # actions used to compute `q_curr` (by passing these actions through the q-net). + # Hence, we can't do `fwd_out[q_curr].detach()`! + # Note further, we minimize here, while the original equation in Haarnoja et + # al. (2018) considers maximization. + # TODO (simon): Rename to `resampled` to `current`. + actor_loss = torch.mean( + alpha.detach() * fwd_out["logp_resampled"] - fwd_out["q_curr"] + ) + + # Optimize also the hyperparameter alpha by using the current policy + # evaluated at the current state (sampled values). + # TODO (simon): Check, why log(alpha) is used, prob. just better + # to optimize and monotonic function. Original equation uses alpha. + alpha_loss = -torch.mean( + self.curr_log_alpha[module_id] + * (fwd_out["logp_resampled"].detach() + self.target_entropy[module_id]) + ) + + total_loss = actor_loss + critic_loss + alpha_loss + # If twin Q networks should be used, add the critic loss of the twin Q network. + if config.twin_q: + # TODO (simon): Check, if we need to multiply the critic_loss then with 0.5. + total_loss += critic_twin_loss + + # Log the TD-error with reduce=None, such that - in case we have n parallel + # Learners - we will re-concatenate the produced TD-error tensors to yield + # a 1:1 representation of the original batch. + self.metrics.log_value( + key=(module_id, TD_ERROR_KEY), + value=td_error, + reduce=None, + clear_on_reduce=True, + ) + # Log other important loss stats (reduce=mean (default), but with window=1 + # in order to keep them history free). + self.metrics.log_dict( + { + POLICY_LOSS_KEY: actor_loss, + QF_LOSS_KEY: critic_loss, + "alpha_loss": alpha_loss, + "alpha_value": alpha[0], + "log_alpha_value": torch.log(alpha)[0], + "target_entropy": self.target_entropy[module_id], + LOGPS_KEY: torch.mean(fwd_out["logp_resampled"]), + QF_MEAN_KEY: torch.mean(fwd_out["q_curr"]), + QF_MAX_KEY: torch.max(fwd_out["q_curr"]), + QF_MIN_KEY: torch.min(fwd_out["q_curr"]), + TD_ERROR_MEAN_KEY: torch.mean(td_error), + }, + key=module_id, + window=1, # <- single items (should not be mean/ema-reduced over time). + ) + + self._temp_losses[(module_id, POLICY_LOSS_KEY)] = actor_loss + self._temp_losses[(module_id, QF_LOSS_KEY)] = critic_loss + self._temp_losses[(module_id, "alpha_loss")] = alpha_loss + + # If twin Q networks should be used add a critic loss for the twin Q network. + # Note, we need this in the `self.compute_gradients()` to optimize. + if config.twin_q: + self.metrics.log_value( + key=(module_id, QF_TWIN_LOSS_KEY), + value=critic_twin_loss, + window=1, # <- single items (should not be mean/ema-reduced over time). + ) + self._temp_losses[(module_id, QF_TWIN_LOSS_KEY)] = critic_twin_loss + + return total_loss + + @override(DQNTorchLearner) + def compute_gradients( + self, loss_per_module: Dict[ModuleID, TensorType], **kwargs + ) -> ParamDict: + grads = {} + for module_id in set(loss_per_module.keys()) - {ALL_MODULES}: + # Loop through optimizers registered for this module. + for optim_name, optim in self.get_optimizers_for_module(module_id): + # Zero the gradients. Note, we need to reset the gradients b/c + # each component for a module operates on the same graph. + optim.zero_grad(set_to_none=True) + + # Compute the gradients for the component and module. + loss_tensor = self._temp_losses.pop((module_id, optim_name + "_loss")) + loss_tensor.backward(retain_graph=True) + # Store the gradients for the component and module. + grads.update( + { + pid: p.grad + for pid, p in self.filter_param_dict_for_optimizer( + self._params, optim + ).items() + } + ) + + assert not self._temp_losses + return grads diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b70b3cf2612b428f2586a61673763593d2847d7e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/algorithms/utils.py @@ -0,0 +1,179 @@ +import platform +from typing import List + +import tree # pip install dm_tree + +import ray +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig +from ray.rllib.policy.sample_batch import MultiAgentBatch, SampleBatch +from ray.rllib.utils.actor_manager import FaultAwareApply +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.metrics.metrics_logger import MetricsLogger +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import DeveloperAPI + +torch, _ = try_import_torch() + + +@DeveloperAPI(stability="alpha") +class AggregatorActor(FaultAwareApply): + """Runs episode lists through ConnectorV2 pipeline and creates train batches. + + The actor should be co-located with a Learner worker. Ideally, there should be one + or two aggregator actors per Learner worker (having even more per Learner probably + won't help. Then the main process driving the RL algo can perform the following + execution logic: + - query n EnvRunners to sample the environment and return n lists of episodes as + Ray.ObjectRefs. + - remote call the set of aggregator actors (in round-robin fashion) with these + list[episodes] refs in async fashion. + - gather the results asynchronously, as each actor returns refs pointing to + ready-to-go train batches. + - as soon as we have at least one train batch per Learner, call the LearnerGroup + with the (already sharded) refs. + - an aggregator actor - when receiving p refs to List[EpisodeType] - does: + -- ray.get() the actual p lists and concatenate the p lists into one + List[EpisodeType]. + -- pass the lists of episodes through its LearnerConnector pipeline + -- buffer the output batches of this pipeline until enough batches have been + collected for creating one train batch (matching the config's + `train_batch_size_per_learner`). + -- concatenate q batches into a train batch and return that train batch. + - the algo main process then passes the ray.ObjectRef to the ready-to-go train batch + to the LearnerGroup for calling each Learner with one train batch. + """ + + def __init__(self, config: AlgorithmConfig, rl_module_spec): + self.config = config + + # Set device and node. + self._node = platform.node() + self._device = torch.device("cpu") + self.metrics = MetricsLogger() + + # Create the RLModule. + # TODO (sven): For now, this RLModule (its weights) never gets updated. + # The reason the module is needed is for the connector to know, which + # sub-modules are stateful (and what their initial state tensors are), and + # which IDs the submodules have (to figure out, whether its multi-agent or + # not). + self._module = rl_module_spec.build() + self._module = self._module.as_multi_rl_module() + + # Create the Learner connector pipeline. + self._learner_connector = self.config.build_learner_connector( + input_observation_space=None, + input_action_space=None, + device=self._device, + ) + + def get_batch(self, episode_refs: List[ray.ObjectRef]): + episodes: List[EpisodeType] = [] + # It's possible that individual refs are invalid due to the EnvRunner + # that produced the ref has crashed or had its entire node go down. + # In this case, try each ref individually and collect only valid results. + try: + episodes = tree.flatten(ray.get(episode_refs)) + except ray.exceptions.OwnerDiedError: + for ref in episode_refs: + try: + episodes.extend(ray.get(ref)) + except ray.exceptions.OwnerDiedError: + pass + + env_steps = sum(len(e) for e in episodes) + + # If we have enough episodes collected to create a single train batch, pass + # them at once through the connector to receive a single train batch. + batch = self._learner_connector( + episodes=episodes, + rl_module=self._module, + metrics=self.metrics, + ) + # Convert to a dict into a `MultiAgentBatch`. + # TODO (sven): Try to get rid of dependency on MultiAgentBatch (once our mini- + # batch iterators support splitting over a dict). + ma_batch = MultiAgentBatch( + policy_batches={ + pid: SampleBatch(pol_batch) for pid, pol_batch in batch.items() + }, + env_steps=env_steps, + ) + return ma_batch + + def get_metrics(self): + return self.metrics.reduce() + + +def _get_env_runner_bundles(config): + return [ + { + "CPU": config.num_cpus_per_env_runner, + "GPU": config.num_gpus_per_env_runner, + **config.custom_resources_per_env_runner, + } + for _ in range(config.num_env_runners) + ] + + +def _get_offline_eval_runner_bundles(config): + return [ + { + "CPU": config.num_cpus_per_offline_eval_runner, + "GPU": config.num_gpus_per_offline_eval_runner, + **config.custom_resources_per_offline_eval_runner, + } + for _ in range(config.num_offline_eval_runners) + ] + + +def _get_learner_bundles(config): + try: + from ray.rllib.extensions.algorithm_utils import _get_learner_bundles as func + + return func(config) + except Exception: + pass + + if config.num_learners == 0: + if config.num_aggregator_actors_per_learner > 0: + return [{"CPU": config.num_aggregator_actors_per_learner}] + else: + return [] + + num_cpus_per_learner = ( + config.num_cpus_per_learner + if config.num_cpus_per_learner != "auto" + else 1 + if config.num_gpus_per_learner == 0 + else 0 + ) + + bundles = [ + { + "CPU": config.num_learners + * (num_cpus_per_learner + config.num_aggregator_actors_per_learner), + "GPU": config.num_learners * config.num_gpus_per_learner, + } + ] + + return bundles + + +def _get_main_process_bundle(config): + if config.num_learners == 0: + num_cpus_per_learner = ( + config.num_cpus_per_learner + if config.num_cpus_per_learner != "auto" + else 1 + if config.num_gpus_per_learner == 0 + else 0 + ) + bundle = { + "CPU": max(num_cpus_per_learner, config.num_cpus_for_main_process), + "GPU": config.num_gpus_per_learner, + } + else: + bundle = {"CPU": config.num_cpus_for_main_process, "GPU": 0} + + return bundle diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/callbacks/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/callbacks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/callbacks/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/callbacks/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44ea5c93e55a37952a609c65964730f8212110fd Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/callbacks/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/callbacks/__pycache__/callbacks.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/callbacks/__pycache__/callbacks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7114270decbd55cf6723e12bfd3579630e70f79a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/callbacks/__pycache__/callbacks.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/callbacks/__pycache__/utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/callbacks/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa191135823436857e7264873f5ac4dd473a1381 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/callbacks/__pycache__/utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/callbacks/callbacks.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/callbacks/callbacks.py new file mode 100644 index 0000000000000000000000000000000000000000..208684f780fc2ddac692b4e442bdddf707ac9c08 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/callbacks/callbacks.py @@ -0,0 +1,741 @@ +import gc +import os +import platform +import tracemalloc +from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union + +import gymnasium as gym + +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.env.base_env import BaseEnv +from ray.rllib.env.env_context import EnvContext +from ray.rllib.evaluation.episode_v2 import EpisodeV2 +from ray.rllib.offline.offline_evaluation_runner_group import ( + OfflineEvaluationRunnerGroup, +) +from ray.rllib.policy import Policy +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.annotations import ( + OldAPIStack, + override, + OverrideToImplementCustomLogic, + PublicAPI, +) +from ray.rllib.utils.metrics.metrics_logger import MetricsLogger +from ray.rllib.utils.typing import AgentID, EnvType, EpisodeType, PolicyID +from ray.tune.callback import _CallbackMeta + +# Import psutil after ray so the packaged version is used. +import psutil + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm import Algorithm + from ray.rllib.env.env_runner import EnvRunner + from ray.rllib.env.env_runner_group import EnvRunnerGroup + + +@PublicAPI +class RLlibCallback(metaclass=_CallbackMeta): + """Abstract base class for RLlib callbacks (similar to Keras callbacks). + + These callbacks can be used for custom metrics and custom postprocessing. + + By default, all of these callbacks are no-ops. To configure custom training + callbacks, subclass RLlibCallback and then set + {"callbacks": YourCallbacksClass} in the algo config. + """ + + @OverrideToImplementCustomLogic + def on_algorithm_init( + self, + *, + algorithm: "Algorithm", + metrics_logger: Optional[MetricsLogger] = None, + **kwargs, + ) -> None: + """Callback run when a new Algorithm instance has finished setup. + + This method gets called at the end of Algorithm.setup() after all + the initialization is done, and before actually training starts. + + Args: + algorithm: Reference to the Algorithm instance. + metrics_logger: The MetricsLogger object inside the `Algorithm`. Can be + used to log custom metrics after algo initialization. + kwargs: Forward compatibility placeholder. + """ + pass + + @OverrideToImplementCustomLogic + def on_train_result( + self, + *, + algorithm: "Algorithm", + metrics_logger: Optional[MetricsLogger] = None, + result: dict, + **kwargs, + ) -> None: + """Called at the end of Algorithm.train(). + + Args: + algorithm: Current Algorithm instance. + metrics_logger: The MetricsLogger object inside the Algorithm. Can be + used to log custom metrics after traing results are available. + result: Dict of results returned from Algorithm.train() call. + You can mutate this object to add additional metrics. + kwargs: Forward compatibility placeholder. + """ + pass + + @OverrideToImplementCustomLogic + def on_evaluate_start( + self, + *, + algorithm: "Algorithm", + metrics_logger: Optional[MetricsLogger] = None, + **kwargs, + ) -> None: + """Callback before evaluation starts. + + This method gets called at the beginning of Algorithm.evaluate(). + + Args: + algorithm: Reference to the algorithm instance. + metrics_logger: The MetricsLogger object inside the `Algorithm`. Can be + used to log custom metrics before running the next round of evaluation. + kwargs: Forward compatibility placeholder. + """ + pass + + @OverrideToImplementCustomLogic + def on_evaluate_offline_start( + self, + *, + algorithm: "Algorithm", + metrics_logger: Optional[MetricsLogger] = None, + **kwargs, + ) -> None: + """Callback before offline evaluation starts. + + This method gets called at the beginning of Algorithm.evaluate_offline(). + + Args: + algorithm: Reference to the algorithm instance. + metrics_logger: The MetricsLogger object inside the `Algorithm`. Can be + used to log custom metrics before running the next round of offline + evaluation. + kwargs: Forward compatibility placeholder. + """ + pass + + @OverrideToImplementCustomLogic + def on_evaluate_end( + self, + *, + algorithm: "Algorithm", + metrics_logger: Optional[MetricsLogger] = None, + evaluation_metrics: dict, + **kwargs, + ) -> None: + """Runs when the evaluation is done. + + Runs at the end of Algorithm.evaluate(). + + Args: + algorithm: Reference to the algorithm instance. + metrics_logger: The MetricsLogger object inside the `Algorithm`. Can be + used to log custom metrics after the most recent evaluation round. + evaluation_metrics: Results dict to be returned from algorithm.evaluate(). + You can mutate this object to add additional metrics. + kwargs: Forward compatibility placeholder. + """ + pass + + @OverrideToImplementCustomLogic + def on_evaluate_offline_end( + self, + *, + algorithm: "Algorithm", + metrics_logger: Optional[MetricsLogger] = None, + evaluation_metrics: dict, + **kwargs, + ) -> None: + """Runs when the offline evaluation is done. + + Runs at the end of Algorithm.evaluate_offline(). + + Args: + algorithm: Reference to the algorithm instance. + metrics_logger: The MetricsLogger object inside the `Algorithm`. Can be + used to log custom metrics after the most recent offline evaluation + round. + evaluation_metrics: Results dict to be returned from + Algorithm.evaluate_offline(). You can mutate this object to add + additional metrics. + kwargs: Forward compatibility placeholder. + """ + pass + + @OverrideToImplementCustomLogic + def on_env_runners_recreated( + self, + *, + algorithm: "Algorithm", + env_runner_group: "EnvRunnerGroup", + env_runner_indices: List[int], + is_evaluation: bool, + **kwargs, + ) -> None: + """Callback run after one or more EnvRunner actors have been recreated. + + You can access and change the EnvRunners in question through the following code + snippet inside your custom override of this method: + + .. testcode:: + from ray.rllib.callbacks.callbacks import RLlibCallback + + class MyCallbacks(RLlibCallback): + def on_env_runners_recreated( + self, + *, + algorithm, + env_runner_group, + env_runner_indices, + is_evaluation, + **kwargs, + ): + # Define what you would like to do on the recreated EnvRunner: + def func(env_runner): + # Here, we just set some arbitrary property to 1. + if is_evaluation: + env_runner._custom_property_for_evaluation = 1 + else: + env_runner._custom_property_for_training = 1 + + # Use the `foreach_env_runner` method of the worker set and + # only loop through those worker IDs that have been restarted. + # Note that we set `local_worker=False` to NOT include it (local + # workers are never recreated; if they fail, the entire Algorithm + # fails). + env_runner_group.foreach_env_runner( + func, + remote_worker_ids=env_runner_indices, + local_env_runner=False, + ) + + Args: + algorithm: Reference to the Algorithm instance. + env_runner_group: The EnvRunnerGroup object in which the workers in question + reside. You can use a `env_runner_group.foreach_env_runner( + remote_worker_ids=..., local_env_runner=False)` method call to execute + custom code on the recreated (remote) workers. Note that the local + worker is never recreated as a failure of this would also crash the + Algorithm. + env_runner_indices: The list of (remote) worker IDs that have been + recreated. + is_evaluation: Whether `worker_set` is the evaluation EnvRunnerGroup + (located in `Algorithm.eval_env_runner_group`) or not. + """ + pass + + @OverrideToImplementCustomLogic + def on_offline_eval_runners_recreated( + self, + *, + algorithm: "Algorithm", + offline_eval_runner_group: "OfflineEvaluationRunnerGroup", + offline_eval_runner_indices: List[int], + **kwargs, + ) -> None: + """Callback run after one or more OfflineEvaluationRunner actors have been recreated. + + You can access and change the OfflineEvaluationRunners in question through the following code + snippet inside your custom override of this method: + + .. testcode:: + from ray.rllib.callbacks.callbacks import RLlibCallback + + class MyCallbacks(RLlibCallback): + def on_offline_eval_runners_recreated( + self, + *, + algorithm, + offline_eval_runner_group, + offline_eval_runner_indices, + **kwargs, + ): + # Define what you would like to do on the recreated EnvRunner: + def func(offline_eval_runner): + # Here, we just set some arbitrary property to 1. + if is_evaluation: + offline_eval_runner._custom_property_for_evaluation = 1 + else: + offline_eval_runner._custom_property_for_training = 1 + + # Use the `foreach_runner` method of the worker set and + # only loop through those worker IDs that have been restarted. + # Note that `local_runner=False` as long as there are remote + # runners. + offline_eval_runner_group.foreach_runner( + func, + remote_runner_ids=offline_eval_runner_indices, + local_runner=False, + ) + + Args: + algorithm: Reference to the Algorithm instance. + offline_eval_runner_group: The OfflineEvaluationRunnerGroup object in which + the workers in question reside. You can use a `runner_group.foreach_runner( + remote_worker_ids=..., local_runner=False)` method call to execute + custom code on the recreated (remote) workers. + offline_eval_runner_indices: The list of (remote) worker IDs that have been + recreated. + """ + pass + + @OverrideToImplementCustomLogic + def on_checkpoint_loaded( + self, + *, + algorithm: "Algorithm", + **kwargs, + ) -> None: + """Callback run when an Algorithm has loaded a new state from a checkpoint. + + This method gets called at the end of `Algorithm.load_checkpoint()`. + + Args: + algorithm: Reference to the Algorithm instance. + kwargs: Forward compatibility placeholder. + """ + pass + + @OverrideToImplementCustomLogic + def on_environment_created( + self, + *, + env_runner: "EnvRunner", + metrics_logger: Optional[MetricsLogger] = None, + env: gym.Env, + env_context: EnvContext, + **kwargs, + ) -> None: + """Callback run when a new environment object has been created. + + Note: This only applies to the new API stack. The env used is usually a + gym.Env (or more specifically a gym.vector.Env). + + Args: + env_runner: Reference to the current EnvRunner instance. + metrics_logger: The MetricsLogger object inside the `env_runner`. Can be + used to log custom metrics after environment creation. + env: The environment object that has been created on `env_runner`. This is + usually a gym.Env (or a gym.vector.Env) object. + env_context: The `EnvContext` object that has been passed to the + `gym.make()` call as kwargs (and to the gym.Env as `config`). It should + have all the config key/value pairs in it as well as the + EnvContext-typical properties: `worker_index`, `num_workers`, and + `remote`. + kwargs: Forward compatibility placeholder. + """ + pass + + @OverrideToImplementCustomLogic + def on_episode_created( + self, + *, + # TODO (sven): Deprecate Episode/EpisodeV2 with new API stack. + episode: Union[EpisodeType, EpisodeV2], + # TODO (sven): Deprecate this arg new API stack (in favor of `env_runner`). + worker: Optional["EnvRunner"] = None, + env_runner: Optional["EnvRunner"] = None, + metrics_logger: Optional[MetricsLogger] = None, + # TODO (sven): Deprecate this arg new API stack (in favor of `env`). + base_env: Optional[BaseEnv] = None, + env: Optional[gym.Env] = None, + # TODO (sven): Deprecate this arg new API stack (in favor of `rl_module`). + policies: Optional[Dict[PolicyID, Policy]] = None, + rl_module: Optional[RLModule] = None, + env_index: int, + **kwargs, + ) -> None: + """Callback run when a new episode is created (but has not started yet!). + + This method gets called after a new SingleAgentEpisode or MultiAgentEpisode + instance has been created. This happens before the respective sub-environment's + `reset()` is called by RLlib. + + 1) SingleAgentEpisode/MultiAgentEpisode created: This callback is called. + 2) Respective sub-environment (gym.Env) is `reset()`. + 3) Callback `on_episode_start` is called. + 4) Stepping through sub-environment/episode commences. + + Args: + episode: The newly created SingleAgentEpisode or MultiAgentEpisode. + This is the episode that is about to be started with an upcoming + `env.reset()`. Only after this reset call, the `on_episode_start` + callback will be called. + env_runner: Reference to the current EnvRunner. + metrics_logger: The MetricsLogger object inside the `env_runner`. Can be + used to log custom metrics after Episode creation. + env: The gym.Env running the episode. + rl_module: The RLModule used to compute actions for stepping the env. In + single-agent mode, this is a simple RLModule, in multi-agent mode, this + is a MultiRLModule. + env_index: The index of the sub-environment that is about to be reset. + kwargs: Forward compatibility placeholder. + """ + pass + + @OverrideToImplementCustomLogic + def on_episode_start( + self, + *, + episode: Union[EpisodeType, EpisodeV2], + env_runner: Optional["EnvRunner"] = None, + metrics_logger: Optional[MetricsLogger] = None, + env: Optional[gym.Env] = None, + env_index: int, + rl_module: Optional[RLModule] = None, + # TODO (sven): Deprecate these args. + worker: Optional["EnvRunner"] = None, + base_env: Optional[BaseEnv] = None, + policies: Optional[Dict[PolicyID, Policy]] = None, + **kwargs, + ) -> None: + """Callback run right after an Episode has been started. + + This method gets called after a SingleAgentEpisode or MultiAgentEpisode instance + has been reset with a call to `env.reset()` by the EnvRunner. + + 1) Single-/MultiAgentEpisode created: `on_episode_created()` is called. + 2) Respective sub-environment (gym.Env) is `reset()`. + 3) Single-/MultiAgentEpisode starts: This callback is called. + 4) Stepping through sub-environment/episode commences. + + Args: + episode: The just started (after `env.reset()`) SingleAgentEpisode or + MultiAgentEpisode object. + env_runner: Reference to the EnvRunner running the env and episode. + metrics_logger: The MetricsLogger object inside the `env_runner`. Can be + used to log custom metrics during env/episode stepping. + env: The gym.Env or gym.vector.Env object running the started episode. + env_index: The index of the sub-environment that is about to be reset + (within the vector of sub-environments of the BaseEnv). + rl_module: The RLModule used to compute actions for stepping the env. In + single-agent mode, this is a simple RLModule, in multi-agent mode, this + is a MultiRLModule. + kwargs: Forward compatibility placeholder. + """ + pass + + @OverrideToImplementCustomLogic + def on_episode_step( + self, + *, + episode: Union[EpisodeType, EpisodeV2], + env_runner: Optional["EnvRunner"] = None, + metrics_logger: Optional[MetricsLogger] = None, + env: Optional[gym.Env] = None, + env_index: int, + rl_module: Optional[RLModule] = None, + # TODO (sven): Deprecate these args. + worker: Optional["EnvRunner"] = None, + base_env: Optional[BaseEnv] = None, + policies: Optional[Dict[PolicyID, Policy]] = None, + **kwargs, + ) -> None: + """Called on each episode step (after the action(s) has/have been logged). + + Note that on the new API stack, this callback is also called after the final + step of an episode, meaning when terminated/truncated are returned as True + from the `env.step()` call, but is still provided with the non-numpy'ized + episode object (meaning the data has NOT been converted to numpy arrays yet). + + The exact time of the call of this callback is after `env.step([action])` and + also after the results of this step (observation, reward, terminated, truncated, + infos) have been logged to the given `episode` object. + + Args: + episode: The just stepped SingleAgentEpisode or MultiAgentEpisode object + (after `env.step()` and after returned obs, rewards, etc.. have been + logged to the episode object). + env_runner: Reference to the EnvRunner running the env and episode. + metrics_logger: The MetricsLogger object inside the `env_runner`. Can be + used to log custom metrics during env/episode stepping. + env: The gym.Env or gym.vector.Env object running the started episode. + env_index: The index of the sub-environment that has just been stepped. + rl_module: The RLModule used to compute actions for stepping the env. In + single-agent mode, this is a simple RLModule, in multi-agent mode, this + is a MultiRLModule. + kwargs: Forward compatibility placeholder. + """ + pass + + @OverrideToImplementCustomLogic + def on_episode_end( + self, + *, + episode: Union[EpisodeType, EpisodeV2], + prev_episode_chunks: Optional[List[EpisodeType]] = None, + env_runner: Optional["EnvRunner"] = None, + metrics_logger: Optional[MetricsLogger] = None, + env: Optional[gym.Env] = None, + env_index: int, + rl_module: Optional[RLModule] = None, + # TODO (sven): Deprecate these args. + worker: Optional["EnvRunner"] = None, + base_env: Optional[BaseEnv] = None, + policies: Optional[Dict[PolicyID, Policy]] = None, + **kwargs, + ) -> None: + """Called when an episode is done (after terminated/truncated have been logged). + + The exact time of the call of this callback is after `env.step([action])` and + also after the results of this step (observation, reward, terminated, truncated, + infos) have been logged to the given `episode` object, where either terminated + or truncated were True: + + - The env is stepped: `final_obs, rewards, ... = env.step([action])` + + - The step results are logged `episode.add_env_step(final_obs, rewards)` + + - Callback `on_episode_step` is fired. + + - Another env-to-module connector call is made (even though we won't need any + RLModule forward pass anymore). We make this additional call to ensure that in + case users use the connector pipeline to process observations (and write them + back into the episode), the episode object has all observations - even the + terminal one - properly processed. + + - ---> This callback `on_episode_end()` is fired. <--- + + - The episode is numpy'ized (i.e. lists of obs/rewards/actions/etc.. are + converted into numpy arrays). + + Args: + episode: The terminated/truncated SingleAgent- or MultiAgentEpisode object + (after `env.step()` that returned terminated=True OR truncated=True and + after the returned obs, rewards, etc.. have been logged to the episode + object). Note that this method is still called before(!) the episode + object is numpy'ized, meaning all its timestep data is still present in + lists of individual timestep data. + prev_episode_chunks: A complete list of all previous episode chunks + with the same ID as `episode` that have been sampled on this EnvRunner. + In order to compile metrics across the complete episode, users should + loop through the list: `[episode] + previous_episode_chunks` and + accumulate the required information. + env_runner: Reference to the EnvRunner running the env and episode. + metrics_logger: The MetricsLogger object inside the `env_runner`. Can be + used to log custom metrics during env/episode stepping. + env: The gym.Env or gym.vector.Env object running the started episode. + env_index: The index of the sub-environment that has just been terminated + or truncated. + rl_module: The RLModule used to compute actions for stepping the env. In + single-agent mode, this is a simple RLModule, in multi-agent mode, this + is a MultiRLModule. + kwargs: Forward compatibility placeholder. + """ + pass + + @OverrideToImplementCustomLogic + def on_sample_end( + self, + *, + env_runner: Optional["EnvRunner"] = None, + metrics_logger: Optional[MetricsLogger] = None, + samples: Union[SampleBatch, List[EpisodeType]], + # TODO (sven): Deprecate these args. + worker: Optional["EnvRunner"] = None, + **kwargs, + ) -> None: + """Called at the end of `EnvRunner.sample()`. + + Args: + env_runner: Reference to the current EnvRunner object. + metrics_logger: The MetricsLogger object inside the `env_runner`. Can be + used to log custom metrics during env/episode stepping. + samples: Lists of SingleAgentEpisode or MultiAgentEpisode instances to be + returned. You can mutate the episodes to modify the returned training + data. + kwargs: Forward compatibility placeholder. + """ + pass + + @OldAPIStack + def on_sub_environment_created( + self, + *, + worker: "EnvRunner", + sub_environment: EnvType, + env_context: EnvContext, + env_index: Optional[int] = None, + **kwargs, + ) -> None: + """Callback run when a new sub-environment has been created. + + This method gets called after each sub-environment (usually a + gym.Env) has been created, validated (RLlib built-in validation + + possible custom validation function implemented by overriding + `Algorithm.validate_env()`), wrapped (e.g. video-wrapper), and seeded. + + Args: + worker: Reference to the current EnvRunner. + sub_environment: The sub-environment instance that has been + created. This is usually a gym.Env object. + env_context: The `EnvContext` object that has been passed to + the env's constructor. + env_index: The index of the sub-environment that has been created + (within the vector of sub-environments of the gym.vector.Env). + kwargs: Forward compatibility placeholder. + """ + pass + + @OldAPIStack + def on_postprocess_trajectory( + self, + *, + worker: "EnvRunner", + episode, + agent_id: AgentID, + policy_id: PolicyID, + policies: Dict[PolicyID, Policy], + postprocessed_batch: SampleBatch, + original_batches: Dict[AgentID, Tuple[Policy, SampleBatch]], + **kwargs, + ) -> None: + """Called immediately after a policy's postprocess_fn is called. + + You can use this callback to do additional postprocessing for a policy, + including looking at the trajectory data of other agents in multi-agent + settings. + + Args: + worker: Reference to the current rollout worker. + episode: Episode object. + agent_id: Id of the current agent. + policy_id: Id of the current policy for the agent. + policies: Dict mapping policy IDs to policy objects. In single + agent mode there will only be a single "default_policy". + postprocessed_batch: The postprocessed sample batch + for this agent. You can mutate this object to apply your own + trajectory postprocessing. + original_batches: Dict mapping agent IDs to their unpostprocessed + trajectory data. You should not mutate this object. + kwargs: Forward compatibility placeholder. + """ + pass + + @OldAPIStack + def on_create_policy(self, *, policy_id: PolicyID, policy: Policy) -> None: + """Callback run whenever a new policy is added to an algorithm. + + Args: + policy_id: ID of the newly created policy. + policy: The policy just created. + """ + pass + + @OldAPIStack + def on_learn_on_batch( + self, *, policy: Policy, train_batch: SampleBatch, result: dict, **kwargs + ) -> None: + """Called at the beginning of Policy.learn_on_batch(). + + Note: This is called before 0-padding via + `pad_batch_to_sequences_of_same_size`. + + Also note, SampleBatch.INFOS column will not be available on + train_batch within this callback if framework is tf1, due to + the fact that tf1 static graph would mistake it as part of the + input dict if present. + It is available though, for tf2 and torch frameworks. + + Args: + policy: Reference to the current Policy object. + train_batch: SampleBatch to be trained on. You can + mutate this object to modify the samples generated. + result: A results dict to add custom metrics to. + kwargs: Forward compatibility placeholder. + """ + pass + + # Deprecated, use `on_env_runners_recreated`, instead. + def on_workers_recreated( + self, + *, + algorithm, + worker_set, + worker_ids, + is_evaluation, + **kwargs, + ) -> None: + pass + + +class MemoryTrackingCallbacks(RLlibCallback): + """MemoryTrackingCallbacks can be used to trace and track memory usage + in rollout workers. + + The Memory Tracking Callbacks uses tracemalloc and psutil to track + python allocations during rollouts, + in training or evaluation. + + The tracking data is logged to the custom_metrics of an episode and + can therefore be viewed in tensorboard + (or in WandB etc..) + + Add MemoryTrackingCallbacks callback to the tune config + e.g. { ...'callbacks': MemoryTrackingCallbacks ...} + + Note: + This class is meant for debugging and should not be used + in production code as tracemalloc incurs + a significant slowdown in execution speed. + """ + + def __init__(self): + super().__init__() + + # Will track the top 10 lines where memory is allocated + tracemalloc.start(10) + + @override(RLlibCallback) + def on_episode_end( + self, + *, + episode: Union[EpisodeType, EpisodeV2], + env_runner: Optional["EnvRunner"] = None, + metrics_logger: Optional[MetricsLogger] = None, + env: Optional[gym.Env] = None, + env_index: int, + rl_module: Optional[RLModule] = None, + # TODO (sven): Deprecate these args. + worker: Optional["EnvRunner"] = None, + base_env: Optional[BaseEnv] = None, + policies: Optional[Dict[PolicyID, Policy]] = None, + **kwargs, + ) -> None: + gc.collect() + snapshot = tracemalloc.take_snapshot() + top_stats = snapshot.statistics("lineno") + + for stat in top_stats[:10]: + count = stat.count + # Convert total size from Bytes to KiB. + size = stat.size / 1024 + + trace = str(stat.traceback) + + episode.custom_metrics[f"tracemalloc/{trace}/size"] = size + episode.custom_metrics[f"tracemalloc/{trace}/count"] = count + + process = psutil.Process(os.getpid()) + worker_rss = process.memory_info().rss + worker_vms = process.memory_info().vms + if platform.system() == "Linux": + # This is only available on Linux + worker_data = process.memory_info().data + episode.custom_metrics["tracemalloc/worker/data"] = worker_data + episode.custom_metrics["tracemalloc/worker/rss"] = worker_rss + episode.custom_metrics["tracemalloc/worker/vms"] = worker_vms diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/callbacks/utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/callbacks/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b6bdf33f3049b51b7b284f084f1044292283845b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/callbacks/utils.py @@ -0,0 +1,156 @@ +from typing import Any, Callable, Dict, List, Optional + +from ray.rllib.callbacks.callbacks import RLlibCallback +from ray.rllib.utils import force_list +from ray.rllib.utils.annotations import OldAPIStack + + +def make_callback( + callback_name: str, + callbacks_objects: Optional[List[RLlibCallback]] = None, + callbacks_functions: Optional[List[Callable]] = None, + *, + args: List[Any] = None, + kwargs: Dict[str, Any] = None, +) -> None: + """Calls an RLlibCallback method or a registered callback callable. + + Args: + callback_name: The name of the callback method or key, for example: + "on_episode_start" or "on_train_result". + callbacks_objects: The RLlibCallback object or list of RLlibCallback objects + to call the `callback_name` method on (in the order they appear in the + list). + callbacks_functions: The callable or list of callables to call + (in the order they appear in the list). + args: Call args to pass to the method/callable calls. + kwargs: Call kwargs to pass to the method/callable calls. + """ + # Loop through all available RLlibCallback objects. + callbacks_objects = force_list(callbacks_objects) + for callback_obj in callbacks_objects: + getattr(callback_obj, callback_name)(*(args or ()), **(kwargs or {})) + + # Loop through all available RLlibCallback objects. + callbacks_functions = force_list(callbacks_functions) + for callback_fn in callbacks_functions: + callback_fn(*(args or ()), **(kwargs or {})) + + +@OldAPIStack +def _make_multi_callbacks(callback_class_list): + class _MultiCallbacks(RLlibCallback): + IS_CALLBACK_CONTAINER = True + + def __init__(self): + super().__init__() + self._callback_list = [ + callback_class() for callback_class in callback_class_list + ] + + def on_algorithm_init(self, **kwargs) -> None: + for callback in self._callback_list: + callback.on_algorithm_init(**kwargs) + + def on_workers_recreated(self, **kwargs) -> None: + for callback in self._callback_list: + callback.on_workers_recreated(**kwargs) + + # Only on new API stack. + def on_env_runners_recreated(self, **kwargs) -> None: + pass + + def on_offline_eval_runners_recreated(self, **kwargs) -> None: + pass + + def on_checkpoint_loaded(self, **kwargs) -> None: + for callback in self._callback_list: + callback.on_checkpoint_loaded(**kwargs) + + def on_create_policy(self, *, policy_id, policy) -> None: + for callback in self._callback_list: + callback.on_create_policy(policy_id=policy_id, policy=policy) + + def on_environment_created(self, **kwargs) -> None: + for callback in self._callback_list: + callback.on_environment_created(**kwargs) + + def on_sub_environment_created(self, **kwargs) -> None: + for callback in self._callback_list: + callback.on_sub_environment_created(**kwargs) + + def on_episode_created(self, **kwargs) -> None: + for callback in self._callback_list: + callback.on_episode_created(**kwargs) + + def on_episode_start(self, **kwargs) -> None: + for callback in self._callback_list: + callback.on_episode_start(**kwargs) + + def on_episode_step(self, **kwargs) -> None: + for callback in self._callback_list: + callback.on_episode_step(**kwargs) + + def on_episode_end(self, **kwargs) -> None: + for callback in self._callback_list: + callback.on_episode_end(**kwargs) + + def on_evaluate_start(self, **kwargs) -> None: + for callback in self._callback_list: + callback.on_evaluate_start(**kwargs) + + def on_evaluate_end(self, **kwargs) -> None: + for callback in self._callback_list: + callback.on_evaluate_end(**kwargs) + + # TODO (simon, sven): Fix the test such that we can simply remove + # these. + def on_evaluate_offline_start(self, **kwargs): + for callback in self._callback_list: + callback.on_evaluate_offline_start(**kwargs) + + def on_evaluate_offline_end(self, **kwargs): + for callback in self._callback_list: + callback.on_evaluate_offline_end(**kwargs) + + def on_postprocess_trajectory( + self, + *, + worker, + episode, + agent_id, + policy_id, + policies, + postprocessed_batch, + original_batches, + **kwargs, + ) -> None: + for callback in self._callback_list: + callback.on_postprocess_trajectory( + worker=worker, + episode=episode, + agent_id=agent_id, + policy_id=policy_id, + policies=policies, + postprocessed_batch=postprocessed_batch, + original_batches=original_batches, + **kwargs, + ) + + def on_sample_end(self, **kwargs) -> None: + for callback in self._callback_list: + callback.on_sample_end(**kwargs) + + def on_learn_on_batch( + self, *, policy, train_batch, result: dict, **kwargs + ) -> None: + for callback in self._callback_list: + callback.on_learn_on_batch( + policy=policy, train_batch=train_batch, result=result, **kwargs + ) + + def on_train_result(self, **kwargs) -> None: + for callback in self._callback_list: + callback.on_train_result(**kwargs) + + return _MultiCallbacks diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32c1a5119148b31896498c3838331207ccf0fd0e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/__pycache__/connector.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/__pycache__/connector.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eec25f6f8c568fae4a01ffb380a3f6754cbefebe Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/__pycache__/connector.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/__pycache__/connector_pipeline_v2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/__pycache__/connector_pipeline_v2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..208e313a8d3db7de4589725b5f306a85c652cfe2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/__pycache__/connector_pipeline_v2.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/__pycache__/connector_v2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/__pycache__/connector_v2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07608b4c41a7c973a120e413f73c5b11068a4182 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/__pycache__/connector_v2.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/__pycache__/registry.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/__pycache__/registry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9e9ca00ba6514a6aceb248dd593b9311fe96f49 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/__pycache__/registry.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/__pycache__/util.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/__pycache__/util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac4fff27a8ba8e1842325dc0363f76ec4515e93c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/__pycache__/util.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..593ee8aef288ee10035a69a9eb613324b841409c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/__pycache__/clip.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/__pycache__/clip.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b0adf2a3e165097f3528dda825715676fdf422a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/__pycache__/clip.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/__pycache__/immutable.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/__pycache__/immutable.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2a00be926030d9bed732343ae8a956c47b4ac71 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/__pycache__/immutable.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/__pycache__/lambdas.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/__pycache__/lambdas.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb3cd7a496ca8ccbfdd9bb8aa42ca40bb2f6ee65 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/__pycache__/lambdas.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/__pycache__/normalize.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/__pycache__/normalize.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac004029f8f19b8064d99e674418f213d8ecb22f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/__pycache__/normalize.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/__pycache__/pipeline.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/__pycache__/pipeline.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3010f100b86ec55e49c9c086f0670c5e37a58cce Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/__pycache__/pipeline.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/clip.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/clip.py new file mode 100644 index 0000000000000000000000000000000000000000..da7c8b97bf927bf4d97c7feed8285faa55ac89cf --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/clip.py @@ -0,0 +1,41 @@ +from typing import Any + +from ray.rllib.connectors.connector import ( + ActionConnector, + ConnectorContext, +) +from ray.rllib.connectors.registry import register_connector +from ray.rllib.utils.spaces.space_utils import clip_action, get_base_struct_from_space +from ray.rllib.utils.typing import ActionConnectorDataType +from ray.rllib.utils.annotations import OldAPIStack + + +@OldAPIStack +class ClipActionsConnector(ActionConnector): + def __init__(self, ctx: ConnectorContext): + super().__init__(ctx) + + self._action_space_struct = get_base_struct_from_space(ctx.action_space) + + def transform(self, ac_data: ActionConnectorDataType) -> ActionConnectorDataType: + assert isinstance( + ac_data.output, tuple + ), "Action connector requires PolicyOutputType data." + + actions, states, fetches = ac_data.output + return ActionConnectorDataType( + ac_data.env_id, + ac_data.agent_id, + ac_data.input_dict, + (clip_action(actions, self._action_space_struct), states, fetches), + ) + + def to_state(self): + return ClipActionsConnector.__name__, None + + @staticmethod + def from_state(ctx: ConnectorContext, params: Any): + return ClipActionsConnector(ctx) + + +register_connector(ClipActionsConnector.__name__, ClipActionsConnector) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/immutable.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/immutable.py new file mode 100644 index 0000000000000000000000000000000000000000..3f5c8bbd197cb6345cf07e712f2477897e25766b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/immutable.py @@ -0,0 +1,40 @@ +from typing import Any + +import tree # pip install dm_tree + +from ray.rllib.connectors.connector import ( + ActionConnector, + ConnectorContext, +) +from ray.rllib.connectors.registry import register_connector +from ray.rllib.utils.numpy import make_action_immutable +from ray.rllib.utils.typing import ActionConnectorDataType +from ray.rllib.utils.annotations import OldAPIStack + + +@OldAPIStack +class ImmutableActionsConnector(ActionConnector): + def transform(self, ac_data: ActionConnectorDataType) -> ActionConnectorDataType: + assert isinstance( + ac_data.output, tuple + ), "Action connector requires PolicyOutputType data." + + actions, states, fetches = ac_data.output + tree.traverse(make_action_immutable, actions, top_down=False) + + return ActionConnectorDataType( + ac_data.env_id, + ac_data.agent_id, + ac_data.input_dict, + (actions, states, fetches), + ) + + def to_state(self): + return ImmutableActionsConnector.__name__, None + + @staticmethod + def from_state(ctx: ConnectorContext, params: Any): + return ImmutableActionsConnector(ctx) + + +register_connector(ImmutableActionsConnector.__name__, ImmutableActionsConnector) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/lambdas.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/lambdas.py new file mode 100644 index 0000000000000000000000000000000000000000..3bf862dd834d57e8b77a677c5f6fa7df8755779e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/lambdas.py @@ -0,0 +1,76 @@ +from typing import Any, Callable, Dict, Type + +from ray.rllib.connectors.connector import ( + ActionConnector, + ConnectorContext, +) +from ray.rllib.connectors.registry import register_connector +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.typing import ( + ActionConnectorDataType, + PolicyOutputType, + StateBatches, + TensorStructType, +) +from ray.rllib.utils.annotations import OldAPIStack + + +@OldAPIStack +def register_lambda_action_connector( + name: str, fn: Callable[[TensorStructType, StateBatches, Dict], PolicyOutputType] +) -> Type[ActionConnector]: + """A util to register any function transforming PolicyOutputType as an ActionConnector. + + The only requirement is that fn should take actions, states, and fetches as input, + and return transformed actions, states, and fetches. + + Args: + name: Name of the resulting actor connector. + fn: The function that transforms PolicyOutputType. + + Returns: + A new ActionConnector class that transforms PolicyOutputType using fn. + """ + + class LambdaActionConnector(ActionConnector): + def transform( + self, ac_data: ActionConnectorDataType + ) -> ActionConnectorDataType: + assert isinstance( + ac_data.output, tuple + ), "Action connector requires PolicyOutputType data." + + actions, states, fetches = ac_data.output + return ActionConnectorDataType( + ac_data.env_id, + ac_data.agent_id, + ac_data.input_dict, + fn(actions, states, fetches), + ) + + def to_state(self): + return name, None + + @staticmethod + def from_state(ctx: ConnectorContext, params: Any): + return LambdaActionConnector(ctx) + + LambdaActionConnector.__name__ = name + LambdaActionConnector.__qualname__ = name + + register_connector(name, LambdaActionConnector) + + return LambdaActionConnector + + +# Convert actions and states into numpy arrays if necessary. +ConvertToNumpyConnector = OldAPIStack( + register_lambda_action_connector( + "ConvertToNumpyConnector", + lambda actions, states, fetches: ( + convert_to_numpy(actions), + convert_to_numpy(states), + fetches, + ), + ), +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/normalize.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/normalize.py new file mode 100644 index 0000000000000000000000000000000000000000..67c3731469a76556350cd327f276f82765a22cff --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/normalize.py @@ -0,0 +1,44 @@ +from typing import Any + +from ray.rllib.connectors.connector import ( + ActionConnector, + ConnectorContext, +) +from ray.rllib.connectors.registry import register_connector +from ray.rllib.utils.spaces.space_utils import ( + get_base_struct_from_space, + unsquash_action, +) +from ray.rllib.utils.typing import ActionConnectorDataType +from ray.rllib.utils.annotations import OldAPIStack + + +@OldAPIStack +class NormalizeActionsConnector(ActionConnector): + def __init__(self, ctx: ConnectorContext): + super().__init__(ctx) + + self._action_space_struct = get_base_struct_from_space(ctx.action_space) + + def transform(self, ac_data: ActionConnectorDataType) -> ActionConnectorDataType: + assert isinstance( + ac_data.output, tuple + ), "Action connector requires PolicyOutputType data." + + actions, states, fetches = ac_data.output + return ActionConnectorDataType( + ac_data.env_id, + ac_data.agent_id, + ac_data.input_dict, + (unsquash_action(actions, self._action_space_struct), states, fetches), + ) + + def to_state(self): + return NormalizeActionsConnector.__name__, None + + @staticmethod + def from_state(ctx: ConnectorContext, params: Any): + return NormalizeActionsConnector(ctx) + + +register_connector(NormalizeActionsConnector.__name__, NormalizeActionsConnector) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/pipeline.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..a93fd3eb340ebd40fb5c7ec23b0bf5960735b992 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/action/pipeline.py @@ -0,0 +1,61 @@ +import logging +from typing import Any, List +from collections import defaultdict + +from ray.rllib.connectors.connector import ( + ActionConnector, + Connector, + ConnectorContext, + ConnectorPipeline, +) +from ray.rllib.connectors.registry import get_connector, register_connector +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.typing import ActionConnectorDataType +from ray.util.timer import _Timer + + +logger = logging.getLogger(__name__) + + +@OldAPIStack +class ActionConnectorPipeline(ConnectorPipeline, ActionConnector): + def __init__(self, ctx: ConnectorContext, connectors: List[Connector]): + super().__init__(ctx, connectors) + self.timers = defaultdict(_Timer) + + def __call__(self, ac_data: ActionConnectorDataType) -> ActionConnectorDataType: + for c in self.connectors: + timer = self.timers[str(c)] + with timer: + ac_data = c(ac_data) + return ac_data + + def to_state(self): + children = [] + for c in self.connectors: + state = c.to_state() + assert isinstance(state, tuple) and len(state) == 2, ( + "Serialized connector state must be in the format of " + f"Tuple[name: str, params: Any]. Instead we got {state}" + f"for connector {c.__name__}." + ) + children.append(state) + return ActionConnectorPipeline.__name__, children + + @staticmethod + def from_state(ctx: ConnectorContext, params: Any): + assert ( + type(params) is list + ), "ActionConnectorPipeline takes a list of connector params." + connectors = [] + for state in params: + try: + name, subparams = state + connectors.append(get_connector(name, ctx, subparams)) + except Exception as e: + logger.error(f"Failed to de-serialize connector state: {state}") + raise e + return ActionConnectorPipeline(ctx, connectors) + + +register_connector(ActionConnectorPipeline.__name__, ActionConnectorPipeline) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff2f27e203fb6ba4e8bf3e271c76aede438ba433 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/clip_reward.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/clip_reward.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b91734647d783ce1472a3f7bf94289b3a9ad920a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/clip_reward.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/env_sampling.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/env_sampling.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d70844a5c698cd8ff964a87cab000470af11c354 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/env_sampling.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/lambdas.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/lambdas.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..402858170d46ec8a57df3dbaa268b4d9c639ab9f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/lambdas.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/mean_std_filter.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/mean_std_filter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d32fd7a1b7263bb96936f350beda906f2c40d1c1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/mean_std_filter.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/obs_preproc.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/obs_preproc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53713a226b21fff4ef08a666c84264976d0a6759 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/obs_preproc.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/pipeline.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/pipeline.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa7c7295e431959b44a7e266ac309430c890b20b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/pipeline.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/state_buffer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/state_buffer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3d98d3a99db755168c994b27cda9018996a561a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/state_buffer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/synced_filter.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/synced_filter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6337d83c92f37a514cd18e18c369fc2121b8019c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/synced_filter.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/view_requirement.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/view_requirement.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6cd20fcf9881f11eb79312e014c6dea5968b8e98 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/__pycache__/view_requirement.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/clip_reward.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/clip_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..8d6c89916c97ebd8b2ede36d840c37de2a602883 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/clip_reward.py @@ -0,0 +1,56 @@ +from typing import Any + +import numpy as np + +from ray.rllib.connectors.connector import ( + AgentConnector, + ConnectorContext, +) +from ray.rllib.connectors.registry import register_connector +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.typing import AgentConnectorDataType +from ray.rllib.utils.annotations import OldAPIStack + + +@OldAPIStack +class ClipRewardAgentConnector(AgentConnector): + def __init__(self, ctx: ConnectorContext, sign=False, limit=None): + super().__init__(ctx) + assert ( + not sign or not limit + ), "should not enable both sign and limit reward clipping." + self.sign = sign + self.limit = limit + + def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType: + d = ac_data.data + assert ( + type(d) is dict + ), "Single agent data must be of type Dict[str, TensorStructType]" + + if SampleBatch.REWARDS not in d: + # Nothing to clip. May happen for initial obs. + return ac_data + + if self.sign: + d[SampleBatch.REWARDS] = np.sign(d[SampleBatch.REWARDS]) + elif self.limit: + d[SampleBatch.REWARDS] = np.clip( + d[SampleBatch.REWARDS], + a_min=-self.limit, + a_max=self.limit, + ) + return ac_data + + def to_state(self): + return ClipRewardAgentConnector.__name__, { + "sign": self.sign, + "limit": self.limit, + } + + @staticmethod + def from_state(ctx: ConnectorContext, params: Any): + return ClipRewardAgentConnector(ctx, **params) + + +register_connector(ClipRewardAgentConnector.__name__, ClipRewardAgentConnector) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/env_sampling.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/env_sampling.py new file mode 100644 index 0000000000000000000000000000000000000000..f0ba6f0a4384caccd6647edde520cb7a84f0dc65 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/env_sampling.py @@ -0,0 +1,30 @@ +from typing import Any + +from ray.rllib.connectors.connector import ( + AgentConnector, + ConnectorContext, +) +from ray.rllib.connectors.registry import register_connector +from ray.rllib.utils.typing import AgentConnectorDataType +from ray.rllib.utils.annotations import OldAPIStack + + +@OldAPIStack +class EnvSamplingAgentConnector(AgentConnector): + def __init__(self, ctx: ConnectorContext, sign=False, limit=None): + super().__init__(ctx) + self.observation_space = ctx.observation_space + + def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType: + # EnvSamplingAgentConnector is a no-op connector. + return ac_data + + def to_state(self): + return EnvSamplingAgentConnector.__name__, {} + + @staticmethod + def from_state(ctx: ConnectorContext, params: Any): + return EnvSamplingAgentConnector(ctx, **params) + + +register_connector(EnvSamplingAgentConnector.__name__, EnvSamplingAgentConnector) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/lambdas.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/lambdas.py new file mode 100644 index 0000000000000000000000000000000000000000..05a714a0df982e36bce96c33ddfb6f6e9ce05188 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/lambdas.py @@ -0,0 +1,86 @@ +from typing import Any, Callable, Type + +import numpy as np +import tree # dm_tree + +from ray.rllib.connectors.connector import ( + AgentConnector, + ConnectorContext, +) +from ray.rllib.connectors.registry import register_connector +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.typing import ( + AgentConnectorDataType, + AgentConnectorsOutput, +) +from ray.rllib.utils.annotations import OldAPIStack + + +@OldAPIStack +def register_lambda_agent_connector( + name: str, fn: Callable[[Any], Any] +) -> Type[AgentConnector]: + """A util to register any simple transforming function as an AgentConnector + + The only requirement is that fn should take a single data object and return + a single data object. + + Args: + name: Name of the resulting actor connector. + fn: The function that transforms env / agent data. + + Returns: + A new AgentConnector class that transforms data using fn. + """ + + class LambdaAgentConnector(AgentConnector): + def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType: + return AgentConnectorDataType( + ac_data.env_id, ac_data.agent_id, fn(ac_data.data) + ) + + def to_state(self): + return name, None + + @staticmethod + def from_state(ctx: ConnectorContext, params: Any): + return LambdaAgentConnector(ctx) + + LambdaAgentConnector.__name__ = name + LambdaAgentConnector.__qualname__ = name + + register_connector(name, LambdaAgentConnector) + + return LambdaAgentConnector + + +@OldAPIStack +def flatten_data(data: AgentConnectorsOutput): + assert isinstance( + data, AgentConnectorsOutput + ), "Single agent data must be of type AgentConnectorsOutput" + + raw_dict = data.raw_dict + sample_batch = data.sample_batch + + flattened = {} + for k, v in sample_batch.items(): + if k in [SampleBatch.INFOS, SampleBatch.ACTIONS] or k.startswith("state_out_"): + # Do not flatten infos, actions, and state_out_ columns. + flattened[k] = v + continue + if v is None: + # Keep the same column shape. + flattened[k] = None + continue + flattened[k] = np.array(tree.flatten(v)) + flattened = SampleBatch(flattened, is_training=False) + + return AgentConnectorsOutput(raw_dict, flattened) + + +# Agent connector to build and return a flattened observation SampleBatch +# in addition to the original input dict. +FlattenDataAgentConnector = OldAPIStack( + register_lambda_agent_connector("FlattenDataAgentConnector", flatten_data) +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/mean_std_filter.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/mean_std_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..b2079344a203d7e08970672fe8fefcaa2caa1bb1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/mean_std_filter.py @@ -0,0 +1,187 @@ +from typing import Any, List +from gymnasium.spaces import Discrete, MultiDiscrete + +import numpy as np +import tree + +from ray.rllib.connectors.agent.synced_filter import SyncedFilterAgentConnector +from ray.rllib.connectors.connector import AgentConnector +from ray.rllib.connectors.connector import ( + ConnectorContext, +) +from ray.rllib.connectors.registry import register_connector +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.filter import Filter +from ray.rllib.utils.filter import MeanStdFilter, ConcurrentMeanStdFilter +from ray.rllib.utils.spaces.space_utils import get_base_struct_from_space +from ray.rllib.utils.typing import AgentConnectorDataType +from ray.rllib.utils.filter import RunningStat + + +@OldAPIStack +class MeanStdObservationFilterAgentConnector(SyncedFilterAgentConnector): + """A connector used to mean-std-filter observations. + + Incoming observations are filtered such that the output of this filter is on + average zero and has a standard deviation of 1. This filtering is applied + separately per element of the observation space. + """ + + def __init__( + self, + ctx: ConnectorContext, + demean: bool = True, + destd: bool = True, + clip: float = 10.0, + ): + SyncedFilterAgentConnector.__init__(self, ctx) + # We simply use the old MeanStdFilter until non-connector env_runner is fully + # deprecated to avoid duplicate code + + filter_shape = tree.map_structure( + lambda s: ( + None + if isinstance(s, (Discrete, MultiDiscrete)) # noqa + else np.array(s.shape) + ), + get_base_struct_from_space(ctx.observation_space), + ) + self.filter = MeanStdFilter(filter_shape, demean=demean, destd=destd, clip=clip) + + def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType: + d = ac_data.data + assert ( + type(d) is dict + ), "Single agent data must be of type Dict[str, TensorStructType]" + if SampleBatch.OBS in d: + d[SampleBatch.OBS] = self.filter( + d[SampleBatch.OBS], update=self._is_training + ) + if SampleBatch.NEXT_OBS in d: + d[SampleBatch.NEXT_OBS] = self.filter( + d[SampleBatch.NEXT_OBS], update=self._is_training + ) + + return ac_data + + def to_state(self): + # Flattening is deterministic + flattened_rs = tree.flatten(self.filter.running_stats) + flattened_buffer = tree.flatten(self.filter.buffer) + return MeanStdObservationFilterAgentConnector.__name__, { + "shape": self.filter.shape, + "no_preprocessor": self.filter.no_preprocessor, + "demean": self.filter.demean, + "destd": self.filter.destd, + "clip": self.filter.clip, + "running_stats": [s.to_state() for s in flattened_rs], + "buffer": [s.to_state() for s in flattened_buffer], + } + + # demean, destd, clip, and a state dict + @staticmethod + def from_state( + ctx: ConnectorContext, + params: List[Any] = None, + demean: bool = True, + destd: bool = True, + clip: float = 10.0, + ): + connector = MeanStdObservationFilterAgentConnector(ctx, demean, destd, clip) + if params: + connector.filter.shape = params["shape"] + connector.filter.no_preprocessor = params["no_preprocessor"] + connector.filter.demean = params["demean"] + connector.filter.destd = params["destd"] + connector.filter.clip = params["clip"] + + # Unflattening is deterministic + running_stats = [RunningStat.from_state(s) for s in params["running_stats"]] + connector.filter.running_stats = tree.unflatten_as( + connector.filter.shape, running_stats + ) + + # Unflattening is deterministic + buffer = [RunningStat.from_state(s) for s in params["buffer"]] + connector.filter.buffer = tree.unflatten_as(connector.filter.shape, buffer) + + return connector + + def reset_state(self) -> None: + """Creates copy of current state and resets accumulated state""" + if not self._is_training: + raise ValueError( + "State of {} can only be changed when trainin.".format(self.__name__) + ) + self.filter.reset_buffer() + + def apply_changes(self, other: "Filter", *args, **kwargs) -> None: + """Updates self with state from other filter.""" + # inline this as soon as we deprecate ordinary filter with non-connector + # env_runner + if not self._is_training: + raise ValueError( + "Changes can only be applied to {} when trainin.".format(self.__name__) + ) + return self.filter.apply_changes(other, *args, **kwargs) + + def copy(self) -> "Filter": + """Creates a new object with same state as self. + + This is a legacy Filter method that we need to keep around for now + + Returns: + A copy of self. + """ + # inline this as soon as we deprecate ordinary filter with non-connector + # env_runner + return self.filter.copy() + + def sync(self, other: "AgentConnector") -> None: + """Copies all state from other filter to self.""" + # inline this as soon as we deprecate ordinary filter with non-connector + # env_runner + if not self._is_training: + raise ValueError( + "{} can only be synced when trainin.".format(self.__name__) + ) + return self.filter.sync(other.filter) + + +@OldAPIStack +class ConcurrentMeanStdObservationFilterAgentConnector( + MeanStdObservationFilterAgentConnector +): + """A concurrent version of the MeanStdObservationFilterAgentConnector. + + This version's filter has all operations wrapped by a threading.RLock. + It can therefore be safely used by multiple threads. + """ + + def __init__(self, ctx: ConnectorContext, demean=True, destd=True, clip=10.0): + SyncedFilterAgentConnector.__init__(self, ctx) + # We simply use the old MeanStdFilter until non-connector env_runner is fully + # deprecated to avoid duplicate code + + filter_shape = tree.map_structure( + lambda s: ( + None + if isinstance(s, (Discrete, MultiDiscrete)) # noqa + else np.array(s.shape) + ), + get_base_struct_from_space(ctx.observation_space), + ) + self.filter = ConcurrentMeanStdFilter( + filter_shape, demean=True, destd=True, clip=10.0 + ) + + +register_connector( + MeanStdObservationFilterAgentConnector.__name__, + MeanStdObservationFilterAgentConnector, +) +register_connector( + ConcurrentMeanStdObservationFilterAgentConnector.__name__, + ConcurrentMeanStdObservationFilterAgentConnector, +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/obs_preproc.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/obs_preproc.py new file mode 100644 index 0000000000000000000000000000000000000000..f783bb6718cca79a26752e2c961f880968a1ce58 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/obs_preproc.py @@ -0,0 +1,69 @@ +from typing import Any + +from ray.rllib.connectors.connector import ( + AgentConnector, + ConnectorContext, +) +from ray.rllib.connectors.registry import register_connector +from ray.rllib.models.preprocessors import get_preprocessor, NoPreprocessor +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.typing import AgentConnectorDataType +from ray.rllib.utils.annotations import OldAPIStack + + +@OldAPIStack +class ObsPreprocessorConnector(AgentConnector): + """A connector that wraps around existing RLlib observation preprocessors. + + This includes: + - OneHotPreprocessor for Discrete and Multi-Discrete spaces. + - GenericPixelPreprocessor and AtariRamPreprocessor for Atari spaces. + - TupleFlatteningPreprocessor and DictFlatteningPreprocessor for flattening + arbitrary nested input observations. + - RepeatedValuesPreprocessor for padding observations from RLlib Repeated + observation space. + """ + + def __init__(self, ctx: ConnectorContext): + super().__init__(ctx) + + if hasattr(ctx.observation_space, "original_space"): + # ctx.observation_space is the space this Policy deals with. + # We need to preprocess data from the original observation space here. + obs_space = ctx.observation_space.original_space + else: + obs_space = ctx.observation_space + + self._preprocessor = get_preprocessor(obs_space)( + obs_space, ctx.config.get("model", {}) + ) + + def is_identity(self): + """Returns whether this preprocessor connector is a no-op preprocessor.""" + return isinstance(self._preprocessor, NoPreprocessor) + + def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType: + d = ac_data.data + assert type(d) is dict, ( + "Single agent data must be of type Dict[str, TensorStructType] but is of " + "type {}".format(type(d)) + ) + + if SampleBatch.OBS in d: + d[SampleBatch.OBS] = self._preprocessor.transform(d[SampleBatch.OBS]) + if SampleBatch.NEXT_OBS in d: + d[SampleBatch.NEXT_OBS] = self._preprocessor.transform( + d[SampleBatch.NEXT_OBS] + ) + + return ac_data + + def to_state(self): + return ObsPreprocessorConnector.__name__, None + + @staticmethod + def from_state(ctx: ConnectorContext, params: Any): + return ObsPreprocessorConnector(ctx) + + +register_connector(ObsPreprocessorConnector.__name__, ObsPreprocessorConnector) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/pipeline.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..898ac79b1c709429e4751eca7eb427b3afa26a4e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/pipeline.py @@ -0,0 +1,72 @@ +import logging +from typing import Any, List +from collections import defaultdict + +from ray.rllib.connectors.connector import ( + AgentConnector, + Connector, + ConnectorContext, + ConnectorPipeline, +) +from ray.rllib.connectors.registry import get_connector, register_connector +from ray.rllib.utils.typing import ActionConnectorDataType, AgentConnectorDataType +from ray.rllib.utils.annotations import OldAPIStack +from ray.util.timer import _Timer + + +logger = logging.getLogger(__name__) + + +@OldAPIStack +class AgentConnectorPipeline(ConnectorPipeline, AgentConnector): + def __init__(self, ctx: ConnectorContext, connectors: List[Connector]): + super().__init__(ctx, connectors) + self.timers = defaultdict(_Timer) + + def reset(self, env_id: str): + for c in self.connectors: + c.reset(env_id) + + def on_policy_output(self, output: ActionConnectorDataType): + for c in self.connectors: + c.on_policy_output(output) + + def __call__( + self, acd_list: List[AgentConnectorDataType] + ) -> List[AgentConnectorDataType]: + ret = acd_list + for c in self.connectors: + timer = self.timers[str(c)] + with timer: + ret = c(ret) + return ret + + def to_state(self): + children = [] + for c in self.connectors: + state = c.to_state() + assert isinstance(state, tuple) and len(state) == 2, ( + "Serialized connector state must be in the format of " + f"Tuple[name: str, params: Any]. Instead we got {state}" + f"for connector {c.__name__}." + ) + children.append(state) + return AgentConnectorPipeline.__name__, children + + @staticmethod + def from_state(ctx: ConnectorContext, params: List[Any]): + assert ( + type(params) is list + ), "AgentConnectorPipeline takes a list of connector params." + connectors = [] + for state in params: + try: + name, subparams = state + connectors.append(get_connector(name, ctx, subparams)) + except Exception as e: + logger.error(f"Failed to de-serialize connector state: {state}") + raise e + return AgentConnectorPipeline(ctx, connectors) + + +register_connector(AgentConnectorPipeline.__name__, AgentConnectorPipeline) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/state_buffer.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/state_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..4516abd8bbe0ad47d6cc96baedb8909ff26b62fd --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/state_buffer.py @@ -0,0 +1,120 @@ +from collections import defaultdict +import logging +import pickle +from typing import Any + +import numpy as np +from ray.rllib.utils.annotations import override +import tree # dm_tree + +from ray.rllib.connectors.connector import ( + AgentConnector, + Connector, + ConnectorContext, +) +from ray import cloudpickle +from ray.rllib.connectors.registry import register_connector +from ray.rllib.core.columns import Columns +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.spaces.space_utils import get_base_struct_from_space +from ray.rllib.utils.typing import ActionConnectorDataType, AgentConnectorDataType +from ray.rllib.utils.annotations import OldAPIStack + + +logger = logging.getLogger(__name__) + + +@OldAPIStack +class StateBufferConnector(AgentConnector): + def __init__(self, ctx: ConnectorContext, states: Any = None): + super().__init__(ctx) + + self._initial_states = ctx.initial_states + self._action_space_struct = get_base_struct_from_space(ctx.action_space) + + self._states = defaultdict(lambda: defaultdict(lambda: (None, None, None))) + self._enable_new_api_stack = False + # TODO(jungong) : we would not need this if policies are never stashed + # during the rollout of a single episode. + if states: + try: + self._states = cloudpickle.loads(states) + except pickle.UnpicklingError: + # StateBufferConnector states are only needed for rare cases + # like stashing then restoring a policy during the rollout of + # a single episode. + # It is ok to ignore the error for most of the cases here. + logger.info( + "Can not restore StateBufferConnector states. This warning can " + "usually be ignore, unless it is from restoring a stashed policy." + ) + + @override(Connector) + def in_eval(self): + super().in_eval() + + def reset(self, env_id: str): + # States should not be carried over between episodes. + if env_id in self._states: + del self._states[env_id] + + def on_policy_output(self, ac_data: ActionConnectorDataType): + # Buffer latest output states for next input __call__. + self._states[ac_data.env_id][ac_data.agent_id] = ac_data.output + + def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType: + d = ac_data.data + assert ( + type(d) is dict + ), "Single agent data must be of type Dict[str, TensorStructType]" + + env_id = ac_data.env_id + agent_id = ac_data.agent_id + assert ( + env_id is not None and agent_id is not None + ), f"StateBufferConnector requires env_id(f{env_id}) and agent_id(f{agent_id})" + + action, states, fetches = self._states[env_id][agent_id] + + if action is not None: + d[SampleBatch.ACTIONS] = action # Last action + else: + # Default zero action. + d[SampleBatch.ACTIONS] = tree.map_structure( + lambda s: np.zeros_like(s.sample(), s.dtype) + if hasattr(s, "dtype") + else np.zeros_like(s.sample()), + self._action_space_struct, + ) + + if states is None: + states = self._initial_states + if self._enable_new_api_stack: + if states: + d[Columns.STATE_OUT] = states + else: + for i, v in enumerate(states): + d["state_out_{}".format(i)] = v + + # Also add extra fetches if available. + if fetches: + d.update(fetches) + + return ac_data + + def to_state(self): + # Note(jungong) : it is ok to use cloudpickle here for stats because: + # 1. self._states may contain arbitary data objects, and will be hard + # to serialize otherwise. + # 2. seriazlized states are only useful if a policy is stashed and + # restored during the rollout of a single episode. So it is ok to + # use cloudpickle for such non-persistent data bits. + states = cloudpickle.dumps(self._states) + return StateBufferConnector.__name__, states + + @staticmethod + def from_state(ctx: ConnectorContext, params: Any): + return StateBufferConnector(ctx, params) + + +register_connector(StateBufferConnector.__name__, StateBufferConnector) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/synced_filter.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/synced_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..51c625d9aceec9401599ef87b42cf522704c5ea3 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/synced_filter.py @@ -0,0 +1,52 @@ +from ray.rllib.connectors.connector import ( + AgentConnector, + ConnectorContext, +) +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.filter import Filter + + +@OldAPIStack +class SyncedFilterAgentConnector(AgentConnector): + """An agent connector that filters with synchronized parameters.""" + + def __init__(self, ctx: ConnectorContext, *args, **kwargs): + super().__init__(ctx) + if args or kwargs: + raise ValueError( + "SyncedFilterAgentConnector does not take any additional arguments, " + "but got args=`{}` and kwargs={}.".format(args, kwargs) + ) + + def apply_changes(self, other: "Filter", *args, **kwargs) -> None: + """Updates self with state from other filter.""" + # TODO: (artur) inline this as soon as we deprecate ordinary filter with + # non-connecto env_runner + return self.filter.apply_changes(other, *args, **kwargs) + + def copy(self) -> "Filter": + """Creates a new object with same state as self. + + This is a legacy Filter method that we need to keep around for now + + Returns: + A copy of self. + """ + # inline this as soon as we deprecate ordinary filter with non-connector + # env_runner + return self.filter.copy() + + def sync(self, other: "AgentConnector") -> None: + """Copies all state from other filter to self.""" + # TODO: (artur) inline this as soon as we deprecate ordinary filter with + # non-connector env_runner + return self.filter.sync(other.filter) + + def reset_state(self) -> None: + """Creates copy of current state and resets accumulated state""" + raise NotImplementedError + + def as_serializable(self) -> "Filter": + # TODO: (artur) inline this as soon as we deprecate ordinary filter with + # non-connector env_runner + return self.filter.as_serializable() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/view_requirement.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/view_requirement.py new file mode 100644 index 0000000000000000000000000000000000000000..7f035bb97a92c7856ecc11e6dc7eac169a823a51 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/agent/view_requirement.py @@ -0,0 +1,135 @@ +from collections import defaultdict +from typing import Any + +from ray.rllib.connectors.connector import ( + AgentConnector, + ConnectorContext, +) +from ray.rllib.connectors.registry import register_connector +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.typing import ( + AgentConnectorDataType, + AgentConnectorsOutput, +) +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.evaluation.collectors.agent_collector import AgentCollector + + +@OldAPIStack +class ViewRequirementAgentConnector(AgentConnector): + """This connector does 2 things: + 1. It filters data columns based on view_requirements for training and inference. + 2. It buffers the right amount of history for computing the sample batch for + action computation. + The output of this connector is AgentConnectorsOut, which basically is + a tuple of 2 things: + { + "raw_dict": {"obs": ...} + "sample_batch": SampleBatch + } + raw_dict, which contains raw data for the latest time slice, + can be used to construct a complete episode by Sampler for training purpose. + The "for_action" SampleBatch can be used to directly call the policy. + """ + + def __init__(self, ctx: ConnectorContext): + super().__init__(ctx) + + self._view_requirements = ctx.view_requirements + _enable_new_api_stack = False + + # a dict of env_id to a dict of agent_id to a list of agent_collector objects + self.agent_collectors = defaultdict( + lambda: defaultdict( + lambda: AgentCollector( + self._view_requirements, + max_seq_len=ctx.config["model"]["max_seq_len"], + intial_states=ctx.initial_states, + disable_action_flattening=ctx.config.get( + "_disable_action_flattening", False + ), + is_policy_recurrent=ctx.is_policy_recurrent, + # Note(jungong): We only leverage AgentCollector for building sample + # batches for computing actions. + # So regardless of whether this ViewRequirement connector is in + # training or inference mode, we should tell these AgentCollectors + # to behave in inference mode, so they don't accumulate episode data + # that is not useful for inference. + is_training=False, + _enable_new_api_stack=_enable_new_api_stack, + ) + ) + ) + + def reset(self, env_id: str): + if env_id in self.agent_collectors: + del self.agent_collectors[env_id] + + def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType: + d = ac_data.data + assert ( + type(d) is dict + ), "Single agent data must be of type Dict[str, TensorStructType]" + + env_id = ac_data.env_id + agent_id = ac_data.agent_id + # TODO: we don't keep episode_id around so use env_id as episode_id ? + episode_id = env_id if SampleBatch.EPS_ID not in d else d[SampleBatch.EPS_ID] + + assert env_id is not None and agent_id is not None, ( + f"ViewRequirementAgentConnector requires env_id({env_id}) " + "and agent_id({agent_id})" + ) + + assert ( + self._view_requirements + ), "ViewRequirements required by ViewRequirementAgentConnector" + + # Note(jungong) : we need to keep the entire input dict here. + # A column may be used by postprocessing (GAE) even if its + # view_requirement.used_for_training is False. + training_dict = d + + agent_collector = self.agent_collectors[env_id][agent_id] + + if SampleBatch.NEXT_OBS not in d: + raise ValueError(f"connector data {d} should contain next_obs.") + # TODO(avnishn; kourosh) Unsure how agent_index is necessary downstream + # since there is no mapping from agent_index to agent_id that exists. + # need to remove this from the SampleBatch later. + # fall back to using dummy index if no index is available + if SampleBatch.AGENT_INDEX in d: + agent_index = d[SampleBatch.AGENT_INDEX] + else: + try: + agent_index = float(agent_id) + except ValueError: + agent_index = -1 + if agent_collector.is_empty(): + agent_collector.add_init_obs( + episode_id=episode_id, + agent_index=agent_index, + env_id=env_id, + init_obs=d[SampleBatch.NEXT_OBS], + init_infos=d.get(SampleBatch.INFOS), + ) + else: + agent_collector.add_action_reward_next_obs(d) + sample_batch = agent_collector.build_for_inference() + + return_data = AgentConnectorDataType( + env_id, agent_id, AgentConnectorsOutput(training_dict, sample_batch) + ) + return return_data + + def to_state(self): + return ViewRequirementAgentConnector.__name__, None + + @staticmethod + def from_state(ctx: ConnectorContext, params: Any): + return ViewRequirementAgentConnector(ctx) + + +register_connector( + ViewRequirementAgentConnector.__name__, ViewRequirementAgentConnector +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6ef51fb150732dcf86a443c41527d75dd2c4e24b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__init__.py @@ -0,0 +1,24 @@ +from ray.rllib.connectors.common.add_observations_from_episodes_to_batch import ( + AddObservationsFromEpisodesToBatch, +) +from ray.rllib.connectors.common.add_states_from_episodes_to_batch import ( + AddStatesFromEpisodesToBatch, +) +from ray.rllib.connectors.common.add_time_dim_to_batch_and_zero_pad import ( + AddTimeDimToBatchAndZeroPad, +) +from ray.rllib.connectors.common.agent_to_module_mapping import AgentToModuleMapping +from ray.rllib.connectors.common.batch_individual_items import BatchIndividualItems +from ray.rllib.connectors.common.numpy_to_tensor import NumpyToTensor +from ray.rllib.connectors.common.tensor_to_numpy import TensorToNumpy + + +__all__ = [ + "AddObservationsFromEpisodesToBatch", + "AddStatesFromEpisodesToBatch", + "AddTimeDimToBatchAndZeroPad", + "AgentToModuleMapping", + "BatchIndividualItems", + "NumpyToTensor", + "TensorToNumpy", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4150f1e3e4cbf20b5d53c8f174c553511ebb3056 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/add_observations_from_episodes_to_batch.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/add_observations_from_episodes_to_batch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58029455328c99ddfd1cb4926220ebfc6f88a08b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/add_observations_from_episodes_to_batch.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/add_states_from_episodes_to_batch.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/add_states_from_episodes_to_batch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0bb7a3a4d00fe5a2397b7aae69db87f6fca4cb9f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/add_states_from_episodes_to_batch.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/add_time_dim_to_batch_and_zero_pad.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/add_time_dim_to_batch_and_zero_pad.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ebc233c898fdff147c10a5506648b97aa1a50e7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/add_time_dim_to_batch_and_zero_pad.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/agent_to_module_mapping.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/agent_to_module_mapping.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..240c24015836d843c4cea88768dcc43f77fb8ec8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/agent_to_module_mapping.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/batch_individual_items.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/batch_individual_items.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e562ee87ab734913cc1523c5710a19313a7f9f9e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/batch_individual_items.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/frame_stacking.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/frame_stacking.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3895b9802b3bac73bf2da37dec8ad4f70a1c7f7a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/frame_stacking.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/module_to_agent_unmapping.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/module_to_agent_unmapping.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4e3c1c5f584e9f76a64c35c23dd6b1747cf4d9f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/module_to_agent_unmapping.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/numpy_to_tensor.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/numpy_to_tensor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..856cc028f23d73fbd8f153c2475e9ffc9f574f5b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/numpy_to_tensor.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/tensor_to_numpy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/tensor_to_numpy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0bdf07e71c6c2b5ba79f8bce9380b25b0626c9a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/__pycache__/tensor_to_numpy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/add_observations_from_episodes_to_batch.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/add_observations_from_episodes_to_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..54fab7b064c55fd00621cb0ebf052690da63a698 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/add_observations_from_episodes_to_batch.py @@ -0,0 +1,180 @@ +from typing import Any, Dict, List, Optional + +import gymnasium as gym + +from ray.rllib.core.columns import Columns +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class AddObservationsFromEpisodesToBatch(ConnectorV2): + """Gets the last observation from a running episode and adds it to the batch. + + Note: This is one of the default env-to-module or Learner ConnectorV2 pieces that + are added automatically by RLlib into every env-to-module/Learner connector + pipeline, unless `config.add_default_connectors_to_env_to_module_pipeline` or + `config.add_default_connectors_to_learner_pipeline ` are set to + False. + + The default env-to-module connector pipeline is: + [ + [0 or more user defined ConnectorV2 pieces], + AddObservationsFromEpisodesToBatch, + AddTimeDimToBatchAndZeroPad, + AddStatesFromEpisodesToBatch, + AgentToModuleMapping, # only in multi-agent setups! + BatchIndividualItems, + NumpyToTensor, + ] + The default Learner connector pipeline is: + [ + [0 or more user defined ConnectorV2 pieces], + AddObservationsFromEpisodesToBatch, + AddColumnsFromEpisodesToTrainBatch, + AddTimeDimToBatchAndZeroPad, + AddStatesFromEpisodesToBatch, + AgentToModuleMapping, # only in multi-agent setups! + BatchIndividualItems, + NumpyToTensor, + ] + + This ConnectorV2: + - Operates on a list of Episode objects (single- or multi-agent). + - Gets the most recent observation(s) from all the given episodes and adds them + to the batch under construction (as a list of individual observations). + - Does NOT alter any observations (or other data) in the given episodes. + - Can be used in EnvToModule and Learner connector pipelines. + + .. testcode:: + + import gymnasium as gym + import numpy as np + + from ray.rllib.connectors.common import AddObservationsFromEpisodesToBatch + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + from ray.rllib.utils.test_utils import check + + # Create two dummy SingleAgentEpisodes, each containing 2 observations, + # 1 action and 1 reward (both are length=1). + obs_space = gym.spaces.Box(-1.0, 1.0, (2,), np.float32) + act_space = gym.spaces.Discrete(2) + + episodes = [SingleAgentEpisode( + observations=[obs_space.sample(), obs_space.sample()], + actions=[act_space.sample()], + rewards=[1.0], + len_lookback_buffer=0, + ) for _ in range(2)] + eps_1_last_obs = episodes[0].get_observations(-1) + eps_2_last_obs = episodes[1].get_observations(-1) + print(f"1st Episode's last obs is {eps_1_last_obs}") + print(f"2nd Episode's last obs is {eps_2_last_obs}") + + # Create an instance of this class. + connector = AddObservationsFromEpisodesToBatch() + + # Call the connector with the two created episodes. + # Note that this particular connector works without an RLModule, so we + # simplify here for the sake of this example. + output_batch = connector( + rl_module=None, + batch={}, + episodes=episodes, + explore=True, + shared_data={}, + ) + # The output data should now contain the last observations of both episodes, + # in a "per-episode organized" fashion. + check( + output_batch, + { + "obs": { + (episodes[0].id_,): [eps_1_last_obs], + (episodes[1].id_,): [eps_2_last_obs], + }, + }, + ) + """ + + def __init__( + self, + input_observation_space: Optional[gym.Space] = None, + input_action_space: Optional[gym.Space] = None, + *, + as_learner_connector: bool = False, + **kwargs, + ): + """Initializes a AddObservationsFromEpisodesToBatch instance. + + Args: + as_learner_connector: Whether this connector is part of a Learner connector + pipeline, as opposed to a env-to-module pipeline. As a Learner + connector, it will add an entire Episode's observations (each timestep) + to the batch. + """ + super().__init__( + input_observation_space=input_observation_space, + input_action_space=input_action_space, + **kwargs, + ) + + self._as_learner_connector = as_learner_connector + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + # If "obs" already in data, early out. + if Columns.OBS in batch: + return batch + for i, sa_episode in enumerate( + self.single_agent_episode_iterator( + episodes, + # If Learner connector, get all episodes (for train batch). + # If EnvToModule, get only those ongoing episodes that just had their + # agent step (b/c those are the ones we need to compute actions for + # next). + agents_that_stepped_only=not self._as_learner_connector, + ) + ): + if self._as_learner_connector: + # TODO (sven): Resolve this hack by adding a new connector piece that + # performs this very task. + if "_" not in sa_episode.id_: + sa_episode.id_ += "_" + str(i) + + self.add_n_batch_items( + batch, + Columns.OBS, + # Add all observations, except the very last one. + # For a terminated episode, this is the terminal observation that + # has no value for training. + # For a truncated episode, algorithms either add an extra NEXT_OBS + # column to the batch (ex. DQN) or extend the episode length by one + # (using a separate connector piece and this truncated last obs), + # then bootstrap the value estimation for that extra timestep. + items_to_add=sa_episode.get_observations(slice(0, len(sa_episode))), + num_items=len(sa_episode), + single_agent_episode=sa_episode, + ) + else: + assert not sa_episode.is_numpy + self.add_batch_item( + batch, + Columns.OBS, + item_to_add=sa_episode.get_observations(-1), + single_agent_episode=sa_episode, + ) + + return batch diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/add_states_from_episodes_to_batch.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/add_states_from_episodes_to_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..6cfe284d347a25daf4269150f4244a7f6148c235 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/add_states_from_episodes_to_batch.py @@ -0,0 +1,353 @@ +import math +from typing import Any, Dict, List, Optional + +import gymnasium as gym +import numpy as np +import tree # pip install dm_tree + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core import DEFAULT_MODULE_ID +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModule +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class AddStatesFromEpisodesToBatch(ConnectorV2): + """Gets last STATE_OUT from running episode and adds it as STATE_IN to the batch. + + Note: This is one of the default env-to-module or Learner ConnectorV2 pieces that + are added automatically by RLlib into every env-to-module/Learner connector + pipeline, unless `config.add_default_connectors_to_env_to_module_pipeline` or + `config.add_default_connectors_to_learner_pipeline ` are set to + False. + + The default env-to-module connector pipeline is: + [ + [0 or more user defined ConnectorV2 pieces], + AddObservationsFromEpisodesToBatch, + AddTimeDimToBatchAndZeroPad, + AddStatesFromEpisodesToBatch, + AgentToModuleMapping, # only in multi-agent setups! + BatchIndividualItems, + NumpyToTensor, + ] + The default Learner connector pipeline is: + [ + [0 or more user defined ConnectorV2 pieces], + AddObservationsFromEpisodesToBatch, + AddColumnsFromEpisodesToTrainBatch, + AddTimeDimToBatchAndZeroPad, + AddStatesFromEpisodesToBatch, + AgentToModuleMapping, # only in multi-agent setups! + BatchIndividualItems, + NumpyToTensor, + ] + + If the RLModule is stateful, the episodes' STATE_OUTS will be extracted + and restructured under a new STATE_IN key. + As a Learner connector, the resulting STATE_IN batch has the shape (B', ...). + Here, B' is the sum of splits we have to do over the given episodes, such that each + chunk is at most `max_seq_len` long (T-axis). + As a EnvToModule connector, the resulting STATE_IN batch simply consists of n + states coming from n vectorized environments/episodes. + + Also, all other data (observations, rewards, etc.. if applicable) will be properly + reshaped into (B, T=max_seq_len (learner) or 1 (env-to-module), ...) and will be + zero-padded, if necessary. + + This ConnectorV2: + - Operates on a list of Episode objects. + - Gets the most recent STATE_OUT from all the given episodes and adds them under + the STATE_IN key to the batch under construction. + - Does NOT alter any data in the given episodes. + - Can be used in EnvToModule and Learner connector pipelines. + + .. testcode:: + + from ray.rllib.connectors.common import AddStatesFromEpisodesToBatch + from ray.rllib.core.columns import Columns + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + from ray.rllib.utils.test_utils import check + + # Create a simple dummy class, pretending to be an RLModule with + # `get_initial_state`, `is_stateful` and `model_config` property defined: + class MyStateModule: + # dummy config + model_config = {"max_seq_len": 2} + + def is_stateful(self): + return True + + def get_initial_state(self): + return 0.0 + + + # Create an empty episode. The connector should use the RLModule's initial state + # to populate STATE_IN for the next forward pass. + episode = SingleAgentEpisode() + + rl_module = MyStateModule() + rl_module_init_state = rl_module.get_initial_state() + + # Create an instance of this class (as a env-to-module connector). + connector = AddStatesFromEpisodesToBatch(as_learner_connector=False) + + # Call the connector. + output_batch = connector( + rl_module=rl_module, + batch={}, + episodes=[episode], + shared_data={}, + ) + # The output data's STATE_IN key should now contain the RLModule's initial state + # plus the one state out found in the episode in a "per-episode organized" + # fashion. + check( + output_batch[Columns.STATE_IN], + { + (episode.id_,): [rl_module_init_state], + }, + ) + + # Create a SingleAgentEpisodes containing 5 observations, + # 4 actions and 4 rewards, and 4 STATE_OUTs. + # The same connector should now use the episode-stored last STATE_OUT as + # STATE_IN for the next forward pass. + episode = SingleAgentEpisode( + observations=[0, 1, 2, 3, 4], + actions=[1, 2, 3, 4], + rewards=[1.0, 2.0, 3.0, 4.0], + # STATE_OUT in episode will show up under STATE_IN in the batch. + extra_model_outputs={ + Columns.STATE_OUT: [-4.0, -3.0, -2.0, -1.0], + }, + len_lookback_buffer = 0, + ) + + # Call the connector. + output_batch = connector( + rl_module=rl_module, + batch={}, + episodes=[episode], + shared_data={}, + ) + # The output data's STATE_IN key should now contain the episode's last + # STATE_OUT, NOT the RLModule's initial state in a "per-episode organized" + # fashion. + check( + output_batch[Columns.STATE_IN], + { + # Expect the episode's last STATE_OUT. + (episode.id_,): [-1.0], + }, + ) + + # Create a new connector as a learner connector with a RNN seq len of 2 (for + # testing purposes only). Passing the same data through this learner connector, + # we expect the STATE_IN data to contain a) the initial module state and then + # every 2nd STATE_OUT stored in the episode. + connector = AddStatesFromEpisodesToBatch(as_learner_connector=True) + + # Call the connector. + output_batch = connector( + rl_module=rl_module, + batch={}, + episodes=[episode], + shared_data={}, + ) + check( + output_batch[Columns.STATE_IN], + { + # Expect initial module state + every 2nd STATE_OUT from episode, but + # not the very last one (just like the very last observation, this data + # is NOT passed through the forward_train, b/c there is nothing to learn + # at that timestep, unless we need to compute e.g. bootstrap value + # predictions). + # Also note that the different STATE_IN timesteps are already present + # as one batched item per episode in the list. + (episode.id_,): [rl_module_init_state, -3.0], + }, + ) + """ + + def __init__( + self, + input_observation_space: Optional[gym.Space] = None, + input_action_space: Optional[gym.Space] = None, + *, + as_learner_connector: bool = False, + **kwargs, + ): + """Initializes a AddObservationsFromEpisodesToBatch instance. + + Args: + as_learner_connector: Whether this connector is part of a Learner connector + pipeline, as opposed to a env-to-module pipeline. As a Learner + connector, it will add an entire Episode's observations (each timestep) + to the batch. + """ + super().__init__( + input_observation_space=input_observation_space, + input_action_space=input_action_space, + **kwargs, + ) + + self._as_learner_connector = as_learner_connector + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + # If not stateful OR STATE_IN already in data, early out. + if ( + rl_module is None + or not rl_module.is_stateful() + or Columns.STATE_IN in batch + ): + return batch + + for sa_episode in self.single_agent_episode_iterator( + episodes, + # If Learner connector, get all episodes (for train batch). + # If EnvToModule, get only those ongoing episodes that just had their + # agent step (b/c those are the ones we need to compute actions for next). + agents_that_stepped_only=not self._as_learner_connector, + ): + if self._as_learner_connector: + # Multi-agent case: Extract correct single agent RLModule (to get its + # individual state). + if sa_episode.module_id is not None: + sa_module = rl_module[sa_episode.module_id] + else: + sa_module = ( + rl_module[DEFAULT_MODULE_ID] + if isinstance(rl_module, MultiRLModule) + else rl_module + ) + # This single-agent RLModule is NOT stateful -> Skip. + if not sa_module.is_stateful(): + continue + + max_seq_len = sa_module.model_config["max_seq_len"] + + # look_back_state.shape=([state-dim],) + look_back_state = ( + # Episode has a (reset) beginning -> Prepend initial + # state. + convert_to_numpy(sa_module.get_initial_state()) + if sa_episode.t_started == 0 + or (Columns.STATE_OUT not in sa_episode.extra_model_outputs) + # Episode starts somewhere in the middle (is a cut + # continuation chunk) -> Use previous chunk's last + # STATE_OUT as initial state. + else sa_episode.get_extra_model_outputs( + key=Columns.STATE_OUT, + indices=-1, + neg_index_as_lookback=True, + ) + ) + # If we have `"state_out"`s (e.g. from rollouts) use them for the + # `"state_in"`s. + if Columns.STATE_OUT in sa_episode.extra_model_outputs: + # state_outs.shape=(T,[state-dim]) T=episode len + state_outs = sa_episode.get_extra_model_outputs( + key=Columns.STATE_OUT + ) + # Otherwise, we have no `"state_out"` (e.g. because we are sampling + # from offline data and the expert policy was not stateful). + else: + # Then simply use the `look_back_state`, i.e. in this case the + # initial state as `"state_in` in training. + if sa_episode.is_numpy: + state_outs = tree.map_structure( + lambda a, _sae=sa_episode: np.repeat( + a[np.newaxis, ...], len(_sae), axis=0 + ), + look_back_state, + ) + else: + state_outs = [look_back_state for _ in range(len(sa_episode))] + # Explanation: + # B=episode len // max_seq_len + # [::max_seq_len]: only keep every Tth state. + # [:-1]: Shift state outs by one; ignore very last + # STATE_OUT, but therefore add the lookback/init state at + # the beginning. + items_to_add = ( + tree.map_structure( + lambda i, o, m=max_seq_len: np.concatenate([[i], o[:-1]])[::m], + look_back_state, + state_outs, + ) + if sa_episode.is_numpy + else ([look_back_state] + state_outs[:-1])[::max_seq_len] + ) + self.add_n_batch_items( + batch=batch, + column=Columns.STATE_IN, + items_to_add=items_to_add, + num_items=int(math.ceil(len(sa_episode) / max_seq_len)), + single_agent_episode=sa_episode, + ) + if Columns.NEXT_OBS in batch: + items_to_add = ( + tree.map_structure( + lambda i, m=max_seq_len: i[::m], + state_outs, + ) + if sa_episode.is_numpy + else state_outs[::max_seq_len] + ) + self.add_n_batch_items( + batch=batch, + column=Columns.NEXT_STATE_IN, + items_to_add=items_to_add, + num_items=int(math.ceil(len(sa_episode) / max_seq_len)), + single_agent_episode=sa_episode, + ) + + else: + assert not sa_episode.is_numpy + + # Multi-agent case: Extract correct single agent RLModule (to get the + # state for individually). + sa_module = rl_module + if sa_episode.module_id is not None: + sa_module = rl_module[sa_episode.module_id] + # This single-agent RLModule is NOT stateful -> Skip. + if not sa_module.is_stateful(): + continue + + # Episode just started or has no `"state_out"` (e.g. in offline + # sampling) -> Get initial state from our RLModule. + if (sa_episode.t_started == 0 and len(sa_episode) == 0) or ( + Columns.STATE_OUT not in sa_episode.extra_model_outputs + ): + state = sa_module.get_initial_state() + state = convert_to_numpy(state) + # Episode is already ongoing -> Use most recent STATE_OUT. + else: + state = sa_episode.get_extra_model_outputs( + key=Columns.STATE_OUT, + indices=-1, + ) + self.add_batch_item( + batch, + Columns.STATE_IN, + item_to_add=state, + single_agent_episode=sa_episode, + ) + + return batch diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/add_time_dim_to_batch_and_zero_pad.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/add_time_dim_to_batch_and_zero_pad.py new file mode 100644 index 0000000000000000000000000000000000000000..8358e44ae28183cbdfd72c475a38caa1908db5b3 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/add_time_dim_to_batch_and_zero_pad.py @@ -0,0 +1,306 @@ +from typing import Any, Dict, List, Optional + +import gymnasium as gym +import numpy as np +import tree # pip install dm_tree + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core import DEFAULT_MODULE_ID +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModule +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.postprocessing.zero_padding import ( + create_mask_and_seq_lens, + split_and_zero_pad, +) +from ray.rllib.utils.spaces.space_utils import BatchedNdArray +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class AddTimeDimToBatchAndZeroPad(ConnectorV2): + """Adds an extra time dim (axis=1) to all data currently in the batch. + + Note: This is one of the default env-to-module or Learner ConnectorV2 pieces that + are added automatically by RLlib into every env-to-module/Learner connector + pipeline, unless `config.add_default_connectors_to_env_to_module_pipeline` or + `config.add_default_connectors_to_learner_pipeline ` are set to + False. + + The default env-to-module connector pipeline is: + [ + [0 or more user defined ConnectorV2 pieces], + AddObservationsFromEpisodesToBatch, + AddTimeDimToBatchAndZeroPad, + AddStatesFromEpisodesToBatch, + AgentToModuleMapping, # only in multi-agent setups! + BatchIndividualItems, + NumpyToTensor, + ] + The default Learner connector pipeline is: + [ + [0 or more user defined ConnectorV2 pieces], + AddObservationsFromEpisodesToBatch, + AddColumnsFromEpisodesToTrainBatch, + AddTimeDimToBatchAndZeroPad, + AddStatesFromEpisodesToBatch, + AgentToModuleMapping, # only in multi-agent setups! + BatchIndividualItems, + NumpyToTensor, + ] + + If the RLModule is stateful, an extra time dim at axis=1 is added to all data in the + batch. + + Also, all data (observations, rewards, etc.. if applicable) will be properly + reshaped into (B, T=max_seq_len (learner) or 1 (env-to-module), ...) and will be + zero-padded, if necessary. + + This ConnectorV2: + - Operates on a list of Episode objects. + - Adds a time dim at axis=1 to all columns already in the batch. + - In case of a learner connector pipeline, zero-pads the data according to the + module's `self.model_config["max_seq_len"]` setting and reshapes all data to + (B, T, ...). The connector also adds SEQ_LENS information and loss mask + information to the batch based on the added zero-padding. + - Does NOT alter any data in the given episodes. + - Can be used in EnvToModule and Learner connector pipelines. + + .. testcode:: + + from ray.rllib.connectors.common import AddTimeDimToBatchAndZeroPad + from ray.rllib.core.columns import Columns + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + from ray.rllib.utils.test_utils import check + + + # Create a simple dummy class, pretending to be an RLModule with + # `get_initial_state`, `is_stateful` and `model_config` property defined: + class MyStateModule: + # dummy config + model_config = {"max_seq_len": 3} + + def is_stateful(self): + return True + + def get_initial_state(self): + return 0.0 + + + # Create an already reset episode. Expect the connector to add a time-dim to the + # reset observation. + episode = SingleAgentEpisode(observations=[0]) + + rl_module = MyStateModule() + + # Create an instance of this class (as an env-to-module connector). + connector = AddTimeDimToBatchAndZeroPad(as_learner_connector=False) + + # Call the connector. + output_batch = connector( + rl_module=rl_module, + batch={Columns.OBS: [0]}, + episodes=[episode], + shared_data={}, + ) + # The output data's OBS key should now be reshaped to (B, T) + check(output_batch[Columns.OBS], [[0]]) + + # Create a SingleAgentEpisodes containing 5 observations, + # 4 actions and 4 rewards. + episode = SingleAgentEpisode( + observations=[0, 1, 2, 3, 4], + actions=[1, 2, 3, 4], + rewards=[1.0, 2.0, 3.0, 4.0], + len_lookback_buffer=0, + ) + + # Call the connector. + output_batch = connector( + rl_module=rl_module, + batch={Columns.OBS: [4]}, + episodes=[episode], + shared_data={}, + ) + # The output data's OBS, ACTIONS, and REWARDS keys should now all have a time + # rank. + check( + # Expect the episode's last OBS. + output_batch[Columns.OBS], [[4]], + ) + + # Create a new connector as a learner connector with a RNN seq len of 4 (for + # testing purposes only). Passing the same data through this learner connector, + # we expect the data to also be zero-padded. + connector = AddTimeDimToBatchAndZeroPad(as_learner_connector=True) + + # Call the connector. + output_batch = connector( + rl_module=rl_module, + batch={Columns.OBS: {(episode.id_,): [0, 1, 2, 3]}}, + episodes=[episode], + shared_data={}, + ) + check(output_batch[Columns.OBS], {(episode.id_,): [[0, 1, 2], [3, 0, 0]]}) + """ + + def __init__( + self, + input_observation_space: Optional[gym.Space] = None, + input_action_space: Optional[gym.Space] = None, + *, + as_learner_connector: bool = False, + **kwargs, + ): + """Initializes a AddObservationsFromEpisodesToBatch instance. + + Args: + as_learner_connector: Whether this connector is part of a Learner connector + pipeline, as opposed to a env-to-module pipeline. As a Learner + connector, it will add an entire Episode's observations (each timestep) + to the batch. + """ + super().__init__( + input_observation_space=input_observation_space, + input_action_space=input_action_space, + **kwargs, + ) + + self._as_learner_connector = as_learner_connector + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + + # If not stateful OR STATE_IN already in data, early out. + if ( + rl_module is None + or not rl_module.is_stateful() + or Columns.STATE_IN in batch + ): + return batch + + # Make all inputs (other than STATE_IN) have an additional T-axis. + # Since data has not been batched yet (we are still operating on lists in the + # batch), we add this time axis as 0 (not 1). When we batch, the batch axis will + # be 0 and the time axis will be 1. + # Also, let module-to-env pipeline know that we had added a single timestep + # time rank to the data (to remove it again). + if not self._as_learner_connector: + for column in batch.keys(): + self.foreach_batch_item_change_in_place( + batch=batch, + column=column, + func=lambda item, eps_id, aid, mid: ( + item + if mid is not None and not rl_module[mid].is_stateful() + # Expand on axis 0 (the to-be-time-dim) if item has not been + # batched yet, otherwise axis=1 (the time-dim). + else tree.map_structure( + lambda s: np.expand_dims( + s, axis=(1 if isinstance(s, BatchedNdArray) else 0) + ), + item, + ) + ), + ) + shared_data["_added_single_ts_time_rank"] = True + else: + # Before adding STATE_IN to the `data`, zero-pad existing data and batch + # into max_seq_len chunks. + for column, column_data in batch.copy().items(): + # Do not zero-pad INFOS column. + if column == Columns.INFOS: + continue + for key, item_list in column_data.items(): + # Multi-agent case AND RLModule is not stateful -> Do not zero-pad + # for this model. + assert isinstance(key, tuple) + mid = None + if len(key) == 3: + eps_id, aid, mid = key + if not rl_module[mid].is_stateful(): + continue + column_data[key] = split_and_zero_pad( + item_list, + max_seq_len=self._get_max_seq_len(rl_module, module_id=mid), + ) + # TODO (sven): Remove this hint/hack once we are not relying on + # SampleBatch anymore (which has to set its property + # zero_padded=True when shuffling). + shared_data[ + ( + "_zero_padded_for_mid=" + f"{mid if mid is not None else DEFAULT_MODULE_ID}" + ) + ] = True + + for sa_episode in self.single_agent_episode_iterator( + # If Learner connector, get all episodes (for train batch). + # If EnvToModule, get only those ongoing episodes that just had their + # agent step (b/c those are the ones we need to compute actions for next). + episodes, + agents_that_stepped_only=False, + ): + # Multi-agent case: Extract correct single agent RLModule (to get its + # individual state). + if sa_episode.module_id is not None: + sa_module = rl_module[sa_episode.module_id] + else: + sa_module = ( + rl_module[DEFAULT_MODULE_ID] + if isinstance(rl_module, MultiRLModule) + else rl_module + ) + # This single-agent RLModule is NOT stateful -> Skip. + if not sa_module.is_stateful(): + continue + + max_seq_len = sa_module.model_config["max_seq_len"] + + # Also, create the loss mask (b/c of our now possibly zero-padded data) + # as well as the seq_lens array and add these to `data` as well. + mask, seq_lens = create_mask_and_seq_lens(len(sa_episode), max_seq_len) + self.add_n_batch_items( + batch=batch, + column=Columns.SEQ_LENS, + items_to_add=seq_lens, + num_items=len(seq_lens), + single_agent_episode=sa_episode, + ) + if not shared_data.get("_added_loss_mask_for_valid_episode_ts"): + self.add_n_batch_items( + batch=batch, + column=Columns.LOSS_MASK, + items_to_add=mask, + num_items=len(mask), + single_agent_episode=sa_episode, + ) + + return batch + + def _get_max_seq_len(self, rl_module, module_id=None): + if not isinstance(rl_module, MultiRLModule): + mod = rl_module + elif module_id: + mod = rl_module[module_id] + else: + mod = next(iter(rl_module.values())) + if "max_seq_len" not in mod.model_config: + raise ValueError( + "You are using a stateful RLModule and are not providing a " + "'max_seq_len' key inside your `model_config`. You can set this " + "dict and/or override keys in it via `config.rl_module(" + "model_config={'max_seq_len': [some int]})`." + ) + return mod.model_config["max_seq_len"] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/agent_to_module_mapping.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/agent_to_module_mapping.py new file mode 100644 index 0000000000000000000000000000000000000000..63bd78cf9b783804aedb63563e5c5fa80f79de50 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/agent_to_module_mapping.py @@ -0,0 +1,291 @@ +from collections import defaultdict +from typing import Any, Dict, List, Optional + +import gymnasium as gym + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.rl_module.rl_module import RLModule, RLModuleSpec +from ray.rllib.env.multi_agent_episode import MultiAgentEpisode +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import EpisodeType, ModuleID +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class AgentToModuleMapping(ConnectorV2): + """ConnectorV2 that performs mapping of data from AgentID based to ModuleID based. + + Note: This is one of the default env-to-module or Learner ConnectorV2 pieces that + are added automatically by RLlib into every env-to-module/Learner connector + pipeline, unless `config.add_default_connectors_to_env_to_module_pipeline` or + `config.add_default_connectors_to_learner_pipeline ` are set to + False. + + The default env-to-module connector pipeline is: + [ + [0 or more user defined ConnectorV2 pieces], + AddObservationsFromEpisodesToBatch, + AddTimeDimToBatchAndZeroPad, + AddStatesFromEpisodesToBatch, + AgentToModuleMapping, # only in multi-agent setups! + BatchIndividualItems, + NumpyToTensor, + ] + The default Learner connector pipeline is: + [ + [0 or more user defined ConnectorV2 pieces], + AddObservationsFromEpisodesToBatch, + AddColumnsFromEpisodesToTrainBatch, + AddTimeDimToBatchAndZeroPad, + AddStatesFromEpisodesToBatch, + AgentToModuleMapping, # only in multi-agent setups! + BatchIndividualItems, + NumpyToTensor, + ] + + This connector piece is only used by RLlib (as a default connector piece) in a + multi-agent setup. + + Note that before the mapping, `data` is expected to have the following + structure: + [col0]: + (eps_id0, ag0, mod0): [list of individual batch items] + (eps_id0, ag1, mod2): [list of individual batch items] + (eps_id1, ag0, mod1): [list of individual batch items] + [col1]: + etc.. + + The target structure of the above `data` would then be: + [mod0]: + [col0]: [batched data -> batch_size_B will be the number of all items in the + input data under col0 that have mod0 as their ModuleID] + [col1]: [batched data] + [mod1]: + [col0]: etc. + + Mapping happens in the following stages: + + 1) Under each column name, sort keys first by EpisodeID, then AgentID. + 2) Add ModuleID keys under each column name (no cost/extra memory) and map these + new keys to empty lists. + [col0] -> [mod0] -> []: Then push items that belong to mod0 into these lists. + 3) Perform batching on the per-module lists under each column: + [col0] -> [mod0]: [...] <- now batched data (numpy array or struct of numpy + arrays). + 4) Flip column names with ModuleIDs (no cost/extra memory): + [mod0]: + [col0]: [batched data] + etc.. + + Note that in order to unmap the resulting batch back into an AgentID based one, + we have to store the env vector index AND AgentID of each module's batch item + in an additionally returned `memorized_map_structure`. + + .. testcode:: + + from ray.rllib.connectors.env_to_module import AgentToModuleMapping + from ray.rllib.utils.test_utils import check + + batch = { + "obs": { + ("MA-EPS0", "agent0", "module0"): [0, 1, 2], + ("MA-EPS0", "agent1", "module1"): [3, 4, 5], + }, + "actions": { + ("MA-EPS1", "agent2", "module0"): [8], + ("MA-EPS0", "agent1", "module1"): [9], + }, + } + + # Create our connector piece. + connector = AgentToModuleMapping( + rl_module_specs={"module0", "module1"}, + agent_to_module_mapping_fn=( + lambda agent_id, eps: "module1" if agent_id == "agent1" else "module0" + ), + ) + + # Call the connector (and thereby flip from AgentID based to ModuleID based + # structure.. + output_batch = connector( + rl_module=None, # This particular connector works without an RLModule. + batch=batch, + episodes=[], # This particular connector works without a list of episodes. + explore=True, + shared_data={}, + ) + + # `data` should now be mapped from ModuleIDs to module data. + check( + output_batch, + { + "module0": { + "obs": [0, 1, 2], + "actions": [8], + }, + "module1": { + "obs": [3, 4, 5], + "actions": [9], + }, + }, + ) + """ + + @override(ConnectorV2) + def recompute_output_observation_space( + self, + input_observation_space: gym.Space, + input_action_space: gym.Space, + ) -> gym.Space: + return self._map_space_if_necessary(input_observation_space, "obs") + + @override(ConnectorV2) + def recompute_output_action_space( + self, + input_observation_space: gym.Space, + input_action_space: gym.Space, + ) -> gym.Space: + return self._map_space_if_necessary(input_action_space, "act") + + def __init__( + self, + input_observation_space: Optional[gym.Space] = None, + input_action_space: Optional[gym.Space] = None, + *, + rl_module_specs: Dict[ModuleID, RLModuleSpec], + agent_to_module_mapping_fn, + ): + super().__init__(input_observation_space, input_action_space) + + self._rl_module_specs = rl_module_specs + self._agent_to_module_mapping_fn = agent_to_module_mapping_fn + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + # Current agent to module mapping function. + # agent_to_module_mapping_fn = shared_data.get("agent_to_module_mapping_fn") + # Store in shared data, which module IDs map to which episode/agent, such + # that the module-to-env pipeline can map the data back to agents. + memorized_map_structure = defaultdict(list) + for column, agent_data in batch.items(): + if rl_module is not None and column in rl_module: + continue + for eps_id, agent_id, module_id in agent_data.keys(): + memorized_map_structure[module_id].append((eps_id, agent_id)) + # TODO (sven): We should check that all columns have the same struct. + break + + shared_data["memorized_map_structure"] = dict(memorized_map_structure) + + # Mapping from ModuleID to column data. + data_by_module = {} + + # Iterating over each column in the original data: + for column, agent_data in batch.items(): + if rl_module is not None and column in rl_module: + if column in data_by_module: + data_by_module[column].update(agent_data) + else: + data_by_module[column] = agent_data + continue + for ( + eps_id, + agent_id, + module_id, + ), values_batch_or_list in agent_data.items(): + assert isinstance(values_batch_or_list, list) + for value in values_batch_or_list: + if module_id not in data_by_module: + data_by_module[module_id] = {column: []} + elif column not in data_by_module[module_id]: + data_by_module[module_id][column] = [] + + # Append the data. + data_by_module[module_id][column].append(value) + + return data_by_module + + def _map_space_if_necessary(self, space: gym.Space, which: str = "obs"): + # Analyze input observation space to check, whether the user has already taken + # care of the agent to module mapping. + if set(self._rl_module_specs) == set(space.spaces.keys()): + return space + + # We need to take care of agent to module mapping. Figure out the resulting + # observation space here. + dummy_eps = MultiAgentEpisode() + + ret_space = {} + for module_id in self._rl_module_specs: + # Easy way out, user has provided space in the RLModule spec dict. + if ( + isinstance(self._rl_module_specs, dict) + and module_id in self._rl_module_specs + ): + if ( + which == "obs" + and self._rl_module_specs[module_id].observation_space + ): + ret_space[module_id] = self._rl_module_specs[ + module_id + ].observation_space + continue + elif which == "act" and self._rl_module_specs[module_id].action_space: + ret_space[module_id] = self._rl_module_specs[module_id].action_space + continue + + # Need to reverse map spaces (for the different agents) to certain + # module IDs (using a dummy MultiAgentEpisode). + one_space = next(iter(space.spaces.values())) + # If all obs spaces are the same anyway, just use the first + # single-agent space. + if all(s == one_space for s in space.spaces.values()): + ret_space[module_id] = one_space + # Otherwise, we have to compare the ModuleID with all possible + # AgentIDs and find the agent ID that matches. + else: + match_aid = None + one_agent_for_module_found = False + for aid in space.spaces.keys(): + # Match: Assign spaces for this agentID to the PolicyID. + if self._agent_to_module_mapping_fn(aid, dummy_eps) == module_id: + # Make sure, different agents that map to the same + # policy don't have different spaces. + if ( + module_id in ret_space + and space[aid] != ret_space[module_id] + ): + raise ValueError( + f"Two agents ({aid} and {match_aid}) in your " + "environment map to the same ModuleID (as per your " + "`agent_to_module_mapping_fn`), however, these agents " + "also have different observation spaces as per the env!" + ) + ret_space[module_id] = space[aid] + match_aid = aid + one_agent_for_module_found = True + # Still no space found for this module ID -> Error out. + if not one_agent_for_module_found: + raise ValueError( + f"Could not find or derive any {which}-space for RLModule " + f"{module_id}! This can happen if your `config.rl_module(rl_" + f"module_spec=...)` does NOT contain space information for this" + " particular single-agent module AND your agent-to-module-" + "mapping function is stochastic (such that for some agent A, " + "more than one ModuleID might be returned somewhat randomly). " + f"Fix this error by providing {which}-space information using " + "`config.rl_module(rl_module_spec=MultiRLModuleSpec(" + f"rl_module_specs={{'{module_id}': RLModuleSpec(" + "observation_space=..., action_space=...)}}))" + ) + + return gym.spaces.Dict(ret_space) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/batch_individual_items.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/batch_individual_items.py new file mode 100644 index 0000000000000000000000000000000000000000..8d3bd5a53cd7aa560d139145135f3a1f679b6238 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/batch_individual_items.py @@ -0,0 +1,200 @@ +from typing import Any, Dict, List, Optional + +import gymnasium as gym + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core import DEFAULT_MODULE_ID +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModule +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.spaces.space_utils import batch as batch_fn +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class BatchIndividualItems(ConnectorV2): + """Batches individual data-items (in lists) into tensors (with batch dimension). + + Note: This is one of the default env-to-module or Learner ConnectorV2 pieces that + are added automatically by RLlib into every env-to-module/Learner connector + pipeline, unless `config.add_default_connectors_to_env_to_module_pipeline` or + `config.add_default_connectors_to_learner_pipeline ` are set to + False. + + The default env-to-module connector pipeline is: + [ + [0 or more user defined ConnectorV2 pieces], + AddObservationsFromEpisodesToBatch, + AddTimeDimToBatchAndZeroPad, + AddStatesFromEpisodesToBatch, + AgentToModuleMapping, # only in multi-agent setups! + BatchIndividualItems, + NumpyToTensor, + ] + The default Learner connector pipeline is: + [ + [0 or more user defined ConnectorV2 pieces], + AddObservationsFromEpisodesToBatch, + AddColumnsFromEpisodesToTrainBatch, + AddTimeDimToBatchAndZeroPad, + AddStatesFromEpisodesToBatch, + AgentToModuleMapping, # only in multi-agent setups! + BatchIndividualItems, + NumpyToTensor, + ] + + This ConnectorV2: + - Operates only on the input `data`, NOT the incoming list of episode objects + (ignored). + - In the single-agent case, `data` must already be a dict, structured as follows by + prior connector pieces of the same pipeline: + [col0] -> {[(eps_id,)]: [list of individual batch items]} + - In the multi-agent case, `data` must already be a dict, structured as follows by + prior connector pieces of the same pipeline (in particular the + `AgentToModuleMapping` piece): + [module_id] -> [col0] -> [list of individual batch items] + - Translates the above data under the different columns (e.g. "obs") into final + (batched) structures. For the single-agent case, the output `data` looks like this: + [col0] -> [possibly complex struct of batches (at the leafs)]. + For the multi-agent case, the output `data` looks like this: + [module_id] -> [col0] -> [possibly complex struct of batches (at the leafs)]. + + .. testcode:: + + from ray.rllib.connectors.common import BatchIndividualItems + from ray.rllib.utils.test_utils import check + + single_agent_batch = { + "obs": { + # Note that at this stage, next-obs is not part of the data anymore .. + ("MA-EPS0",): [0, 1], + ("MA-EPS1",): [2, 3], + }, + "actions": { + # .. so we have as many actions per episode as we have observations. + ("MA-EPS0",): [4, 5], + ("MA-EPS1",): [6, 7], + }, + } + + # Create our (single-agent) connector piece. + connector = BatchIndividualItems() + + # Call the connector (and thereby batch the individual items). + output_batch = connector( + rl_module=None, # This particular connector works without an RLModule. + batch=single_agent_batch, + episodes=[], # This particular connector works without a list of episodes. + explore=True, + shared_data={}, + ) + + # `output_batch` should now be batched (episode IDs should have been removed + # from the struct). + check( + output_batch, + {"obs": [0, 1, 2, 3], "actions": [4, 5, 6, 7]}, + ) + """ + + def __init__( + self, + input_observation_space: Optional[gym.Space] = None, + input_action_space: Optional[gym.Space] = None, + *, + multi_agent: bool = False, + **kwargs, + ): + """Initializes a BatchIndividualItems instance. + + Args: + multi_agent: Whether this is a connector operating on a multi-agent + observation space mapping AgentIDs to individual agents' observations. + """ + super().__init__( + input_observation_space=input_observation_space, + input_action_space=input_action_space, + **kwargs, + ) + self._multi_agent = multi_agent + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + is_multi_rl_module = isinstance(rl_module, MultiRLModule) + + # Convert lists of individual items into properly batched data. + for column, column_data in batch.copy().items(): + # Multi-agent case: This connector piece should only be used after(!) + # the AgentToModuleMapping connector has already been applied, leading + # to a batch structure of: + # [module_id] -> [col0] -> [list of individual batch items] + if is_multi_rl_module and column in rl_module: + # Case, in which a column has already been properly batched before this + # connector piece is called. + if not self._multi_agent: + continue + # If MA Off-Policy and independent sampling we need to overcome this + # check. + module_data = column_data + for col, col_data in module_data.copy().items(): + if isinstance(col_data, list) and col != Columns.INFOS: + module_data[col] = batch_fn( + col_data, + individual_items_already_have_batch_dim="auto", + ) + + # Simple case: There is a list directly under `column`: + # Batch the list. + elif isinstance(column_data, list): + batch[column] = batch_fn( + column_data, + individual_items_already_have_batch_dim="auto", + ) + + # Single-agent case: There is a dict under `column` mapping + # `eps_id` to lists of items: + # Concat all these lists, then batch. + elif not self._multi_agent: + # TODO: only really need this in non-Learner connector pipeline + memorized_map_structure = [] + list_to_be_batched = [] + for (eps_id,) in column_data.keys(): + for item in column_data[(eps_id,)]: + # Only record structure for OBS column. + if column == Columns.OBS: + memorized_map_structure.append(eps_id) + list_to_be_batched.append(item) + # INFOS should not be batched (remain a list). + batch[column] = ( + list_to_be_batched + if column == Columns.INFOS + else batch_fn( + list_to_be_batched, + individual_items_already_have_batch_dim="auto", + ) + ) + if is_multi_rl_module: + if DEFAULT_MODULE_ID not in batch: + batch[DEFAULT_MODULE_ID] = {} + batch[DEFAULT_MODULE_ID][column] = batch.pop(column) + + # Only record structure for OBS column. + if column == Columns.OBS: + shared_data["memorized_map_structure"] = memorized_map_structure + # Multi-agent case: But Module ID not found in our RLModule -> Ignore this + # `module_id` entirely. + # else: + # pass + + return batch diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/frame_stacking.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/frame_stacking.py new file mode 100644 index 0000000000000000000000000000000000000000..f889d1c6c506b5796a04323ce298a0ac2532d9ad --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/frame_stacking.py @@ -0,0 +1,149 @@ +import numpy as np +from typing import Any, Dict, List, Optional + +import gymnasium as gym +import tree # pip install dm_tree + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class FrameStacking(ConnectorV2): + """A connector piece that stacks the previous n observations into one.""" + + @override(ConnectorV2) + def recompute_output_observation_space( + self, + input_observation_space: gym.Space, + input_action_space: gym.Space, + ) -> gym.Space: + # Change our observation space according to the given stacking settings. + if self._multi_agent: + ret = {} + for agent_id, obs_space in input_observation_space.spaces.items(): + ret[agent_id] = self._convert_individual_space(obs_space) + return gym.spaces.Dict(ret) + else: + return self._convert_individual_space(input_observation_space) + + def __init__( + self, + input_observation_space: Optional[gym.Space] = None, + input_action_space: Optional[gym.Space] = None, + *, + num_frames: int = 1, + multi_agent: bool = False, + as_learner_connector: bool = False, + **kwargs, + ): + """Initializes a FrameStackingConnector instance. + + Args: + num_frames: The number of observation frames to stack up (into a single + observation) for the RLModule's forward pass. + multi_agent: Whether this is a connector operating on a multi-agent + observation space mapping AgentIDs to individual agents' observations. + as_learner_connector: Whether this connector is part of a Learner connector + pipeline, as opposed to an env-to-module pipeline. + """ + super().__init__( + input_observation_space=input_observation_space, + input_action_space=input_action_space, + **kwargs, + ) + + self._multi_agent = multi_agent + self.num_frames = num_frames + self._as_learner_connector = as_learner_connector + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + # Learner connector pipeline. Episodes have been numpy'ized. + if self._as_learner_connector: + for sa_episode in self.single_agent_episode_iterator( + episodes, agents_that_stepped_only=False + ): + + def _map_fn(s, _sa_episode=sa_episode): + # Squeeze out last dim. + s = np.squeeze(s, axis=-1) + # Calculate new shape and strides + new_shape = (len(_sa_episode), self.num_frames) + s.shape[1:] + new_strides = (s.strides[0],) + s.strides + # Create a strided view of the array. + # But return a copy to avoid non-contiguous memory in the object + # store (which is very expensive to deserialize). + return np.transpose( + np.lib.stride_tricks.as_strided( + s, shape=new_shape, strides=new_strides + ), + axes=[0, 2, 3, 1], + ).copy() + + # Get all observations from the episode in one np array (except for + # the very last one, which is the final observation not needed for + # learning). + self.add_n_batch_items( + batch=batch, + column=Columns.OBS, + items_to_add=tree.map_structure( + _map_fn, + sa_episode.get_observations( + indices=slice(-self.num_frames + 1, len(sa_episode)), + neg_index_as_lookback=True, + fill=0.0, + ), + ), + num_items=len(sa_episode), + single_agent_episode=sa_episode, + ) + + # Env-to-module pipeline. Episodes still operate on lists. + else: + for sa_episode in self.single_agent_episode_iterator(episodes): + assert not sa_episode.is_numpy + # Get the list of observations to stack. + obs_stack = sa_episode.get_observations( + indices=slice(-self.num_frames, None), + fill=0.0, + ) + # Observation components are (w, h, 1) + # -> concatenate along axis=-1 to (w, h, [num_frames]). + stacked_obs = tree.map_structure( + lambda *s: np.concatenate(s, axis=2), + *obs_stack, + ) + self.add_batch_item( + batch=batch, + column=Columns.OBS, + item_to_add=stacked_obs, + single_agent_episode=sa_episode, + ) + + return batch + + def _convert_individual_space(self, obs_space): + # Some assumptions: Space is box AND last dim (the stacking one) is 1. + assert isinstance(obs_space, gym.spaces.Box), obs_space + assert obs_space.shape[-1] == 1, obs_space + + return gym.spaces.Box( + low=np.repeat(obs_space.low, repeats=self.num_frames, axis=-1), + high=np.repeat(obs_space.high, repeats=self.num_frames, axis=-1), + shape=list(obs_space.shape)[:-1] + [self.num_frames], + dtype=obs_space.dtype, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/module_to_agent_unmapping.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/module_to_agent_unmapping.py new file mode 100644 index 0000000000000000000000000000000000000000..fb3a2b1e954e98ee89a455c53d70304d2cd9b7f0 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/module_to_agent_unmapping.py @@ -0,0 +1,48 @@ +from collections import defaultdict +from typing import Any, Dict, List, Optional + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.env.multi_agent_episode import MultiAgentEpisode +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class ModuleToAgentUnmapping(ConnectorV2): + """Performs flipping of `data` from ModuleID- to AgentID based mapping. + + Before mapping: + data[module1] -> [col, e.g. ACTIONS] + -> [dict mapping episode-identifying tuples to lists of data] + data[module2] -> ... + + After mapping: + data[ACTIONS]: [dict mapping episode-identifying tuples to lists of data] + + Note that episode-identifying tuples have the form of: (episode_id,) in the + single-agent case and (ma_episode_id, agent_id, module_id) in the multi-agent + case. + """ + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + # This Connector should only be used in a multi-agent setting. + assert isinstance(episodes[0], MultiAgentEpisode) + + agent_data = defaultdict(dict) + for module_id, module_data in batch.items(): + for column, values_dict in module_data.items(): + agent_data[column].update(values_dict) + + return dict(agent_data) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/numpy_to_tensor.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/numpy_to_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..17274fa656f134e96ee4168782ad82f53344ebcb --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/numpy_to_tensor.py @@ -0,0 +1,122 @@ +from typing import Any, Dict, List, Optional + +import gymnasium as gym + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core import DEFAULT_MODULE_ID +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModule +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.torch_utils import convert_to_torch_tensor +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class NumpyToTensor(ConnectorV2): + """Converts numpy arrays across the entire input data into (framework) tensors. + + The framework information is received via the provided `rl_module` arg in the + `__call__()` method. + + Note: This is one of the default env-to-module or Learner ConnectorV2 pieces that + are added automatically by RLlib into every env-to-module/Learner connector + pipeline, unless `config.add_default_connectors_to_env_to_module_pipeline` or + `config.add_default_connectors_to_learner_pipeline ` are set to + False. + + The default env-to-module connector pipeline is: + [ + [0 or more user defined ConnectorV2 pieces], + AddObservationsFromEpisodesToBatch, + AddTimeDimToBatchAndZeroPad, + AddStatesFromEpisodesToBatch, + AgentToModuleMapping, # only in multi-agent setups! + BatchIndividualItems, + NumpyToTensor, + ] + The default Learner connector pipeline is: + [ + [0 or more user defined ConnectorV2 pieces], + AddObservationsFromEpisodesToBatch, + AddColumnsFromEpisodesToTrainBatch, + AddTimeDimToBatchAndZeroPad, + AddStatesFromEpisodesToBatch, + AgentToModuleMapping, # only in multi-agent setups! + BatchIndividualItems, + NumpyToTensor, + ] + + This ConnectorV2: + - Loops through the input `data` and converts all found numpy arrays into + framework-specific tensors (possibly on a GPU). + """ + + def __init__( + self, + input_observation_space: Optional[gym.Space] = None, + input_action_space: Optional[gym.Space] = None, + *, + pin_memory: bool = False, + device: Optional[str] = None, + **kwargs, + ): + """Initializes a NumpyToTensor instance. + + Args: + pin_memory: Whether to pin memory when creating (torch) tensors. + If None (default), pins memory if `as_learner_connector` is True, + otherwise doesn't pin memory. + device: An optional device to move the resulting tensors to. If not + provided, all data will be left on the CPU. + **kwargs: + """ + super().__init__( + input_observation_space=input_observation_space, + input_action_space=input_action_space, + **kwargs, + ) + self._pin_memory = pin_memory + self._device = device + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + is_single_agent = False + is_multi_rl_module = isinstance(rl_module, MultiRLModule) + # `data` already a ModuleID to batch mapping format. + if not (is_multi_rl_module and all(c in rl_module._rl_modules for c in batch)): + is_single_agent = True + batch = {DEFAULT_MODULE_ID: batch} + + for module_id, module_data in batch.copy().items(): + # If `rl_module` is None, leave data in numpy format. + if rl_module is not None: + infos = module_data.pop(Columns.INFOS, None) + if rl_module.framework == "torch": + module_data = convert_to_torch_tensor( + module_data, pin_memory=self._pin_memory, device=self._device + ) + else: + raise ValueError( + "`NumpyToTensor`does NOT support frameworks other than torch!" + ) + if infos is not None: + module_data[Columns.INFOS] = infos + + # Early out with data under(!) `DEFAULT_MODULE_ID`, b/c we are in plain + # single-agent mode. + if is_single_agent: + return module_data + batch[module_id] = module_data + + return batch diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/tensor_to_numpy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/tensor_to_numpy.py new file mode 100644 index 0000000000000000000000000000000000000000..f6bbb2669c7942087e2e9fc1817a9dd3d48e1280 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/common/tensor_to_numpy.py @@ -0,0 +1,26 @@ +from typing import Any, Dict, List, Optional + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class TensorToNumpy(ConnectorV2): + """Converts (framework) tensors across the entire input data into numpy arrays.""" + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + return convert_to_numpy(batch) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/connector.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/connector.py new file mode 100644 index 0000000000000000000000000000000000000000..ea53243331ebdedf210b4026d691318f452c80f5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/connector.py @@ -0,0 +1,478 @@ +"""This file defines base types and common structures for RLlib connectors. +""" + +import abc +import logging +from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Union + +import gymnasium as gym + +from ray.rllib.policy.view_requirement import ViewRequirement +from ray.rllib.utils.typing import ( + ActionConnectorDataType, + AgentConnectorDataType, + AlgorithmConfigDict, + TensorType, +) +from ray.rllib.utils.annotations import OldAPIStack + +if TYPE_CHECKING: + from ray.rllib.policy.policy import Policy + +logger = logging.getLogger(__name__) + + +@OldAPIStack +class ConnectorContext: + """Data bits that may be needed for running connectors. + + Note(jungong) : we need to be really careful with the data fields here. + E.g., everything needs to be serializable, in case we need to fetch them + in a remote setting. + """ + + # TODO(jungong) : figure out how to fetch these in a remote setting. + # Probably from a policy server when initializing a policy client. + + def __init__( + self, + config: AlgorithmConfigDict = None, + initial_states: List[TensorType] = None, + observation_space: gym.Space = None, + action_space: gym.Space = None, + view_requirements: Dict[str, ViewRequirement] = None, + is_policy_recurrent: bool = False, + ): + """Construct a ConnectorContext instance. + + Args: + initial_states: States that are used for constructing + the initial input dict for RNN models. [] if a model is not recurrent. + action_space_struct: a policy's action space, in python + data format. E.g., python dict instead of DictSpace, python tuple + instead of TupleSpace. + """ + self.config = config or {} + self.initial_states = initial_states or [] + self.observation_space = observation_space + self.action_space = action_space + self.view_requirements = view_requirements + self.is_policy_recurrent = is_policy_recurrent + + @staticmethod + def from_policy(policy: "Policy") -> "ConnectorContext": + """Build ConnectorContext from a given policy. + + Args: + policy: Policy + + Returns: + A ConnectorContext instance. + """ + return ConnectorContext( + config=policy.config, + initial_states=policy.get_initial_state(), + observation_space=policy.observation_space, + action_space=policy.action_space, + view_requirements=policy.view_requirements, + is_policy_recurrent=policy.is_recurrent(), + ) + + +@OldAPIStack +class Connector(abc.ABC): + """Connector base class. + + A connector is a step of transformation, of either envrionment data before they + get to a policy, or policy output before it is sent back to the environment. + + Connectors may be training-aware, for example, behave slightly differently + during training and inference. + + All connectors are required to be serializable and implement to_state(). + """ + + def __init__(self, ctx: ConnectorContext): + # Default is training mode. + self._is_training = True + + def in_training(self): + self._is_training = True + + def in_eval(self): + self._is_training = False + + def __str__(self, indentation: int = 0): + return " " * indentation + self.__class__.__name__ + + def to_state(self) -> Tuple[str, Any]: + """Serialize a connector into a JSON serializable Tuple. + + to_state is required, so that all Connectors are serializable. + + Returns: + A tuple of connector's name and its serialized states. + String should match the name used to register the connector, + while state can be any single data structure that contains the + serialized state of the connector. If a connector is stateless, + state can simply be None. + """ + # Must implement by each connector. + return NotImplementedError + + @staticmethod + def from_state(ctx: ConnectorContext, params: Any) -> "Connector": + """De-serialize a JSON params back into a Connector. + + from_state is required, so that all Connectors are serializable. + + Args: + ctx: Context for constructing this connector. + params: Serialized states of the connector to be recovered. + + Returns: + De-serialized connector. + """ + # Must implement by each connector. + return NotImplementedError + + +@OldAPIStack +class AgentConnector(Connector): + """Connector connecting user environments to RLlib policies. + + An agent connector transforms a list of agent data in AgentConnectorDataType + format into a new list in the same AgentConnectorDataTypes format. + The input API is designed so agent connectors can have access to all the + agents assigned to a particular policy. + + AgentConnectorDataTypes can be used to specify arbitrary type of env data, + + Example: + + Represent a list of agent data from one env step() call. + + .. testcode:: + + import numpy as np + ac = AgentConnectorDataType( + env_id="env_1", + agent_id=None, + data={ + "agent_1": np.array([1, 2, 3]), + "agent_2": np.array([4, 5, 6]), + } + ) + + Or a single agent data ready to be preprocessed. + + .. testcode:: + + ac = AgentConnectorDataType( + env_id="env_1", + agent_id="agent_1", + data=np.array([1, 2, 3]), + ) + + We can also adapt a simple stateless function into an agent connector by + using register_lambda_agent_connector: + + .. testcode:: + + import numpy as np + from ray.rllib.connectors.agent.lambdas import ( + register_lambda_agent_connector + ) + TimesTwoAgentConnector = register_lambda_agent_connector( + "TimesTwoAgentConnector", lambda data: data * 2 + ) + + # More complicated agent connectors can be implemented by extending this + # AgentConnector class: + + class FrameSkippingAgentConnector(AgentConnector): + def __init__(self, n): + self._n = n + self._frame_count = default_dict(str, default_dict(str, int)) + + def reset(self, env_id: str): + del self._frame_count[env_id] + + def __call__( + self, ac_data: List[AgentConnectorDataType] + ) -> List[AgentConnectorDataType]: + ret = [] + for d in ac_data: + assert d.env_id and d.agent_id, "Skipping works per agent!" + + count = self._frame_count[ac_data.env_id][ac_data.agent_id] + self._frame_count[ac_data.env_id][ac_data.agent_id] = ( + count + 1 + ) + + if count % self._n == 0: + ret.append(d) + return ret + + As shown, an agent connector may choose to emit an empty list to stop input + observations from being further prosessed. + """ + + def reset(self, env_id: str): + """Reset connector state for a specific environment. + + For example, at the end of an episode. + + Args: + env_id: required. ID of a user environment. Required. + """ + pass + + def on_policy_output(self, output: ActionConnectorDataType): + """Callback on agent connector of policy output. + + This is useful for certain connectors, for example RNN state buffering, + where the agent connect needs to be aware of the output of a policy + forward pass. + + Args: + ctx: Context for running this connector call. + output: Env and agent IDs, plus data output from policy forward pass. + """ + pass + + def __call__( + self, acd_list: List[AgentConnectorDataType] + ) -> List[AgentConnectorDataType]: + """Transform a list of data items from env before they reach policy. + + Args: + ac_data: List of env and agent IDs, plus arbitrary data items from + an environment or upstream agent connectors. + + Returns: + A list of transformed data items in AgentConnectorDataType format. + The shape of a returned list does not have to match that of the input list. + An AgentConnector may choose to derive multiple outputs for a single piece + of input data, for example multi-agent obs -> multiple single agent obs. + Agent connectors may also choose to skip emitting certain inputs, + useful for connectors such as frame skipping. + """ + assert isinstance( + acd_list, (list, tuple) + ), "Input to agent connectors are list of AgentConnectorDataType." + # Default implementation. Simply call transform on each agent connector data. + return [self.transform(d) for d in acd_list] + + def transform(self, ac_data: AgentConnectorDataType) -> AgentConnectorDataType: + """Transform a single agent connector data item. + + Args: + data: Env and agent IDs, plus arbitrary data item from a single agent + of an environment. + + Returns: + A transformed piece of agent connector data. + """ + raise NotImplementedError + + +@OldAPIStack +class ActionConnector(Connector): + """Action connector connects policy outputs including actions, + to user environments. + + An action connector transforms a single piece of policy output in + ActionConnectorDataType format, which is basically PolicyOutputType plus env and + agent IDs. + + Any functions that operate directly on PolicyOutputType can be easily adapted + into an ActionConnector by using register_lambda_action_connector. + + Example: + + .. testcode:: + + from ray.rllib.connectors.action.lambdas import ( + register_lambda_action_connector + ) + ZeroActionConnector = register_lambda_action_connector( + "ZeroActionsConnector", + lambda actions, states, fetches: ( + np.zeros_like(actions), states, fetches + ) + ) + + More complicated action connectors can also be implemented by sub-classing + this ActionConnector class. + """ + + def __call__(self, ac_data: ActionConnectorDataType) -> ActionConnectorDataType: + """Transform policy output before they are sent to a user environment. + + Args: + ac_data: Env and agent IDs, plus policy output. + + Returns: + The processed action connector data. + """ + return self.transform(ac_data) + + def transform(self, ac_data: ActionConnectorDataType) -> ActionConnectorDataType: + """Implementation of the actual transform. + + Users should override transform instead of __call__ directly. + + Args: + ac_data: Env and agent IDs, plus policy output. + + Returns: + The processed action connector data. + """ + raise NotImplementedError + + +@OldAPIStack +class ConnectorPipeline(abc.ABC): + """Utility class for quick manipulation of a connector pipeline.""" + + def __init__(self, ctx: ConnectorContext, connectors: List[Connector]): + self.connectors = connectors + + def in_training(self): + for c in self.connectors: + c.in_training() + + def in_eval(self): + for c in self.connectors: + c.in_eval() + + def remove(self, name: str): + """Remove a connector by + + Args: + name: name of the connector to be removed. + """ + idx = -1 + for i, c in enumerate(self.connectors): + if c.__class__.__name__ == name: + idx = i + break + if idx >= 0: + del self.connectors[idx] + logger.info(f"Removed connector {name} from {self.__class__.__name__}.") + else: + logger.warning(f"Trying to remove a non-existent connector {name}.") + + def insert_before(self, name: str, connector: Connector): + """Insert a new connector before connector + + Args: + name: name of the connector before which a new connector + will get inserted. + connector: a new connector to be inserted. + """ + idx = -1 + for idx, c in enumerate(self.connectors): + if c.__class__.__name__ == name: + break + if idx < 0: + raise ValueError(f"Can not find connector {name}") + self.connectors.insert(idx, connector) + + logger.info( + f"Inserted {connector.__class__.__name__} before {name} " + f"to {self.__class__.__name__}." + ) + + def insert_after(self, name: str, connector: Connector): + """Insert a new connector after connector + + Args: + name: name of the connector after which a new connector + will get inserted. + connector: a new connector to be inserted. + """ + idx = -1 + for idx, c in enumerate(self.connectors): + if c.__class__.__name__ == name: + break + if idx < 0: + raise ValueError(f"Can not find connector {name}") + self.connectors.insert(idx + 1, connector) + + logger.info( + f"Inserted {connector.__class__.__name__} after {name} " + f"to {self.__class__.__name__}." + ) + + def prepend(self, connector: Connector): + """Append a new connector at the beginning of a connector pipeline. + + Args: + connector: a new connector to be appended. + """ + self.connectors.insert(0, connector) + + logger.info( + f"Added {connector.__class__.__name__} to the beginning of " + f"{self.__class__.__name__}." + ) + + def append(self, connector: Connector): + """Append a new connector at the end of a connector pipeline. + + Args: + connector: a new connector to be appended. + """ + self.connectors.append(connector) + + logger.info( + f"Added {connector.__class__.__name__} to the end of " + f"{self.__class__.__name__}." + ) + + def __str__(self, indentation: int = 0): + return "\n".join( + [" " * indentation + self.__class__.__name__] + + [c.__str__(indentation + 4) for c in self.connectors] + ) + + def __getitem__(self, key: Union[str, int, type]): + """Returns a list of connectors that fit 'key'. + + If key is a number n, we return a list with the nth element of this pipeline. + If key is a Connector class or a string matching the class name of a + Connector class, we return a list of all connectors in this pipeline matching + the specified class. + + Args: + key: The key to index by + + Returns: The Connector at index `key`. + """ + # In case key is a class + if not isinstance(key, str): + if isinstance(key, slice): + raise NotImplementedError( + "Slicing of ConnectorPipeline is currently not supported." + ) + elif isinstance(key, int): + return [self.connectors[key]] + elif isinstance(key, type): + results = [] + for c in self.connectors: + if issubclass(c.__class__, key): + results.append(c) + return results + else: + raise NotImplementedError( + "Indexing by {} is currently not supported.".format(type(key)) + ) + + results = [] + for c in self.connectors: + if c.__class__.__name__ == key: + results.append(c) + + return results diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/connector_pipeline_v2.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/connector_pipeline_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..f8273b3233f9895fe85706188b3f82109b9d4522 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/connector_pipeline_v2.py @@ -0,0 +1,415 @@ +import logging +from typing import Any, Collection, Dict, List, Optional, Tuple, Type, Union + +import gymnasium as gym + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.checkpoints import Checkpointable +from ray.rllib.utils.metrics import TIMERS, CONNECTOR_PIPELINE_TIMER, CONNECTOR_TIMERS +from ray.rllib.utils.metrics.metrics_logger import MetricsLogger +from ray.rllib.utils.metrics.utils import to_snake_case +from ray.rllib.utils.typing import EpisodeType, StateDict +from ray.util.annotations import PublicAPI + +logger = logging.getLogger(__name__) + + +@PublicAPI(stability="alpha") +class ConnectorPipelineV2(ConnectorV2): + """Utility class for quick manipulation of a connector pipeline.""" + + @override(ConnectorV2) + def recompute_output_observation_space( + self, + input_observation_space: gym.Space, + input_action_space: gym.Space, + ) -> gym.Space: + self._fix_spaces(input_observation_space, input_action_space) + return self.observation_space + + @override(ConnectorV2) + def recompute_output_action_space( + self, + input_observation_space: gym.Space, + input_action_space: gym.Space, + ) -> gym.Space: + self._fix_spaces(input_observation_space, input_action_space) + return self.action_space + + def __init__( + self, + input_observation_space: Optional[gym.Space] = None, + input_action_space: Optional[gym.Space] = None, + *, + connectors: Optional[List[ConnectorV2]] = None, + **kwargs, + ): + """Initializes a ConnectorPipelineV2 instance. + + Args: + input_observation_space: The (optional) input observation space for this + connector piece. This is the space coming from a previous connector + piece in the (env-to-module or learner) pipeline or is directly + defined within the gym.Env. + input_action_space: The (optional) input action space for this connector + piece. This is the space coming from a previous connector piece in the + (module-to-env) pipeline or is directly defined within the gym.Env. + connectors: A list of individual ConnectorV2 pieces to be added to this + pipeline during construction. Note that you can always add (or remove) + more ConnectorV2 pieces later on the fly. + """ + self.connectors = [] + + for conn in connectors: + # If we have a `ConnectorV2` instance just append. + if isinstance(conn, ConnectorV2): + self.connectors.append(conn) + # If, we have a class with `args` and `kwargs`, build the instance. + # Note that this way of constructing a pipeline should only be + # used internally when restoring the pipeline state from a + # checkpoint. + elif isinstance(conn, tuple) and len(conn) == 3: + self.connectors.append(conn[0](*conn[1], **conn[2])) + + super().__init__(input_observation_space, input_action_space, **kwargs) + + def __len__(self): + return len(self.connectors) + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + metrics: Optional[MetricsLogger] = None, + **kwargs, + ) -> Any: + """In a pipeline, we simply call each of our connector pieces after each other. + + Each connector piece receives as input the output of the previous connector + piece in the pipeline. + """ + shared_data = shared_data if shared_data is not None else {} + full_stats = None + if metrics: + full_stats = metrics.log_time( + kwargs.get("metrics_prefix_key", ()) + (CONNECTOR_PIPELINE_TIMER,) + ) + full_stats.__enter__() + + # Loop through connector pieces and call each one with the output of the + # previous one. Thereby, time each connector piece's call. + for connector in self.connectors: + # TODO (sven): Add MetricsLogger to non-Learner components that have a + # LearnerConnector pipeline. + stats = None + if metrics: + stats = metrics.log_time( + kwargs.get("metrics_prefix_key", ()) + + ( + TIMERS, + CONNECTOR_TIMERS, + to_snake_case(connector.__class__.__name__), + ) + ) + stats.__enter__() + + batch = connector( + rl_module=rl_module, + batch=batch, + episodes=episodes, + explore=explore, + shared_data=shared_data, + metrics=metrics, + # Deprecated arg. + data=batch, + **kwargs, + ) + + if metrics: + stats.__exit__(None, None, None) + + if not isinstance(batch, dict): + raise ValueError( + f"`data` returned by ConnectorV2 {connector} must be a dict! " + f"You returned {batch}. Check your (custom) connectors' " + f"`__call__()` method's return value and make sure you return " + f"the `batch` arg passed in (either altered or unchanged)." + ) + + if metrics: + full_stats.__exit__(None, None, None) + + return batch + + def remove(self, name_or_class: Union[str, Type]): + """Remove a single connector piece in this pipeline by its name or class. + + Args: + name_or_class: The name of the connector piece to be removed from the + pipeline. + """ + idx = -1 + for i, c in enumerate(self.connectors): + if (isinstance(name_or_class, type) and c.__class__ is name_or_class) or ( + isinstance(name_or_class, str) and c.__class__.__name__ == name_or_class + ): + idx = i + break + if idx >= 0: + del self.connectors[idx] + self._fix_spaces(self.input_observation_space, self.input_action_space) + logger.info( + f"Removed connector {name_or_class} from {self.__class__.__name__}." + ) + else: + logger.warning( + f"Trying to remove a non-existent connector {name_or_class}." + ) + + def insert_before( + self, + name_or_class: Union[str, type], + connector: ConnectorV2, + ) -> ConnectorV2: + """Insert a new connector piece before an existing piece (by name or class). + + Args: + name_or_class: Name or class of the connector piece before which `connector` + will get inserted. + connector: The new connector piece to be inserted. + + Returns: + The ConnectorV2 before which `connector` has been inserted. + """ + idx = -1 + for idx, c in enumerate(self.connectors): + if ( + isinstance(name_or_class, str) and c.__class__.__name__ == name_or_class + ) or (isinstance(name_or_class, type) and c.__class__ is name_or_class): + break + if idx < 0: + raise ValueError( + f"Can not find connector with name or type '{name_or_class}'!" + ) + next_connector = self.connectors[idx] + + self.connectors.insert(idx, connector) + self._fix_spaces(self.input_observation_space, self.input_action_space) + + logger.info( + f"Inserted {connector.__class__.__name__} before {name_or_class} " + f"to {self.__class__.__name__}." + ) + return next_connector + + def insert_after( + self, + name_or_class: Union[str, Type], + connector: ConnectorV2, + ) -> ConnectorV2: + """Insert a new connector piece after an existing piece (by name or class). + + Args: + name_or_class: Name or class of the connector piece after which `connector` + will get inserted. + connector: The new connector piece to be inserted. + + Returns: + The ConnectorV2 after which `connector` has been inserted. + """ + idx = -1 + for idx, c in enumerate(self.connectors): + if ( + isinstance(name_or_class, str) and c.__class__.__name__ == name_or_class + ) or (isinstance(name_or_class, type) and c.__class__ is name_or_class): + break + if idx < 0: + raise ValueError( + f"Can not find connector with name or type '{name_or_class}'!" + ) + prev_connector = self.connectors[idx] + + self.connectors.insert(idx + 1, connector) + self._fix_spaces(self.input_observation_space, self.input_action_space) + + logger.info( + f"Inserted {connector.__class__.__name__} after {name_or_class} " + f"to {self.__class__.__name__}." + ) + + return prev_connector + + def prepend(self, connector: ConnectorV2) -> None: + """Prepend a new connector at the beginning of a connector pipeline. + + Args: + connector: The new connector piece to be prepended to this pipeline. + """ + self.connectors.insert(0, connector) + self._fix_spaces(self.input_observation_space, self.input_action_space) + + logger.info( + f"Added {connector.__class__.__name__} to the beginning of " + f"{self.__class__.__name__}." + ) + + def append(self, connector: ConnectorV2) -> None: + """Append a new connector at the end of a connector pipeline. + + Args: + connector: The new connector piece to be appended to this pipeline. + """ + self.connectors.append(connector) + self._fix_spaces(self.input_observation_space, self.input_action_space) + + logger.info( + f"Added {connector.__class__.__name__} to the end of " + f"{self.__class__.__name__}." + ) + + @override(ConnectorV2) + def get_state( + self, + components: Optional[Union[str, Collection[str]]] = None, + *, + not_components: Optional[Union[str, Collection[str]]] = None, + **kwargs, + ) -> StateDict: + state = {} + for conn in self.connectors: + conn_name = type(conn).__name__ + if self._check_component(conn_name, components, not_components): + sts = conn.get_state( + components=self._get_subcomponents(conn_name, components), + not_components=self._get_subcomponents(conn_name, not_components), + **kwargs, + ) + # Ignore empty dicts. + if sts: + state[conn_name] = sts + return state + + @override(ConnectorV2) + def set_state(self, state: Dict[str, Any]) -> None: + for conn in self.connectors: + conn_name = type(conn).__name__ + if conn_name in state: + conn.set_state(state[conn_name]) + + @override(Checkpointable) + def get_checkpointable_components(self) -> List[Tuple[str, "Checkpointable"]]: + return [(type(conn).__name__, conn) for conn in self.connectors] + + # Note that we don't have to override Checkpointable.get_ctor_args_and_kwargs and + # don't have to return the `connectors` c'tor kwarg from there. This is b/c all + # connector pieces in this pipeline are themselves Checkpointable components, + # so they will be properly written into this pipeline's checkpoint. + @override(Checkpointable) + def get_ctor_args_and_kwargs(self) -> Tuple[Tuple, Dict[str, Any]]: + return ( + (self.input_observation_space, self.input_action_space), # *args + { + "connectors": [ + (type(conn), *conn.get_ctor_args_and_kwargs()) + for conn in self.connectors + ] + }, + ) + + @override(ConnectorV2) + def reset_state(self) -> None: + for conn in self.connectors: + conn.reset_state() + + @override(ConnectorV2) + def merge_states(self, states: List[Dict[str, Any]]) -> Dict[str, Any]: + merged_states = {} + if not states: + return merged_states + for i, (key, item) in enumerate(states[0].items()): + state_list = [state[key] for state in states] + conn = self.connectors[i] + merged_states[key] = conn.merge_states(state_list) + return merged_states + + def __repr__(self, indentation: int = 0): + return "\n".join( + [" " * indentation + self.__class__.__name__] + + [c.__str__(indentation + 4) for c in self.connectors] + ) + + def __getitem__( + self, + key: Union[str, int, Type], + ) -> Union[ConnectorV2, List[ConnectorV2]]: + """Returns a single ConnectorV2 or list of ConnectorV2s that fit `key`. + + If key is an int, we return a single ConnectorV2 at that index in this pipeline. + If key is a ConnectorV2 type or a string matching the class name of a + ConnectorV2 in this pipeline, we return a list of all ConnectorV2s in this + pipeline matching the specified class. + + Args: + key: The key to find or to index by. + + Returns: + A single ConnectorV2 or a list of ConnectorV2s matching `key`. + """ + # Key is an int -> Index into pipeline and return. + if isinstance(key, int): + return self.connectors[key] + # Key is a class. + elif isinstance(key, type): + results = [] + for c in self.connectors: + if issubclass(c.__class__, key): + results.append(c) + return results + # Key is a string -> Find connector(s) by name. + elif isinstance(key, str): + results = [] + for c in self.connectors: + if c.name == key: + results.append(c) + return results + # Slicing not supported (yet). + elif isinstance(key, slice): + raise NotImplementedError( + "Slicing of ConnectorPipelineV2 is currently not supported!" + ) + else: + raise NotImplementedError( + f"Indexing ConnectorPipelineV2 by {type(key)} is currently not " + f"supported!" + ) + + @property + def observation_space(self): + if len(self) > 0: + return self.connectors[-1].observation_space + return self._observation_space + + @property + def action_space(self): + if len(self) > 0: + return self.connectors[-1].action_space + return self._action_space + + def _fix_spaces(self, input_observation_space, input_action_space): + if len(self) > 0: + # Fix each connector's input_observation- and input_action space in + # the pipeline. + obs_space = input_observation_space + act_space = input_action_space + for con in self.connectors: + con.input_action_space = act_space + con.input_observation_space = obs_space + obs_space = con.observation_space + act_space = con.action_space diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/connector_v2.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/connector_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..311957717aad64e09f475dfcf19e6b83fb845aeb --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/connector_v2.py @@ -0,0 +1,1017 @@ +import abc +from collections import defaultdict +import inspect +from typing import ( + Any, + Callable, + Collection, + Dict, + Iterator, + List, + Optional, + Tuple, + Union, +) + +import gymnasium as gym +import tree + +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.env.single_agent_episode import SingleAgentEpisode +from ray.rllib.utils import force_list +from ray.rllib.utils.annotations import override, OverrideToImplementCustomLogic +from ray.rllib.utils.checkpoints import Checkpointable +from ray.rllib.utils.metrics.metrics_logger import MetricsLogger +from ray.rllib.utils.spaces.space_utils import BatchedNdArray +from ray.rllib.utils.typing import AgentID, EpisodeType, ModuleID, StateDict +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class ConnectorV2(Checkpointable, abc.ABC): + """Base class defining the API for an individual "connector piece". + + A ConnectorV2 ("connector piece") is usually part of a whole series of connector + pieces within a so-called connector pipeline, which in itself also abides to this + very API. + For example, you might have a connector pipeline consisting of two connector pieces, + A and B, both instances of subclasses of ConnectorV2 and each one performing a + particular transformation on their input data. The resulting connector pipeline + (A->B) itself also abides to this very ConnectorV2 API and could thus be part of yet + another, higher-level connector pipeline, e.g. (A->B)->C->D. + + Any ConnectorV2 instance (individual pieces or several connector pieces in a + pipeline) is a callable and users should override the `__call__()` method. + When called, they take the outputs of a previous connector piece (or an empty dict + if there are no previous pieces) and all the data collected thus far in the + ongoing episode(s) (only applies to connectors used in EnvRunners) or retrieved + from a replay buffer or from an environment sampling step (only applies to + connectors used in Learner pipelines). From this input data, a ConnectorV2 then + performs a transformation step. + + There are 3 types of pipelines any ConnectorV2 piece can belong to: + 1) EnvToModulePipeline: The connector transforms environment data before it gets to + the RLModule. This type of pipeline is used by an EnvRunner for transforming + env output data into RLModule readable data (for the next RLModule forward pass). + For example, such a pipeline would include observation postprocessors, -filters, + or any RNN preparation code related to time-sequences and zero-padding. + 2) ModuleToEnvPipeline: This type of pipeline is used by an + EnvRunner to transform RLModule output data to env readable actions (for the next + `env.step()` call). For example, in case the RLModule only outputs action + distribution parameters (but not actual actions), the ModuleToEnvPipeline would + take care of sampling the actions to be sent back to the end from the + resulting distribution (made deterministic if exploration is off). + 3) LearnerConnectorPipeline: This connector pipeline type transforms data coming + from an `EnvRunner.sample()` call or a replay buffer and will then be sent into the + RLModule's `forward_train()` method in order to compute loss function inputs. + This type of pipeline is used by a Learner worker to transform raw training data + (a batch or a list of episodes) to RLModule readable training data (for the next + RLModule `forward_train()` call). + + Some connectors might be stateful, for example for keeping track of observation + filtering stats (mean and stddev values). Any Algorithm, which uses connectors is + responsible for frequently synchronizing the states of all connectors and connector + pipelines between the EnvRunners (owning the env-to-module and module-to-env + pipelines) and the Learners (owning the Learner pipelines). + """ + + def __init__( + self, + input_observation_space: Optional[gym.Space] = None, + input_action_space: Optional[gym.Space] = None, + **kwargs, + ): + """Initializes a ConnectorV2 instance. + + Args: + input_observation_space: The (optional) input observation space for this + connector piece. This is the space coming from a previous connector + piece in the (env-to-module or learner) pipeline or is directly + defined within the gym.Env. + input_action_space: The (optional) input action space for this connector + piece. This is the space coming from a previous connector piece in the + (module-to-env) pipeline or is directly defined within the gym.Env. + **kwargs: Forward API-compatibility kwargs. + """ + self._observation_space = None + self._action_space = None + self._input_observation_space = None + self._input_action_space = None + + self.input_action_space = input_action_space + self.input_observation_space = input_observation_space + + # Store child's constructor args and kwargs for the default + # `get_ctor_args_and_kwargs` implementation (to be able to restore from a + # checkpoint). + if self.__class__.__dict__.get("__init__") is not None: + caller_frame = inspect.stack()[1].frame + arg_info = inspect.getargvalues(caller_frame) + # Separate positional arguments and keyword arguments. + caller_locals = ( + arg_info.locals + ) # Dictionary of all local variables in the caller + self._ctor_kwargs = { + arg: caller_locals[arg] for arg in arg_info.args if arg != "self" + } + else: + self._ctor_kwargs = { + "input_observation_space": self.input_observation_space, + "input_action_space": self.input_action_space, + } + + @OverrideToImplementCustomLogic + def recompute_output_observation_space( + self, + input_observation_space: gym.Space, + input_action_space: gym.Space, + ) -> gym.Space: + """Re-computes a new (output) observation space based on the input spaces. + + This method should be overridden by users to make sure a ConnectorPipelineV2 + knows how the input spaces through its individual ConnectorV2 pieces are being + transformed. + + .. testcode:: + + from gymnasium.spaces import Box, Discrete + import numpy as np + + from ray.rllib.connectors.connector_v2 import ConnectorV2 + from ray.rllib.utils.numpy import one_hot + from ray.rllib.utils.test_utils import check + + class OneHotConnector(ConnectorV2): + def recompute_output_observation_space( + self, + input_observation_space, + input_action_space, + ): + return Box(0.0, 1.0, (input_observation_space.n,), np.float32) + + def __call__( + self, + *, + rl_module, + batch, + episodes, + explore=None, + shared_data=None, + metrics=None, + **kwargs, + ): + assert "obs" in batch + batch["obs"] = one_hot(batch["obs"]) + return batch + + connector = OneHotConnector(input_observation_space=Discrete(2)) + batch = {"obs": np.array([1, 0, 0], np.int32)} + output = connector(rl_module=None, batch=batch, episodes=None) + + check(output, {"obs": np.array([[0.0, 1.0], [1.0, 0.0], [1.0, 0.0]])}) + + If this ConnectorV2 does not change the observation space in any way, leave + this parent method implementation untouched. + + Args: + input_observation_space: The input observation space (either coming from the + environment if `self` is the first connector piece in the pipeline or + from the previous connector piece in the pipeline). + input_action_space: The input action space (either coming from the + environment if `self` is the first connector piece in the pipeline or + from the previous connector piece in the pipeline). + + Returns: + The new observation space (after data has passed through this ConnectorV2 + piece). + """ + return self.input_observation_space + + @OverrideToImplementCustomLogic + def recompute_output_action_space( + self, + input_observation_space: gym.Space, + input_action_space: gym.Space, + ) -> gym.Space: + """Re-computes a new (output) action space based on the input space. + + This method should be overridden by users to make sure a ConnectorPipelineV2 + knows how the input spaces through its individual ConnectorV2 pieces are being + transformed. + + If this ConnectorV2 does not change the action space in any way, leave + this parent method implementation untouched. + + Args: + input_observation_space: The input observation space (either coming from the + environment if `self` is the first connector piece in the pipeline or + from the previous connector piece in the pipeline). + input_action_space: The input action space (either coming from the + environment if `self` is the first connector piece in the pipeline or + from the previous connector piece in the pipeline). + + Returns: + The new action space (after data has passed through this ConenctorV2 + piece). + """ + return self.input_action_space + + @abc.abstractmethod + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + metrics: Optional[MetricsLogger] = None, + **kwargs, + ) -> Any: + """Method for transforming an input `batch` into an output `batch`. + + Args: + rl_module: The RLModule object that the connector connects to or from. + batch: The input data to be transformed by this connector. Transformations + might either be done in-place or a new structure may be returned. + Note that the information in `batch` will eventually either become the + forward batch for the RLModule (env-to-module and learner connectors) + or the input to the `env.step()` call (module-to-env connectors). Note + that in the first case (`batch` is a forward batch for RLModule), the + information in `batch` will be discarded after that RLModule forward + pass. Any transformation of information (e.g. observation preprocessing) + that you have only done inside `batch` will be lost, unless you have + written it back into the corresponding `episodes` during the connector + pass. + episodes: The list of SingleAgentEpisode or MultiAgentEpisode objects, + each corresponding to one slot in the vector env. Note that episodes + can be read from (e.g. to place information into `batch`), but also + written to. You should only write back (changed, transformed) + information into the episodes, if you want these changes to be + "permanent". For example if you sample from an environment, pick up + observations from the episodes and place them into `batch`, then + transform these observations, and would like to make these + transformations permanent (note that `batch` gets discarded after the + RLModule forward pass), then you have to write the transformed + observations back into the episode to make sure you do not have to + perform the same transformation again on the learner (or replay buffer) + side. The Learner will hence work on the already changed episodes (and + compile the train batch using the Learner connector). + explore: Whether `explore` is currently on. Per convention, if True, the + RLModule's `forward_exploration` method should be called, if False, the + EnvRunner should call `forward_inference` instead. + shared_data: Optional additional context data that needs to be exchanged + between different ConnectorV2 pieces (in the same pipeline) or across + ConnectorV2 pipelines (meaning between env-to-module and module-to-env). + metrics: Optional MetricsLogger instance to log custom metrics to. + kwargs: Forward API-compatibility kwargs. + + Returns: + The transformed connector output. + """ + + @staticmethod + def single_agent_episode_iterator( + episodes: List[EpisodeType], + agents_that_stepped_only: bool = True, + zip_with_batch_column: Optional[Union[List[Any], Dict[Tuple, Any]]] = None, + ) -> Iterator[SingleAgentEpisode]: + """An iterator over a list of episodes yielding always SingleAgentEpisodes. + + In case items in the list are MultiAgentEpisodes, these are broken down + into their individual agents' SingleAgentEpisodes and those are then yielded + one after the other. + + Useful for connectors that operate on both single-agent and multi-agent + episodes. + + Args: + episodes: The list of SingleAgent- or MultiAgentEpisode objects. + agents_that_stepped_only: If True (and multi-agent setup), will only place + items of those agents into the batch that have just stepped in the + actual MultiAgentEpisode (this is checked via a + `MultiAgentEpside.episode.get_agents_to_act()`). Note that this setting + is ignored in a single-agent setups b/c the agent steps at each timestep + regardless. + zip_with_batch_column: If provided, must be a list of batch items + corresponding to the given `episodes` (single agent case) or a dict + mapping (AgentID, ModuleID) tuples to lists of individual batch items + corresponding to this agent/module combination. The iterator will then + yield tuples of SingleAgentEpisode objects (1st item) along with the + data item (2nd item) that this episode was responsible for generating + originally. + + Yields: + All SingleAgentEpisodes in the input list, whereby MultiAgentEpisodes will + be broken down into their individual SingleAgentEpisode components. + """ + list_indices = defaultdict(int) + + # Single-agent case. + if episodes and isinstance(episodes[0], SingleAgentEpisode): + if zip_with_batch_column is not None: + if len(zip_with_batch_column) != len(episodes): + raise ValueError( + "Invalid `zip_with_batch_column` data: Must have the same " + f"length as the list of episodes ({len(episodes)}), but has " + f"length {len(zip_with_batch_column)}!" + ) + # Simple case: Items are stored in lists directly under the column (str) + # key. + if isinstance(zip_with_batch_column, list): + for episode, data in zip(episodes, zip_with_batch_column): + yield episode, data + # Normal single-agent case: Items are stored in dicts under the column + # (str) key. These dicts map (eps_id,)-tuples to lists of individual + # items. + else: + for episode, (eps_id_tuple, data) in zip( + episodes, + zip_with_batch_column.items(), + ): + assert episode.id_ == eps_id_tuple[0] + d = data[list_indices[eps_id_tuple]] + list_indices[eps_id_tuple] += 1 + yield episode, d + else: + for episode in episodes: + yield episode + return + + # Multi-agent case. + for episode in episodes: + for agent_id in ( + episode.get_agents_that_stepped() + if agents_that_stepped_only + else episode.agent_ids + ): + sa_episode = episode.agent_episodes[agent_id] + # for sa_episode in episode.agent_episodes.values(): + if zip_with_batch_column is not None: + key = ( + sa_episode.multi_agent_episode_id, + sa_episode.agent_id, + sa_episode.module_id, + ) + if len(zip_with_batch_column[key]) <= list_indices[key]: + raise ValueError( + "Invalid `zip_with_batch_column` data: Must structurally " + "match the single-agent contents in the given list of " + "(multi-agent) episodes!" + ) + d = zip_with_batch_column[key][list_indices[key]] + list_indices[key] += 1 + yield sa_episode, d + else: + yield sa_episode + + @staticmethod + def add_batch_item( + batch: Dict[str, Any], + column: str, + item_to_add: Any, + single_agent_episode: Optional[SingleAgentEpisode] = None, + ) -> None: + """Adds a data item under `column` to the given `batch`. + + The `item_to_add` is stored in the `batch` in the following manner: + 1) If `single_agent_episode` is not provided (None), will store the item in a + list directly under `column`: + `column` -> [item, item, ...] + 2) If `single_agent_episode`'s `agent_id` and `module_id` properties are None + (`single_agent_episode` is not part of a multi-agent episode), will append + `item_to_add` to a list under a `(,)` key under `column`: + `column` -> `(,)` -> [item, item, ...] + 3) If `single_agent_episode`'s `agent_id` and `module_id` are NOT None + (`single_agent_episode` is part of a multi-agent episode), will append + `item_to_add` to a list under a `(,,)` key + under `column`: + `column` -> `(,,)` -> [item, item, ...] + + See the these examples here for clarification of these three cases: + + .. testcode:: + + from ray.rllib.connectors.connector_v2 import ConnectorV2 + from ray.rllib.env.multi_agent_episode import MultiAgentEpisode + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + from ray.rllib.utils.test_utils import check + + # 1) Simple case (no episodes provided) -> Store data in a list directly + # under `column`: + batch = {} + ConnectorV2.add_batch_item(batch, "test_col", item_to_add=5) + ConnectorV2.add_batch_item(batch, "test_col", item_to_add=6) + check(batch, {"test_col": [5, 6]}) + ConnectorV2.add_batch_item(batch, "test_col_2", item_to_add=-10) + check(batch, { + "test_col": [5, 6], + "test_col_2": [-10], + }) + + # 2) Single-agent case (SingleAgentEpisode provided) -> Store data in a list + # under the keys: `column` -> `(,)` -> [...]: + batch = {} + episode = SingleAgentEpisode( + id_="SA-EPS0", + observations=[0, 1, 2, 3], + actions=[1, 2, 3], + rewards=[1.0, 2.0, 3.0], + ) + ConnectorV2.add_batch_item(batch, "test_col", 5, episode) + ConnectorV2.add_batch_item(batch, "test_col", 6, episode) + ConnectorV2.add_batch_item(batch, "test_col_2", -10, episode) + check(batch, { + "test_col": {("SA-EPS0",): [5, 6]}, + "test_col_2": {("SA-EPS0",): [-10]}, + }) + + # 3) Multi-agent case (SingleAgentEpisode provided that has `agent_id` and + # `module_id` information) -> Store data in a list under the keys: + # `column` -> `(,,)` -> [...]: + batch = {} + ma_episode = MultiAgentEpisode( + id_="MA-EPS1", + observations=[ + {"ag0": 0, "ag1": 1}, {"ag0": 2, "ag1": 4} + ], + actions=[{"ag0": 0, "ag1": 1}], + rewards=[{"ag0": -0.1, "ag1": -0.2}], + # ag0 maps to mod0, ag1 maps to mod1, etc.. + agent_to_module_mapping_fn=lambda aid, eps: f"mod{aid[2:]}", + ) + ConnectorV2.add_batch_item( + batch, + "test_col", + item_to_add=5, + single_agent_episode=ma_episode.agent_episodes["ag0"], + ) + ConnectorV2.add_batch_item( + batch, + "test_col", + item_to_add=6, + single_agent_episode=ma_episode.agent_episodes["ag0"], + ) + ConnectorV2.add_batch_item( + batch, + "test_col_2", + item_to_add=10, + single_agent_episode=ma_episode.agent_episodes["ag1"], + ) + check( + batch, + { + "test_col": {("MA-EPS1", "ag0", "mod0"): [5, 6]}, + "test_col_2": {("MA-EPS1", "ag1", "mod1"): [10]}, + }, + ) + + Args: + batch: The batch to store `item_to_add` in. + column: The column name (str) within the `batch` to store `item_to_add` + under. + item_to_add: The data item to store in the batch. + single_agent_episode: An optional SingleAgentEpisode. + If provided and its `agent_id` and `module_id` properties are None, + creates a further sub dictionary under `column`, mapping from + `(,)` to a list of data items (to which `item_to_add` will + be appended in this call). + If provided and its `agent_id` and `module_id` properties are NOT None, + creates a further sub dictionary under `column`, mapping from + `(,,,)` to a list of data items (to which + `item_to_add` will be appended in this call). + If not provided, will append `item_to_add` to a list directly under + `column`. + """ + sub_key = None + # SAEpisode is provided ... + if single_agent_episode is not None: + module_id = single_agent_episode.module_id + # ... and has `module_id` AND that `module_id` is already a top-level key in + # `batch` (`batch` is already in module-major form, mapping ModuleID to + # columns mapping to data). + if module_id is not None and module_id in batch: + raise ValueError( + "Can't call `add_batch_item` on a `batch` that is already " + "module-major (meaning ModuleID is top-level with column names on " + "the level thereunder)! Make sure to only call `add_batch_items` " + "before the `AgentToModuleMapping` ConnectorV2 piece is applied." + ) + + # ... and has `agent_id` -> Use `single_agent_episode`'s agent ID and + # module ID. + elif single_agent_episode.agent_id is not None: + sub_key = ( + single_agent_episode.multi_agent_episode_id, + single_agent_episode.agent_id, + single_agent_episode.module_id, + ) + # Otherwise, just use episode's ID. + else: + sub_key = (single_agent_episode.id_,) + + if column not in batch: + batch[column] = [] if sub_key is None else {sub_key: []} + if sub_key is not None: + if sub_key not in batch[column]: + batch[column][sub_key] = [] + batch[column][sub_key].append(item_to_add) + else: + batch[column].append(item_to_add) + + @staticmethod + def add_n_batch_items( + batch: Dict[str, Any], + column: str, + items_to_add: Any, + num_items: int, + single_agent_episode: Optional[SingleAgentEpisode] = None, + ) -> None: + """Adds a list of items (or batched item) under `column` to the given `batch`. + + If `items_to_add` is not a list, but an already batched struct (of np.ndarray + leafs), the `items_to_add` will be appended to possibly existing data under the + same `column` as-is. A subsequent `BatchIndividualItems` ConnectorV2 piece will + recognize this and batch the data properly into a single (batched) item. + This is much faster than first splitting up `items_to_add` and then adding each + item individually. + + If `single_agent_episode` is provided and its `agent_id` and `module_id` + properties are None, creates a further sub dictionary under `column`, mapping + from `(,)` to a list of data items (to which `items_to_add` will + be appended in this call). + If `single_agent_episode` is provided and its `agent_id` and `module_id` + properties are NOT None, creates a further sub dictionary under `column`, + mapping from `(,,,)` to a list of data items (to + which `items_to_add` will be appended in this call). + If `single_agent_episode` is not provided, will append `items_to_add` to a list + directly under `column`. + + .. testcode:: + + import numpy as np + + from ray.rllib.connectors.connector_v2 import ConnectorV2 + from ray.rllib.env.multi_agent_episode import MultiAgentEpisode + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + from ray.rllib.utils.test_utils import check + + # Simple case (no episodes provided) -> Store data in a list directly under + # `column`: + batch = {} + ConnectorV2.add_n_batch_items( + batch, + "test_col", + # List of (complex) structs. + [{"a": np.array(3), "b": 4}, {"a": np.array(5), "b": 6}], + num_items=2, + ) + check( + batch["test_col"], + [{"a": np.array(3), "b": 4}, {"a": np.array(5), "b": 6}], + ) + # In a new column (test_col_2), store some already batched items. + # This way, you may avoid having to disassemble an already batched item + # (e.g. a numpy array of shape (10, 2)) into its individual items (e.g. + # split the array into a list of len=10) and then adding these individually. + # The performance gains may be quite large when providing already batched + # items (such as numpy arrays with a batch dim): + ConnectorV2.add_n_batch_items( + batch, + "test_col_2", + # One (complex) already batched struct. + {"a": np.array([3, 5]), "b": np.array([4, 6])}, + num_items=2, + ) + # Add more already batched items (this time with a different batch size) + ConnectorV2.add_n_batch_items( + batch, + "test_col_2", + {"a": np.array([7, 7, 7]), "b": np.array([8, 8, 8])}, + num_items=3, # <- in this case, this must be the batch size + ) + check( + batch["test_col_2"], + [ + {"a": np.array([3, 5]), "b": np.array([4, 6])}, + {"a": np.array([7, 7, 7]), "b": np.array([8, 8, 8])}, + ], + ) + + # Single-agent case (SingleAgentEpisode provided) -> Store data in a list + # under the keys: `column` -> `(,)`: + batch = {} + episode = SingleAgentEpisode( + id_="SA-EPS0", + observations=[0, 1, 2, 3], + actions=[1, 2, 3], + rewards=[1.0, 2.0, 3.0], + ) + ConnectorV2.add_n_batch_items( + batch=batch, + column="test_col", + items_to_add=[5, 6, 7], + num_items=3, + single_agent_episode=episode, + ) + check(batch, { + "test_col": {("SA-EPS0",): [5, 6, 7]}, + }) + + # Multi-agent case (SingleAgentEpisode provided that has `agent_id` and + # `module_id` information) -> Store data in a list under the keys: + # `column` -> `(,,)`: + batch = {} + ma_episode = MultiAgentEpisode( + id_="MA-EPS1", + observations=[ + {"ag0": 0, "ag1": 1}, {"ag0": 2, "ag1": 4} + ], + actions=[{"ag0": 0, "ag1": 1}], + rewards=[{"ag0": -0.1, "ag1": -0.2}], + # ag0 maps to mod0, ag1 maps to mod1, etc.. + agent_to_module_mapping_fn=lambda aid, eps: f"mod{aid[2:]}", + ) + ConnectorV2.add_batch_item( + batch, + "test_col", + item_to_add=5, + single_agent_episode=ma_episode.agent_episodes["ag0"], + ) + ConnectorV2.add_batch_item( + batch, + "test_col", + item_to_add=6, + single_agent_episode=ma_episode.agent_episodes["ag0"], + ) + ConnectorV2.add_batch_item( + batch, + "test_col_2", + item_to_add=10, + single_agent_episode=ma_episode.agent_episodes["ag1"], + ) + check( + batch, + { + "test_col": {("MA-EPS1", "ag0", "mod0"): [5, 6]}, + "test_col_2": {("MA-EPS1", "ag1", "mod1"): [10]}, + }, + ) + + Args: + batch: The batch to store n `items_to_add` in. + column: The column name (str) within the `batch` to store `item_to_add` + under. + items_to_add: The list of data items to store in the batch OR an already + batched (possibly nested) struct. In the latter case, the `items_to_add` + will be appended to possibly existing data under the same `column` + as-is. A subsequent `BatchIndividualItems` ConnectorV2 piece will + recognize this and batch the data properly into a single (batched) item. + This is much faster than first splitting up `items_to_add` and then + adding each item individually. + num_items: The number of items in `items_to_add`. This arg is mostly for + asserting the correct usage of this method by checking, whether the + given data in `items_to_add` really has the right amount of individual + items. + single_agent_episode: An optional SingleAgentEpisode. + If provided and its `agent_id` and `module_id` properties are None, + creates a further sub dictionary under `column`, mapping from + `(,)` to a list of data items (to which `items_to_add` will + be appended in this call). + If provided and its `agent_id` and `module_id` properties are NOT None, + creates a further sub dictionary under `column`, mapping from + `(,,,)` to a list of data items (to which + `items_to_add` will be appended in this call). + If not provided, will append `items_to_add` to a list directly under + `column`. + """ + # Process n list items by calling `add_batch_item` on each of them individually. + if isinstance(items_to_add, list): + if len(items_to_add) != num_items: + raise ValueError( + f"Mismatch between `num_items` ({num_items}) and the length " + f"of the provided list ({len(items_to_add)}) in " + f"{ConnectorV2.__name__}.add_n_batch_items()!" + ) + for item in items_to_add: + ConnectorV2.add_batch_item( + batch=batch, + column=column, + item_to_add=item, + single_agent_episode=single_agent_episode, + ) + return + + # Process a batched (possibly complex) struct. + # We could just unbatch the item (split it into a list) and then add each + # individual item to our `batch`. However, this comes with a heavy performance + # penalty. Instead, we tag the thus added array(s) here as "_has_batch_dim=True" + # and then know that when batching the entire list under the respective + # (eps_id, agent_id, module_id)-tuple key, we need to concatenate, not stack + # the items in there. + def _tag(s): + return BatchedNdArray(s) + + ConnectorV2.add_batch_item( + batch=batch, + column=column, + # Convert given input into BatchedNdArray(s) such that the `batch` utility + # knows that it'll have to concat, not stack. + item_to_add=tree.map_structure(_tag, items_to_add), + single_agent_episode=single_agent_episode, + ) + + @staticmethod + def foreach_batch_item_change_in_place( + batch: Dict[str, Any], + column: Union[str, List[str], Tuple[str]], + func: Callable[ + [Any, Optional[int], Optional[AgentID], Optional[ModuleID]], Any + ], + ) -> None: + """Runs the provided `func` on all items under one or more columns in the batch. + + Use this method to conveniently loop through all items in a batch + and transform them in place. + + `func` takes the following as arguments: + - The item itself. If column is a list of column names, this argument is a tuple + of items. + - The EpisodeID. This value might be None. + - The AgentID. This value might be None in the single-agent case. + - The ModuleID. This value might be None in the single-agent case. + + The return value(s) of `func` are used to directly override the values in the + given `batch`. + + Args: + batch: The batch to process in-place. + column: A single column name (str) or a list thereof. If a list is provided, + the first argument to `func` is a tuple of items. If a single + str is provided, the first argument to `func` is an individual + item. + func: The function to call on each item or tuple of item(s). + + .. testcode:: + + from ray.rllib.connectors.connector_v2 import ConnectorV2 + from ray.rllib.utils.test_utils import check + + # Simple case: Batch items are in lists directly under their column names. + batch = { + "col1": [0, 1, 2, 3], + "col2": [0, -1, -2, -3], + } + # Increase all ints by 1. + ConnectorV2.foreach_batch_item_change_in_place( + batch=batch, + column="col1", + func=lambda item, *args: item + 1, + ) + check(batch["col1"], [1, 2, 3, 4]) + + # Further increase all ints by 1 in col1 and flip sign in col2. + ConnectorV2.foreach_batch_item_change_in_place( + batch=batch, + column=["col1", "col2"], + func=(lambda items, *args: (items[0] + 1, -items[1])), + ) + check(batch["col1"], [2, 3, 4, 5]) + check(batch["col2"], [0, 1, 2, 3]) + + # Single-agent case: Batch items are in lists under (eps_id,)-keys in a dict + # under their column names. + batch = { + "col1": { + ("eps1",): [0, 1, 2, 3], + ("eps2",): [400, 500, 600], + }, + } + # Increase all ints of eps1 by 1 and divide all ints of eps2 by 100. + ConnectorV2.foreach_batch_item_change_in_place( + batch=batch, + column="col1", + func=lambda item, eps_id, *args: ( + item + 1 if eps_id == "eps1" else item / 100 + ), + ) + check(batch["col1"], { + ("eps1",): [1, 2, 3, 4], + ("eps2",): [4, 5, 6], + }) + + # Multi-agent case: Batch items are in lists under + # (eps_id, agent_id, module_id)-keys in a dict + # under their column names. + batch = { + "col1": { + ("eps1", "ag1", "mod1"): [1, 2, 3, 4], + ("eps2", "ag1", "mod2"): [400, 500, 600], + ("eps2", "ag2", "mod3"): [-1, -2, -3, -4, -5], + }, + } + # Decrease all ints of "eps1" by 1, divide all ints of "mod2" by 100, and + # flip sign of all ints of "ag2". + ConnectorV2.foreach_batch_item_change_in_place( + batch=batch, + column="col1", + func=lambda item, eps_id, ag_id, mod_id: ( + item - 1 + if eps_id == "eps1" + else item / 100 + if mod_id == "mod2" + else -item + ), + ) + check(batch["col1"], { + ("eps1", "ag1", "mod1"): [0, 1, 2, 3], + ("eps2", "ag1", "mod2"): [4, 5, 6], + ("eps2", "ag2", "mod3"): [1, 2, 3, 4, 5], + }) + """ + data_to_process = [batch.get(c) for c in force_list(column)] + single_col = isinstance(column, str) + if any(d is None for d in data_to_process): + raise ValueError( + f"Invalid column name(s) ({column})! One or more not found in " + f"given batch. Found columns {list(batch.keys())}." + ) + + # Simple case: Data items are stored in a list directly under the column + # name(s). + if isinstance(data_to_process[0], list): + for list_pos, data_tuple in enumerate(zip(*data_to_process)): + results = func( + data_tuple[0] if single_col else data_tuple, + None, # episode_id + None, # agent_id + None, # module_id + ) + # Tuple'ize results if single_col. + results = (results,) if single_col else results + for col_slot, result in enumerate(force_list(results)): + data_to_process[col_slot][list_pos] = result + # Single-agent/multi-agent cases. + else: + for key, d0_list in data_to_process[0].items(): + # Multi-agent case: There is a dict mapping from a + # (eps id, AgentID, ModuleID)-tuples to lists of individual data items. + if len(key) == 3: + eps_id, agent_id, module_id = key + # Single-agent case: There is a dict mapping from a (eps_id,)-tuple + # to lists of individual data items. + # AgentID and ModuleID are both None. + else: + eps_id = key[0] + agent_id = module_id = None + other_lists = [d[key] for d in data_to_process[1:]] + for list_pos, data_tuple in enumerate(zip(d0_list, *other_lists)): + results = func( + data_tuple[0] if single_col else data_tuple, + eps_id, + agent_id, + module_id, + ) + # Tuple'ize results if single_col. + results = (results,) if single_col else results + for col_slot, result in enumerate(results): + data_to_process[col_slot][key][list_pos] = result + + @staticmethod + def switch_batch_from_column_to_module_ids( + batch: Dict[str, Dict[ModuleID, Any]] + ) -> Dict[ModuleID, Dict[str, Any]]: + """Switches the first two levels of a `col_name -> ModuleID -> data` type batch. + + Assuming that the top level consists of column names as keys and the second + level (under these columns) consists of ModuleID keys, the resulting batch + will have these two reversed and thus map ModuleIDs to dicts mapping column + names to data items. + + .. testcode:: + + from ray.rllib.utils.test_utils import check + + batch = { + "obs": {"module_0": [1, 2, 3]}, + "actions": {"module_0": [4, 5, 6], "module_1": [7]}, + } + switched_batch = ConnectorV2.switch_batch_from_column_to_module_ids(batch) + check( + switched_batch, + { + "module_0": {"obs": [1, 2, 3], "actions": [4, 5, 6]}, + "module_1": {"actions": [7]}, + }, + ) + + Args: + batch: The batch to switch from being column name based (then ModuleIDs) + to being ModuleID based (then column names). + + Returns: + A new batch dict mapping ModuleIDs to dicts mapping column names (e.g. + "obs") to data. + """ + module_data = defaultdict(dict) + for column, column_data in batch.items(): + for module_id, data in column_data.items(): + module_data[module_id][column] = data + return dict(module_data) + + @override(Checkpointable) + def get_state( + self, + components: Optional[Union[str, Collection[str]]] = None, + *, + not_components: Optional[Union[str, Collection[str]]] = None, + **kwargs, + ) -> StateDict: + return {} + + @override(Checkpointable) + def set_state(self, state: StateDict) -> None: + pass + + @override(Checkpointable) + def get_ctor_args_and_kwargs(self) -> Tuple[Tuple, Dict[str, Any]]: + return ( + (), # *args + self._ctor_kwargs, # **kwargs + ) + + def reset_state(self) -> None: + """Resets the state of this ConnectorV2 to some initial value. + + Note that this may NOT be the exact state that this ConnectorV2 was originally + constructed with. + """ + return + + def merge_states(self, states: List[Dict[str, Any]]) -> Dict[str, Any]: + """Computes a resulting state given self's state and a list of other states. + + Algorithms should use this method for merging states between connectors + running on parallel EnvRunner workers. For example, to synchronize the connector + states of n remote workers and a local worker, one could: + - Gather all remote worker connector states in a list. + - Call `self.merge_states()` on the local worker passing it the states list. + - Broadcast the resulting local worker's connector state back to all remote + workers. After this, all workers (including the local one) hold a + merged/synchronized new connecto state. + + Args: + states: The list of n other ConnectorV2 states to merge with self's state + into a single resulting state. + + Returns: + The resulting state dict. + """ + return {} + + @property + def observation_space(self): + """Getter for our (output) observation space. + + Logic: Use user provided space (if set via `observation_space` setter) + otherwise, use the same as the input space, assuming this connector piece + does not alter the space. + """ + return self._observation_space + + @property + def action_space(self): + """Getter for our (output) action space. + + Logic: Use user provided space (if set via `action_space` setter) + otherwise, use the same as the input space, assuming this connector piece + does not alter the space. + """ + return self._action_space + + @property + def input_observation_space(self): + return self._input_observation_space + + @input_observation_space.setter + def input_observation_space(self, value): + self._input_observation_space = value + if value is not None: + self._observation_space = self.recompute_output_observation_space( + value, self.input_action_space + ) + + @property + def input_action_space(self): + return self._input_action_space + + @input_action_space.setter + def input_action_space(self, value): + self._input_action_space = value + if value is not None: + self._action_space = self.recompute_output_action_space( + self.input_observation_space, value + ) + + def __str__(self, indentation: int = 0): + return " " * indentation + self.__class__.__name__ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d513e596446c3d51ee0b0a065ca4cc434caf65ed --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/__init__.py @@ -0,0 +1,40 @@ +from ray.rllib.connectors.common.add_observations_from_episodes_to_batch import ( + AddObservationsFromEpisodesToBatch, +) +from ray.rllib.connectors.common.add_states_from_episodes_to_batch import ( + AddStatesFromEpisodesToBatch, +) +from ray.rllib.connectors.common.add_time_dim_to_batch_and_zero_pad import ( + AddTimeDimToBatchAndZeroPad, +) +from ray.rllib.connectors.common.agent_to_module_mapping import AgentToModuleMapping +from ray.rllib.connectors.common.batch_individual_items import BatchIndividualItems +from ray.rllib.connectors.common.numpy_to_tensor import NumpyToTensor +from ray.rllib.connectors.env_to_module.env_to_module_pipeline import ( + EnvToModulePipeline, +) +from ray.rllib.connectors.env_to_module.flatten_observations import ( + FlattenObservations, +) +from ray.rllib.connectors.env_to_module.mean_std_filter import MeanStdFilter +from ray.rllib.connectors.env_to_module.prev_actions_prev_rewards import ( + PrevActionsPrevRewards, +) +from ray.rllib.connectors.env_to_module.write_observations_to_episodes import ( + WriteObservationsToEpisodes, +) + + +__all__ = [ + "AddObservationsFromEpisodesToBatch", + "AddStatesFromEpisodesToBatch", + "AddTimeDimToBatchAndZeroPad", + "AgentToModuleMapping", + "BatchIndividualItems", + "EnvToModulePipeline", + "FlattenObservations", + "MeanStdFilter", + "NumpyToTensor", + "PrevActionsPrevRewards", + "WriteObservationsToEpisodes", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..190e9bd65183a5c12cf45494be97ae420b8501b9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/__pycache__/env_to_module_pipeline.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/__pycache__/env_to_module_pipeline.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75b28f66febde85baf82a65a02042bc113317c7f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/__pycache__/env_to_module_pipeline.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/__pycache__/flatten_observations.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/__pycache__/flatten_observations.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9536c1d427bcca08a889ae02ef8162a47b0f455d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/__pycache__/flatten_observations.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/__pycache__/frame_stacking.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/__pycache__/frame_stacking.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e2302e4a799b8bf2d9db388db4f8e94d0660e14 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/__pycache__/frame_stacking.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/__pycache__/mean_std_filter.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/__pycache__/mean_std_filter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea3c5d7b6d4f4e5213b0b1f33aef3c5e2f6df3bf Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/__pycache__/mean_std_filter.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/__pycache__/observation_preprocessor.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/__pycache__/observation_preprocessor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca677d70f6f4fb8938f84d1c509b7735d49856b9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/__pycache__/observation_preprocessor.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/__pycache__/prev_actions_prev_rewards.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/__pycache__/prev_actions_prev_rewards.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d17bbdc1beb3771cee4f16a0db1a2b206cea3b21 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/__pycache__/prev_actions_prev_rewards.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/__pycache__/write_observations_to_episodes.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/__pycache__/write_observations_to_episodes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e9950a9ed34f632107a4affc5596aac06686c64 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/__pycache__/write_observations_to_episodes.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/env_to_module_pipeline.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/env_to_module_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..04a5389737e1ffded64793b77b48207687ad6af0 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/env_to_module_pipeline.py @@ -0,0 +1,55 @@ +from typing import Any, Dict, List, Optional + +from ray.rllib.connectors.connector_pipeline_v2 import ConnectorPipelineV2 +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.metrics import ( + ENV_TO_MODULE_SUM_EPISODES_LENGTH_IN, + ENV_TO_MODULE_SUM_EPISODES_LENGTH_OUT, +) +from ray.rllib.utils.metrics.metrics_logger import MetricsLogger +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class EnvToModulePipeline(ConnectorPipelineV2): + @override(ConnectorPipelineV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Optional[Dict[str, Any]] = None, + episodes: List[EpisodeType], + explore: bool, + shared_data: Optional[dict] = None, + metrics: Optional[MetricsLogger] = None, + **kwargs, + ): + # Log the sum of lengths of all episodes incoming. + if metrics: + metrics.log_value( + ENV_TO_MODULE_SUM_EPISODES_LENGTH_IN, + sum(map(len, episodes)), + ) + + # Make sure user does not necessarily send initial input into this pipeline. + # Might just be empty and to be populated from `episodes`. + ret = super().__call__( + rl_module=rl_module, + batch=batch if batch is not None else {}, + episodes=episodes, + explore=explore, + shared_data=shared_data if shared_data is not None else {}, + metrics=metrics, + **kwargs, + ) + + # Log the sum of lengths of all episodes outgoing. + if metrics: + metrics.log_value( + ENV_TO_MODULE_SUM_EPISODES_LENGTH_OUT, + sum(map(len, episodes)), + ) + + return ret diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/flatten_observations.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/flatten_observations.py new file mode 100644 index 0000000000000000000000000000000000000000..986341685d5e4dc8ff7bce163e49c5d1fe22308e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/flatten_observations.py @@ -0,0 +1,208 @@ +from typing import Any, Collection, Dict, List, Optional + +import gymnasium as gym +from gymnasium.spaces import Box +import numpy as np +import tree # pip install dm_tree + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.numpy import flatten_inputs_to_1d_tensor +from ray.rllib.utils.spaces.space_utils import get_base_struct_from_space +from ray.rllib.utils.typing import AgentID, EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class FlattenObservations(ConnectorV2): + """A connector piece that flattens all observation components into a 1D array. + + - Should be used only in env-to-module pipelines. + - Works directly on the incoming episodes list and changes the last observation + in-place (write the flattened observation back into the episode). + - This connector does NOT alter the incoming batch (`data`) when called. + - This connector does NOT work in a `LearnerConnectorPipeline` because it requires + the incoming episodes to still be ongoing (in progress) as it only alters the + latest observation, not all observations in an episode. + + .. testcode:: + + import gymnasium as gym + import numpy as np + + from ray.rllib.connectors.env_to_module import FlattenObservations + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + from ray.rllib.utils.test_utils import check + + # Some arbitrarily nested, complex observation space. + obs_space = gym.spaces.Dict({ + "a": gym.spaces.Box(-10.0, 10.0, (), np.float32), + "b": gym.spaces.Tuple([ + gym.spaces.Discrete(2), + gym.spaces.Box(-1.0, 1.0, (2, 1), np.float32), + ]), + "c": gym.spaces.MultiDiscrete([2, 3]), + }) + act_space = gym.spaces.Discrete(2) + + # Two example episodes, both with initial (reset) observations coming from the + # above defined observation space. + episode_1 = SingleAgentEpisode( + observations=[ + { + "a": np.array(-10.0, np.float32), + "b": (1, np.array([[-1.0], [-1.0]], np.float32)), + "c": np.array([0, 2]), + }, + ], + ) + episode_2 = SingleAgentEpisode( + observations=[ + { + "a": np.array(10.0, np.float32), + "b": (0, np.array([[1.0], [1.0]], np.float32)), + "c": np.array([1, 1]), + }, + ], + ) + + # Construct our connector piece. + connector = FlattenObservations(obs_space, act_space) + + # Call our connector piece with the example data. + output_batch = connector( + rl_module=None, # This connector works without an RLModule. + batch={}, # This connector does not alter the input batch. + episodes=[episode_1, episode_2], + explore=True, + shared_data={}, + ) + + # The connector does not alter the data and acts as pure pass-through. + check(output_batch, {}) + + # The connector has flattened each item in the episodes to a 1D tensor. + check( + episode_1.get_observations(0), + # box() disc(2). box(2, 1). multidisc(2, 3)........ + np.array([-10.0, 0.0, 1.0, -1.0, -1.0, 1.0, 0.0, 0.0, 0.0, 1.0]), + ) + check( + episode_2.get_observations(0), + # box() disc(2). box(2, 1). multidisc(2, 3)........ + np.array([10.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0]), + ) + """ + + @override(ConnectorV2) + def recompute_output_observation_space( + self, + input_observation_space, + input_action_space, + ) -> gym.Space: + self._input_obs_base_struct = get_base_struct_from_space( + self.input_observation_space + ) + if self._multi_agent: + spaces = {} + for agent_id, space in self._input_obs_base_struct.items(): + if self._agent_ids and agent_id not in self._agent_ids: + spaces[agent_id] = self._input_obs_base_struct[agent_id] + else: + sample = flatten_inputs_to_1d_tensor( + tree.map_structure( + lambda s: s.sample(), + self._input_obs_base_struct[agent_id], + ), + self._input_obs_base_struct[agent_id], + batch_axis=False, + ) + spaces[agent_id] = Box( + float("-inf"), float("inf"), (len(sample),), np.float32 + ) + return gym.spaces.Dict(spaces) + else: + sample = flatten_inputs_to_1d_tensor( + tree.map_structure( + lambda s: s.sample(), + self._input_obs_base_struct, + ), + self._input_obs_base_struct, + batch_axis=False, + ) + return Box(float("-inf"), float("inf"), (len(sample),), np.float32) + + def __init__( + self, + input_observation_space: Optional[gym.Space] = None, + input_action_space: Optional[gym.Space] = None, + *, + multi_agent: bool = False, + agent_ids: Optional[Collection[AgentID]] = None, + **kwargs, + ): + """Initializes a FlattenObservations instance. + + Args: + multi_agent: Whether this connector operates on multi-agent observations, + in which case, the top-level of the Dict space (where agent IDs are + mapped to individual agents' observation spaces) is left as-is. + agent_ids: If multi_agent is True, this argument defines a collection of + AgentIDs for which to flatten. AgentIDs not in this collection are + ignored. + If None, flatten observations for all AgentIDs. None is the default. + """ + self._input_obs_base_struct = None + self._multi_agent = multi_agent + self._agent_ids = agent_ids + + super().__init__(input_observation_space, input_action_space, **kwargs) + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + for sa_episode in self.single_agent_episode_iterator( + episodes, agents_that_stepped_only=True + ): + last_obs = sa_episode.get_observations(-1) + + if self._multi_agent: + if ( + self._agent_ids is not None + and sa_episode.agent_id not in self._agent_ids + ): + flattened_obs = last_obs + else: + flattened_obs = flatten_inputs_to_1d_tensor( + inputs=last_obs, + # In the multi-agent case, we need to use the specific agent's + # space struct, not the multi-agent observation space dict. + spaces_struct=self._input_obs_base_struct[sa_episode.agent_id], + # Our items are individual observations (no batch axis present). + batch_axis=False, + ) + else: + flattened_obs = flatten_inputs_to_1d_tensor( + inputs=last_obs, + spaces_struct=self._input_obs_base_struct, + # Our items are individual observations (no batch axis present). + batch_axis=False, + ) + + # Write new observation directly back into the episode. + sa_episode.set_observations(at_indices=-1, new_data=flattened_obs) + # We set the Episode's observation space to ours so that we can safely + # set the last obs to the new value (without causing a space mismatch + # error). + sa_episode.observation_space = self.observation_space + + return batch diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/frame_stacking.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/frame_stacking.py new file mode 100644 index 0000000000000000000000000000000000000000..d6e7dea498a5362a1519fd893ae8f1d7a41f7d9e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/frame_stacking.py @@ -0,0 +1,6 @@ +from functools import partial + +from ray.rllib.connectors.common.frame_stacking import FrameStacking + + +FrameStackingEnvToModule = partial(FrameStacking, as_learner_connector=False) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/mean_std_filter.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/mean_std_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..39a452657f5dc6a153de71ee75463b85abcd79f7 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/mean_std_filter.py @@ -0,0 +1,253 @@ +from typing import Any, Collection, Dict, List, Optional, Union + +import gymnasium as gym +from gymnasium.spaces import Discrete, MultiDiscrete +import numpy as np +import tree + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.filter import MeanStdFilter as _MeanStdFilter, RunningStat +from ray.rllib.utils.spaces.space_utils import get_base_struct_from_space +from ray.rllib.utils.typing import AgentID, EpisodeType, StateDict +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class MeanStdFilter(ConnectorV2): + """A connector used to mean-std-filter observations. + + Incoming observations are filtered such that the output of this filter is on + average 0.0 and has a standard deviation of 1.0. If the observation space is + a (possibly nested) dict, this filtering is applied separately per element of + the observation space (except for discrete- and multi-discrete elements, which + are left as-is). + + This connector is stateful as it continues to update its internal stats on mean + and std values as new data is pushed through it (unless `update_stats` is False). + """ + + @override(ConnectorV2) + def recompute_output_observation_space( + self, + input_observation_space: gym.Space, + input_action_space: gym.Space, + ) -> gym.Space: + _input_observation_space_struct = get_base_struct_from_space( + input_observation_space + ) + + # Adjust our observation space's Boxes (only if clipping is active). + _observation_space_struct = tree.map_structure( + lambda s: ( + s + if not isinstance(s, gym.spaces.Box) + else gym.spaces.Box( + low=-self.clip_by_value, + high=self.clip_by_value, + shape=s.shape, + dtype=s.dtype, + ) + ), + _input_observation_space_struct, + ) + if isinstance(input_observation_space, (gym.spaces.Dict, gym.spaces.Tuple)): + return type(input_observation_space)(_observation_space_struct) + else: + return _observation_space_struct + + def __init__( + self, + *, + multi_agent: bool = False, + de_mean_to_zero: bool = True, + de_std_to_one: bool = True, + clip_by_value: Optional[float] = 10.0, + update_stats: bool = True, + **kwargs, + ): + """Initializes a MeanStdFilter instance. + + Args: + multi_agent: Whether this is a connector operating on a multi-agent + observation space mapping AgentIDs to individual agents' observations. + de_mean_to_zero: Whether to transform the mean values of the output data to + 0.0. This is done by subtracting the incoming data by the currently + stored mean value. + de_std_to_one: Whether to transform the standard deviation values of the + output data to 1.0. This is done by dividing the incoming data by the + currently stored std value. + clip_by_value: If not None, clip the incoming data within the interval: + [-clip_by_value, +clip_by_value]. + update_stats: Whether to update the internal mean and std stats with each + incoming sample (with each `__call__()`) or not. You should set this to + False if you would like to perform inference in a production + environment, without continuing to "learn" stats from new data. + """ + super().__init__(**kwargs) + + self._multi_agent = multi_agent + + # We simply use the old MeanStdFilter until non-connector env_runner is fully + # deprecated to avoid duplicate code + self.de_mean_to_zero = de_mean_to_zero + self.de_std_to_one = de_std_to_one + self.clip_by_value = clip_by_value + self._update_stats = update_stats + + self._filters: Optional[Dict[AgentID, _MeanStdFilter]] = None + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + persistent_data: Optional[dict] = None, + **kwargs, + ) -> Any: + if self._filters is None: + self._init_new_filters() + + # This connector acts as a classic preprocessor. We process and then replace + # observations inside the episodes directly. Thus, all following connectors + # will only see and operate on the already normalized data (w/o having access + # anymore to the original observations). + for sa_episode in self.single_agent_episode_iterator(episodes): + sa_obs = sa_episode.get_observations(indices=-1) + try: + normalized_sa_obs = self._filters[sa_episode.agent_id]( + sa_obs, update=self._update_stats + ) + except KeyError: + raise KeyError( + "KeyError trying to access a filter by agent ID " + f"`{sa_episode.agent_id}`! You probably did NOT pass the " + f"`multi_agent=True` flag into the `MeanStdFilter()` constructor. " + ) + sa_episode.set_observations(at_indices=-1, new_data=normalized_sa_obs) + # We set the Episode's observation space to ours so that we can safely + # set the last obs to the new value (without causing a space mismatch + # error). + sa_episode.observation_space = self.observation_space + + # Leave `batch` as is. RLlib's default connector will automatically + # populate the OBS column therein from the episodes' now transformed + # observations. + return batch + + @override(ConnectorV2) + def get_state( + self, + components: Optional[Union[str, Collection[str]]] = None, + *, + not_components: Optional[Union[str, Collection[str]]] = None, + **kwargs, + ) -> StateDict: + if self._filters is None: + self._init_new_filters() + return self._get_state_from_filters(self._filters) + + @override(ConnectorV2) + def set_state(self, state: StateDict) -> None: + if self._filters is None: + self._init_new_filters() + for agent_id, agent_state in state.items(): + filter = self._filters[agent_id] + filter.shape = agent_state["shape"] + filter.demean = agent_state["de_mean_to_zero"] + filter.destd = agent_state["de_std_to_one"] + filter.clip = agent_state["clip_by_value"] + filter.running_stats = tree.unflatten_as( + filter.shape, + [RunningStat.from_state(s) for s in agent_state["running_stats"]], + ) + # Do not update the buffer. + + @override(ConnectorV2) + def reset_state(self) -> None: + """Creates copy of current state and resets accumulated state""" + if not self._update_stats: + raise ValueError( + f"State of {type(self).__name__} can only be changed when " + f"`update_stats` was set to False." + ) + self._init_new_filters() + + @override(ConnectorV2) + def merge_states(self, states: List[Dict[str, Any]]) -> Dict[str, Any]: + if self._filters is None: + self._init_new_filters() + + # Make sure data is uniform across given states. + ref = next(iter(states[0].values())) + + for state in states: + for agent_id, agent_state in state.items(): + assert ( + agent_state["shape"] == ref["shape"] + and agent_state["de_mean_to_zero"] == ref["de_mean_to_zero"] + and agent_state["de_std_to_one"] == ref["de_std_to_one"] + and agent_state["clip_by_value"] == ref["clip_by_value"] + ) + + _filter = _MeanStdFilter( + ref["shape"], + demean=ref["de_mean_to_zero"], + destd=ref["de_std_to_one"], + clip=ref["clip_by_value"], + ) + # Override running stats of the filter with the ones stored in + # `agent_state`. + _filter.buffer = tree.unflatten_as( + agent_state["shape"], + [ + RunningStat.from_state(stats) + for stats in agent_state["running_stats"] + ], + ) + + # Leave the buffers as-is, since they should always only reflect + # what has happened on the particular env runner. + self._filters[agent_id].apply_changes(_filter, with_buffer=False) + + return MeanStdFilter._get_state_from_filters(self._filters) + + def _init_new_filters(self): + filter_shape = tree.map_structure( + lambda s: ( + None if isinstance(s, (Discrete, MultiDiscrete)) else np.array(s.shape) + ), + get_base_struct_from_space(self.input_observation_space), + ) + if not self._multi_agent: + filter_shape = {None: filter_shape} + + del self._filters + self._filters = { + agent_id: _MeanStdFilter( + agent_filter_shape, + demean=self.de_mean_to_zero, + destd=self.de_std_to_one, + clip=self.clip_by_value, + ) + for agent_id, agent_filter_shape in filter_shape.items() + } + + @staticmethod + def _get_state_from_filters(filters: Dict[AgentID, Dict[str, Any]]): + ret = {} + for agent_id, agent_filter in filters.items(): + ret[agent_id] = { + "shape": agent_filter.shape, + "de_mean_to_zero": agent_filter.demean, + "de_std_to_one": agent_filter.destd, + "clip_by_value": agent_filter.clip, + "running_stats": [ + s.to_state() for s in tree.flatten(agent_filter.running_stats) + ], + } + return ret diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/observation_preprocessor.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/observation_preprocessor.py new file mode 100644 index 0000000000000000000000000000000000000000..2910173500ad8a8adbe1e728d3be6df5ff82d6e9 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/observation_preprocessor.py @@ -0,0 +1,181 @@ +import abc +from typing import Any, Dict, List, Optional + +import gymnasium as gym + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.env.multi_agent_episode import MultiAgentEpisode +from ray.rllib.env.single_agent_episode import SingleAgentEpisode +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class SingleAgentObservationPreprocessor(ConnectorV2, abc.ABC): + """Env-to-module connector preprocessing the most recent single-agent observation. + + This is a convenience class that simplifies the writing of few-step preprocessor + connectors. + + Note that this class also works in a multi-agent setup, in which case RLlib + separately calls this connector piece with each agents' observation and + `SingleAgentEpisode` object. + + Users must implement the `preprocess()` method, which simplifies the usual procedure + of extracting some data from a list of episodes and adding it to the batch to a mere + "old-observation --transform--> return new-observation" step. + """ + + @override(ConnectorV2) + def recompute_output_observation_space( + self, + input_observation_space: gym.Space, + input_action_space: gym.Space, + ) -> gym.Space: + # Users should override this method only in case the + # `SingleAgentObservationPreprocessor` changes the observation space of the + # pipeline. In this case, return the new observation space based on the + # incoming one (`input_observation_space`). + return super().recompute_output_observation_space( + input_observation_space, input_action_space + ) + + @abc.abstractmethod + def preprocess(self, observation, episode: SingleAgentEpisode): + """Override to implement the preprocessing logic. + + Args: + observation: A single (non-batched) observation item for a single agent to + be preprocessed by this connector. + episode: The `SingleAgentEpisode` instance, from which `observation` was + taken. You can extract information on the particular AgentID and the + ModuleID through `episode.agent_id` and `episode.module_id`. + + Returns: + The new observation for the agent after `observation` has been preprocessed. + """ + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + persistent_data: Optional[dict] = None, + **kwargs, + ) -> Any: + # We process and then replace observations inside the episodes directly. + # Thus, all following connectors will only see and operate on the already + # processed observation (w/o having access anymore to the original + # observations). + for sa_episode in self.single_agent_episode_iterator(episodes): + observation = sa_episode.get_observations(-1) + + # Process the observation and write the new observation back into the + # episode. + new_observation = self.preprocess( + observation=observation, + episode=sa_episode, + ) + sa_episode.set_observations(at_indices=-1, new_data=new_observation) + # We set the Episode's observation space to ours so that we can safely + # set the last obs to the new value (without causing a space mismatch + # error). + sa_episode.observation_space = self.observation_space + + # Leave `batch` as is. RLlib's default connector automatically populates + # the OBS column therein from the episodes' now transformed observations. + return batch + + +@PublicAPI(stability="alpha") +class MultiAgentObservationPreprocessor(ConnectorV2, abc.ABC): + """Env-to-module connector preprocessing the most recent multi-agent observation. + + The observation is always a dict of individual agents' observations. + + This is a convenience class that simplifies the writing of few-step preprocessor + connectors. + + Users must implement the `preprocess()` method, which simplifies the usual procedure + of extracting some data from a list of episodes and adding it to the batch to a mere + "old-observation --transform--> return new-observation" step. + """ + + @override(ConnectorV2) + def recompute_output_observation_space( + self, + input_observation_space: gym.Space, + input_action_space: gym.Space, + ) -> gym.Space: + # Users should override this method only in case the + # `MultiAgentObservationPreprocessor` changes the observation space of the + # pipeline. In this case, return the new observation space based on the + # incoming one (`input_observation_space`). + return super().recompute_output_observation_space( + input_observation_space, input_action_space + ) + + @abc.abstractmethod + def preprocess(self, observations, episode: MultiAgentEpisode): + """Override to implement the preprocessing logic. + + Args: + observations: An observation dict containing each stepping agents' + (non-batched) observation to be preprocessed by this connector. + episode: The MultiAgentEpisode instance, where the `observation` dict + originated from. + + Returns: + The new multi-agent observation dict after `observations` has been + preprocessed. + """ + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + persistent_data: Optional[dict] = None, + **kwargs, + ) -> Any: + # We process and then replace observations inside the episodes directly. + # Thus, all following connectors will only see and operate on the already + # processed observation (w/o having access anymore to the original + # observations). + for ma_episode in episodes: + observations = ma_episode.get_observations(-1) + + # Process the observation and write the new observation back into the + # episode. + new_observation = self.preprocess( + observations=observations, + episode=ma_episode, + ) + # TODO (sven): Implement set_observations API for multi-agent episodes. + # For now, we'll hack it through the single agent APIs. + # ma_episode.set_observations(at_indices=-1, new_data=new_observation) + for agent_id, obs in new_observation.items(): + ma_episode.agent_episodes[agent_id].set_observations( + at_indices=-1, + new_data=obs, + ) + # We set the Episode's observation space to ours so that we can safely + # set the last obs to the new value (without causing a space mismatch + # error). + ma_episode.observation_space = self.observation_space + + # Leave `batch` as is. RLlib's default connector automatically populates + # the OBS column therein from the episodes' now transformed observations. + return batch + + +# Backward compatibility +ObservationPreprocessor = SingleAgentObservationPreprocessor diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/prev_actions_prev_rewards.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/prev_actions_prev_rewards.py new file mode 100644 index 0000000000000000000000000000000000000000..35e29d02a5214938ee175129eb49787a829b0df4 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/prev_actions_prev_rewards.py @@ -0,0 +1,168 @@ +from typing import Any, Dict, List, Optional + +import gymnasium as gym +from gymnasium.spaces import Box +import numpy as np + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.spaces.space_utils import ( + batch as batch_fn, + flatten_to_single_ndarray, +) +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class PrevActionsPrevRewards(ConnectorV2): + """A connector piece that adds previous rewards and actions to the input obs. + + - Requires Columns.OBS to be already a part of the batch. + - This connector makes the assumption that under the Columns.OBS key in batch, + there is either a list of individual env observations to be flattened (single-agent + case) or a dict mapping (AgentID, ModuleID)-tuples to lists of data items to be + flattened (multi-agent case). + - Converts Columns.OBS data into a dict (or creates a sub-dict if obs are + already a dict), and adds "prev_rewards" and "prev_actions" + to this dict. The original observations are stored under the self.ORIG_OBS_KEY in + that dict. + - If your RLModule does not handle dict inputs, you will have to plug in an + `FlattenObservations` connector piece after this one. + - Does NOT work in a Learner pipeline as it operates on individual observation + items (as opposed to batched/time-ranked data). + - Therefore, assumes that the altered (flattened) observations will be written + back into the episode by a later connector piece in the env-to-module pipeline + (which this piece is part of as well). + - Only reads reward- and action information from the given list of Episode objects. + - Does NOT write any observations (or other data) to the given Episode objects. + """ + + ORIG_OBS_KEY = "_orig_obs" + PREV_ACTIONS_KEY = "prev_n_actions" + PREV_REWARDS_KEY = "prev_n_rewards" + + @override(ConnectorV2) + def recompute_output_observation_space( + self, + input_observation_space: gym.Space, + input_action_space: gym.Space, + ) -> gym.Space: + if self._multi_agent: + ret = {} + for agent_id, obs_space in input_observation_space.spaces.items(): + act_space = input_action_space[agent_id] + ret[agent_id] = self._convert_individual_space(obs_space, act_space) + return gym.spaces.Dict(ret) + else: + return self._convert_individual_space( + input_observation_space, input_action_space + ) + + def __init__( + self, + input_observation_space: Optional[gym.Space] = None, + input_action_space: Optional[gym.Space] = None, + *, + multi_agent: bool = False, + n_prev_actions: int = 1, + n_prev_rewards: int = 1, + **kwargs, + ): + """Initializes a PrevActionsPrevRewards instance. + + Args: + multi_agent: Whether this is a connector operating on a multi-agent + observation space mapping AgentIDs to individual agents' observations. + n_prev_actions: The number of previous actions to include in the output + data. Discrete actions are ont-hot'd. If > 1, will concatenate the + individual action tensors. + n_prev_rewards: The number of previous rewards to include in the output + data. + """ + super().__init__( + input_observation_space=input_observation_space, + input_action_space=input_action_space, + **kwargs, + ) + + self._multi_agent = multi_agent + self.n_prev_actions = n_prev_actions + self.n_prev_rewards = n_prev_rewards + + # TODO: Move into input_observation_space setter + # Thus far, this connector piece only operates on discrete action spaces. + # act_spaces = [self.input_action_space] + # if self._multi_agent: + # act_spaces = self.input_action_space.spaces.values() + # if not all(isinstance(s, gym.spaces.Discrete) for s in act_spaces): + # raise ValueError( + # f"{type(self).__name__} only works on Discrete action spaces " + # f"thus far (or, for multi-agent, on Dict spaces mapping AgentIDs to " + # f"the individual agents' Discrete action spaces)!" + # ) + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Optional[Dict[str, Any]], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + for sa_episode in self.single_agent_episode_iterator( + episodes, agents_that_stepped_only=True + ): + # Episode is not numpy'ized yet and thus still operates on lists of items. + assert not sa_episode.is_numpy + + augmented_obs = {self.ORIG_OBS_KEY: sa_episode.get_observations(-1)} + + if self.n_prev_actions: + augmented_obs[self.PREV_ACTIONS_KEY] = flatten_to_single_ndarray( + batch_fn( + sa_episode.get_actions( + indices=slice(-self.n_prev_actions, None), + fill=0.0, + one_hot_discrete=True, + ) + ) + ) + + if self.n_prev_rewards: + augmented_obs[self.PREV_REWARDS_KEY] = np.array( + sa_episode.get_rewards( + indices=slice(-self.n_prev_rewards, None), + fill=0.0, + ) + ) + + # Write new observation directly back into the episode. + sa_episode.set_observations(at_indices=-1, new_data=augmented_obs) + # We set the Episode's observation space to ours so that we can safely + # set the last obs to the new value (without causing a space mismatch + # error). + sa_episode.observation_space = self.observation_space + + return batch + + def _convert_individual_space(self, obs_space, act_space): + return gym.spaces.Dict( + { + self.ORIG_OBS_KEY: obs_space, + # Currently only works for Discrete action spaces. + self.PREV_ACTIONS_KEY: Box( + 0.0, 1.0, (act_space.n * self.n_prev_actions,), np.float32 + ), + self.PREV_REWARDS_KEY: Box( + float("-inf"), + float("inf"), + (self.n_prev_rewards,), + np.float32, + ), + } + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/write_observations_to_episodes.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/write_observations_to_episodes.py new file mode 100644 index 0000000000000000000000000000000000000000..9b92da4984fd20cb8fe704692e1473eab4b925a4 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/env_to_module/write_observations_to_episodes.py @@ -0,0 +1,131 @@ +from typing import Any, Dict, List, Optional + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class WriteObservationsToEpisodes(ConnectorV2): + """Writes the observations from the batch into the running episodes. + + Note: This is one of the default env-to-module ConnectorV2 pieces that are added + automatically by RLlib into every env-to-module connector pipelines, unless + `config.add_default_connectors_to_env_to_module_pipeline` is set to False. + + The default env-to-module connector pipeline is: + [ + [0 or more user defined ConnectorV2 pieces], + AddObservationsFromEpisodesToBatch, + AddStatesFromEpisodesToBatch, + AgentToModuleMapping, # only in multi-agent setups! + BatchIndividualItems, + NumpyToTensor, + ] + + This ConnectorV2: + - Operates on a batch that already has observations in it and a list of Episode + objects. + - Writes the observation(s) from the batch to all the given episodes. Thereby + the number of observations in the batch must match the length of the list of + episodes given. + - Does NOT alter any observations (or other data) in the batch. + - Can only be used in an EnvToModule pipeline (writing into Episode objects in a + Learner pipeline does not make a lot of sense as - after the learner update - the + list of episodes is discarded). + + .. testcode:: + + import gymnasium as gym + import numpy as np + + from ray.rllib.connectors.env_to_module import WriteObservationsToEpisodes + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + from ray.rllib.utils.test_utils import check + + # Assume we have two episodes (vectorized), then our forward batch will carry + # two observation records (batch size = 2). + # The connector in this example will write these two (possibly transformed) + # observations back into the two respective SingleAgentEpisode objects. + batch = { + "obs": [np.array([0.0, 1.0], np.float32), np.array([2.0, 3.0], np.float32)], + } + + # Our two episodes have one observation each (i.e. the reset one). This is the + # one that will be overwritten by the connector in this example. + obs_space = gym.spaces.Box(-10.0, 10.0, (2,), np.float32) + act_space = gym.spaces.Discrete(2) + episodes = [ + SingleAgentEpisode( + observation_space=obs_space, + observations=[np.array([-10, -20], np.float32)], + len_lookback_buffer=0, + ) for _ in range(2) + ] + # Make sure everything is setup correctly. + check(episodes[0].get_observations(0), [-10.0, -20.0]) + check(episodes[1].get_observations(-1), [-10.0, -20.0]) + + # Create our connector piece. + connector = WriteObservationsToEpisodes(obs_space, act_space) + + # Call the connector (and thereby write the transformed observations back + # into the episodes). + output_batch = connector( + rl_module=None, # This particular connector works without an RLModule. + batch=batch, + episodes=episodes, + explore=True, + shared_data={}, + ) + + # The connector does NOT change the data batch being passed through. + check(output_batch, batch) + + # However, the connector has overwritten the last observations in the episodes. + check(episodes[0].get_observations(-1), [0.0, 1.0]) + check(episodes[1].get_observations(0), [2.0, 3.0]) + """ + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Optional[Dict[str, Any]], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + observations = batch.get(Columns.OBS) + + if observations is None: + raise ValueError( + f"`batch` must already have a column named {Columns.OBS} in it " + f"for this connector to work!" + ) + + # Note that the following loop works with multi-agent as well as with + # single-agent episode, as long as the following conditions are met (these + # will be validated by `self.single_agent_episode_iterator()`): + # - Per single agent episode, one observation item is expected to exist in + # `data`, either in a list directly under the "obs" key OR for multi-agent: + # in a list sitting under a key `(agent_id, module_id)` of a dict sitting + # under the "obs" key. + for sa_episode, obs in self.single_agent_episode_iterator( + episodes=episodes, zip_with_batch_column=observations + ): + # Make sure episodes are NOT numpy'ized yet (we are expecting to run in an + # env-to-module pipeline). + assert not sa_episode.is_numpy + # Write new information into the episode. + sa_episode.set_observations(at_indices=-1, new_data=obs) + # Change the observation space of the sa_episode. + sa_episode.observation_space = self.observation_space + + # Return the unchanged `batch`. + return batch diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1bf09d5c9d67493ebfa30dbe3b2f7494efe5ae67 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__init__.py @@ -0,0 +1,47 @@ +from ray.rllib.connectors.common.add_observations_from_episodes_to_batch import ( + AddObservationsFromEpisodesToBatch, +) +from ray.rllib.connectors.common.add_states_from_episodes_to_batch import ( + AddStatesFromEpisodesToBatch, +) +from ray.rllib.connectors.common.add_time_dim_to_batch_and_zero_pad import ( + AddTimeDimToBatchAndZeroPad, +) +from ray.rllib.connectors.common.agent_to_module_mapping import AgentToModuleMapping +from ray.rllib.connectors.common.batch_individual_items import BatchIndividualItems +from ray.rllib.connectors.common.numpy_to_tensor import NumpyToTensor +from ray.rllib.connectors.learner.add_columns_from_episodes_to_train_batch import ( + AddColumnsFromEpisodesToTrainBatch, +) +from ray.rllib.connectors.learner.add_infos_from_episodes_to_train_batch import ( + AddInfosFromEpisodesToTrainBatch, +) +from ray.rllib.connectors.learner.add_next_observations_from_episodes_to_train_batch import ( # noqa + AddNextObservationsFromEpisodesToTrainBatch, +) +from ray.rllib.connectors.learner.add_one_ts_to_episodes_and_truncate import ( + AddOneTsToEpisodesAndTruncate, +) +from ray.rllib.connectors.learner.compute_returns_to_go import ComputeReturnsToGo +from ray.rllib.connectors.learner.general_advantage_estimation import ( + GeneralAdvantageEstimation, +) +from ray.rllib.connectors.learner.learner_connector_pipeline import ( + LearnerConnectorPipeline, +) + +__all__ = [ + "AddColumnsFromEpisodesToTrainBatch", + "AddInfosFromEpisodesToTrainBatch", + "AddNextObservationsFromEpisodesToTrainBatch", + "AddObservationsFromEpisodesToBatch", + "AddOneTsToEpisodesAndTruncate", + "AddStatesFromEpisodesToBatch", + "AddTimeDimToBatchAndZeroPad", + "AgentToModuleMapping", + "BatchIndividualItems", + "ComputeReturnsToGo", + "GeneralAdvantageEstimation", + "LearnerConnectorPipeline", + "NumpyToTensor", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f5b0477a63e17fe2114ae9e6b885525d3b9def4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__pycache__/add_columns_from_episodes_to_train_batch.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__pycache__/add_columns_from_episodes_to_train_batch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03d53ab3f91d463ffddd0357b6f4a1ea0a46eac3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__pycache__/add_columns_from_episodes_to_train_batch.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__pycache__/add_infos_from_episodes_to_train_batch.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__pycache__/add_infos_from_episodes_to_train_batch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2761639622a9b65b6d51f36aac8cefa929b8520d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__pycache__/add_infos_from_episodes_to_train_batch.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__pycache__/add_next_observations_from_episodes_to_train_batch.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__pycache__/add_next_observations_from_episodes_to_train_batch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e5dc1ade3663e1c1c7a43513f46eef17880ab7f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__pycache__/add_next_observations_from_episodes_to_train_batch.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__pycache__/add_one_ts_to_episodes_and_truncate.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__pycache__/add_one_ts_to_episodes_and_truncate.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5145efaef3d7fa7610417b13e97be2011fa42ca2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__pycache__/add_one_ts_to_episodes_and_truncate.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__pycache__/compute_returns_to_go.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__pycache__/compute_returns_to_go.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e3dce945f0677ad89a8da66017f1fb6cb5d645e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__pycache__/compute_returns_to_go.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__pycache__/frame_stacking.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__pycache__/frame_stacking.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16a2376c4689770b27d03365c1d845590e43dc5b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__pycache__/frame_stacking.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__pycache__/general_advantage_estimation.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__pycache__/general_advantage_estimation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a78462ac008d18651753846aefd42537d45af2c1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__pycache__/general_advantage_estimation.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__pycache__/learner_connector_pipeline.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__pycache__/learner_connector_pipeline.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27e4c01af26579e673b31720b19ac7e8ba2871a1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/__pycache__/learner_connector_pipeline.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/add_columns_from_episodes_to_train_batch.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/add_columns_from_episodes_to_train_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..b55729c8231406b669bee077fa5d5b3862732db1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/add_columns_from_episodes_to_train_batch.py @@ -0,0 +1,167 @@ +from typing import Any, Dict, List, Optional + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class AddColumnsFromEpisodesToTrainBatch(ConnectorV2): + """Adds actions/rewards/terminateds/... to train batch. Excluding the infos column. + + Note: This is one of the default Learner ConnectorV2 pieces that are added + automatically by RLlib into every Learner connector pipeline, unless + `config.add_default_connectors_to_learner_pipeline` is set to False. + + The default Learner connector pipeline is: + [ + [0 or more user defined ConnectorV2 pieces], + AddObservationsFromEpisodesToBatch, + AddColumnsFromEpisodesToTrainBatch, + AddTimeDimToBatchAndZeroPad, + AddStatesFromEpisodesToBatch, + AgentToModuleMapping, # only in multi-agent setups! + BatchIndividualItems, + NumpyToTensor, + ] + + Does NOT add observations or infos to train batch. + Observations should have already been added by another ConnectorV2 piece: + `AddObservationsToTrainBatch` in the same pipeline. + Infos can be added manually by the user through setting this in the config: + + .. testcode:: + :skipif: True + + from ray.rllib.connectors.learner import AddInfosFromEpisodesToTrainBatch + config.training( + learner_connector=lambda obs_sp, act_sp: AddInfosFromEpisodesToTrainBatch() + )` + + If provided with `episodes` data, this connector piece makes sure that the final + train batch going into the RLModule for updating (`forward_train()` call) contains + at the minimum: + - Observations: From all episodes under the Columns.OBS key. + - Actions, rewards, terminal/truncation flags: From all episodes under the + respective keys. + - All data inside the episodes' `extra_model_outs` property, e.g. action logp and + action probs under the respective keys. + - Internal states: These will NOT be added to the batch by this connector piece + as this functionality is handled by a different default connector piece: + `AddStatesFromEpisodesToBatch`. + + If the user wants to customize their own data under the given keys (e.g. obs, + actions, ...), they can extract from the episodes or recompute from `data` + their own data and store it in `data` under those keys. In this case, the default + connector will not change the data under these keys and simply act as a + pass-through. + """ + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Optional[Dict[str, Any]], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + + # Actions. + if Columns.ACTIONS not in batch: + for sa_episode in self.single_agent_episode_iterator( + episodes, + agents_that_stepped_only=False, + ): + self.add_n_batch_items( + batch, + Columns.ACTIONS, + items_to_add=[ + sa_episode.get_actions(indices=ts) + for ts in range(len(sa_episode)) + ], + num_items=len(sa_episode), + single_agent_episode=sa_episode, + ) + + # Rewards. + if Columns.REWARDS not in batch: + for sa_episode in self.single_agent_episode_iterator( + episodes, + agents_that_stepped_only=False, + ): + self.add_n_batch_items( + batch, + Columns.REWARDS, + items_to_add=[ + sa_episode.get_rewards(indices=ts) + for ts in range(len(sa_episode)) + ], + num_items=len(sa_episode), + single_agent_episode=sa_episode, + ) + + # Terminateds. + if Columns.TERMINATEDS not in batch: + for sa_episode in self.single_agent_episode_iterator( + episodes, + agents_that_stepped_only=False, + ): + self.add_n_batch_items( + batch, + Columns.TERMINATEDS, + items_to_add=( + [False] * (len(sa_episode) - 1) + [sa_episode.is_terminated] + if len(sa_episode) > 0 + else [] + ), + num_items=len(sa_episode), + single_agent_episode=sa_episode, + ) + + # Truncateds. + if Columns.TRUNCATEDS not in batch: + for sa_episode in self.single_agent_episode_iterator( + episodes, + agents_that_stepped_only=False, + ): + self.add_n_batch_items( + batch, + Columns.TRUNCATEDS, + items_to_add=( + [False] * (len(sa_episode) - 1) + [sa_episode.is_truncated] + if len(sa_episode) > 0 + else [] + ), + num_items=len(sa_episode), + single_agent_episode=sa_episode, + ) + + # Extra model outputs (except for STATE_OUT, which will be handled by another + # default connector piece). Also, like with all the fields above, skip + # those that the user already seemed to have populated via custom connector + # pieces. + skip_columns = set(batch.keys()) | {Columns.STATE_IN, Columns.STATE_OUT} + for sa_episode in self.single_agent_episode_iterator( + episodes, + agents_that_stepped_only=False, + ): + for column in sa_episode.extra_model_outputs.keys(): + if column not in skip_columns: + self.add_n_batch_items( + batch, + column, + items_to_add=[ + sa_episode.get_extra_model_outputs(key=column, indices=ts) + for ts in range(len(sa_episode)) + ], + num_items=len(sa_episode), + single_agent_episode=sa_episode, + ) + + return batch diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/add_infos_from_episodes_to_train_batch.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/add_infos_from_episodes_to_train_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..145d6d86acb061d7e8a6ffe4808a67b81b216340 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/add_infos_from_episodes_to_train_batch.py @@ -0,0 +1,51 @@ +from typing import Any, Dict, List, Optional + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class AddInfosFromEpisodesToTrainBatch(ConnectorV2): + """Adds the infos column to th train batch. + + If provided with `episodes` data, this connector piece makes sure that the final + train batch going into the RLModule for updating (`forward_train()` call) contains + an `infos` column. + + If the user wants to customize their own data under the given keys (e.g. obs, + actions, ...), they can extract from the episodes or recompute from `data` + their own data and store it in `data` under those keys. In this case, the default + connector will not change the data under these keys and simply act as a + pass-through. + """ + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Optional[Dict[str, Any]], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + # Infos. + if Columns.INFOS not in batch: + for sa_episode in self.single_agent_episode_iterator( + episodes, + agents_that_stepped_only=False, + ): + self.add_n_batch_items( + batch, + Columns.INFOS, + items_to_add=sa_episode.get_infos(slice(0, len(sa_episode))), + num_items=len(sa_episode), + single_agent_episode=sa_episode, + ) + + return batch diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/add_next_observations_from_episodes_to_train_batch.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/add_next_observations_from_episodes_to_train_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..6efa3b706bf1f24e61f9791b273e7f11b08b5066 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/add_next_observations_from_episodes_to_train_batch.py @@ -0,0 +1,103 @@ +from typing import Any, Dict, List, Optional + +from ray.rllib.core.columns import Columns +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class AddNextObservationsFromEpisodesToTrainBatch(ConnectorV2): + """Adds the NEXT_OBS column with the correct episode observations to train batch. + + - Operates on a list of Episode objects. + - Gets all observation(s) from all the given episodes (except the very first ones) + and adds them to the batch under construction in the NEXT_OBS column (as a list of + individual observations). + - Does NOT alter any observations (or other data) in the given episodes. + - Can be used in Learner connector pipelines. + + .. testcode:: + + import gymnasium as gym + import numpy as np + + from ray.rllib.connectors.learner import ( + AddNextObservationsFromEpisodesToTrainBatch + ) + from ray.rllib.core.columns import Columns + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + from ray.rllib.utils.test_utils import check + + # Create two dummy SingleAgentEpisodes, each containing 3 observations, + # 2 actions and 2 rewards (both episodes are length=2). + obs_space = gym.spaces.Box(-1.0, 1.0, (2,), np.float32) + act_space = gym.spaces.Discrete(2) + + episodes = [SingleAgentEpisode( + observations=[obs_space.sample(), obs_space.sample(), obs_space.sample()], + actions=[act_space.sample(), act_space.sample()], + rewards=[1.0, 2.0], + len_lookback_buffer=0, + ) for _ in range(2)] + eps_1_next_obses = episodes[0].get_observations([1, 2]) + eps_2_next_obses = episodes[1].get_observations([1, 2]) + print(f"1st Episode's next obses are {eps_1_next_obses}") + print(f"2nd Episode's next obses are {eps_2_next_obses}") + + # Create an instance of this class. + connector = AddNextObservationsFromEpisodesToTrainBatch() + + # Call the connector with the two created episodes. + # Note that this particular connector works without an RLModule, so we + # simplify here for the sake of this example. + output_data = connector( + rl_module=None, + batch={}, + episodes=episodes, + explore=True, + shared_data={}, + ) + # The output data should now contain the last observations of both episodes, + # in a "per-episode organized" fashion. + check( + output_data, + { + Columns.NEXT_OBS: { + (episodes[0].id_,): eps_1_next_obses, + (episodes[1].id_,): eps_2_next_obses, + }, + }, + ) + """ + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + # If "obs" already in `batch`, early out. + if Columns.NEXT_OBS in batch: + return batch + + for sa_episode in self.single_agent_episode_iterator( + # This is a Learner-only connector -> Get all episodes (for train batch). + episodes, + agents_that_stepped_only=False, + ): + self.add_n_batch_items( + batch, + Columns.NEXT_OBS, + items_to_add=sa_episode.get_observations(slice(1, len(sa_episode) + 1)), + num_items=len(sa_episode), + single_agent_episode=sa_episode, + ) + return batch diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/add_one_ts_to_episodes_and_truncate.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/add_one_ts_to_episodes_and_truncate.py new file mode 100644 index 0000000000000000000000000000000000000000..fcd3703eeb855e1ab1fad584c1aa01b5f922f5cb --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/add_one_ts_to_episodes_and_truncate.py @@ -0,0 +1,168 @@ +from typing import Any, Dict, List, Optional + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.env.multi_agent_episode import MultiAgentEpisode +from ray.rllib.utils.annotations import override +from ray.rllib.utils.postprocessing.episodes import add_one_ts_to_episodes_and_truncate +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class AddOneTsToEpisodesAndTruncate(ConnectorV2): + """Adds an artificial timestep to all incoming episodes at the end. + + In detail: The last observations, infos, actions, and all `extra_model_outputs` + will be duplicated and appended to each episode's data. An extra 0.0 reward + will be appended to the episode's rewards. The episode's timestep will be + increased by 1. Also, adds the truncated=True flag to each episode if the + episode is not already done (terminated or truncated). + + Useful for value function bootstrapping, where it is required to compute a + forward pass for the very last timestep within the episode, + i.e. using the following input dict: { + obs=[final obs], + state=[final state output], + prev. reward=[final reward], + etc.. + } + + .. testcode:: + + from ray.rllib.connectors.learner import AddOneTsToEpisodesAndTruncate + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + from ray.rllib.utils.test_utils import check + + # Create 2 episodes (both to be extended by one timestep). + episode1 = SingleAgentEpisode( + observations=[0, 1, 2], + actions=[0, 1], + rewards=[0.0, 1.0], + terminated=False, + truncated=False, + len_lookback_buffer=0, + ).to_numpy() + check(len(episode1), 2) + check(episode1.is_truncated, False) + + episode2 = SingleAgentEpisode( + observations=[0, 1, 2, 3, 4, 5], + actions=[0, 1, 2, 3, 4], + rewards=[0.0, 1.0, 2.0, 3.0, 4.0], + terminated=True, # a terminated episode + truncated=False, + len_lookback_buffer=0, + ).to_numpy() + check(len(episode2), 5) + check(episode2.is_truncated, False) + check(episode2.is_terminated, True) + + # Create an instance of this class. + connector = AddOneTsToEpisodesAndTruncate() + + # Call the connector. + shared_data = {} + _ = connector( + rl_module=None, # Connector used here does not require RLModule. + batch={}, + episodes=[episode1, episode2], + shared_data=shared_data, + ) + # Check on the episodes. Both of them should now be 1 timestep longer. + check(len(episode1), 3) + check(episode1.is_truncated, True) + check(len(episode2), 6) + check(episode2.is_truncated, False) + check(episode2.is_terminated, True) + """ + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + # Build the loss mask to make sure the extra added timesteps do not influence + # the final loss and fix the terminateds and truncateds in the batch. + + # For proper v-trace execution, the rules must be as follows: + # Legend: + # T: terminal=True + # R: truncated=True + # B0: bootstrap with value 0 (also: terminal=True) + # Bx: bootstrap with some vf-computed value (also: terminal=True) + + # batch: - - - - - - - T B0- - - - - R Bx- - - - R Bx + # mask : t t t t t t t t f t t t t t t f t t t t t f + + # TODO (sven): Same situation as in TODO below, but for multi-agent episode. + # Maybe add a dedicated connector piece for this task? + # We extend the MultiAgentEpisode's ID by a running number here to make sure + # we treat each MAEpisode chunk as separate (for potentially upcoming v-trace + # and LSTM zero-padding) and don't mix data from different chunks. + if isinstance(episodes[0], MultiAgentEpisode): + for i, ma_episode in enumerate(episodes): + ma_episode.id_ += "_" + str(i) + # Also change the underlying single-agent episode's + # `multi_agent_episode_id` properties. + for sa_episode in ma_episode.agent_episodes.values(): + sa_episode.multi_agent_episode_id = ma_episode.id_ + + for i, sa_episode in enumerate( + self.single_agent_episode_iterator(episodes, agents_that_stepped_only=False) + ): + # TODO (sven): This is a little bit of a hack: By extending the Episode's + # ID, we make sure that each episode chunk in `episodes` is treated as a + # separate episode in the `self.add_n_batch_items` below. Some algos (e.g. + # APPO) may have >1 episode chunks from the same episode (same ID) in the + # training data, thus leading to a malformatted batch in case of + # RNN-triggered zero-padding of the train batch. + # For example, if e1 (id=a len=4) and e2 (id=a len=5) are two chunks of the + # same episode in `episodes`, the resulting batch would have an additional + # timestep in the middle of the episode's "row": + # { "obs": { + # ("a", <- eps ID): [0, 1, 2, 3 <- len=4, [additional 1 ts (bad)], + # 0, 1, 2, 3, 4 <- len=5, [additional 1 ts]] + # }} + sa_episode.id_ += "_" + str(i) + + len_ = len(sa_episode) + + # Extend all episodes by one ts. + add_one_ts_to_episodes_and_truncate([sa_episode]) + + loss_mask = [True for _ in range(len_)] + [False] + self.add_n_batch_items( + batch, + Columns.LOSS_MASK, + loss_mask, + len_ + 1, + sa_episode, + ) + + terminateds = ( + [False for _ in range(len_ - 1)] + + [bool(sa_episode.is_terminated)] + + [True] # extra timestep + ) + self.add_n_batch_items( + batch, + Columns.TERMINATEDS, + terminateds, + len_ + 1, + sa_episode, + ) + + # Signal to following connector pieces that the loss-mask which masks out + # invalid episode ts (for the extra added ts at the end) has already been + # added to `data`. + shared_data["_added_loss_mask_for_valid_episode_ts"] = True + + return batch diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/compute_returns_to_go.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/compute_returns_to_go.py new file mode 100644 index 0000000000000000000000000000000000000000..d005b8c5accbc7eb80da11885d847e2c3a950584 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/compute_returns_to_go.py @@ -0,0 +1,68 @@ +from typing import Any, List, Dict + +import scipy + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModule +from ray.rllib.utils.typing import EpisodeType + + +class ComputeReturnsToGo(ConnectorV2): + """Learner ConnectorV2 piece computing discounted returns to go till end of episode. + + This ConnectorV2: + - Operates on a list of Episode objects (single- or multi-agent). + - Should be used only in the Learner pipeline as a preparation for an upcoming loss + computation that requires the discounted returns to go (until the end of the + episode). + - For each agent, for each episode and at each timestep, sums up the rewards + (discounted) until the end of the episode and assigns the results to a new + column: RETURNS_TO_GO in the batch. + """ + + def __init__( + self, + input_observation_space=None, + input_action_space=None, + *, + gamma, + ): + """Initializes a ComputeReturnsToGo instance. + + Args: + gamma: The discount factor gamma. + """ + super().__init__(input_observation_space, input_action_space) + self.gamma = gamma + + def __call__( + self, + *, + rl_module: MultiRLModule, + episodes: List[EpisodeType], + batch: Dict[str, Any], + **kwargs, + ): + for sa_episode in self.single_agent_episode_iterator( + episodes, agents_that_stepped_only=False + ): + # Reverse the rewards sequence. + rewards_reversed = sa_episode.get_rewards()[::-1] + # Use lfilter to compute the discounted cumulative sums. + discounted_cumsum_reversed = scipy.signal.lfilter( + [1], [1, -self.gamma], rewards_reversed + ) + # Reverse the result to get the correct order. + discounted_returns = discounted_cumsum_reversed[::-1] + + # Add the results to the batch under a new column: RETURNS_TO_GO. + self.add_n_batch_items( + batch=batch, + column=Columns.RETURNS_TO_GO, + items_to_add=discounted_returns, + num_items=len(sa_episode), + single_agent_episode=sa_episode, + ) + + return batch diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/frame_stacking.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/frame_stacking.py new file mode 100644 index 0000000000000000000000000000000000000000..f431eb7272594aa959a8c8738eb3304525f8f1e8 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/frame_stacking.py @@ -0,0 +1,6 @@ +from functools import partial + +from ray.rllib.connectors.common.frame_stacking import FrameStacking + + +FrameStackingLearner = partial(FrameStacking, as_learner_connector=True) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/general_advantage_estimation.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/general_advantage_estimation.py new file mode 100644 index 0000000000000000000000000000000000000000..cf99887328cf0b090680d0770d3d824d4bb9aed1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/general_advantage_estimation.py @@ -0,0 +1,196 @@ +from typing import Any, List, Dict + +import numpy as np + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.connectors.common.numpy_to_tensor import NumpyToTensor +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.apis.value_function_api import ValueFunctionAPI +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModule +from ray.rllib.evaluation.postprocessing import Postprocessing +from ray.rllib.utils.annotations import override +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.postprocessing.value_predictions import compute_value_targets +from ray.rllib.utils.postprocessing.zero_padding import ( + split_and_zero_pad_n_episodes, + unpad_data_if_necessary, +) +from ray.rllib.utils.typing import EpisodeType + + +class GeneralAdvantageEstimation(ConnectorV2): + """Learner ConnectorV2 piece computing GAE advantages and value targets on episodes. + + This ConnectorV2: + - Operates on a list of Episode objects (single- or multi-agent). + - Should be used only in the Learner pipeline and as one of the last pieces (due + to the fact that it requires the batch for the value functions to be already + complete). + - Requires the incoming episodes to already be elongated by one artificial timestep + at the end (last obs, actions, states, etc.. repeated, last reward=0.0, etc..), + making it possible to combine the per-timestep value computations with the + necessary "bootstrap" value computations at the episode (chunk) truncation points. + The extra timestep should be added using the `ray.rllib.connectors.learner. + add_one_ts_to_episodes_and_truncate.AddOneTsToEpisodesAndTruncate` connector piece. + + The GAE computation is performed in an efficient way through using the arriving + `batch` as forward batch for the value function, extracting the bootstrap values + (at the artificially added time steos) and all other value predictions (all other + timesteps), performing GAE, and adding the results back into `batch` (under + Postprocessing.ADVANTAGES and Postprocessing.VALUE_TARGETS. + """ + + def __init__( + self, + input_observation_space=None, + input_action_space=None, + *, + gamma, + lambda_, + ): + """Initializes a GeneralAdvantageEstimation instance. + + Args: + gamma: The discount factor gamma. + lambda_: The lambda parameter for General Advantage Estimation (GAE). + Defines the exponential weight used between actually measured rewards + vs value function estimates over multiple time steps. Specifically, + `lambda_` balances short-term, low-variance estimates with longer-term, + high-variance returns. A `lambda_` or 0.0 makes the GAE rely only on + immediate rewards (and vf predictions from there on, reducing variance, + but increasing bias), while a `lambda_` of 1.0 only incorporates vf + predictions at the truncation points of the given episodes or episode + chunks (reducing bias but increasing variance). + """ + super().__init__(input_observation_space, input_action_space) + self.gamma = gamma + self.lambda_ = lambda_ + + # Internal numpy-to-tensor connector to translate GAE results (advantages and + # vf targets) into tensors. + self._numpy_to_tensor_connector = None + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: MultiRLModule, + episodes: List[EpisodeType], + batch: Dict[str, Any], + **kwargs, + ): + # Device to place all GAE result tensors (advantages and value targets) on. + device = None + + # Extract all single-agent episodes. + sa_episodes_list = list( + self.single_agent_episode_iterator(episodes, agents_that_stepped_only=False) + ) + # Perform the value nets' forward passes. + # TODO (sven): We need to check here in the pipeline already, whether a module + # should even be updated or not (which we usually do after(!) the Learner + # pipeline). This is an open TODO to move this filter into a connector as well. + # For now, we'll just check, whether `mid` is in batch and skip if it isn't. + vf_preds = rl_module.foreach_module( + func=lambda mid, module: ( + module.compute_values(batch[mid]) + if mid in batch and isinstance(module, ValueFunctionAPI) + else None + ), + return_dict=True, + ) + # Loop through all modules and perform each one's GAE computation. + for module_id, module_vf_preds in vf_preds.items(): + # Skip those outputs of RLModules that are not implementers of + # `ValueFunctionAPI`. + if module_vf_preds is None: + continue + + module = rl_module[module_id] + device = module_vf_preds.device + # Convert to numpy for the upcoming GAE computations. + module_vf_preds = convert_to_numpy(module_vf_preds) + + # Collect (single-agent) episode lengths for this particular module. + episode_lens = [ + len(e) for e in sa_episodes_list if e.module_id in [None, module_id] + ] + + # Remove all zero-padding again, if applicable, for the upcoming + # GAE computations. + module_vf_preds = unpad_data_if_necessary(episode_lens, module_vf_preds) + # Compute value targets. + module_value_targets = compute_value_targets( + values=module_vf_preds, + rewards=unpad_data_if_necessary( + episode_lens, + convert_to_numpy(batch[module_id][Columns.REWARDS]), + ), + terminateds=unpad_data_if_necessary( + episode_lens, + convert_to_numpy(batch[module_id][Columns.TERMINATEDS]), + ), + truncateds=unpad_data_if_necessary( + episode_lens, + convert_to_numpy(batch[module_id][Columns.TRUNCATEDS]), + ), + gamma=self.gamma, + lambda_=self.lambda_, + ) + assert module_value_targets.shape[0] == sum(episode_lens) + + module_advantages = module_value_targets - module_vf_preds + # Drop vf-preds, not needed in loss. Note that in the DefaultPPORLModule, + # vf-preds are recomputed with each `forward_train` call anyway to compute + # the vf loss. + # Standardize advantages (used for more stable and better weighted + # policy gradient computations). + module_advantages = (module_advantages - module_advantages.mean()) / max( + 1e-4, module_advantages.std() + ) + + # Zero-pad the new computations, if necessary. + if module.is_stateful(): + module_advantages = np.stack( + split_and_zero_pad_n_episodes( + module_advantages, + episode_lens=episode_lens, + max_seq_len=module.model_config["max_seq_len"], + ), + axis=0, + ) + module_value_targets = np.stack( + split_and_zero_pad_n_episodes( + module_value_targets, + episode_lens=episode_lens, + max_seq_len=module.model_config["max_seq_len"], + ), + axis=0, + ) + batch[module_id][Postprocessing.ADVANTAGES] = module_advantages + batch[module_id][Postprocessing.VALUE_TARGETS] = module_value_targets + + # Convert all GAE results to tensors. + if self._numpy_to_tensor_connector is None: + self._numpy_to_tensor_connector = NumpyToTensor( + as_learner_connector=True, device=device + ) + tensor_results = self._numpy_to_tensor_connector( + rl_module=rl_module, + batch={ + mid: { + Postprocessing.ADVANTAGES: module_batch[Postprocessing.ADVANTAGES], + Postprocessing.VALUE_TARGETS: ( + module_batch[Postprocessing.VALUE_TARGETS] + ), + } + for mid, module_batch in batch.items() + if vf_preds[mid] is not None + }, + episodes=episodes, + ) + # Move converted tensors back to `batch`. + for mid, module_batch in tensor_results.items(): + batch[mid].update(module_batch) + + return batch diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/learner_connector_pipeline.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/learner_connector_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..08c25347594aff4c8518af11e9d4912c29b0e981 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/learner/learner_connector_pipeline.py @@ -0,0 +1,60 @@ +from typing import Any, Dict, List, Optional +from ray.rllib.connectors.connector_pipeline_v2 import ConnectorPipelineV2 +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.metrics import ( + ALL_MODULES, + LEARNER_CONNECTOR, + LEARNER_CONNECTOR_SUM_EPISODES_LENGTH_IN, + LEARNER_CONNECTOR_SUM_EPISODES_LENGTH_OUT, +) +from ray.rllib.utils.metrics.metrics_logger import MetricsLogger +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class LearnerConnectorPipeline(ConnectorPipelineV2): + @override(ConnectorPipelineV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Optional[Dict[str, Any]] = None, + episodes: List[EpisodeType], + explore: bool = False, + shared_data: Optional[dict] = None, + metrics: Optional[MetricsLogger] = None, + **kwargs, + ): + # Log the sum of lengths of all episodes incoming. + if metrics: + metrics.log_value( + (ALL_MODULES, LEARNER_CONNECTOR_SUM_EPISODES_LENGTH_IN), + sum(map(len, episodes)), + ) + + # Make sure user does not necessarily send initial input into this pipeline. + # Might just be empty and to be populated from `episodes`. + ret = super().__call__( + rl_module=rl_module, + batch=batch if batch is not None else {}, + episodes=episodes, + shared_data=shared_data if shared_data is not None else {}, + explore=explore, + metrics=metrics, + metrics_prefix_key=( + ALL_MODULES, + LEARNER_CONNECTOR, + ), + **kwargs, + ) + + # Log the sum of lengths of all episodes outgoing. + if metrics: + metrics.log_value( + (ALL_MODULES, LEARNER_CONNECTOR_SUM_EPISODES_LENGTH_OUT), + sum(map(len, episodes)), + ) + + return ret diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2fc76488be7b7550e3fdbf7177731c758194fd5b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/__init__.py @@ -0,0 +1,30 @@ +from ray.rllib.connectors.common.tensor_to_numpy import TensorToNumpy +from ray.rllib.connectors.common.module_to_agent_unmapping import ModuleToAgentUnmapping +from ray.rllib.connectors.module_to_env.get_actions import GetActions +from ray.rllib.connectors.module_to_env.listify_data_for_vector_env import ( + ListifyDataForVectorEnv, +) +from ray.rllib.connectors.module_to_env.module_to_env_pipeline import ( + ModuleToEnvPipeline, +) +from ray.rllib.connectors.module_to_env.normalize_and_clip_actions import ( + NormalizeAndClipActions, +) +from ray.rllib.connectors.module_to_env.remove_single_ts_time_rank_from_batch import ( + RemoveSingleTsTimeRankFromBatch, +) +from ray.rllib.connectors.module_to_env.unbatch_to_individual_items import ( + UnBatchToIndividualItems, +) + + +__all__ = [ + "GetActions", + "ListifyDataForVectorEnv", + "ModuleToAgentUnmapping", + "ModuleToEnvPipeline", + "NormalizeAndClipActions", + "RemoveSingleTsTimeRankFromBatch", + "TensorToNumpy", + "UnBatchToIndividualItems", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4071734336c9e22201bf3e404544c76555cf7522 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/__pycache__/get_actions.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/__pycache__/get_actions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2cf61be6b4842a299c241628b4767ecd7a6ad2c5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/__pycache__/get_actions.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/__pycache__/listify_data_for_vector_env.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/__pycache__/listify_data_for_vector_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bfa00c98445ef82ff661058adb8b9081695bf402 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/__pycache__/listify_data_for_vector_env.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/__pycache__/module_to_env_pipeline.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/__pycache__/module_to_env_pipeline.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30a2bdcc72ead89bfdd0f77957ace602792e3cd0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/__pycache__/module_to_env_pipeline.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/__pycache__/normalize_and_clip_actions.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/__pycache__/normalize_and_clip_actions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ea5977675ac7125e240fae309ed9e8bfa59d30c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/__pycache__/normalize_and_clip_actions.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/__pycache__/remove_single_ts_time_rank_from_batch.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/__pycache__/remove_single_ts_time_rank_from_batch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a7a1abd70513281db8f6cb47951267671d9d7e1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/__pycache__/remove_single_ts_time_rank_from_batch.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/__pycache__/unbatch_to_individual_items.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/__pycache__/unbatch_to_individual_items.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29527038a39efefaf0bc40b8cf8fa1d7d6f5e7e6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/__pycache__/unbatch_to_individual_items.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/get_actions.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/get_actions.py new file mode 100644 index 0000000000000000000000000000000000000000..1e862231b4fbd10500ffee1f4b03f604a8af2472 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/get_actions.py @@ -0,0 +1,91 @@ +from typing import Any, Dict, List, Optional + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.env.multi_agent_episode import MultiAgentEpisode +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class GetActions(ConnectorV2): + """Connector piece sampling actions from ACTION_DIST_INPUTS from an RLModule. + + Note: This is one of the default module-to-env ConnectorV2 pieces that + are added automatically by RLlib into every module-to-env connector pipeline, + unless `config.add_default_connectors_to_module_to_env_pipeline` is set to + False. + + The default module-to-env connector pipeline is: + [ + GetActions, + TensorToNumpy, + UnBatchToIndividualItems, + ModuleToAgentUnmapping, # only in multi-agent setups! + RemoveSingleTsTimeRankFromBatch, + + [0 or more user defined ConnectorV2 pieces], + + NormalizeAndClipActions, + ListifyDataForVectorEnv, + ] + + If necessary, this connector samples actions, given action dist. inputs and a + dist. class. + The connector will only sample from the action distribution, if the + Columns.ACTIONS key cannot be found in `data`. Otherwise, it'll behave + as pass-through. If Columns.ACTIONS is NOT present in `data`, but + Columns.ACTION_DIST_INPUTS is, this connector will create a new action + distribution using the given RLModule and sample from its distribution class + (deterministically, if we are not exploring, stochastically, if we are). + """ + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + is_multi_agent = isinstance(episodes[0], MultiAgentEpisode) + + if is_multi_agent: + for module_id, module_data in batch.copy().items(): + self._get_actions(module_data, rl_module[module_id], explore) + else: + self._get_actions(batch, rl_module, explore) + + return batch + + def _get_actions(self, batch, sa_rl_module, explore): + # Action have already been sampled -> Early out. + if Columns.ACTIONS in batch: + return + + # ACTION_DIST_INPUTS field returned by `forward_exploration|inference()` -> + # Create a new action distribution object. + if Columns.ACTION_DIST_INPUTS in batch: + if explore: + action_dist_class = sa_rl_module.get_exploration_action_dist_cls() + else: + action_dist_class = sa_rl_module.get_inference_action_dist_cls() + action_dist = action_dist_class.from_logits( + batch[Columns.ACTION_DIST_INPUTS], + ) + if not explore: + action_dist = action_dist.to_deterministic() + + # Sample actions from the distribution. + actions = action_dist.sample() + batch[Columns.ACTIONS] = actions + + # For convenience and if possible, compute action logp from distribution + # and add to output. + if Columns.ACTION_LOGP not in batch: + batch[Columns.ACTION_LOGP] = action_dist.logp(actions) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/listify_data_for_vector_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/listify_data_for_vector_env.py new file mode 100644 index 0000000000000000000000000000000000000000..c52489a8b1e5531f46287a554ab551f39e5e891a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/listify_data_for_vector_env.py @@ -0,0 +1,89 @@ +from typing import Any, Dict, List, Optional + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.env.multi_agent_episode import MultiAgentEpisode +from ray.rllib.utils.annotations import override +from ray.rllib.utils.spaces.space_utils import batch as batch_fn +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class ListifyDataForVectorEnv(ConnectorV2): + """Performs conversion from ConnectorV2-style format to env/episode insertion. + + Note: This is one of the default module-to-env ConnectorV2 pieces that + are added automatically by RLlib into every module-to-env connector pipeline, + unless `config.add_default_connectors_to_module_to_env_pipeline` is set to + False. + + The default module-to-env connector pipeline is: + [ + GetActions, + TensorToNumpy, + UnBatchToIndividualItems, + ModuleToAgentUnmapping, # only in multi-agent setups! + RemoveSingleTsTimeRankFromBatch, + + [0 or more user defined ConnectorV2 pieces], + + NormalizeAndClipActions, + ListifyDataForVectorEnv, + ] + + Single agent case: + Convert from: + [col] -> [(episode_id,)] -> [list of items]. + To: + [col] -> [list of items]. + + Multi-agent case: + Convert from: + [col] -> [(episode_id, agent_id, module_id)] -> list of items. + To: + [col] -> [list of multi-agent dicts]. + """ + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + for column, column_data in batch.copy().items(): + # Multi-agent case: Create lists of multi-agent dicts under each column. + if isinstance(episodes[0], MultiAgentEpisode): + # For each environment/episode one entry. + new_column_data = [{} for _ in episodes] + episode_map_structure = shared_data.get("old_episode_ids", {}) + for key, value in batch[column].items(): + assert len(value) == 1 + eps_id, agent_id, module_id = key + # Get the episode index that corresponds to the ID in the batch. + # Note, the order in the `EnvRunner`s episode list needs to be + # kept for each batch column. + eps_id = episode_map_structure.get(eps_id, eps_id) + eps_index = next( + (i for i, eps in enumerate(episodes) if eps.id_ == eps_id), 0 + ) + + new_column_data[eps_index][agent_id] = value[0] + batch[column] = new_column_data + # Single-agent case: Create simple lists under each column. + else: + batch[column] = [ + d for key in batch[column].keys() for d in batch[column][key] + ] + # Batch actions for (single-agent) gym.vector.Env. + # All other columns, leave listify'ed. + if column in [Columns.ACTIONS_FOR_ENV, Columns.ACTIONS]: + batch[column] = batch_fn(batch[column]) + + return batch diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/module_to_env_pipeline.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/module_to_env_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..63d5f00bfa4cda7a59e1cd22b3476e2091241090 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/module_to_env_pipeline.py @@ -0,0 +1,7 @@ +from ray.rllib.connectors.connector_pipeline_v2 import ConnectorPipelineV2 +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class ModuleToEnvPipeline(ConnectorPipelineV2): + pass diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/normalize_and_clip_actions.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/normalize_and_clip_actions.py new file mode 100644 index 0000000000000000000000000000000000000000..1698b1d0fe1e1aa5a0a3b4bfd32e65b6efc3b60b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/normalize_and_clip_actions.py @@ -0,0 +1,146 @@ +import copy +from typing import Any, Dict, List, Optional + +import gymnasium as gym + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.spaces.space_utils import ( + clip_action, + get_base_struct_from_space, + unsquash_action, +) +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class NormalizeAndClipActions(ConnectorV2): + """Normalizes or clips actions in the input data (coming from the RLModule). + + Note: This is one of the default module-to-env ConnectorV2 pieces that + are added automatically by RLlib into every module-to-env connector pipeline, + unless `config.add_default_connectors_to_module_to_env_pipeline` is set to + False. + + The default module-to-env connector pipeline is: + [ + GetActions, + TensorToNumpy, + UnBatchToIndividualItems, + ModuleToAgentUnmapping, # only in multi-agent setups! + RemoveSingleTsTimeRankFromBatch, + + [0 or more user defined ConnectorV2 pieces], + + NormalizeAndClipActions, + ListifyDataForVectorEnv, + ] + + This ConnectorV2: + - Deep copies the Columns.ACTIONS in the incoming `data` into a new column: + Columns.ACTIONS_FOR_ENV. + - Loops through the Columns.ACTIONS in the incoming `data` and normalizes or clips + these depending on the c'tor settings in `config.normalize_actions` and + `config.clip_actions`. + - Only applies to envs with Box action spaces. + + Normalizing is the process of mapping NN-outputs (which are usually small + numbers, e.g. between -1.0 and 1.0) to the bounds defined by the action-space. + Normalizing helps the NN to learn faster in environments with large ranges between + `low` and `high` bounds or skewed action bounds (e.g. Box(-3000.0, 1.0, ...)). + + Clipping clips the actions computed by the NN (and sampled from a distribution) + between the bounds defined by the action-space. Note that clipping is only performed + if `normalize_actions` is False. + """ + + @override(ConnectorV2) + def recompute_output_action_space( + self, + input_observation_space: gym.Space, + input_action_space: gym.Space, + ) -> gym.Space: + self._action_space_struct = get_base_struct_from_space(input_action_space) + return input_action_space + + def __init__( + self, + input_observation_space: Optional[gym.Space] = None, + input_action_space: Optional[gym.Space] = None, + *, + normalize_actions: bool, + clip_actions: bool, + **kwargs, + ): + """Initializes a DefaultModuleToEnv (connector piece) instance. + + Args: + normalize_actions: If True, actions coming from the RLModule's distribution + (or are directly computed by the RLModule w/o sampling) will + be assumed 0.0 centered with a small stddev (only affecting Box + components) and thus be unsquashed (and clipped, just in case) to the + bounds of the env's action space. For example, if the action space of + the environment is `Box(-2.0, -0.5, (1,))`, the model outputs + mean and stddev as 0.1 and exp(0.2), and we sample an action of 0.9 + from the resulting distribution, then this 0.9 will be unsquashed into + the [-2.0 -0.5] interval. If - after unsquashing - the action still + breaches the action space, it will simply be clipped. + clip_actions: If True, actions coming from the RLModule's distribution + (or are directly computed by the RLModule w/o sampling) will be clipped + such that they fit into the env's action space's bounds. + For example, if the action space of the environment is + `Box(-0.5, 0.5, (1,))`, the model outputs + mean and stddev as 0.1 and exp(0.2), and we sample an action of 0.9 + from the resulting distribution, then this 0.9 will be clipped to 0.5 + to fit into the [-0.5 0.5] interval. + """ + self._action_space_struct = None + + super().__init__(input_observation_space, input_action_space, **kwargs) + + self.normalize_actions = normalize_actions + self.clip_actions = clip_actions + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Optional[Dict[str, Any]], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + """Based on settings, will normalize (unsquash) and/or clip computed actions. + + This is such that the final actions (to be sent to the env) match the + environment's action space and thus don't lead to an error. + """ + + def _unsquash_or_clip(action_for_env, env_id, agent_id, module_id): + if agent_id is not None: + struct = self._action_space_struct[agent_id] + else: + struct = self._action_space_struct + + if self.normalize_actions: + return unsquash_action(action_for_env, struct) + else: + return clip_action(action_for_env, struct) + + # Normalize or clip this new actions_for_env column, leaving the originally + # computed/sampled actions intact. + if self.normalize_actions or self.clip_actions: + # Copy actions into separate column, just to go to the env. + batch[Columns.ACTIONS_FOR_ENV] = copy.deepcopy(batch[Columns.ACTIONS]) + self.foreach_batch_item_change_in_place( + batch=batch, + column=Columns.ACTIONS_FOR_ENV, + func=_unsquash_or_clip, + ) + + return batch diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/remove_single_ts_time_rank_from_batch.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/remove_single_ts_time_rank_from_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..3e3b200ebc071b38825004fab89002e9693a5a98 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/remove_single_ts_time_rank_from_batch.py @@ -0,0 +1,70 @@ +from typing import Any, Dict, List, Optional + +import numpy as np +import tree # pip install dm_tree + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class RemoveSingleTsTimeRankFromBatch(ConnectorV2): + """ + Note: This is one of the default module-to-env ConnectorV2 pieces that + are added automatically by RLlib into every module-to-env connector pipeline, + unless `config.add_default_connectors_to_module_to_env_pipeline` is set to + False. + + The default module-to-env connector pipeline is: + [ + GetActions, + TensorToNumpy, + UnBatchToIndividualItems, + ModuleToAgentUnmapping, # only in multi-agent setups! + RemoveSingleTsTimeRankFromBatch, + + [0 or more user defined ConnectorV2 pieces], + + NormalizeAndClipActions, + ListifyDataForVectorEnv, + ] + + """ + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Optional[Dict[str, Any]], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + # If single ts time-rank had not been added, early out. + if shared_data is None or not shared_data.get("_added_single_ts_time_rank"): + return batch + + def _remove_single_ts(item, eps_id, aid, mid): + # Only remove time-rank for modules that are statefule (only for those, a + # timerank has been added). + if mid is None or rl_module[mid].is_stateful(): + return tree.map_structure(lambda s: np.squeeze(s, axis=0), item) + return item + + for column, column_data in batch.copy().items(): + # Skip state_out (doesn't have a time rank). + if column == Columns.STATE_OUT: + continue + self.foreach_batch_item_change_in_place( + batch, + column=column, + func=_remove_single_ts, + ) + + return batch diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/unbatch_to_individual_items.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/unbatch_to_individual_items.py new file mode 100644 index 0000000000000000000000000000000000000000..b8b84a9f92f20117451efaf7fd63325a7c7cca58 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/module_to_env/unbatch_to_individual_items.py @@ -0,0 +1,110 @@ +from collections import defaultdict +from typing import Any, Dict, List, Optional + +import tree # pip install dm_tree + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.spaces.space_utils import unbatch as unbatch_fn +from ray.rllib.utils.typing import EpisodeType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class UnBatchToIndividualItems(ConnectorV2): + """Unbatches the given `data` back into the individual-batch-items format. + + Note: This is one of the default module-to-env ConnectorV2 pieces that + are added automatically by RLlib into every module-to-env connector pipeline, + unless `config.add_default_connectors_to_module_to_env_pipeline` is set to + False. + + The default module-to-env connector pipeline is: + [ + GetActions, + TensorToNumpy, + UnBatchToIndividualItems, + ModuleToAgentUnmapping, # only in multi-agent setups! + RemoveSingleTsTimeRankFromBatch, + + [0 or more user defined ConnectorV2 pieces], + + NormalizeAndClipActions, + ListifyDataForVectorEnv, + ] + """ + + @override(ConnectorV2) + def __call__( + self, + *, + rl_module: RLModule, + batch: Dict[str, Any], + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + memorized_map_structure = shared_data.get("memorized_map_structure") + episode_map_structure = shared_data.get("vector_env_episodes_map", {}) + # Simple case (no structure stored): Just unbatch. + if memorized_map_structure is None: + return tree.map_structure(lambda s: unbatch_fn(s), batch) + # Single agent case: Memorized structure is a list, whose indices map to + # eps_id values. + elif isinstance(memorized_map_structure, list): + for column, column_data in batch.copy().items(): + column_data = unbatch_fn(column_data) + new_column_data = defaultdict(list) + for i, eps_id in enumerate(memorized_map_structure): + # Keys are always tuples to resemble multi-agent keys, which + # have the structure (eps_id, agent_id, module_id). + key = (eps_id,) + new_column_data[key].append(column_data[i]) + batch[column] = dict(new_column_data) + # Multi-agent case: Memorized structure is dict mapping module_ids to lists of + # (eps_id, agent_id)-tuples, such that the original individual-items-based form + # can be constructed. + else: + for module_id, module_data in batch.copy().items(): + if module_id not in memorized_map_structure: + raise KeyError( + f"ModuleID={module_id} not found in `memorized_map_structure`!" + ) + for column, column_data in module_data.items(): + column_data = unbatch_fn(column_data) + new_column_data = defaultdict(list) + for i, (eps_id, agent_id) in enumerate( + memorized_map_structure[module_id] + ): + key = (eps_id, agent_id, module_id) + + # Check, if an agent episode is already done. For this we need + # to get the corresponding episode in the `EnvRunner`s list of + # episodes. + eps_id = episode_map_structure.get(eps_id, eps_id) + episode = next( + (eps for eps in episodes if eps.id_ == eps_id), None + ) + + if episode is None: + raise ValueError( + f"No episode found that matches the ID={eps_id}. Check " + "shared_data['vector_env_episodes_map'] for a missing ", + "mapping.", + ) + # If an episode has not just started and the agent's episode + # is done do not return data. + # This should not be `True` for new `MultiAgentEpisode`s. + if ( + episode.agent_episodes + and episode.agent_episodes[agent_id].is_done + and not episode.is_done + ): + continue + + new_column_data[key].append(column_data[i]) + module_data[column] = dict(new_column_data) + + return batch diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/registry.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..8efe64515eea485a13799330260758a68a11e21b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/registry.py @@ -0,0 +1,46 @@ +"""Registry of connector names for global access.""" +from typing import Any + +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.connectors.connector import Connector, ConnectorContext + + +ALL_CONNECTORS = dict() + + +@OldAPIStack +def register_connector(name: str, cls: Connector): + """Register a connector for use with RLlib. + + Args: + name: Name to register. + cls: Callable that creates an env. + """ + if name in ALL_CONNECTORS: + return + + if not issubclass(cls, Connector): + raise TypeError("Can only register Connector type.", cls) + + # Record it in local registry in case we need to register everything + # again in the global registry, for example in the event of cluster + # restarts. + ALL_CONNECTORS[name] = cls + + +@OldAPIStack +def get_connector(name: str, ctx: ConnectorContext, params: Any = None) -> Connector: + # TODO(jungong) : switch the order of parameters man!! + """Get a connector by its name and serialized config. + + Args: + name: name of the connector. + ctx: Connector context. + params: serialized parameters of the connector. + + Returns: + Constructed connector. + """ + if name not in ALL_CONNECTORS: + raise NameError("connector not found.", name) + return ALL_CONNECTORS[name].from_state(ctx, params) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/util.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/util.py new file mode 100644 index 0000000000000000000000000000000000000000..ff00b6d49dfec12ef766c166c9fe7d02ca4a33a0 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/connectors/util.py @@ -0,0 +1,170 @@ +import logging +from typing import Any, Tuple, TYPE_CHECKING + +from ray.rllib.connectors.action.clip import ClipActionsConnector +from ray.rllib.connectors.action.immutable import ImmutableActionsConnector +from ray.rllib.connectors.action.lambdas import ConvertToNumpyConnector +from ray.rllib.connectors.action.normalize import NormalizeActionsConnector +from ray.rllib.connectors.action.pipeline import ActionConnectorPipeline +from ray.rllib.connectors.agent.clip_reward import ClipRewardAgentConnector +from ray.rllib.connectors.agent.obs_preproc import ObsPreprocessorConnector +from ray.rllib.connectors.agent.pipeline import AgentConnectorPipeline +from ray.rllib.connectors.agent.state_buffer import StateBufferConnector +from ray.rllib.connectors.agent.view_requirement import ViewRequirementAgentConnector +from ray.rllib.connectors.connector import Connector, ConnectorContext +from ray.rllib.connectors.registry import get_connector +from ray.rllib.connectors.agent.mean_std_filter import ( + MeanStdObservationFilterAgentConnector, + ConcurrentMeanStdObservationFilterAgentConnector, +) +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.connectors.agent.synced_filter import SyncedFilterAgentConnector + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + from ray.rllib.policy.policy import Policy + +logger = logging.getLogger(__name__) + + +def __preprocessing_enabled(config: "AlgorithmConfig"): + if config._disable_preprocessor_api: + return False + # Same conditions as in RolloutWorker.__init__. + if config.is_atari and config.preprocessor_pref == "deepmind": + return False + if config.preprocessor_pref is None: + return False + return True + + +def __clip_rewards(config: "AlgorithmConfig"): + # Same logic as in RolloutWorker.__init__. + # We always clip rewards for Atari games. + return config.clip_rewards or config.is_atari + + +@OldAPIStack +def get_agent_connectors_from_config( + ctx: ConnectorContext, + config: "AlgorithmConfig", +) -> AgentConnectorPipeline: + connectors = [] + + clip_rewards = __clip_rewards(config) + if clip_rewards is True: + connectors.append(ClipRewardAgentConnector(ctx, sign=True)) + elif type(clip_rewards) is float: + connectors.append(ClipRewardAgentConnector(ctx, limit=abs(clip_rewards))) + + if __preprocessing_enabled(config): + connectors.append(ObsPreprocessorConnector(ctx)) + + # Filters should be after observation preprocessing + filter_connector = get_synced_filter_connector( + ctx, + ) + # Configuration option "NoFilter" results in `filter_connector==None`. + if filter_connector: + connectors.append(filter_connector) + + connectors.extend( + [ + StateBufferConnector(ctx), + ViewRequirementAgentConnector(ctx), + ] + ) + + return AgentConnectorPipeline(ctx, connectors) + + +@OldAPIStack +def get_action_connectors_from_config( + ctx: ConnectorContext, + config: "AlgorithmConfig", +) -> ActionConnectorPipeline: + """Default list of action connectors to use for a new policy. + + Args: + ctx: context used to create connectors. + config: The AlgorithmConfig object. + """ + connectors = [ConvertToNumpyConnector(ctx)] + if config.get("normalize_actions", False): + connectors.append(NormalizeActionsConnector(ctx)) + if config.get("clip_actions", False): + connectors.append(ClipActionsConnector(ctx)) + connectors.append(ImmutableActionsConnector(ctx)) + return ActionConnectorPipeline(ctx, connectors) + + +@OldAPIStack +def create_connectors_for_policy(policy: "Policy", config: "AlgorithmConfig"): + """Util to create agent and action connectors for a Policy. + + Args: + policy: Policy instance. + config: Algorithm config dict. + """ + ctx: ConnectorContext = ConnectorContext.from_policy(policy) + + assert ( + policy.agent_connectors is None and policy.action_connectors is None + ), "Can not create connectors for a policy that already has connectors." + + policy.agent_connectors = get_agent_connectors_from_config(ctx, config) + policy.action_connectors = get_action_connectors_from_config(ctx, config) + + logger.info("Using connectors:") + logger.info(policy.agent_connectors.__str__(indentation=4)) + logger.info(policy.action_connectors.__str__(indentation=4)) + + +@OldAPIStack +def restore_connectors_for_policy( + policy: "Policy", connector_config: Tuple[str, Tuple[Any]] +) -> Connector: + """Util to create connector for a Policy based on serialized config. + + Args: + policy: Policy instance. + connector_config: Serialized connector config. + """ + ctx: ConnectorContext = ConnectorContext.from_policy(policy) + name, params = connector_config + return get_connector(name, ctx, params) + + +# We need this filter selection mechanism temporarily to remain compatible to old API +@OldAPIStack +def get_synced_filter_connector(ctx: ConnectorContext): + filter_specifier = ctx.config.get("observation_filter") + if filter_specifier == "MeanStdFilter": + return MeanStdObservationFilterAgentConnector(ctx, clip=None) + elif filter_specifier == "ConcurrentMeanStdFilter": + return ConcurrentMeanStdObservationFilterAgentConnector(ctx, clip=None) + elif filter_specifier == "NoFilter": + return None + else: + raise Exception("Unknown observation_filter: " + str(filter_specifier)) + + +@OldAPIStack +def maybe_get_filters_for_syncing(rollout_worker, policy_id): + # As long as the historic filter synchronization mechanism is in + # place, we need to put filters into self.filters so that they get + # synchronized + policy = rollout_worker.policy_map[policy_id] + if not policy.agent_connectors: + return + + filter_connectors = policy.agent_connectors[SyncedFilterAgentConnector] + # There can only be one filter at a time + if not filter_connectors: + return + + assert len(filter_connectors) == 1, ( + "ConnectorPipeline has multiple connectors of type " + "SyncedFilterAgentConnector but can only have one." + ) + rollout_worker.filters[policy_id] = filter_connectors[0].filter diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bff33528c9af02fa036eb82c6c6833ceb59bff08 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/__init__.py @@ -0,0 +1,35 @@ +from ray.rllib.core.columns import Columns + + +DEFAULT_AGENT_ID = "default_agent" +DEFAULT_POLICY_ID = "default_policy" +# TODO (sven): Change this to "default_module" +DEFAULT_MODULE_ID = DEFAULT_POLICY_ID +ALL_MODULES = "__all_modules__" + +COMPONENT_ENV_RUNNER = "env_runner" +COMPONENT_ENV_TO_MODULE_CONNECTOR = "env_to_module_connector" +COMPONENT_EVAL_ENV_RUNNER = "eval_env_runner" +COMPONENT_LEARNER = "learner" +COMPONENT_LEARNER_GROUP = "learner_group" +COMPONENT_METRICS_LOGGER = "metrics_logger" +COMPONENT_MODULE_TO_ENV_CONNECTOR = "module_to_env_connector" +COMPONENT_OPTIMIZER = "optimizer" +COMPONENT_RL_MODULE = "rl_module" + + +__all__ = [ + "Columns", + "COMPONENT_ENV_RUNNER", + "COMPONENT_ENV_TO_MODULE_CONNECTOR", + "COMPONENT_EVAL_ENV_RUNNER", + "COMPONENT_LEARNER", + "COMPONENT_LEARNER_GROUP", + "COMPONENT_METRICS_LOGGER", + "COMPONENT_MODULE_TO_ENV_CONNECTOR", + "COMPONENT_OPTIMIZER", + "COMPONENT_RL_MODULE", + "DEFAULT_AGENT_ID", + "DEFAULT_MODULE_ID", + "DEFAULT_POLICY_ID", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc51e253ae3e088673bdb670f807c22b34c9b7b4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/__pycache__/columns.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/__pycache__/columns.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b18bffc4444e9ffcad538736336333d48060137 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/__pycache__/columns.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/columns.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/columns.py new file mode 100644 index 0000000000000000000000000000000000000000..98cb8646913e2b333eab3243308b82419f05d9bc --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/columns.py @@ -0,0 +1,73 @@ +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +class Columns: + """Definitions of common column names for RL data, e.g. 'obs', 'rewards', etc.. + + Note that this replaces the `SampleBatch` and `Postprocessing` columns (of the same + name). + """ + + # Observation received from an environment after `reset()` or `step()`. + OBS = "obs" + # Infos received from an environment after `reset()` or `step()`. + INFOS = "infos" + + # Action computed/sampled by an RLModule. + ACTIONS = "actions" + # Action actually sent to the (gymnasium) `Env.step()` method. + ACTIONS_FOR_ENV = "actions_for_env" + # Reward returned by `env.step()`. + REWARDS = "rewards" + # Termination signal received from an environment after `step()`. + TERMINATEDS = "terminateds" + # Truncation signal received from an environment after `step()` (e.g. because + # of a reached time limit). + TRUNCATEDS = "truncateds" + + # Next observation: Only used by algorithms that need to look at TD-data for + # training, such as off-policy/DQN algos. + NEXT_OBS = "new_obs" + + # Uniquely identifies an episode + EPS_ID = "eps_id" + AGENT_ID = "agent_id" + MODULE_ID = "module_id" + + # The size of non-zero-padded data within a (e.g. LSTM) zero-padded + # (B, T, ...)-style train batch. + SEQ_LENS = "seq_lens" + # Episode timestep counter. + T = "t" + + # Common extra RLModule output keys. + STATE_IN = "state_in" + NEXT_STATE_IN = "next_state_in" + STATE_OUT = "state_out" + NEXT_STATE_OUT = "next_state_out" + EMBEDDINGS = "embeddings" + ACTION_DIST_INPUTS = "action_dist_inputs" + ACTION_PROB = "action_prob" + ACTION_LOGP = "action_logp" + + # Value function predictions. + VF_PREDS = "vf_preds" + # Values, predicted at one timestep beyond the last timestep taken. + # These are usually calculated via the value function network using the final + # observation (and in case of an RNN: the last returned internal state). + VALUES_BOOTSTRAPPED = "values_bootstrapped" + + # Postprocessing columns. + ADVANTAGES = "advantages" + VALUE_TARGETS = "value_targets" + + # Intrinsic rewards (learning with curiosity). + INTRINSIC_REWARDS = "intrinsic_rewards" + # Discounted sum of rewards till the end of the episode (or chunk). + RETURNS_TO_GO = "returns_to_go" + + # Loss mask. If provided in a train batch, a Learner's compute_loss_for_module + # method should respect the False-set value in here and mask out the respective + # items form the loss. + LOSS_MASK = "loss_mask" diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/distribution/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/distribution/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/distribution/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/distribution/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45065ac08acc3bc566e3dc17ed24dfed5feebee5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/distribution/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/distribution/__pycache__/distribution.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/distribution/__pycache__/distribution.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd8970bf12a43452badfe8101eba954500141b5b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/distribution/__pycache__/distribution.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/distribution/distribution.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/distribution/distribution.py new file mode 100644 index 0000000000000000000000000000000000000000..f9dbf137917cae6543740b0bfdf667e9ac12419c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/distribution/distribution.py @@ -0,0 +1,250 @@ +"""This is the next version of action distribution base class.""" +from typing import Tuple +import gymnasium as gym +import abc + +from ray.rllib.utils.annotations import ExperimentalAPI +from ray.rllib.utils.typing import TensorType, Union +from ray.rllib.utils.annotations import override + + +@ExperimentalAPI +class Distribution(abc.ABC): + """The base class for distribution over a random variable. + + Examples: + + .. testcode:: + + import torch + from ray.rllib.core.models.configs import MLPHeadConfig + from ray.rllib.core.distribution.torch.torch_distribution import ( + TorchCategorical + ) + + model = MLPHeadConfig(input_dims=[1]).build(framework="torch") + + # Create an action distribution from model logits + action_logits = model(torch.Tensor([[1]])) + action_dist = TorchCategorical.from_logits(action_logits) + action = action_dist.sample() + + # Create another distribution from a dummy Tensor + action_dist2 = TorchCategorical.from_logits(torch.Tensor([0])) + + # Compute some common metrics + logp = action_dist.logp(action) + kl = action_dist.kl(action_dist2) + entropy = action_dist.entropy() + """ + + @abc.abstractmethod + def sample( + self, + *, + sample_shape: Tuple[int, ...] = None, + return_logp: bool = False, + **kwargs, + ) -> Union[TensorType, Tuple[TensorType, TensorType]]: + """Draw a sample from the distribution. + + Args: + sample_shape: The shape of the sample to draw. + return_logp: Whether to return the logp of the sampled values. + **kwargs: Forward compatibility placeholder. + + Returns: + The sampled values. If return_logp is True, returns a tuple of the + sampled values and its logp. + """ + + @abc.abstractmethod + def rsample( + self, + *, + sample_shape: Tuple[int, ...] = None, + return_logp: bool = False, + **kwargs, + ) -> Union[TensorType, Tuple[TensorType, TensorType]]: + """Draw a re-parameterized sample from the action distribution. + + If this method is implemented, we can take gradients of samples w.r.t. the + distribution parameters. + + Args: + sample_shape: The shape of the sample to draw. + return_logp: Whether to return the logp of the sampled values. + **kwargs: Forward compatibility placeholder. + + Returns: + The sampled values. If return_logp is True, returns a tuple of the + sampled values and its logp. + """ + + @abc.abstractmethod + def logp(self, value: TensorType, **kwargs) -> TensorType: + """The log-likelihood of the distribution computed at `value` + + Args: + value: The value to compute the log-likelihood at. + **kwargs: Forward compatibility placeholder. + + Returns: + The log-likelihood of the value. + """ + + @abc.abstractmethod + def kl(self, other: "Distribution", **kwargs) -> TensorType: + """The KL-divergence between two distributions. + + Args: + other: The other distribution. + **kwargs: Forward compatibility placeholder. + + Returns: + The KL-divergence between the two distributions. + """ + + @abc.abstractmethod + def entropy(self, **kwargs) -> TensorType: + """The entropy of the distribution. + + Args: + **kwargs: Forward compatibility placeholder. + + Returns: + The entropy of the distribution. + """ + + @staticmethod + @abc.abstractmethod + def required_input_dim(space: gym.Space, **kwargs) -> int: + """Returns the required length of an input parameter tensor. + + Args: + space: The space this distribution will be used for, + whose shape attributes will be used to determine the required shape of + the input parameter tensor. + **kwargs: Forward compatibility placeholder. + + Returns: + size of the required input vector (minus leading batch dimension). + """ + + @classmethod + def from_logits(cls, logits: TensorType, **kwargs) -> "Distribution": + """Creates a Distribution from logits. + + The caller does not need to have knowledge of the distribution class in order + to create it and sample from it. The passed batched logits vectors might be + split up and are passed to the distribution class' constructor as kwargs. + + Args: + logits: The logits to create the distribution from. + **kwargs: Forward compatibility placeholder. + + Returns: + The created distribution. + + .. testcode:: + + import numpy as np + from ray.rllib.core.distribution.distribution import Distribution + + class Uniform(Distribution): + def __init__(self, lower, upper): + self.lower = lower + self.upper = upper + + def sample(self): + return self.lower + (self.upper - self.lower) * np.random.rand() + + def logp(self, x): + ... + + def kl(self, other): + ... + + def entropy(self): + ... + + @staticmethod + def required_input_dim(space): + ... + + def rsample(self): + ... + + @classmethod + def from_logits(cls, logits, **kwargs): + return Uniform(logits[:, 0], logits[:, 1]) + + logits = np.array([[0.0, 1.0], [2.0, 3.0]]) + my_dist = Uniform.from_logits(logits) + sample = my_dist.sample() + """ + raise NotImplementedError + + @classmethod + def get_partial_dist_cls( + parent_cls: "Distribution", **partial_kwargs + ) -> "Distribution": + """Returns a partial child of TorchMultiActionDistribution. + + This is useful if inputs needed to instantiate the Distribution from logits + are available, but the logits are not. + """ + + class DistributionPartial(parent_cls): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + @staticmethod + def _merge_kwargs(**kwargs): + """Checks if keys in kwargs don't clash with partial_kwargs.""" + overlap = set(kwargs) & set(partial_kwargs) + if overlap: + raise ValueError( + f"Cannot override the following kwargs: {overlap}.\n" + f"This is because they were already set at the time this " + f"partial class was defined." + ) + merged_kwargs = {**partial_kwargs, **kwargs} + return merged_kwargs + + @classmethod + @override(parent_cls) + def required_input_dim(cls, space: gym.Space, **kwargs) -> int: + merged_kwargs = cls._merge_kwargs(**kwargs) + assert space == merged_kwargs["space"] + return parent_cls.required_input_dim(**merged_kwargs) + + @classmethod + @override(parent_cls) + def from_logits( + cls, + logits: TensorType, + **kwargs, + ) -> "DistributionPartial": + merged_kwargs = cls._merge_kwargs(**kwargs) + distribution = parent_cls.from_logits(logits, **merged_kwargs) + # Replace the class of the returned distribution with this partial + # This makes it so that we can use type() on this distribution and + # get back the partial class. + distribution.__class__ = cls + return distribution + + # Substitute name of this partial class to match the original class. + DistributionPartial.__name__ = f"{parent_cls}Partial" + + return DistributionPartial + + def to_deterministic(self) -> "Distribution": + """Returns a deterministic equivalent for this distribution. + + Specifically, the deterministic equivalent for a Categorical distribution is a + Deterministic distribution that selects the action with maximum logit value. + Generally, the choice of the deterministic replacement is informed by + established conventions. + """ + return self diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/distribution/torch/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/distribution/torch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/distribution/torch/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/distribution/torch/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1da44295855ae03def90d59f7732f2ee51233065 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/distribution/torch/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/distribution/torch/__pycache__/torch_distribution.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/distribution/torch/__pycache__/torch_distribution.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74cd4062c7bb42c14cc81271e676d9af521bddff Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/distribution/torch/__pycache__/torch_distribution.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/distribution/torch/torch_distribution.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/distribution/torch/torch_distribution.py new file mode 100644 index 0000000000000000000000000000000000000000..e234f6f10c084041a346900e4f98d7938b4301eb --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/distribution/torch/torch_distribution.py @@ -0,0 +1,707 @@ +"""The main difference between this and the old ActionDistribution is that this one +has more explicit input args. So that the input format does not have to be guessed from +the code. This matches the design pattern of torch distribution which developers may +already be familiar with. +""" +import gymnasium as gym +import numpy as np +from typing import Dict, Iterable, List, Optional +import tree +import abc + + +from ray.rllib.core.distribution.distribution import Distribution +from ray.rllib.utils.annotations import override, DeveloperAPI +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.numpy import MAX_LOG_NN_OUTPUT, MIN_LOG_NN_OUTPUT, SMALL_NUMBER +from ray.rllib.utils.typing import TensorType, Union, Tuple + +torch, nn = try_import_torch() + + +@DeveloperAPI +class TorchDistribution(Distribution, abc.ABC): + """Wrapper class for torch.distributions.""" + + def __init__(self, *args, **kwargs): + super().__init__() + self._dist = self._get_torch_distribution(*args, **kwargs) + + @abc.abstractmethod + def _get_torch_distribution( + self, *args, **kwargs + ) -> "torch.distributions.Distribution": + """Returns the torch.distributions.Distribution object to use.""" + + @override(Distribution) + def logp(self, value: TensorType, **kwargs) -> TensorType: + return self._dist.log_prob(value, **kwargs) + + @override(Distribution) + def entropy(self) -> TensorType: + return self._dist.entropy() + + @override(Distribution) + def kl(self, other: "Distribution") -> TensorType: + return torch.distributions.kl.kl_divergence(self._dist, other._dist) + + @override(Distribution) + def sample( + self, + *, + sample_shape=None, + ) -> Union[TensorType, Tuple[TensorType, TensorType]]: + sample = self._dist.sample( + sample_shape if sample_shape is not None else torch.Size() + ) + return sample + + @override(Distribution) + def rsample( + self, + *, + sample_shape=None, + ) -> Union[TensorType, Tuple[TensorType, TensorType]]: + rsample = self._dist.rsample( + sample_shape if sample_shape is not None else torch.Size() + ) + return rsample + + @classmethod + @override(Distribution) + def from_logits(cls, logits: TensorType, **kwargs) -> "TorchDistribution": + return cls(logits=logits, **kwargs) + + +@DeveloperAPI +class TorchCategorical(TorchDistribution): + r"""Wrapper class for PyTorch Categorical distribution. + + Creates a categorical distribution parameterized by either :attr:`probs` or + :attr:`logits` (but not both). + + Samples are integers from :math:`\{0, \ldots, K-1\}` where `K` is + ``probs.size(-1)``. + + If `probs` is 1-dimensional with length-`K`, each element is the relative + probability of sampling the class at that index. + + If `probs` is N-dimensional, the first N-1 dimensions are treated as a batch of + relative probability vectors. + + .. testcode:: + :skipif: True + + m = TorchCategorical(torch.tensor([ 0.25, 0.25, 0.25, 0.25 ])) + m.sample(sample_shape=(2,)) # equal probability of 0, 1, 2, 3 + + .. testoutput:: + + tensor([3, 4]) + + Args: + logits: Event log probabilities (unnormalized) + probs: The probabilities of each event. + temperature: In case of using logits, this parameter can be used to determine + the sharpness of the distribution. i.e. + ``probs = softmax(logits / temperature)``. The temperature must be strictly + positive. A low value (e.g. 1e-10) will result in argmax sampling while a + larger value will result in uniform sampling. + """ + + @override(TorchDistribution) + def __init__( + self, + logits: "torch.Tensor" = None, + probs: "torch.Tensor" = None, + ) -> None: + # We assert this here because to_deterministic makes this assumption. + assert (probs is None) != ( + logits is None + ), "Exactly one out of `probs` and `logits` must be set!" + + self.probs = probs + self.logits = logits + super().__init__(logits=logits, probs=probs) + + # Build this distribution only if really needed (in `self.rsample()`). It's + # quite expensive according to cProfile. + self._one_hot = None + + @override(TorchDistribution) + def _get_torch_distribution( + self, + logits: "torch.Tensor" = None, + probs: "torch.Tensor" = None, + ) -> "torch.distributions.Distribution": + return torch.distributions.categorical.Categorical( + logits=logits, probs=probs, validate_args=False + ) + + @staticmethod + @override(Distribution) + def required_input_dim(space: gym.Space, **kwargs) -> int: + assert isinstance(space, gym.spaces.Discrete) + return int(space.n) + + @override(Distribution) + def rsample(self, sample_shape=()): + if self._one_hot is None: + self._one_hot = torch.distributions.one_hot_categorical.OneHotCategorical( + logits=self.logits, probs=self.probs, validate_args=False + ) + one_hot_sample = self._one_hot.sample(sample_shape) + return (one_hot_sample - self.probs).detach() + self.probs + + def to_deterministic(self) -> "TorchDeterministic": + if self.probs is not None: + probs_or_logits = self.probs + else: + probs_or_logits = self.logits + + return TorchDeterministic(loc=torch.argmax(probs_or_logits, dim=-1)) + + +@DeveloperAPI +class TorchDiagGaussian(TorchDistribution): + """Wrapper class for PyTorch Normal distribution. + + Creates a normal distribution parameterized by :attr:`loc` and :attr:`scale`. In + case of multi-dimensional distribution, the variance is assumed to be diagonal. + + .. testcode:: + :skipif: True + + loc, scale = torch.tensor([0.0, 0.0]), torch.tensor([1.0, 1.0]) + m = TorchDiagGaussian(loc=loc, scale=scale) + m.sample(sample_shape=(2,)) # 2d normal dist with loc=0 and scale=1 + + .. testoutput:: + + tensor([[ 0.1046, -0.6120], [ 0.234, 0.556]]) + + .. testcode:: + :skipif: True + + # scale is None + m = TorchDiagGaussian(loc=torch.tensor([0.0, 1.0])) + m.sample(sample_shape=(2,)) # normally distributed with loc=0 and scale=1 + + .. testoutput:: + + tensor([0.1046, 0.6120]) + + + Args: + loc: mean of the distribution (often referred to as mu). If scale is None, the + second half of the `loc` will be used as the log of scale. + scale: standard deviation of the distribution (often referred to as sigma). + Has to be positive. + """ + + @override(TorchDistribution) + def __init__( + self, + loc: Union[float, "torch.Tensor"], + scale: Optional[Union[float, "torch.Tensor"]], + ): + self.loc = loc + super().__init__(loc=loc, scale=scale) + + def _get_torch_distribution(self, loc, scale) -> "torch.distributions.Distribution": + return torch.distributions.normal.Normal(loc, scale, validate_args=False) + + @override(TorchDistribution) + def logp(self, value: TensorType) -> TensorType: + return super().logp(value).sum(-1) + + @override(TorchDistribution) + def entropy(self) -> TensorType: + return super().entropy().sum(-1) + + @override(TorchDistribution) + def kl(self, other: "TorchDistribution") -> TensorType: + return super().kl(other).sum(-1) + + @staticmethod + @override(Distribution) + def required_input_dim(space: gym.Space, **kwargs) -> int: + assert isinstance(space, gym.spaces.Box) + return int(np.prod(space.shape, dtype=np.int32) * 2) + + @classmethod + @override(Distribution) + def from_logits(cls, logits: TensorType, **kwargs) -> "TorchDiagGaussian": + loc, log_std = logits.chunk(2, dim=-1) + scale = log_std.exp() + return cls(loc=loc, scale=scale) + + def to_deterministic(self) -> "TorchDeterministic": + return TorchDeterministic(loc=self.loc) + + +@DeveloperAPI +class TorchSquashedGaussian(TorchDistribution): + @override(TorchDistribution) + def __init__( + self, + loc: Union[float, "torch.Tensor"], + scale: Optional[Union[float, "torch.Tensor"]] = 1.0, + low: float = -1.0, + high: float = 1.0, + ): + self.loc = loc + self.low = low + self.high = high + + super().__init__(loc=loc, scale=scale) + + def _get_torch_distribution(self, loc, scale) -> "torch.distributions.Distribution": + return torch.distributions.normal.Normal(loc, scale, validate_args=False) + + @override(TorchDistribution) + def sample( + self, *, sample_shape=None + ) -> Union[TensorType, Tuple[TensorType, TensorType]]: + # Sample from the Normal distribution. + sample = super().sample( + sample_shape=sample_shape if sample_shape is not None else torch.Size() + ) + # Return the squashed sample. + return self._squash(sample) + + @override(TorchDistribution) + def rsample( + self, *, sample_shape=None + ) -> Union[TensorType, Tuple[TensorType, TensorType]]: + # Sample from the Normal distribution. + sample = super().rsample( + sample_shape=sample_shape if sample_shape is not None else torch.Size() + ) + # Return the squashed sample. + return self._squash(sample) + + @override(TorchDistribution) + def logp(self, value: TensorType, **kwargs) -> TensorType: + # Unsquash value. + value = self._unsquash(value) + # Get log-probabilities from Normal distribution. + logp = super().logp(value, **kwargs) + # Clip the log probabilities as a safeguard and sum. + logp = torch.clamp(logp, -100, 100).sum(-1) + # Return the log probabilities for squashed Normal. + value = torch.tanh(value) + return logp - torch.log(1 - value**2 + SMALL_NUMBER).sum(-1) + + @override(TorchDistribution) + def entropy(self) -> TensorType: + raise ValueError("ENtropy not defined for `TorchSquashedGaussian`.") + + @override(TorchDistribution) + def kl(self, other: Distribution) -> TensorType: + raise ValueError("KL not defined for `TorchSquashedGaussian`.") + + def _squash(self, sample: TensorType) -> TensorType: + # Rescale the sample to interval given by the bounds (including the bounds). + sample = ((torch.tanh(sample) + 1.0) / 2.0) * (self.high - self.low) + self.low + # Return a clipped sample to comply with the bounds. + return torch.clamp(sample, self.low, self.high) + + def _unsquash(self, sample: TensorType) -> TensorType: + # Rescale to [-1.0, 1.0]. + sample = (sample - self.low) / (self.high - self.low) * 2.0 - 1.0 + # Stabilize input to atanh function. + sample = torch.clamp(sample, -1.0 + SMALL_NUMBER, 1.0 - SMALL_NUMBER) + return torch.atanh(sample) + + @staticmethod + @override(Distribution) + def required_input_dim(space: gym.Space, **kwargs) -> int: + assert isinstance(space, gym.spaces.Box), space + return int(np.prod(space.shape, dtype=np.int32) * 2) + + @classmethod + @override(TorchDistribution) + def from_logits( + cls, logits: TensorType, low: float = -1.0, high: float = 1.0, **kwargs + ) -> "TorchSquashedGaussian": + loc, log_std = logits.chunk(2, dim=-1) + # Clip the `scale` values (coming from the `RLModule.forward()`) to + # reasonable values. + log_std = torch.clamp(log_std, MIN_LOG_NN_OUTPUT, MAX_LOG_NN_OUTPUT) + scale = log_std.exp() + + # Assert that `low` is smaller than `high`. + assert np.all(np.less(low, high)) + # Return class instance. + return cls(loc=loc, scale=scale, low=low, high=high, **kwargs) + + def to_deterministic(self) -> Distribution: + return TorchDeterministic(loc=self.loc) + + +@DeveloperAPI +class TorchDeterministic(Distribution): + """The distribution that returns the input values directly. + + This is similar to DiagGaussian with standard deviation zero (thus only + requiring the "mean" values as NN output). + + Note: entropy is always zero, ang logp and kl are not implemented. + + .. testcode:: + :skipif: True + + m = TorchDeterministic(loc=torch.tensor([0.0, 0.0])) + m.sample(sample_shape=(2,)) + + .. testoutput:: + + tensor([[ 0.0, 0.0], [ 0.0, 0.0]]) + + Args: + loc: the determinsitic value to return + """ + + @override(Distribution) + def __init__(self, loc: "torch.Tensor") -> None: + super().__init__() + self.loc = loc + + @override(Distribution) + def sample( + self, + *, + sample_shape=None, + **kwargs, + ) -> Union[TensorType, Tuple[TensorType, TensorType]]: + device = self.loc.device + dtype = self.loc.dtype + shape = ( + sample_shape if sample_shape is not None else torch.Size() + ) + self.loc.shape + return torch.ones(shape, device=device, dtype=dtype) * self.loc + + def rsample( + self, + *, + sample_shape: Tuple[int, ...] = None, + **kwargs, + ) -> Union[TensorType, Tuple[TensorType, TensorType]]: + raise NotImplementedError + + @override(Distribution) + def logp(self, value: TensorType, **kwargs) -> TensorType: + return torch.zeros_like(self.loc) + + @override(Distribution) + def entropy(self, **kwargs) -> TensorType: + raise RuntimeError(f"`entropy()` not supported for {self.__class__.__name__}.") + + @override(Distribution) + def kl(self, other: "Distribution", **kwargs) -> TensorType: + raise RuntimeError(f"`kl()` not supported for {self.__class__.__name__}.") + + @staticmethod + @override(Distribution) + def required_input_dim(space: gym.Space, **kwargs) -> int: + assert isinstance(space, gym.spaces.Box) + return int(np.prod(space.shape, dtype=np.int32)) + + def to_deterministic(self) -> "TorchDeterministic": + return self + + +@DeveloperAPI +class TorchMultiCategorical(Distribution): + """MultiCategorical distribution for MultiDiscrete action spaces.""" + + @override(Distribution) + def __init__( + self, + categoricals: List[TorchCategorical], + ): + super().__init__() + self._cats = categoricals + + @override(Distribution) + def sample(self) -> TensorType: + arr = [cat.sample() for cat in self._cats] + sample_ = torch.stack(arr, dim=-1) + return sample_ + + @override(Distribution) + def rsample(self, sample_shape=()): + arr = [cat.rsample() for cat in self._cats] + sample_ = torch.stack(arr, dim=-1) + return sample_ + + @override(Distribution) + def logp(self, value: "torch.Tensor") -> TensorType: + value = torch.unbind(value, dim=-1) + logps = torch.stack([cat.logp(act) for cat, act in zip(self._cats, value)]) + return torch.sum(logps, dim=0) + + @override(Distribution) + def entropy(self) -> TensorType: + return torch.sum( + torch.stack([cat.entropy() for cat in self._cats], dim=-1), dim=-1 + ) + + @override(Distribution) + def kl(self, other: Distribution) -> TensorType: + kls = torch.stack( + [cat.kl(oth_cat) for cat, oth_cat in zip(self._cats, other._cats)], + dim=-1, + ) + return torch.sum(kls, dim=-1) + + @staticmethod + @override(Distribution) + def required_input_dim(space: gym.Space, **kwargs) -> int: + assert isinstance(space, gym.spaces.MultiDiscrete) + return int(np.sum(space.nvec)) + + @classmethod + @override(Distribution) + def from_logits( + cls, + logits: "torch.Tensor", + input_lens: List[int], + temperatures: List[float] = None, + **kwargs, + ) -> "TorchMultiCategorical": + """Creates this Distribution from logits (and additional arguments). + + If you wish to create this distribution from logits only, please refer to + `Distribution.get_partial_dist_cls()`. + + Args: + logits: The tensor containing logits to be separated by logit_lens. + child_distribution_cls_struct: A struct of Distribution classes that can + be instantiated from the given logits. + input_lens: A list of integers that indicate the length of the logits + vectors to be passed into each child distribution. + temperatures: A list of floats representing the temperature to use for + each Categorical distribution. If not provided, 1.0 is used for all. + **kwargs: Forward compatibility kwargs. + """ + if not temperatures: + # If temperatures are not provided, use 1.0 for all actions. + temperatures = [1.0] * len(input_lens) + + assert ( + sum(input_lens) == logits.shape[-1] + ), "input_lens must sum to logits.shape[-1]" + assert len(input_lens) == len( + temperatures + ), "input_lens and temperatures must be same length" + + categoricals = [ + TorchCategorical(logits=logits) + for logits in torch.split(logits, input_lens, dim=-1) + ] + + return cls(categoricals=categoricals) + + def to_deterministic(self) -> "TorchDeterministic": + """Converts `TorchMultiCategorical` into `TorchDeterministic`.""" + logits_list = [cat.logits for cat in self._cats] + # Check, if the module is recurrent. + is_recurrent = logits_list[0].dim() == 3 # (B, T, K_i) + + # Determine max number of categories across all categorical distributions + max_K = max(logits.shape[-1] for logits in logits_list) + + padded_logits = [] + for logits in logits_list: + # Pad last dimension (category dim) to max_K + pad_width = max_K - logits.shape[-1] + # If the distributions have different number of categories, pad. + if pad_width > 0: + # Pad only last dimension + pad_dims = (0, pad_width) + logits = nn.functional.pad(logits, pad_dims, value=-float("inf")) + padded_logits.append(logits) + + # Stack along new dim=0 (categorical dimension). + # Shape: (num_components, B, T, max_K) or (num_components, B, max_K) + stacked = torch.stack(padded_logits, dim=0) + + # Move categorical dim (0) to last if needed, and take argmax. + if is_recurrent: + # Current shape is (num_components, B, T, K) and we want to have + # (B, T, num_components) via argmax over last dimension. So take + # argmax over last dim (K), then permute. + argmax = torch.argmax(stacked, dim=-1) # shape: (num_components, B, T) + loc = argmax.permute(1, 2, 0) # (B, T, num_components) + else: + # stacked: (num_components, B, K) + # → argmax over last dim (K), shape: (num_components, B) + # → transpose to (B, num_components) + argmax = torch.argmax(stacked, dim=-1) # (num_components, B) + loc = argmax.transpose(0, 1) # (B, num_components) + + return TorchDeterministic(loc=loc) + + +@DeveloperAPI +class TorchMultiDistribution(Distribution): + """Action distribution that operates on multiple, possibly nested actions.""" + + def __init__( + self, + child_distribution_struct: Union[Tuple, List, Dict], + ): + """Initializes a TorchMultiDistribution object. + + Args: + child_distribution_struct: A complex struct that contains the child + distribution instances that make up this multi-distribution. + """ + super().__init__() + self._original_struct = child_distribution_struct + self._flat_child_distributions = tree.flatten(child_distribution_struct) + + @override(Distribution) + def rsample( + self, + *, + sample_shape: Tuple[int, ...] = None, + **kwargs, + ) -> Union[TensorType, Tuple[TensorType, TensorType]]: + rsamples = [] + for dist in self._flat_child_distributions: + rsample = dist.rsample(sample_shape=sample_shape, **kwargs) + rsamples.append(rsample) + + rsamples = tree.unflatten_as(self._original_struct, rsamples) + + return rsamples + + @override(Distribution) + def logp(self, value: TensorType) -> TensorType: + # Different places in RLlib use this method with different inputs. + # We therefore need to handle a flattened and concatenated input, as well as + # a nested one. + # TODO(Artur): Deprecate tensor inputs, only allow nested structures. + if isinstance(value, torch.Tensor): + split_indices = [] + for dist in self._flat_child_distributions: + if isinstance(dist, TorchCategorical): + split_indices.append(1) + elif isinstance(dist, TorchMultiCategorical): + split_indices.append(len(dist._cats)) + else: + sample = dist.sample() + # Cover Box(shape=()) case. + if len(sample.shape) == 1: + split_indices.append(1) + else: + split_indices.append(sample.size()[1]) + split_value = list(torch.split(value, split_indices, dim=1)) + else: + split_value = tree.flatten(value) + + def map_(val, dist): + # Remove extra dimension if present. + if ( + isinstance(dist, TorchCategorical) + and val.shape[-1] == 1 + and len(val.shape) > 1 + ): + val = torch.squeeze(val, dim=-1) + return dist.logp(val) + + flat_logps = tree.map_structure( + map_, split_value, self._flat_child_distributions + ) + + return sum(flat_logps) + + @override(Distribution) + def kl(self, other: Distribution) -> TensorType: + kl_list = [ + d.kl(o) + for d, o in zip( + self._flat_child_distributions, other._flat_child_distributions + ) + ] + return sum(kl_list) + + @override(Distribution) + def entropy(self): + entropy_list = [d.entropy() for d in self._flat_child_distributions] + return sum(entropy_list) + + @override(Distribution) + def sample(self): + child_distributions_struct = tree.unflatten_as( + self._original_struct, self._flat_child_distributions + ) + return tree.map_structure(lambda s: s.sample(), child_distributions_struct) + + @staticmethod + @override(Distribution) + def required_input_dim( + space: gym.Space, input_lens: List[int], as_list: bool = False, **kwargs + ) -> int: + if as_list: + return input_lens + else: + return sum(input_lens) + + @classmethod + @override(Distribution) + def from_logits( + cls, + logits: "torch.Tensor", + child_distribution_cls_struct: Union[Dict, Iterable], + input_lens: Union[Dict, List[int]], + **kwargs, + ) -> "TorchMultiDistribution": + """Creates this Distribution from logits (and additional arguments). + + If you wish to create this distribution from logits only, please refer to + `Distribution.get_partial_dist_cls()`. + + Args: + logits: The tensor containing logits to be separated by `input_lens`. + child_distribution_cls_struct: A struct of Distribution classes that can + be instantiated from the given logits. + child_distribution_cls_struct: A struct of Distribution classes that can + be instantiated from the given logits. + input_lens: A list or dict of integers that indicate the length of each + logit. If this is given as a dict, the structure should match the + structure of child_distribution_cls_struct. + **kwargs: Forward compatibility kwargs. + + Returns: + A TorchMultiDistribution object. + """ + logit_lens = tree.flatten(input_lens) + child_distribution_cls_list = tree.flatten(child_distribution_cls_struct) + split_logits = torch.split(logits, logit_lens, dim=-1) + + child_distribution_list = tree.map_structure( + lambda dist, input_: dist.from_logits(input_), + child_distribution_cls_list, + list(split_logits), + ) + + child_distribution_struct = tree.unflatten_as( + child_distribution_cls_struct, child_distribution_list + ) + + return cls( + child_distribution_struct=child_distribution_struct, + ) + + def to_deterministic(self) -> "TorchMultiDistribution": + flat_deterministic_dists = [ + dist.to_deterministic() for dist in self._flat_child_distributions + ] + deterministic_dists = tree.unflatten_as( + self._original_struct, flat_deterministic_dists + ) + return TorchMultiDistribution(deterministic_dists) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1265532aa05f4cf40792ccec9b2309465c7fae54 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/__init__.py @@ -0,0 +1,8 @@ +from ray.rllib.core.learner.learner import Learner +from ray.rllib.core.learner.learner_group import LearnerGroup + + +__all__ = [ + "Learner", + "LearnerGroup", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59ebd649aeb94ad9c81c90e7076ca370fa4c8189 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/__pycache__/differentiable_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/__pycache__/differentiable_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50146b7433344c4fb69f53352e880bc714c7a254 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/__pycache__/differentiable_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/__pycache__/differentiable_learner_config.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/__pycache__/differentiable_learner_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..048a147129304e619e5c2b3b515556fc9b9e0d69 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/__pycache__/differentiable_learner_config.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/__pycache__/learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/__pycache__/learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99c27548632146293caefc5d432b31881bb2d7f8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/__pycache__/learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/__pycache__/learner_group.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/__pycache__/learner_group.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f282775090b67e7af4fa858c946c563986b78f5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/__pycache__/learner_group.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/__pycache__/training_data.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/__pycache__/training_data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f2f695c596a89ba699c92988b9570301a05c9a8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/__pycache__/training_data.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/__pycache__/utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7400e9cdb701d855086d201a9f2b4e0ccffa232f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/__pycache__/utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/differentiable_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/differentiable_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..8d118aacfae8169a78c58bf272090c04167a7165 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/differentiable_learner.py @@ -0,0 +1,812 @@ +import abc +import logging +import numpy +from typing import ( + Any, + Collection, + Dict, + Iterable, + Optional, + Tuple, + TYPE_CHECKING, + Union, +) + +from ray.rllib.connectors.learner.learner_connector_pipeline import ( + LearnerConnectorPipeline, +) +from ray.rllib.core import ALL_MODULES, COMPONENT_METRICS_LOGGER +from ray.rllib.core.learner.training_data import TrainingData +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModule +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.policy.sample_batch import MultiAgentBatch, SampleBatch +from ray.rllib.utils import unflatten_dict +from ray.rllib.utils.annotations import ( + override, + OverrideToImplementCustomLogic, + OverrideToImplementCustomLogic_CallToSuperRecommended, +) +from ray.rllib.utils.checkpoints import Checkpointable +from ray.rllib.utils.metrics import ( + DATASET_NUM_ITERS_TRAINED, + DATASET_NUM_ITERS_TRAINED_LIFETIME, + NUM_ENV_STEPS_TRAINED, + NUM_ENV_STEPS_TRAINED_LIFETIME, + NUM_MODULE_STEPS_TRAINED, + NUM_MODULE_STEPS_TRAINED_LIFETIME, + MODULE_TRAIN_BATCH_SIZE_MEAN, + WEIGHTS_SEQ_NO, +) +from ray.rllib.utils.metrics.metrics_logger import MetricsLogger +from ray.rllib.utils.minibatch_utils import ( + MiniBatchCyclicIterator, + MiniBatchDummyIterator, + MiniBatchRayDataIterator, +) +from ray.rllib.utils.typing import ( + DeviceType, + ModuleID, + NamedParamDict, + ResultDict, + StateDict, + TensorType, +) + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + from ray.rllib.core.learner.differentiable_learner_config import ( + DifferentiableLearnerConfig, + ) + +logger = logging.getLogger(__name__) + + +class DifferentiableLearner(Checkpointable): + """A differentiable `Learner` class enabling functional parameter updates. + + This class is part of RLlib's Meta Learning API and provides a differentiable + `Learner`, allowing higher-order updates within the meta-learning loop. + + Unlike standard learners, this class operates on a provided `RLModule` reference + instead of creating its own. Updated cloned module parameters are returned to the + caller, facilitating further update processes. + + The `update`, `_update`, `compute_gradients`, and `apply_gradients` methods + require, in addition to other arguments, a dictionary of cloned `RLModule` + parameters for functional updates. + """ + + # The framework an instance uses. + framework_str: str + + # The key for the total loss. + TOTAL_LOSS_KEY: str = "total_loss" + + def __init__( + self, + *, + config: "AlgorithmConfig", + learner_config: "DifferentiableLearnerConfig", + module: Optional[RLModule] = None, + **kwargs, + ) -> None: + + # An `AlgorithmConfig` used to access certain global configurations. + self.config: "AlgorithmConfig" = config.copy(copy_frozen=False) + # The specific configuration for the differentiable learner instance. + self.learner_config: "DifferentiableLearnerConfig" = learner_config + # The reference to the caller's module. + self._module: Optional[MultiRLModule] = module + # The reference to the caller's device. + self._device: Optional[DeviceType] = None + # A counter for functional weight updates. + self._weights_seq_no: int = 0 + + # Whether self.build has already been called. + self._is_built: bool = False + + # The learner connector pipeline. + self._learner_connector: Optional[LearnerConnectorPipeline] = None + + # The Learner's own MetricsLogger to be used to log RLlib's built-in metrics or + # custom user-defined ones (e.g. custom loss values). When returning from an + # `update_from_...()` method call, the Learner will do a `self.metrics.reduce()` + # and return the resulting (reduced) dict. + self.metrics: MetricsLogger = MetricsLogger() + + # In case of offline learning and multiple learners, each learner receives a + # repeatable iterator that iterates over a split of the streamed data. + self.iterator: MiniBatchRayDataIterator = None + + @OverrideToImplementCustomLogic_CallToSuperRecommended + def build(self, device: Optional[DeviceType] = None) -> None: + + if self._is_built: + logger.debug("DifferentiableLearner already built. Skipping built.") + + # If a dvice was passed, set the `DifferentiableLearner`'s device. + if device: + self._device = device + + # TODO (simon): Move the `build_learner_connector` to the + # `DifferentiableLearnerConfig`. + self._learner_connector = self.learner_config.build_learner_connector( + input_observation_space=None, + input_action_space=None, + device=self._device, + ) + + # This instance is now ready for use. + self._is_built = True + + @OverrideToImplementCustomLogic + @abc.abstractmethod + def compute_gradients( + self, + loss_per_module: Dict[ModuleID, TensorType], + params: Dict[ModuleID, NamedParamDict], + **kwargs, + ) -> Dict[ModuleID, NamedParamDict]: + """Computes functional gradients based on the given losses. + + Note that this method requires computing gradients functionally, + without relying on an optimizer. If an optimizer is needed, a + differentiable optimizer from a third-party package must be used. + + Args: + loss_per_module: Dict mapping module IDs to their individual total loss + terms, computed by the individual `compute_loss_for_module()` calls. + The overall total loss (sum of loss terms over all modules) is stored + under `loss_per_module[ALL_MODULES]`. + params: A dictionary containing cloned parameters for each module id. + **kwargs: Forward compatibility kwargs. + + Returns: + The gradients in the same (dict) format as `params`. + """ + + @OverrideToImplementCustomLogic + @abc.abstractmethod + def apply_gradients( + self, + gradients: Dict[ModuleID, NamedParamDict], + params: Dict[ModuleID, NamedParamDict], + ) -> Dict[ModuleID, NamedParamDict]: + """Applies given gradients functionally. + + Note that this method requires functional parameter updates, + meaning modifications must not be performed in-place (e.g., via an + optimizer or directly within the `MultiRLModule`). + + Args: + gradients: A dictionary containing named gradients for each module id. + params: A dictionary containing named parameters for each module id. + + Returns: + The updated parameters in the same (dict) format as `params`. + """ + + @OverrideToImplementCustomLogic + def should_module_be_updated(self, module_id, multi_agent_batch=None): + """Returns whether a module should be updated or not based on `self.config`. + + Args: + module_id: The ModuleID that we want to query on whether this module + should be updated or not. + multi_agent_batch: An optional MultiAgentBatch to possibly provide further + information on the decision on whether the RLModule should be updated + or not. + """ + should_module_be_updated_fn = self.config.policies_to_train + # If None, return True (by default, all modules should be updated). + if should_module_be_updated_fn is None: + return True + # If collection given, return whether `module_id` is in that container. + elif not callable(should_module_be_updated_fn): + return module_id in set(should_module_be_updated_fn) + + return should_module_be_updated_fn(module_id, multi_agent_batch) + + @OverrideToImplementCustomLogic + def compute_losses( + self, *, fwd_out: Dict[str, Any], batch: Dict[str, Any] + ) -> Dict[str, Any]: + """Computes the loss(es) for the module being optimized. + + This method must be overridden by MultiRLModule-specific Learners in order to + define the specific loss computation logic. If the algorithm is single-agent, + only `compute_loss_for_module()` should be overridden instead. If the algorithm + uses independent multi-agent learning (default behavior for RLlib's multi-agent + setups), also only `compute_loss_for_module()` should be overridden, but it will + be called for each individual RLModule inside the MultiRLModule. + For the functional update to work, no `forward` call should be made + within this method, especially not a non-functional one. Instead, use + the model outputs provided by `fwd_out`. + + Args: + fwd_out: Output from a functional call to the `forward_train()` method of the + underlying MultiRLModule (`self.module`) during training + (`self.update()`). + batch: The train batch that was used to compute `fwd_out`. + + Returns: + A dictionary mapping module IDs to individual loss terms. + """ + loss_per_module = {} + for module_id in fwd_out: + loss = self.compute_loss_for_module( + module_id=module_id, + # TODO (simon): Check, if this should be provided per + # `DifferentiableLearnerConfig`. + config=self.config.get_config_for_module(module_id), + batch=batch[module_id], + fwd_out=fwd_out[module_id], + ) + loss_per_module[module_id] = loss + + return loss_per_module + + @OverrideToImplementCustomLogic + @abc.abstractmethod + def compute_loss_for_module( + self, + *, + module_id: ModuleID, + config: "AlgorithmConfig", + batch: Dict[str, Any], + fwd_out: Dict[str, TensorType], + ) -> TensorType: + """Computes the loss for a single module. + + Think of this as computing loss for a single agent. For multi-agent use-cases + that require more complicated computation for loss, consider overriding the + `compute_losses` method instead. + + Args: + module_id: The id of the module. + config: The AlgorithmConfig specific to the given `module_id`. + batch: The train batch for this particular module. + fwd_out: The output of the forward pass for this particular module. + + Returns: + A single total loss tensor. If you have more than one optimizer on the + provided `module_id` and would like to compute gradients separately using + these different optimizers, simply add up the individual loss terms for + each optimizer and return the sum. Also, for recording/logging any + individual loss terms, you can use the `Learner.metrics.log_value( + key=..., value=...)` or `DifferentiableLearner.metrics.log_dict()` APIs. + See: :py:class:`~ray.rllib.utils.metrics.metrics_logger.MetricsLogger` for + more information. + """ + + def update( + self, + params: Dict[ModuleID, NamedParamDict], + training_data: TrainingData, + *, + _no_metrics_reduce: bool = False, + **kwargs, + ) -> Tuple[Dict[ModuleID, NamedParamDict], ResultDict]: + """Make a functional update on provided parameters. + + You can use this method to take more than one backward pass on the batch. All + configuration parameters for the iteration loop are set within the + `learner_config`. Note, the same configuration will be used for all module ids + in `MultiRLModule`. + + Args: + params: A parameter dictionary holding named parameters for each module id. + These parameters must be a clone of the module's original parameters to + perform a functional update on them. + training_data: A `TrainingData` instance containing the data or data iterators + to be used in updating the given parameters in `param`. + + Returns: + The functionally updated parameters in the (dict) format they were passed in + and a `ResultDict` object produced by a call to `self.metrics.reduce()`. The + returned dict may be arbitrarily nested and must have `Stats` objects at + all its leafs, allowing components further downstream (i.e. a user of this + Learner) to further reduce these results (for example over n parallel + Learners). + """ + self._check_is_built() + + # TODO (simon): Implement a `before_gradient_based_update`, if necessary. + # Call `before_gradient_based_update` to allow for non-gradient based + # preparations-, logging-, and update logic to happen. + # self.before_gradient_based_update(timesteps=timesteps or {}) + + training_data.validate() + training_data.solve_refs() + assert training_data.batches is None, "`training_data.batches` must be None!" + + self._weights_seq_no += 1 + + batch_iter = self._create_iterator_if_necessary( + training_data=training_data, + num_total_minibatches=self.learner_config.num_total_minibatches, + num_epochs=self.learner_config.num_epochs, + minibatch_size=self.learner_config.minibatch_size, + shuffle_batch_per_epoch=self.learner_config.shuffle_batch_per_epoch, + ) + + self.metrics.activate_tensor_mode() + + # Perform the actual looping through the minibatches or the given data iterator. + for iteration, tensor_minibatch in enumerate(batch_iter): + # Check the MultiAgentBatch, whether our RLModule contains all ModuleIDs + # found in this batch. If not, throw an error. + unknown_module_ids = set(tensor_minibatch.policy_batches.keys()) - set( + self.module.keys() + ) + if unknown_module_ids: + raise ValueError( + f"Batch contains one or more ModuleIDs ({unknown_module_ids}) that " + f"are not in this Learner!" + ) + + # Make the actual in-graph/traced `_update` call. This should return + # all tensor values (no numpy). + fwd_out, loss_per_module, params, _ = self._update( + # TODO (simon): Maybe filter ParamDict by module keys in batch. + tensor_minibatch.policy_batches, + params, + ) + + # TODO (sven): Maybe move this into loop above to get metrics more accuratcely + # cover the minibatch/epoch logic. + # Log all timesteps (env, agent, modules) based on given episodes/batch. + self._log_steps_trained_metrics(tensor_minibatch) + + self._set_slicing_by_batch_id(tensor_minibatch, value=False) + + if self.iterator: + # Record the number of batches pulled from the dataset. + self.metrics.log_value( + (ALL_MODULES, DATASET_NUM_ITERS_TRAINED), + iteration + 1, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (ALL_MODULES, DATASET_NUM_ITERS_TRAINED_LIFETIME), + iteration + 1, + reduce="sum", + ) + # Log all individual RLModules' loss terms and its registered optimizers' + # current learning rates. + # Note: We do this only once for the last of the minibatch updates, b/c the + # window is only 1 anyways. + for mid, loss in loss_per_module.items(): + self.metrics.log_value( + key=(mid, self.TOTAL_LOSS_KEY), + value=loss, + window=1, + ) + + # Call `after_gradient_based_update` to allow for non-gradient based + # cleanups-, logging-, and update logic to happen. + # TODO (simon): Check, if this should stay here, when running multiple + # gradient steps inside the iterator loop above (could be a complete epoch) + # the target networks might need to be updated earlier. + # self.after_gradient_based_update(timesteps=timesteps or {}) + self.metrics.deactivate_tensor_mode() + + # Reduce results across all minibatch update steps. + if not _no_metrics_reduce: + return params, loss_per_module, self.metrics.reduce() + else: + return params, loss_per_module, {} + + def _create_iterator_if_necessary( + self, + *, + training_data: TrainingData, + num_total_minibatches: int = 0, + num_epochs: int = 1, + minibatch_size: Optional[int] = None, + shuffle_batch_per_epoch: bool = False, + **kwargs, + ) -> Iterable: + """Provides a batch iterator.""" + + # Data iterator provided. + if training_data.data_iterators: + num_iters = kwargs.pop("num_iters", None) + if num_iters is None: + raise ValueError( + "Learner.update(data_iterators=..) requires `num_iters` kwarg!" + ) + + def _collate_fn(_batch: Dict[str, numpy.ndarray]) -> MultiAgentBatch: + _batch = unflatten_dict(_batch) + _batch = MultiAgentBatch( + { + module_id: SampleBatch(module_data) + for module_id, module_data in _batch.items() + }, + env_steps=sum( + len(next(iter(module_data.values()))) + for module_data in _batch.values() + ), + ) + _batch = self._convert_batch_type(_batch, to_device=False) + return self._set_slicing_by_batch_id(_batch, value=True) + + def _finalize_fn(batch: MultiAgentBatch) -> MultiAgentBatch: + return self._convert_batch_type(batch, to_device=True, use_stream=True) + + if not self.iterator: + # This iterator holds a `ray.data.DataIterator` and manages it state. + self.iterator = MiniBatchRayDataIterator( + iterator=training_data.data_iterators[0], + collate_fn=_collate_fn, + finalize_fn=_finalize_fn, + minibatch_size=minibatch_size, + num_iters=num_iters, + **kwargs, + ) + + batch_iter = self.iterator + else: + batch = self._make_batch_if_necessary(training_data=training_data) + assert batch is not None + + # TODO: Move this into LearnerConnector pipeline? + # Filter out those RLModules from the final train batch that should not be + # updated. + for module_id in list(batch.policy_batches.keys()): + if not self.should_module_be_updated(module_id, batch): + del batch.policy_batches[module_id] + if not batch.policy_batches: + return {} + + batch = self._set_slicing_by_batch_id(batch, value=True) + + if minibatch_size: + batch_iter_cls = MiniBatchCyclicIterator + elif num_epochs > 1: + # `minibatch_size` was not set but `num_epochs` > 1. + minibatch_size = batch.count + # Note that there is no need to shuffle here, b/c we don't have + # minibatches. + batch_iter_cls = MiniBatchCyclicIterator + else: + # `minibatch_size` and `num_epochs` are not set by the user. + batch_iter_cls = MiniBatchDummyIterator + + batch_iter = batch_iter_cls( + batch, + num_epochs=num_epochs, + minibatch_size=minibatch_size, + shuffle_batch_per_epoch=shuffle_batch_per_epoch and (num_epochs > 1), + num_total_minibatches=num_total_minibatches, + ) + return batch_iter + + @OverrideToImplementCustomLogic + @abc.abstractmethod + def _update( + self, + batch: Dict[str, Any], + params: Dict[ModuleID, NamedParamDict], + **kwargs, + ) -> Tuple[Any, Dict[ModuleID, NamedParamDict], Any, Any]: + """Contains all logic for an in-graph/traceable functional update step. + + Framework specific subclasses must implement this method. This should include + functional calls to the RLModule's `forward_train`, `compute_loss`, + `compute_gradients`, `postprocess_gradients`, and `apply_gradients` methods + and return a tuple with all the individual results as well as the functionally + updated parameter dictionary. + + Args: + batch: The train batch already converted to a Dict mapping str to (possibly + nested) tensors. + kwargs: Forward compatibility kwargs. + + Returns: + A tuple consisting of: + 1) the output of a functional forward call to the RLModule using + `params`, + 2) the functionally updated parameters in the (dict) format passed in, + 3) the `loss_per_module` dictionary mapping module IDs to individual + loss tensors, + 4) a metrics dict mapping module IDs to metrics key/value pairs. + + """ + + @override(Checkpointable) + def get_state( + self, + components: Optional[Union[str, Collection[str]]] = None, + *, + not_components: Optional[Union[str, Collection[str]]] = None, + **kwargs, + ) -> StateDict: + """Gets the state of the `DifferentiableLearner` instance. + + Note, because the `MultiRLModule` held by this class is only a reference + it is not contained in the class' state. + """ + self._check_is_built() + + state = { + "should_module_be_updated": self.config.policies_to_train, + WEIGHTS_SEQ_NO: self._weights_seq_no, + } + + if self._check_component(COMPONENT_METRICS_LOGGER, components, not_components): + # TODO (sven): Make `MetricsLogger` a Checkpointable. + state[COMPONENT_METRICS_LOGGER] = self.metrics.get_state() + + return state + + @override(Checkpointable) + def set_state(self, state: StateDict) -> None: + """Sets the state of the `DifferentiableLearner` instance.""" + self._check_is_built() + + weights_seq_no = state.get(WEIGHTS_SEQ_NO, 0) + + # Update our weights_seq_no, if the new one is > 0. + if weights_seq_no > 0: + self._weights_seq_no = weights_seq_no + + # Update our trainable Modules information/function via our config. + # If not provided in state (None), all Modules will be trained by default. + if "should_module_be_updated" in state: + self.config.multi_agent(policies_to_train=state["should_module_be_updated"]) + + # TODO (sven): Make `MetricsLogger` a Checkpointable. + if COMPONENT_METRICS_LOGGER in state: + self.metrics.set_state(state[COMPONENT_METRICS_LOGGER]) + + @override(Checkpointable) + def get_ctor_args_and_kwargs(self): + return ( + (), # *args, + { + "config": self.config, + }, # **kwargs + ) + + @override(Checkpointable) + def get_checkpointable_components(self): + if not self._check_is_built(error=False): + self.build() + return [] + + # TODO (simon): Duplicate in Learner. Move to base class "Learnable". + def _make_batch_if_necessary(self, training_data): + batch = training_data.batch + + # Call the learner connector on the given `episodes` (if we have one). + if training_data.episodes is not None: + # If we want to learn from Episodes, we must have a LearnerConnector + # pipeline to translate into a train batch first. + if self._learner_connector is None: + raise ValueError( + f"If episodes provided for training, Learner ({self}) must have a " + "LearnerConnector pipeline (but pipeline is None)!" + ) + + # Call the learner connector pipeline. + shared_data = {} + batch = self._learner_connector( + rl_module=self.module, + batch=training_data.batch if training_data.batch is not None else {}, + episodes=training_data.episodes, + shared_data=shared_data, + metrics=self.metrics, + ) + # Convert to a batch. + # TODO (sven): Try to not require MultiAgentBatch anymore. + batch = MultiAgentBatch( + { + module_id: ( + SampleBatch(module_data, _zero_padded=True) + if shared_data.get(f"_zero_padded_for_mid={module_id}") + else SampleBatch(module_data) + ) + for module_id, module_data in batch.items() + }, + env_steps=sum(len(e) for e in training_data.episodes), + ) + # Single-agent SampleBatch: Have to convert to MultiAgentBatch. + elif isinstance(training_data.batch, SampleBatch): + if len(self.module) != 1: + raise ValueError( + f"SampleBatch provided, but RLModule ({self.module}) has more than " + f"one sub-RLModule! Need to provide MultiAgentBatch instead." + ) + + batch = MultiAgentBatch( + {next(iter(self.module.keys())): training_data.batch}, + env_steps=len(training_data.batch), + ) + # If we already have an `MultiAgentBatch` but with `numpy` array, convert to + # tensors. + elif ( + isinstance(training_data.batch, MultiAgentBatch) + and training_data.batch.policy_batches + and ( + isinstance( + next(iter(training_data.batch.policy_batches.values()))["obs"], + numpy.ndarray, + ) + or next(iter(training_data.batch.policy_batches.values()))["obs"].device + != self._device + ) + ): + batch = self._convert_batch_type(training_data.batch) + + return batch + + # TODO (simon): Duplicate in Learner. Move to base class "Learnable". + def _set_slicing_by_batch_id( + self, batch: MultiAgentBatch, *, value: bool + ) -> MultiAgentBatch: + """Enables slicing by batch id in the given batch. + + If the input batch contains batches of sequences we need to make sure when + slicing happens it is sliced via batch id and not timestamp. Calling this + method enables the same flag on each SampleBatch within the input + MultiAgentBatch. + + Args: + batch: The MultiAgentBatch to enable slicing by batch id on. + value: The value to set the flag to. + + Returns: + The input MultiAgentBatch with the indexing flag is enabled / disabled on. + """ + + for pid, policy_batch in batch.policy_batches.items(): + # We assume that arriving batches for recurrent modules OR batches that + # have a SEQ_LENS column are already zero-padded to the max sequence length + # and have tensors of shape [B, T, ...]. Therefore, we slice sequence + # lengths in B. See SampleBatch for more information. + if ( + self.module[pid].is_stateful() + or policy_batch.get("seq_lens") is not None + ): + if value: + policy_batch.enable_slicing_by_batch_id() + else: + policy_batch.disable_slicing_by_batch_id() + + return batch + + # TODO (simon): Duplicate in Learner. Move to base class "Learnable". + def _check_is_built(self, error: bool = True) -> bool: + if self.module is None: + if error: + raise ValueError( + "Learner.build() must be called after constructing a " + "Learner and before calling any methods on it." + ) + return False + return True + + @abc.abstractmethod + def _get_tensor_variable( + self, + value: Any, + dtype: Any = None, + trainable: bool = False, + ) -> TensorType: + """Returns a framework-specific tensor variable with the initial given value. + + This is a framework specific method that should be implemented by the + framework specific sub-classes. + + Args: + value: The initial value for the tensor variable variable. + + Returns: + The framework specific tensor variable of the given initial value, + dtype and trainable/requires_grad property. + """ + + # TODO (simon): Duplicate in Learner. Move to base class "Learnable". + def _reset(self): + self.metrics = MetricsLogger() + self._is_built = False + + # TODO (simon): Duplicate in Learner. Move to base class "Learnable". + def _log_steps_trained_metrics(self, batch: MultiAgentBatch): + """Logs this iteration's steps trained, based on given `batch`.""" + for mid, module_batch in batch.policy_batches.items(): + # Log weights seq no for this batch. + self.metrics.log_value( + (mid, WEIGHTS_SEQ_NO), + self._weights_seq_no, + window=1, + ) + + module_batch_size = len(module_batch) + # Log average batch size (for each module). + self.metrics.log_value( + key=(mid, MODULE_TRAIN_BATCH_SIZE_MEAN), + value=module_batch_size, + ) + # Log module steps (for each module). + self.metrics.log_value( + key=(mid, NUM_MODULE_STEPS_TRAINED), + value=module_batch_size, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + key=(mid, NUM_MODULE_STEPS_TRAINED_LIFETIME), + value=module_batch_size, + reduce="sum", + ) + # Log module steps (sum of all modules). + self.metrics.log_value( + key=(ALL_MODULES, NUM_MODULE_STEPS_TRAINED), + value=module_batch_size, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + key=(ALL_MODULES, NUM_MODULE_STEPS_TRAINED_LIFETIME), + value=module_batch_size, + reduce="sum", + ) + # Log env steps (all modules). + self.metrics.log_value( + (ALL_MODULES, NUM_ENV_STEPS_TRAINED), + batch.env_steps(), + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (ALL_MODULES, NUM_ENV_STEPS_TRAINED_LIFETIME), + batch.env_steps(), + reduce="sum", + with_throughput=True, + ) + + @OverrideToImplementCustomLogic + @abc.abstractmethod + def _make_functional_call( + self, + module: MultiRLModule, + params: Dict[ModuleID, NamedParamDict], + batch: MultiAgentBatch, + **kwargs, + ) -> Dict[ModuleID, Dict[str, TensorType]]: + """Makes a functional call to a module. + + Functional calls enable the Learner to (a) use the same module as its + `MetaLearner` and (b) to generate and apply gradients without modifying + the `RLModule` parameters directly. + + Args: + module: The `MultiRLModule` to be used for the functional call. Note, this + module's `forward` method must call the `foward_train`. + params: A dictionary containing containing for each `RLModule`'s id its + named parameter dictionary. For functional calls to work, these + parameters need to be cloned. + batch: A `MultiAgentBatch` instance to be used in the functional call. + + Returns: + A dictionary with the output of the module's forward pass. + """ + + @property + def module(self) -> MultiRLModule: + """The MultiRLModule reference that is being used in updates.""" + return self._module + + @module.setter + def module(self, module: MultiRLModule) -> None: + """Sets the `MultiRLModule`. + + Args: + module: The reference to the `MultiRLModule` of the class that holds the + instance of this `DifferentiableLearner` instance. + """ + self._module = module diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/differentiable_learner_config.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/differentiable_learner_config.py new file mode 100644 index 0000000000000000000000000000000000000000..d8b5a134d4aa368851da6f11b6dd2e18e5706c4a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/differentiable_learner_config.py @@ -0,0 +1,148 @@ +import gymnasium as gym +from dataclasses import dataclass, fields + +from typing import Callable, List, Optional, Union + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.learner.differentiable_learner import DifferentiableLearner +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec +from ray.rllib.utils.typing import DeviceType, ModuleID + + +@dataclass +class DifferentiableLearnerConfig: + """Configures a `DifferentiableLearner`.""" + + # TODO (simon): We implement only for `PyTorch`, so maybe we use here directly + # TorchDifferentiableLearner` and check for this? + # The `DifferentiableLearner` class. Must be derived from `DifferentiableLearner`. + learner_class: Callable + + learner_connector: Optional[ + Callable[["RLModule"], Union["ConnectorV2", List["ConnectorV2"]]] + ] = None + + add_default_connectors_to_learner_pipeline: bool = True + + is_multi_agent: bool = False + + policies_to_update: List[ModuleID] = None + + # The learning rate to use for the nested update. Note, in the default case this + # learning rate is only used to update parameters in a functional form, i.e. the + # `RLModule`'s stateful parameters are only updated in the `MetaLearner`. Different + # logic can be implemented in customized `DifferentiableLearner`s. + lr: float = 3e-5 + + # TODO (simon): Add further hps like clip_grad, ... + # The total number of minibatches to be formed from the batch per learner, e.g. + # setting `train_batch_size_per_learner=10` and `num_total_minibatches` to 2 + # runs 2 SGD minibatch updates with a batch of 5 per training iteration. + num_total_minibatches: int = 0 + + # The number of epochs per training iteration. + num_epochs: int = 1 + + # The minibatch size per SGD minibatch update, e.g. with a `train_batch_size_per_learner=10` + # and a `minibatch_size=2` the training step runs 5 SGD minibatch updates with minibatches + # of 2. + minibatch_size: int = None + + # If the batch should be shuffled between epochs. + shuffle_batch_per_epoch: bool = False + + def __post_init__(self): + """Additional initialization processes.""" + + # Ensure we have a `DifferentiableLearner` class. + if not issubclass(self.learner_class, DifferentiableLearner): + raise ValueError( + "`learner_class` must be a subclass of `DifferentiableLearner " + f"but is {self.learner_class}." + ) + + def build_learner_connector( + self, + input_observation_space: Optional[gym.spaces.Space], + input_action_space: Optional[gym.spaces.Space], + device: Optional[DeviceType] = None, + ): + from ray.rllib.connectors.learner import ( + AddColumnsFromEpisodesToTrainBatch, + AddObservationsFromEpisodesToBatch, + AddStatesFromEpisodesToBatch, + AddTimeDimToBatchAndZeroPad, + AgentToModuleMapping, + BatchIndividualItems, + LearnerConnectorPipeline, + NumpyToTensor, + ) + + custom_connectors = [] + # Create a learner connector pipeline (including RLlib's default + # learner connector piece) and return it. + if self.learner_connector is not None: + val_ = self.learner_connector( + input_observation_space, + input_action_space, + # device, # TODO (sven): Also pass device into custom builder. + ) + + from ray.rllib.connectors.connector_v2 import ConnectorV2 + + # ConnectorV2 (piece or pipeline). + if isinstance(val_, ConnectorV2): + custom_connectors = [val_] + # Sequence of individual ConnectorV2 pieces. + elif isinstance(val_, (list, tuple)): + custom_connectors = list(val_) + # Unsupported return value. + else: + raise ValueError( + "`AlgorithmConfig.training(learner_connector=..)` must return " + "a ConnectorV2 object or a list thereof (to be added to a " + f"pipeline)! Your function returned {val_}." + ) + + pipeline = LearnerConnectorPipeline( + connectors=custom_connectors, + input_observation_space=input_observation_space, + input_action_space=input_action_space, + ) + if self.add_default_connectors_to_learner_pipeline: + # Append OBS handling. + pipeline.append( + AddObservationsFromEpisodesToBatch(as_learner_connector=True) + ) + # Append all other columns handling. + pipeline.append(AddColumnsFromEpisodesToTrainBatch()) + # Append time-rank handler. + pipeline.append(AddTimeDimToBatchAndZeroPad(as_learner_connector=True)) + # Append STATE_IN/STATE_OUT handler. + pipeline.append(AddStatesFromEpisodesToBatch(as_learner_connector=True)) + # If multi-agent -> Map from AgentID-based data to ModuleID based data. + if self.is_multi_agent: + pipeline.append( + AgentToModuleMapping( + rl_module_specs=( + self.rl_module_spec.rl_module_specs + if isinstance(self.rl_module_spec, MultiRLModuleSpec) + else set(self.policies) + ), + agent_to_module_mapping_fn=self.policy_mapping_fn, + ) + ) + # Batch all data. + pipeline.append(BatchIndividualItems(multi_agent=self.is_multi_agent)) + # Convert to Tensors. + pipeline.append(NumpyToTensor(as_learner_connector=True, device=device)) + return pipeline + + def update_from_kwargs(self, **kwargs): + """Sets all slots with values defined in `kwargs`.""" + # Get all field names (i.e., slot names). + field_names = {f.name for f in fields(self)} + for key, value in kwargs.items(): + if key in field_names: + setattr(self, key, value) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/learner.py new file mode 100644 index 0000000000000000000000000000000000000000..3eab6072ff6fa9378f2d8ffddd58eb0731be6384 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/learner.py @@ -0,0 +1,1701 @@ +import abc +from collections import defaultdict +import copy +import logging +import numpy +import platform +import tree +from typing import ( + Any, + Callable, + Collection, + Dict, + List, + Hashable, + Iterable, + Optional, + Sequence, + Tuple, + TYPE_CHECKING, + Union, +) + +import ray +from ray.rllib.connectors.learner.learner_connector_pipeline import ( + LearnerConnectorPipeline, +) +from ray.rllib.core import ( + COMPONENT_METRICS_LOGGER, + COMPONENT_OPTIMIZER, + COMPONENT_RL_MODULE, + DEFAULT_MODULE_ID, +) +from ray.rllib.core.learner.training_data import TrainingData +from ray.rllib.core.rl_module.apis import SelfSupervisedLossAPI +from ray.rllib.core.rl_module import validate_module_id +from ray.rllib.core.rl_module.multi_rl_module import ( + MultiRLModule, + MultiRLModuleSpec, +) +from ray.rllib.core.rl_module.rl_module import RLModule, RLModuleSpec +from ray.rllib.policy.policy import PolicySpec +from ray.rllib.policy.sample_batch import MultiAgentBatch, SampleBatch +from ray.rllib.utils.annotations import ( + override, + OverrideToImplementCustomLogic, + OverrideToImplementCustomLogic_CallToSuperRecommended, +) +from ray.rllib.utils.checkpoints import Checkpointable +from ray.rllib.utils.debug import update_global_seed_if_necessary +from ray.rllib.utils.deprecation import Deprecated +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.metrics import ( + ALL_MODULES, + DATASET_NUM_ITERS_TRAINED, + DATASET_NUM_ITERS_TRAINED_LIFETIME, + NUM_ENV_STEPS_SAMPLED_LIFETIME, + NUM_ENV_STEPS_TRAINED, + NUM_ENV_STEPS_TRAINED_LIFETIME, + NUM_MODULE_STEPS_TRAINED, + NUM_MODULE_STEPS_TRAINED_LIFETIME, + MODULE_TRAIN_BATCH_SIZE_MEAN, + WEIGHTS_SEQ_NO, +) +from ray.rllib.utils.metrics.metrics_logger import MetricsLogger +from ray.rllib.utils.minibatch_utils import ( + MiniBatchDummyIterator, + MiniBatchCyclicIterator, + MiniBatchRayDataIterator, +) +from ray.rllib.utils.schedules.scheduler import Scheduler +from ray.rllib.utils.typing import ( + EpisodeType, + LearningRateOrSchedule, + ModuleID, + Optimizer, + Param, + ParamRef, + ParamDict, + ResultDict, + ShouldModuleBeUpdatedFn, + StateDict, + TensorType, +) +from ray.util.annotations import PublicAPI + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + + +torch, _ = try_import_torch() + +logger = logging.getLogger(__name__) + +DEFAULT_OPTIMIZER = "default_optimizer" + +# COMMON LEARNER LOSS_KEYS +POLICY_LOSS_KEY = "policy_loss" +VF_LOSS_KEY = "vf_loss" +ENTROPY_KEY = "entropy" + +# Additional update keys +LR_KEY = "learning_rate" + + +@PublicAPI(stability="alpha") +class Learner(Checkpointable): + """Base class for Learners. + + This class will be used to train RLModules. It is responsible for defining the loss + function, and updating the neural network weights that it owns. It also provides a + way to add/remove modules to/from RLModules in a multi-agent scenario, in the + middle of training (This is useful for league based training). + + Deep learning framework-specific implementations of this class fill in the + details for distributed training, and for computing and applying + gradients. User should not need to subclass this class, but instead inherit from + the deep learning framework (for example torch) specific subclasses to implement + their algorithm-specific update logic. + + Args: + config: The AlgorithmConfig object from which to derive most of the settings + needed to build the Learner. + module_spec: The module specification for the RLModule that is being trained. + If the module is a single agent module, after building the module it will + be converted to a multi-agent module with a default key. Can be none if the + module is provided directly via the `module` argument. Refer to + ray.rllib.core.rl_module.RLModuleSpec + or ray.rllib.core.rl_module.MultiRLModuleSpec for more info. + module: If learner is being used stand-alone, the RLModule can be optionally + passed in directly instead of the through the `module_spec`. + + Note: We use PPO and torch as an example here because many of the showcased + components need implementations to come together. However, the same + pattern is generally applicable. + + .. testcode:: + + import gymnasium as gym + + from ray.rllib.algorithms.ppo.ppo import PPOConfig + from ray.rllib.algorithms.ppo.ppo_catalog import PPOCatalog + from ray.rllib.algorithms.ppo.torch.ppo_torch_rl_module import ( + PPOTorchRLModule + ) + from ray.rllib.core import COMPONENT_RL_MODULE, DEFAULT_MODULE_ID + from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig + from ray.rllib.core.rl_module.rl_module import RLModuleSpec + + env = gym.make("CartPole-v1") + + # Create a PPO config object first. + config = ( + PPOConfig() + .framework("torch") + .training(model={"fcnet_hiddens": [128, 128]}) + ) + + # Create a learner instance directly from our config. All we need as + # extra information here is the env to be able to extract space information + # (needed to construct the RLModule inside the Learner). + learner = config.build_learner(env=env) + + # Take one gradient update on the module and report the results. + # results = learner.update(...) + + # Add a new module, perhaps for league based training. + learner.add_module( + module_id="new_player", + module_spec=RLModuleSpec( + module_class=PPOTorchRLModule, + observation_space=env.observation_space, + action_space=env.action_space, + model_config=DefaultModelConfig(fcnet_hiddens=[64, 64]), + catalog_class=PPOCatalog, + ) + ) + + # Take another gradient update with both previous and new modules. + # results = learner.update(...) + + # Remove a module. + learner.remove_module("new_player") + + # Will train previous modules only. + # results = learner.update(...) + + # Get the state of the learner. + state = learner.get_state() + + # Set the state of the learner. + learner.set_state(state) + + # Get the weights of the underlying MultiRLModule. + weights = learner.get_state(components=COMPONENT_RL_MODULE) + + # Set the weights of the underlying MultiRLModule. + learner.set_state({COMPONENT_RL_MODULE: weights}) + + + Extension pattern: + + .. testcode:: + + from ray.rllib.core.learner.torch.torch_learner import TorchLearner + + class MyLearner(TorchLearner): + + def compute_losses(self, fwd_out, batch): + # Compute the losses per module based on `batch` and output of the + # forward pass (`fwd_out`). To access the (algorithm) config for a + # specific RLModule, do: + # `self.config.get_config_for_module([moduleID])`. + return {DEFAULT_MODULE_ID: module_loss} + """ + + framework: str = None + TOTAL_LOSS_KEY: str = "total_loss" + + def __init__( + self, + *, + config: "AlgorithmConfig", + module_spec: Optional[Union[RLModuleSpec, MultiRLModuleSpec]] = None, + module: Optional[RLModule] = None, + ): + # TODO (sven): Figure out how to do this + self.config = config.copy(copy_frozen=False) + self._module_spec: Optional[MultiRLModuleSpec] = module_spec + self._module_obj: Optional[MultiRLModule] = module + + # Make node and device of this Learner available. + self._node = platform.node() + self._device = None + + # Set a seed, if necessary. + if self.config.seed is not None: + update_global_seed_if_necessary(self.framework, self.config.seed) + + # Whether self.build has already been called. + self._is_built = False + + # Attributes to be set separately (not by user's custom `build()` code) + # by a LearnerGroup. + self._learner_index = 0 + self._placement_group = None + + # These are the attributes that are set during build. + + # The actual MultiRLModule used by this Learner. + self._module: Optional[MultiRLModule] = None + self._weights_seq_no = 0 + # Our Learner connector pipeline. + self._learner_connector: Optional[LearnerConnectorPipeline] = None + # These are set for properly applying optimizers and adding or removing modules. + self._optimizer_parameters: Dict[Optimizer, List[ParamRef]] = {} + self._named_optimizers: Dict[str, Optimizer] = {} + self._params: ParamDict = {} + # Dict mapping ModuleID to a list of optimizer names. Note that the optimizer + # name includes the ModuleID as a prefix: optimizer_name=`[ModuleID]_[.. rest]`. + self._module_optimizers: Dict[ModuleID, List[str]] = defaultdict(list) + self._optimizer_name_to_module: Dict[str, ModuleID] = {} + + # Only manage optimizer's learning rate if user has NOT overridden + # the `configure_optimizers_for_module` method. Otherwise, leave responsibility + # to handle lr-updates entirely in user's hands. + self._optimizer_lr_schedules: Dict[Optimizer, Scheduler] = {} + + # The Learner's own MetricsLogger to be used to log RLlib's built-in metrics or + # custom user-defined ones (e.g. custom loss values). When returning from an + # `update_from_...()` method call, the Learner will do a `self.metrics.reduce()` + # and return the resulting (reduced) dict. + self.metrics = MetricsLogger() + + # In case of offline learning and multiple learners, each learner receives a + # repeatable iterator that iterates over a split of the streamed data. + self.iterator: MiniBatchRayDataIterator = None + + # TODO (sven): Do we really need this API? It seems like LearnerGroup constructs + # all Learner workers and then immediately builds them any ways? Unless there is + # a reason related to Train worker group setup. + @OverrideToImplementCustomLogic_CallToSuperRecommended + def build(self) -> None: + """Builds the Learner. + + This method should be called before the learner is used. It is responsible for + setting up the LearnerConnectorPipeline, the RLModule, optimizer(s), and + (optionally) the optimizers' learning rate schedulers. + """ + if self._is_built: + logger.debug("Learner already built. Skipping build.") + return + + # Build learner connector pipeline used on this Learner worker. + self._learner_connector = None + # If the Algorithm uses aggregation actors to run episodes through the learner + # connector, its Learners don't need a connector pipelines and instead learn + # directly from pre-loaded batches already on the GPU. + if self.config.num_aggregator_actors_per_learner == 0: + # TODO (sven): Figure out which space to provide here. For now, + # it doesn't matter, as the default connector piece doesn't use + # this information anyway. + # module_spec = self._module_spec.as_multi_rl_module_spec() + self._learner_connector = self.config.build_learner_connector( + input_observation_space=None, + input_action_space=None, + device=self._device, + ) + + # Build the module to be trained by this learner. + self._module = self._make_module() + + # Configure, construct, and register all optimizers needed to train + # `self.module`. + self.configure_optimizers() + + # Log the number of trainable/non-trainable parameters. + self._log_trainable_parameters() + + self._is_built = True + + @property + def distributed(self) -> bool: + """Whether the learner is running in distributed mode.""" + return self.config.num_learners > 1 + + @property + def module(self) -> MultiRLModule: + """The MultiRLModule that is being trained.""" + return self._module + + @property + def node(self) -> Any: + return self._node + + @property + def device(self) -> Any: + return self._device + + def register_optimizer( + self, + *, + module_id: ModuleID = ALL_MODULES, + optimizer_name: str = DEFAULT_OPTIMIZER, + optimizer: Optimizer, + params: Sequence[Param], + lr_or_lr_schedule: Optional[LearningRateOrSchedule] = None, + ) -> None: + """Registers an optimizer with a ModuleID, name, param list and lr-scheduler. + + Use this method in your custom implementations of either + `self.configure_optimizers()` or `self.configure_optimzers_for_module()` (you + should only override one of these!). If you register a learning rate Scheduler + setting together with an optimizer, RLlib will automatically keep this + optimizer's learning rate updated throughout the training process. + Alternatively, you can construct your optimizers directly with a learning rate + and manage learning rate scheduling or updating yourself. + + Args: + module_id: The `module_id` under which to register the optimizer. If not + provided, will assume ALL_MODULES. + optimizer_name: The name (str) of the optimizer. If not provided, will + assume DEFAULT_OPTIMIZER. + optimizer: The already instantiated optimizer object to register. + params: A list of parameters (framework-specific variables) that will be + trained/updated + lr_or_lr_schedule: An optional fixed learning rate or learning rate schedule + setup. If provided, RLlib will automatically keep the optimizer's + learning rate updated. + """ + # Validate optimizer instance and its param list. + self._check_registered_optimizer(optimizer, params) + + full_registration_name = module_id + "_" + optimizer_name + + # Store the given optimizer under the given `module_id`. + self._module_optimizers[module_id].append(full_registration_name) + self._optimizer_name_to_module[full_registration_name] = module_id + + # Store the optimizer instance under its full `module_id`_`optimizer_name` + # key. + self._named_optimizers[full_registration_name] = optimizer + + # Store all given parameters under the given optimizer. + self._optimizer_parameters[optimizer] = [] + for param in params: + param_ref = self.get_param_ref(param) + self._optimizer_parameters[optimizer].append(param_ref) + self._params[param_ref] = param + + # Optionally, store a scheduler object along with this optimizer. If such a + # setting is provided, RLlib will handle updating the optimizer's learning rate + # over time. + if lr_or_lr_schedule is not None: + # Validate the given setting. + Scheduler.validate( + fixed_value_or_schedule=lr_or_lr_schedule, + setting_name="lr_or_lr_schedule", + description="learning rate or schedule", + ) + # Create the scheduler object for this optimizer. + scheduler = Scheduler( + fixed_value_or_schedule=lr_or_lr_schedule, + framework=self.framework, + device=self._device, + ) + self._optimizer_lr_schedules[optimizer] = scheduler + # Set the optimizer to the current (first) learning rate. + self._set_optimizer_lr( + optimizer=optimizer, + lr=scheduler.get_current_value(), + ) + + @OverrideToImplementCustomLogic + def configure_optimizers(self) -> None: + """Configures, creates, and registers the optimizers for this Learner. + + Optimizers are responsible for updating the model's parameters during training, + based on the computed gradients. + + Normally, you should not override this method for your custom algorithms + (which require certain optimizers), but rather override the + `self.configure_optimizers_for_module(module_id=..)` method and register those + optimizers in there that you need for the given `module_id`. + + You can register an optimizer for any RLModule within `self.module` (or for + the ALL_MODULES ID) by calling `self.register_optimizer()` and passing the + module_id, optimizer_name (only in case you would like to register more than + one optimizer for a given module), the optimizer instane itself, a list + of all the optimizer's parameters (to be updated by the optimizer), and + an optional learning rate or learning rate schedule setting. + + This method is called once during building (`self.build()`). + """ + # The default implementation simply calls `self.configure_optimizers_for_module` + # on each RLModule within `self.module`. + for module_id in self.module.keys(): + if self.rl_module_is_compatible(self.module[module_id]): + config = self.config.get_config_for_module(module_id) + self.configure_optimizers_for_module(module_id=module_id, config=config) + + @OverrideToImplementCustomLogic + @abc.abstractmethod + def configure_optimizers_for_module( + self, module_id: ModuleID, config: "AlgorithmConfig" = None + ) -> None: + """Configures an optimizer for the given module_id. + + This method is called for each RLModule in the MultiRLModule being + trained by the Learner, as well as any new module added during training via + `self.add_module()`. It should configure and construct one or more optimizers + and register them via calls to `self.register_optimizer()` along with the + `module_id`, an optional optimizer name (str), a list of the optimizer's + framework specific parameters (variables), and an optional learning rate value + or -schedule. + + Args: + module_id: The module_id of the RLModule that is being configured. + config: The AlgorithmConfig specific to the given `module_id`. + """ + + @OverrideToImplementCustomLogic + @abc.abstractmethod + def compute_gradients( + self, loss_per_module: Dict[ModuleID, TensorType], **kwargs + ) -> ParamDict: + """Computes the gradients based on the given losses. + + Args: + loss_per_module: Dict mapping module IDs to their individual total loss + terms, computed by the individual `compute_loss_for_module()` calls. + The overall total loss (sum of loss terms over all modules) is stored + under `loss_per_module[ALL_MODULES]`. + **kwargs: Forward compatibility kwargs. + + Returns: + The gradients in the same (flat) format as self._params. Note that all + top-level structures, such as module IDs, will not be present anymore in + the returned dict. It will merely map parameter tensor references to their + respective gradient tensors. + """ + + @OverrideToImplementCustomLogic + def postprocess_gradients(self, gradients_dict: ParamDict) -> ParamDict: + """Applies potential postprocessing operations on the gradients. + + This method is called after gradients have been computed and modifies them + before they are applied to the respective module(s) by the optimizer(s). + This might include grad clipping by value, norm, or global-norm, or other + algorithm specific gradient postprocessing steps. + + This default implementation calls `self.postprocess_gradients_for_module()` + on each of the sub-modules in our MultiRLModule: `self.module` and + returns the accumulated gradients dicts. + + Args: + gradients_dict: A dictionary of gradients in the same (flat) format as + self._params. Note that top-level structures, such as module IDs, + will not be present anymore in this dict. It will merely map gradient + tensor references to gradient tensors. + + Returns: + A dictionary with the updated gradients and the exact same (flat) structure + as the incoming `gradients_dict` arg. + """ + + # The flat gradients dict (mapping param refs to params), returned by this + # method. + postprocessed_gradients = {} + + for module_id in self.module.keys(): + # Send a gradients dict for only this `module_id` to the + # `self.postprocess_gradients_for_module()` method. + module_grads_dict = {} + for optimizer_name, optimizer in self.get_optimizers_for_module(module_id): + optim_grads = self.filter_param_dict_for_optimizer( + gradients_dict, optimizer + ) + for ref, grad in optim_grads.items(): + assert ref not in module_grads_dict + module_grads_dict[ref] = grad + + module_grads_dict = self.postprocess_gradients_for_module( + module_id=module_id, + config=self.config.get_config_for_module(module_id), + module_gradients_dict=module_grads_dict, + ) + assert isinstance(module_grads_dict, dict) + + # Update our return dict. + postprocessed_gradients.update(module_grads_dict) + + return postprocessed_gradients + + @OverrideToImplementCustomLogic_CallToSuperRecommended + def postprocess_gradients_for_module( + self, + *, + module_id: ModuleID, + config: Optional["AlgorithmConfig"] = None, + module_gradients_dict: ParamDict, + ) -> ParamDict: + """Applies postprocessing operations on the gradients of the given module. + + Args: + module_id: The module ID for which we will postprocess computed gradients. + Note that `module_gradients_dict` already only carries those gradient + tensors that belong to this `module_id`. Other `module_id`'s gradients + are not available in this call. + config: The AlgorithmConfig specific to the given `module_id`. + module_gradients_dict: A dictionary of gradients in the same (flat) format + as self._params, mapping gradient refs to gradient tensors, which are to + be postprocessed. You may alter these tensors in place or create new + ones and return these in a new dict. + + Returns: + A dictionary with the updated gradients and the exact same (flat) structure + as the incoming `module_gradients_dict` arg. + """ + postprocessed_grads = {} + + if config.grad_clip is None and not config.log_gradients: + postprocessed_grads.update(module_gradients_dict) + return postprocessed_grads + + for optimizer_name, optimizer in self.get_optimizers_for_module(module_id): + grad_dict_to_clip = self.filter_param_dict_for_optimizer( + param_dict=module_gradients_dict, + optimizer=optimizer, + ) + if config.grad_clip: + # Perform gradient clipping, if configured. + global_norm = self._get_clip_function()( + grad_dict_to_clip, + grad_clip=config.grad_clip, + grad_clip_by=config.grad_clip_by, + ) + if config.grad_clip_by == "global_norm" or config.log_gradients: + # If we want to log gradients, but do not use the global norm + # for clipping compute it here. + if config.log_gradients and config.grad_clip_by != "global_norm": + # Compute the global norm of gradients. + global_norm = self._get_global_norm_function()( + # Note, `tf.linalg.global_norm` needs a list of tensors. + list(grad_dict_to_clip.values()), + ) + self.metrics.log_value( + key=(module_id, f"gradients_{optimizer_name}_global_norm"), + value=global_norm, + window=1, + ) + postprocessed_grads.update(grad_dict_to_clip) + # In the other case check, if we want to log gradients only. + elif config.log_gradients: + # Compute the global norm of gradients and log it. + global_norm = self._get_global_norm_function()( + # Note, `tf.linalg.global_norm` needs a list of tensors. + list(grad_dict_to_clip.values()), + ) + self.metrics.log_value( + key=(module_id, f"gradients_{optimizer_name}_global_norm"), + value=global_norm, + window=1, + ) + + return postprocessed_grads + + @OverrideToImplementCustomLogic + @abc.abstractmethod + def apply_gradients(self, gradients_dict: ParamDict) -> None: + """Applies the gradients to the MultiRLModule parameters. + + Args: + gradients_dict: A dictionary of gradients in the same (flat) format as + self._params. Note that top-level structures, such as module IDs, + will not be present anymore in this dict. It will merely map gradient + tensor references to gradient tensors. + """ + + def get_optimizer( + self, + module_id: ModuleID = DEFAULT_MODULE_ID, + optimizer_name: str = DEFAULT_OPTIMIZER, + ) -> Optimizer: + """Returns the optimizer object, configured under the given module_id and name. + + If only one optimizer was registered under `module_id` (or ALL_MODULES) + via the `self.register_optimizer` method, `optimizer_name` is assumed to be + DEFAULT_OPTIMIZER. + + Args: + module_id: The ModuleID for which to return the configured optimizer. + If not provided, will assume DEFAULT_MODULE_ID. + optimizer_name: The name of the optimizer (registered under `module_id` via + `self.register_optimizer()`) to return. If not provided, will assume + DEFAULT_OPTIMIZER. + + Returns: + The optimizer object, configured under the given `module_id` and + `optimizer_name`. + """ + # `optimizer_name` could possibly be the full optimizer name (including the + # module_id under which it is registered). + if optimizer_name in self._named_optimizers: + return self._named_optimizers[optimizer_name] + + # Normally, `optimizer_name` is just the optimizer's name, not including the + # `module_id`. + full_registration_name = module_id + "_" + optimizer_name + if full_registration_name in self._named_optimizers: + return self._named_optimizers[full_registration_name] + + # No optimizer found. + raise KeyError( + f"Optimizer not found! module_id={module_id} " + f"optimizer_name={optimizer_name}" + ) + + def get_optimizers_for_module( + self, module_id: ModuleID = ALL_MODULES + ) -> List[Tuple[str, Optimizer]]: + """Returns a list of (optimizer_name, optimizer instance)-tuples for module_id. + + Args: + module_id: The ModuleID for which to return the configured + (optimizer name, optimizer)-pairs. If not provided, will return + optimizers registered under ALL_MODULES. + + Returns: + A list of tuples of the format: ([optimizer_name], [optimizer object]), + where optimizer_name is the name under which the optimizer was registered + in `self.register_optimizer`. If only a single optimizer was + configured for `module_id`, [optimizer_name] will be DEFAULT_OPTIMIZER. + """ + named_optimizers = [] + for full_registration_name in self._module_optimizers[module_id]: + optimizer = self._named_optimizers[full_registration_name] + # TODO (sven): How can we avoid registering optimziers under this + # constructed `[module_id]_[optim_name]` format? + optim_name = full_registration_name[len(module_id) + 1 :] + named_optimizers.append((optim_name, optimizer)) + return named_optimizers + + def filter_param_dict_for_optimizer( + self, param_dict: ParamDict, optimizer: Optimizer + ) -> ParamDict: + """Reduces the given ParamDict to contain only parameters for given optimizer. + + Args: + param_dict: The ParamDict to reduce/filter down to the given `optimizer`. + The returned dict will be a subset of `param_dict` only containing keys + (param refs) that were registered together with `optimizer` (and thus + that `optimizer` is responsible for applying gradients to). + optimizer: The optimizer object to whose parameter refs the given + `param_dict` should be reduced. + + Returns: + A new ParamDict only containing param ref keys that belong to `optimizer`. + """ + # Return a sub-dict only containing those param_ref keys (and their values) + # that belong to the `optimizer`. + return { + ref: param_dict[ref] + for ref in self._optimizer_parameters[optimizer] + if ref in param_dict and param_dict[ref] is not None + } + + @abc.abstractmethod + def get_param_ref(self, param: Param) -> Hashable: + """Returns a hashable reference to a trainable parameter. + + This should be overridden in framework specific specialization. For example in + torch it will return the parameter itself, while in tf it returns the .ref() of + the variable. The purpose is to retrieve a unique reference to the parameters. + + Args: + param: The parameter to get the reference to. + + Returns: + A reference to the parameter. + """ + + @abc.abstractmethod + def get_parameters(self, module: RLModule) -> Sequence[Param]: + """Returns the list of parameters of a module. + + This should be overridden in framework specific learner. For example in torch it + will return .parameters(), while in tf it returns .trainable_variables. + + Args: + module: The module to get the parameters from. + + Returns: + The parameters of the module. + """ + + @abc.abstractmethod + def _convert_batch_type( + self, + batch: MultiAgentBatch, + to_device: bool = False, + pin_memory: bool = False, + use_stream: bool = False, + ) -> MultiAgentBatch: + """Converts the elements of a MultiAgentBatch to Tensors on the correct device. + + Args: + batch: The MultiAgentBatch object to convert. + + Returns: + The resulting MultiAgentBatch with framework-specific tensor values placed + on the correct device. + """ + + @OverrideToImplementCustomLogic_CallToSuperRecommended + def add_module( + self, + *, + module_id: ModuleID, + module_spec: RLModuleSpec, + config_overrides: Optional[Dict] = None, + new_should_module_be_updated: Optional[ShouldModuleBeUpdatedFn] = None, + ) -> MultiRLModuleSpec: + """Adds a module to the underlying MultiRLModule. + + Changes this Learner's config in order to make this architectural change + permanent wrt. to checkpointing. + + Args: + module_id: The ModuleID of the module to be added. + module_spec: The ModuleSpec of the module to be added. + config_overrides: The `AlgorithmConfig` overrides that should apply to + the new Module, if any. + new_should_module_be_updated: An optional sequence of ModuleIDs or a + callable taking ModuleID and SampleBatchType and returning whether the + ModuleID should be updated (trained). + If None, will keep the existing setup in place. RLModules, + whose IDs are not in the list (or for which the callable + returns False) will not be updated. + + Returns: + The new MultiRLModuleSpec (after the RLModule has been added). + """ + validate_module_id(module_id, error=True) + self._check_is_built() + + # Force-set inference-only = False. + module_spec = copy.deepcopy(module_spec) + module_spec.inference_only = False + + # Build the new RLModule and add it to self.module. + module = module_spec.build() + self.module.add_module(module_id, module) + + # Change our config (AlgorithmConfig) to contain the new Module. + # TODO (sven): This is a hack to manipulate the AlgorithmConfig directly, + # but we'll deprecate config.policies soon anyway. + self.config.policies[module_id] = PolicySpec() + if config_overrides is not None: + self.config.multi_agent( + algorithm_config_overrides_per_module={module_id: config_overrides} + ) + self.config.rl_module(rl_module_spec=MultiRLModuleSpec.from_module(self.module)) + self._module_spec = self.config.rl_module_spec + if new_should_module_be_updated is not None: + self.config.multi_agent(policies_to_train=new_should_module_be_updated) + + # Allow the user to configure one or more optimizers for this new module. + self.configure_optimizers_for_module( + module_id=module_id, + config=self.config.get_config_for_module(module_id), + ) + return self.config.rl_module_spec + + @OverrideToImplementCustomLogic_CallToSuperRecommended + def remove_module( + self, + module_id: ModuleID, + *, + new_should_module_be_updated: Optional[ShouldModuleBeUpdatedFn] = None, + ) -> MultiRLModuleSpec: + """Removes a module from the Learner. + + Args: + module_id: The ModuleID of the module to be removed. + new_should_module_be_updated: An optional sequence of ModuleIDs or a + callable taking ModuleID and SampleBatchType and returning whether the + ModuleID should be updated (trained). + If None, will keep the existing setup in place. RLModules, + whose IDs are not in the list (or for which the callable + returns False) will not be updated. + + Returns: + The new MultiRLModuleSpec (after the RLModule has been removed). + """ + self._check_is_built() + module = self.module[module_id] + + # Delete the removed module's parameters and optimizers. + if self.rl_module_is_compatible(module): + parameters = self.get_parameters(module) + for param in parameters: + param_ref = self.get_param_ref(param) + if param_ref in self._params: + del self._params[param_ref] + for optimizer_name, optimizer in self.get_optimizers_for_module(module_id): + del self._optimizer_parameters[optimizer] + name = module_id + "_" + optimizer_name + del self._named_optimizers[name] + if optimizer in self._optimizer_lr_schedules: + del self._optimizer_lr_schedules[optimizer] + del self._module_optimizers[module_id] + + # Remove the module from the MultiRLModule. + self.module.remove_module(module_id) + + # Change self.config to reflect the new architecture. + # TODO (sven): This is a hack to manipulate the AlgorithmConfig directly, + # but we'll deprecate config.policies soon anyway. + del self.config.policies[module_id] + self.config.algorithm_config_overrides_per_module.pop(module_id, None) + if new_should_module_be_updated is not None: + self.config.multi_agent(policies_to_train=new_should_module_be_updated) + self.config.rl_module(rl_module_spec=MultiRLModuleSpec.from_module(self.module)) + + # Remove all stats from the module from our metrics logger, so we don't report + # results from this module again. + if module_id in self.metrics.stats: + del self.metrics.stats[module_id] + + return self.config.rl_module_spec + + @OverrideToImplementCustomLogic + def should_module_be_updated(self, module_id, multi_agent_batch=None): + """Returns whether a module should be updated or not based on `self.config`. + + Args: + module_id: The ModuleID that we want to query on whether this module + should be updated or not. + multi_agent_batch: An optional MultiAgentBatch to possibly provide further + information on the decision on whether the RLModule should be updated + or not. + """ + should_module_be_updated_fn = self.config.policies_to_train + # If None, return True (by default, all modules should be updated). + if should_module_be_updated_fn is None: + return True + # If collection given, return whether `module_id` is in that container. + elif not callable(should_module_be_updated_fn): + return module_id in set(should_module_be_updated_fn) + + return should_module_be_updated_fn(module_id, multi_agent_batch) + + @OverrideToImplementCustomLogic + def compute_losses( + self, *, fwd_out: Dict[str, Any], batch: Dict[str, Any] + ) -> Dict[str, Any]: + """Computes the loss(es) for the module being optimized. + + This method must be overridden by MultiRLModule-specific Learners in order to + define the specific loss computation logic. If the algorithm is single-agent, + only `compute_loss_for_module()` should be overridden instead. If the algorithm + uses independent multi-agent learning (default behavior for RLlib's multi-agent + setups), also only `compute_loss_for_module()` should be overridden, but it will + be called for each individual RLModule inside the MultiRLModule. + It is recommended to not compute any forward passes within this method, and to + use the `forward_train()` outputs of the RLModule(s) to compute the required + loss tensors. + See here for a custom loss function example script: + https://github.com/ray-project/ray/blob/master/rllib/examples/learners/ppo_with_custom_loss_fn.py # noqa + + Args: + fwd_out: Output from a call to the `forward_train()` method of the + underlying MultiRLModule (`self.module`) during training + (`self.update()`). + batch: The train batch that was used to compute `fwd_out`. + + Returns: + A dictionary mapping module IDs to individual loss terms. + """ + loss_per_module = {} + for module_id in fwd_out: + module_batch = batch[module_id] + module_fwd_out = fwd_out[module_id] + + module = self.module[module_id].unwrapped() + if isinstance(module, SelfSupervisedLossAPI): + loss = module.compute_self_supervised_loss( + learner=self, + module_id=module_id, + config=self.config.get_config_for_module(module_id), + batch=module_batch, + fwd_out=module_fwd_out, + ) + else: + loss = self.compute_loss_for_module( + module_id=module_id, + config=self.config.get_config_for_module(module_id), + batch=module_batch, + fwd_out=module_fwd_out, + ) + loss_per_module[module_id] = loss + + return loss_per_module + + @OverrideToImplementCustomLogic + @abc.abstractmethod + def compute_loss_for_module( + self, + *, + module_id: ModuleID, + config: "AlgorithmConfig", + batch: Dict[str, Any], + fwd_out: Dict[str, TensorType], + ) -> TensorType: + """Computes the loss for a single module. + + Think of this as computing loss for a single agent. For multi-agent use-cases + that require more complicated computation for loss, consider overriding the + `compute_losses` method instead. + + Args: + module_id: The id of the module. + config: The AlgorithmConfig specific to the given `module_id`. + batch: The train batch for this particular module. + fwd_out: The output of the forward pass for this particular module. + + Returns: + A single total loss tensor. If you have more than one optimizer on the + provided `module_id` and would like to compute gradients separately using + these different optimizers, simply add up the individual loss terms for + each optimizer and return the sum. Also, for recording/logging any + individual loss terms, you can use the `Learner.metrics.log_value( + key=..., value=...)` or `Learner.metrics.log_dict()` APIs. See: + :py:class:`~ray.rllib.utils.metrics.metrics_logger.MetricsLogger` for more + information. + """ + + @OverrideToImplementCustomLogic + def update( + self, + batch: Optional[MultiAgentBatch] = None, + batches: Optional[List[MultiAgentBatch]] = None, + batch_refs: Optional[List[ray.ObjectRef]] = None, + episodes: Optional[List[EpisodeType]] = None, + episodes_refs: Optional[List[ray.ObjectRef]] = None, + data_iterators: Optional[List[ray.data.DataIterator]] = None, + training_data: Optional[TrainingData] = None, + *, + # TODO (sven): Make this a more formal structure with its own type. + timesteps: Optional[Dict[str, Any]] = None, + num_total_minibatches: int = 0, + num_epochs: int = 1, + minibatch_size: Optional[int] = None, + shuffle_batch_per_epoch: bool = False, + _no_metrics_reduce: bool = False, + **kwargs, + ) -> ResultDict: + """Run `num_epochs` epochs over the given train batch. + + You can use this method to take more than one backward pass on the batch. + The same `minibatch_size` and `num_epochs` will be used for all module ids in + MultiRLModule. + + Args: + batch: A batch of training data to update from. + timesteps: Timesteps dict, which must have the key + `NUM_ENV_STEPS_SAMPLED_LIFETIME`. + # TODO (sven): Make this a more formal structure with its own type. + num_epochs: The number of complete passes over the entire train batch. Each + pass might be further split into n minibatches (if `minibatch_size` + provided). + minibatch_size: The size of minibatches to use to further split the train + `batch` into sub-batches. The `batch` is then iterated over n times + where n is `len(batch) // minibatch_size`. + shuffle_batch_per_epoch: Whether to shuffle the train batch once per epoch. + If the train batch has a time rank (axis=1), shuffling will only take + place along the batch axis to not disturb any intact (episode) + trajectories. Also, shuffling is always skipped if `minibatch_size` is + None, meaning the entire train batch is processed each epoch, making it + unnecessary to shuffle. + + Returns: + A `ResultDict` object produced by a call to `self.metrics.reduce()`. The + returned dict may be arbitrarily nested and must have `Stats` objects at + all its leafs, allowing components further downstream (i.e. a user of this + Learner) to further reduce these results (for example over n parallel + Learners). + """ + self._check_is_built() + + # Call `before_gradient_based_update` to allow for non-gradient based + # preparations-, logging-, and update logic to happen. + self.before_gradient_based_update(timesteps=timesteps or {}) + + if training_data is None: + training_data = TrainingData( + batch=batch, + batches=batches, + batch_refs=batch_refs, + episodes=episodes, + episodes_refs=episodes_refs, + data_iterators=data_iterators, + ) + training_data.validate() + training_data.solve_refs() + assert training_data.batches is None, "`training_data.batches` must be None!" + + self._weights_seq_no += 1 + + batch_iter = self._create_iterator_if_necessary( + training_data=training_data, + num_total_minibatches=num_total_minibatches, + num_epochs=num_epochs, + minibatch_size=minibatch_size, + shuffle_batch_per_epoch=shuffle_batch_per_epoch, + **kwargs, + ) + + self.metrics.activate_tensor_mode() + + # Perform the actual looping through the minibatches or the given data iterator. + for iteration, tensor_minibatch in enumerate(batch_iter): + # Check the MultiAgentBatch, whether our RLModule contains all ModuleIDs + # found in this batch. If not, throw an error. + unknown_module_ids = set(tensor_minibatch.policy_batches.keys()) - set( + self.module.keys() + ) + if unknown_module_ids: + raise ValueError( + f"Batch contains one or more ModuleIDs ({unknown_module_ids}) that " + f"are not in this Learner!" + ) + + # Make the actual in-graph/traced `_update` call. This should return + # all tensor values (no numpy). + fwd_out, loss_per_module, _ = self._update(tensor_minibatch.policy_batches) + + # TODO (sven): Maybe move this into loop above to get metrics more accuratcely + # cover the minibatch/epoch logic. + # Log all timesteps (env, agent, modules) based on given episodes/batch. + self._log_steps_trained_metrics(tensor_minibatch) + + self._set_slicing_by_batch_id(tensor_minibatch, value=False) + + if self.iterator: + # Record the number of batches pulled from the dataset. + self.metrics.log_value( + (ALL_MODULES, DATASET_NUM_ITERS_TRAINED), + iteration + 1, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (ALL_MODULES, DATASET_NUM_ITERS_TRAINED_LIFETIME), + iteration + 1, + reduce="sum", + ) + # Log all individual RLModules' loss terms and its registered optimizers' + # current learning rates. + # Note: We do this only once for the last of the minibatch updates, b/c the + # window is only 1 anyways. + for mid, loss in loss_per_module.items(): + self.metrics.log_value( + key=(mid, self.TOTAL_LOSS_KEY), + value=loss, + window=1, + ) + + # Call `after_gradient_based_update` to allow for non-gradient based + # cleanups-, logging-, and update logic to happen. + # TODO (simon): Check, if this should stay here, when running multiple + # gradient steps inside the iterator loop above (could be a complete epoch) + # the target networks might need to be updated earlier. + self.after_gradient_based_update(timesteps=timesteps or {}) + + self.metrics.deactivate_tensor_mode() + + # Reduce results across all minibatch update steps. + if not _no_metrics_reduce: + return self.metrics.reduce() + + def _create_iterator_if_necessary( + self, + *, + training_data: TrainingData, + num_total_minibatches: int = 0, + num_epochs: int = 1, + minibatch_size: Optional[int] = None, + shuffle_batch_per_epoch: bool = False, + **kwargs, + ) -> Iterable: + # Data iterator provided. + if training_data.data_iterators: + num_iters = kwargs.pop("num_iters", None) + if num_iters is None: + raise ValueError( + "Learner.update(data_iterators=..) requires `num_iters` kwarg!" + ) + + if not self.iterator: + # This iterator holds a `ray.data.DataIterator` and manages it state. + self.iterator = MiniBatchRayDataIterator( + iterator=training_data.data_iterators[0], + device=self.device, + minibatch_size=minibatch_size, + num_iters=num_iters, + **kwargs, + ) + + batch_iter = self.iterator + else: + batch = self._make_batch_if_necessary(training_data=training_data) + assert batch is not None + + # TODO: Move this into LearnerConnector pipeline? + # Filter out those RLModules from the final train batch that should not be + # updated. + for module_id in list(batch.policy_batches.keys()): + if not self.should_module_be_updated(module_id, batch): + del batch.policy_batches[module_id] + if not batch.policy_batches: + return {} + + batch = self._set_slicing_by_batch_id(batch, value=True) + + if minibatch_size: + batch_iter_cls = MiniBatchCyclicIterator + elif num_epochs > 1: + # `minibatch_size` was not set but `num_epochs` > 1. + minibatch_size = batch.count + # Note that there is no need to shuffle here, b/c we don't have + # minibatches. + batch_iter_cls = MiniBatchCyclicIterator + else: + # `minibatch_size` and `num_epochs` are not set by the user. + batch_iter_cls = MiniBatchDummyIterator + + batch_iter = batch_iter_cls( + batch, + num_epochs=num_epochs, + minibatch_size=minibatch_size, + shuffle_batch_per_epoch=shuffle_batch_per_epoch and (num_epochs > 1), + num_total_minibatches=num_total_minibatches, + ) + return batch_iter + + @OverrideToImplementCustomLogic + @abc.abstractmethod + def _update( + self, + batch: Dict[str, Any], + **kwargs, + ) -> Tuple[Any, Any, Any]: + """Contains all logic for an in-graph/traceable update step. + + Framework specific subclasses must implement this method. This should include + calls to the RLModule's `forward_train`, `compute_loss`, compute_gradients`, + `postprocess_gradients`, and `apply_gradients` methods and return a tuple + with all the individual results. + + Args: + batch: The train batch already converted to a Dict mapping str to (possibly + nested) tensors. + kwargs: Forward compatibility kwargs. + + Returns: + A tuple consisting of: + 1) The `forward_train()` output of the RLModule, + 2) the loss_per_module dictionary mapping module IDs to individual loss + tensors + 3) a metrics dict mapping module IDs to metrics key/value pairs. + + """ + + @override(Checkpointable) + def get_state( + self, + components: Optional[Union[str, Collection[str]]] = None, + *, + not_components: Optional[Union[str, Collection[str]]] = None, + **kwargs, + ) -> StateDict: + self._check_is_built() + + state = { + "should_module_be_updated": self.config.policies_to_train, + WEIGHTS_SEQ_NO: self._weights_seq_no, + } + + if self._check_component(COMPONENT_RL_MODULE, components, not_components): + state[COMPONENT_RL_MODULE] = self.module.get_state( + components=self._get_subcomponents(COMPONENT_RL_MODULE, components), + not_components=self._get_subcomponents( + COMPONENT_RL_MODULE, not_components + ), + **kwargs, + ) + if self._check_component(COMPONENT_OPTIMIZER, components, not_components): + state[COMPONENT_OPTIMIZER] = self._get_optimizer_state() + + if self._check_component(COMPONENT_METRICS_LOGGER, components, not_components): + # TODO (sven): Make `MetricsLogger` a Checkpointable. + state[COMPONENT_METRICS_LOGGER] = self.metrics.get_state() + + return state + + @override(Checkpointable) + def set_state(self, state: StateDict) -> None: + self._check_is_built() + + weights_seq_no = state.get(WEIGHTS_SEQ_NO, 0) + + if COMPONENT_RL_MODULE in state: + if weights_seq_no == 0 or self._weights_seq_no < weights_seq_no: + self.module.set_state(state[COMPONENT_RL_MODULE]) + + if COMPONENT_OPTIMIZER in state: + self._set_optimizer_state(state[COMPONENT_OPTIMIZER]) + + # Update our weights_seq_no, if the new one is > 0. + if weights_seq_no > 0: + self._weights_seq_no = weights_seq_no + + # Update our trainable Modules information/function via our config. + # If not provided in state (None), all Modules will be trained by default. + if "should_module_be_updated" in state: + self.config.multi_agent(policies_to_train=state["should_module_be_updated"]) + + # TODO (sven): Make `MetricsLogger` a Checkpointable. + if COMPONENT_METRICS_LOGGER in state: + self.metrics.set_state(state[COMPONENT_METRICS_LOGGER]) + + @override(Checkpointable) + def get_ctor_args_and_kwargs(self): + return ( + (), # *args, + { + "config": self.config, + "module_spec": self._module_spec, + "module": self._module_obj, + }, # **kwargs + ) + + @override(Checkpointable) + def get_checkpointable_components(self): + if not self._check_is_built(error=False): + self.build() + return [ + (COMPONENT_RL_MODULE, self.module), + ] + + def _make_batch_if_necessary(self, training_data): + batch = training_data.batch + + # Call the learner connector on the given `episodes` (if we have one). + if training_data.episodes is not None: + # If we want to learn from Episodes, we must have a LearnerConnector + # pipeline to translate into a train batch first. + if self._learner_connector is None: + raise ValueError( + f"If episodes provided for training, Learner ({self}) must have a " + "LearnerConnector pipeline (but pipeline is None)!" + ) + + # Call the learner connector pipeline. + shared_data = {} + batch = self._learner_connector( + rl_module=self.module, + batch=training_data.batch if training_data.batch is not None else {}, + episodes=training_data.episodes, + shared_data=shared_data, + metrics=self.metrics, + ) + # Convert to a batch. + # TODO (sven): Try to not require MultiAgentBatch anymore. + batch = MultiAgentBatch( + { + module_id: ( + SampleBatch(module_data, _zero_padded=True) + if shared_data.get(f"_zero_padded_for_mid={module_id}") + else SampleBatch(module_data) + ) + for module_id, module_data in batch.items() + }, + env_steps=sum(len(e) for e in training_data.episodes), + ) + # Single-agent SampleBatch: Have to convert to MultiAgentBatch. + elif isinstance(training_data.batch, SampleBatch): + if len(self.module) != 1: + raise ValueError( + f"SampleBatch provided, but RLModule ({self.module}) has more than " + f"one sub-RLModule! Need to provide MultiAgentBatch instead." + ) + + batch = MultiAgentBatch( + {next(iter(self.module.keys())): training_data.batch}, + env_steps=len(training_data.batch), + ) + # If we already have an `MultiAgentBatch` but with `numpy` array, convert to + # tensors. + elif ( + isinstance(training_data.batch, MultiAgentBatch) + and training_data.batch.policy_batches + and ( + any( + tree.map_structure( + lambda a: isinstance(a, numpy.ndarray), + tree.flatten(training_data.batch.policy_batches), + ) + ) + or any( + tree.map_structure( + lambda a: isinstance(a, torch.Tensor) + and a.device != self._device, + tree.flatten(training_data.batch.policy_batches), + ) + ) + ) + ): + batch = self._convert_batch_type(training_data.batch) + + return batch + + def _get_optimizer_state(self) -> StateDict: + """Returns the state of all optimizers currently registered in this Learner. + + Returns: + The current state of all optimizers currently registered in this Learner. + """ + raise NotImplementedError + + def _set_optimizer_state(self, state: StateDict) -> None: + """Sets the state of all optimizers currently registered in this Learner. + + Args: + state: The state of the optimizers. + """ + raise NotImplementedError + + @OverrideToImplementCustomLogic_CallToSuperRecommended + def before_gradient_based_update(self, *, timesteps: Dict[str, Any]) -> None: + """Called before gradient-based updates are completed. + + Should be overridden to implement custom preparation-, logging-, or + non-gradient-based Learner/RLModule update logic before(!) gradient-based + updates are performed. + + Args: + timesteps: Timesteps dict, which must have the key + `NUM_ENV_STEPS_SAMPLED_LIFETIME`. + # TODO (sven): Make this a more formal structure with its own type. + """ + + @OverrideToImplementCustomLogic_CallToSuperRecommended + def after_gradient_based_update(self, *, timesteps: Dict[str, Any]) -> None: + """Called after gradient-based updates are completed. + + Should be overridden to implement custom cleanup-, logging-, or non-gradient- + based Learner/RLModule update logic after(!) gradient-based updates have been + completed. + + Args: + timesteps: Timesteps dict, which must have the key + `NUM_ENV_STEPS_SAMPLED_LIFETIME`. + # TODO (sven): Make this a more formal structure with its own type. + """ + # Only update this optimizer's lr, if a scheduler has been registered + # along with it. + for module_id, optimizer_names in self._module_optimizers.items(): + for optimizer_name in optimizer_names: + optimizer = self._named_optimizers[optimizer_name] + # Update and log learning rate of this optimizer. + lr_schedule = self._optimizer_lr_schedules.get(optimizer) + if lr_schedule is not None: + new_lr = lr_schedule.update( + timestep=timesteps.get(NUM_ENV_STEPS_SAMPLED_LIFETIME, 0) + ) + self._set_optimizer_lr(optimizer, lr=new_lr) + self.metrics.log_value( + # Cut out the module ID from the beginning since it's already part + # of the key sequence: (ModuleID, "[optim name]_lr"). + key=(module_id, f"{optimizer_name[len(module_id) + 1:]}_{LR_KEY}"), + value=self._get_optimizer_lr(optimizer), + window=1, + ) + + def _set_slicing_by_batch_id( + self, batch: MultiAgentBatch, *, value: bool + ) -> MultiAgentBatch: + """Enables slicing by batch id in the given batch. + + If the input batch contains batches of sequences we need to make sure when + slicing happens it is sliced via batch id and not timestamp. Calling this + method enables the same flag on each SampleBatch within the input + MultiAgentBatch. + + Args: + batch: The MultiAgentBatch to enable slicing by batch id on. + value: The value to set the flag to. + + Returns: + The input MultiAgentBatch with the indexing flag is enabled / disabled on. + """ + + for pid, policy_batch in batch.policy_batches.items(): + # We assume that arriving batches for recurrent modules OR batches that + # have a SEQ_LENS column are already zero-padded to the max sequence length + # and have tensors of shape [B, T, ...]. Therefore, we slice sequence + # lengths in B. See SampleBatch for more information. + if ( + self.module[pid].is_stateful() + or policy_batch.get("seq_lens") is not None + ): + if value: + policy_batch.enable_slicing_by_batch_id() + else: + policy_batch.disable_slicing_by_batch_id() + + return batch + + def _make_module(self) -> MultiRLModule: + """Construct the multi-agent RL module for the learner. + + This method uses `self._module_specs` or `self._module_obj` to construct the + module. If the module_class is a single agent RL module it will be wrapped to a + multi-agent RL module. Override this method if there are other things that + need to happen for instantiation of the module. + + Returns: + A constructed MultiRLModule. + """ + # Module was provided directly through constructor -> Use as-is. + if self._module_obj is not None: + module = self._module_obj + self._module_spec = MultiRLModuleSpec.from_module(module) + # RLModuleSpec was provided directly through constructor -> Use it to build the + # RLModule. + elif self._module_spec is not None: + module = self._module_spec.build() + # Try using our config object. Note that this would only work if the config + # object has all the necessary space information already in it. + else: + module = self.config.get_multi_rl_module_spec().build() + + # If not already, convert to MultiRLModule. + module = module.as_multi_rl_module() + + return module + + def rl_module_is_compatible(self, module: RLModule) -> bool: + """Check whether the given `module` is compatible with this Learner. + + The default implementation checks the Learner-required APIs and whether the + given `module` implements all of them (if not, returns False). + + Args: + module: The RLModule to check. + + Returns: + True if the module is compatible with this Learner. + """ + return all(isinstance(module, api) for api in self.rl_module_required_apis()) + + @classmethod + def rl_module_required_apis(cls) -> list[type]: + """Returns the required APIs for an RLModule to be compatible with this Learner. + + The returned values may or may not be used inside the `rl_module_is_compatible` + method. + + Args: + module: The RLModule to check. + + Returns: + A list of RLModule API classes that an RLModule must implement in order + to be compatible with this Learner. + """ + return [] + + def _check_registered_optimizer( + self, + optimizer: Optimizer, + params: Sequence[Param], + ) -> None: + """Checks that the given optimizer and parameters are valid for the framework. + + Args: + optimizer: The optimizer object to check. + params: The list of parameters to check. + """ + if not isinstance(params, list): + raise ValueError( + f"`params` ({params}) must be a list of framework-specific parameters " + "(variables)!" + ) + + def _log_trainable_parameters(self) -> None: + """Logs the number of trainable and non-trainable parameters to self.metrics. + + Use MetricsLogger (self.metrics) tuple-keys: + (ALL_MODULES, NUM_TRAINABLE_PARAMETERS) and + (ALL_MODULES, NUM_NON_TRAINABLE_PARAMETERS) with EMA. + """ + pass + + def _check_is_built(self, error: bool = True) -> bool: + if self.module is None: + if error: + raise ValueError( + "Learner.build() must be called after constructing a " + "Learner and before calling any methods on it." + ) + return False + return True + + def _reset(self): + self._params = {} + self._optimizer_parameters = {} + self._named_optimizers = {} + self._module_optimizers = defaultdict(list) + self._optimizer_lr_schedules = {} + self.metrics = MetricsLogger() + self._is_built = False + + def apply(self, func, *_args, **_kwargs): + return func(self, *_args, **_kwargs) + + @abc.abstractmethod + def _get_tensor_variable( + self, + value: Any, + dtype: Any = None, + trainable: bool = False, + ) -> TensorType: + """Returns a framework-specific tensor variable with the initial given value. + + This is a framework specific method that should be implemented by the + framework specific sub-classes. + + Args: + value: The initial value for the tensor variable variable. + + Returns: + The framework specific tensor variable of the given initial value, + dtype and trainable/requires_grad property. + """ + + @staticmethod + @abc.abstractmethod + def _get_optimizer_lr(optimizer: Optimizer) -> float: + """Returns the current learning rate of the given local optimizer. + + Args: + optimizer: The local optimizer to get the current learning rate for. + + Returns: + The learning rate value (float) of the given optimizer. + """ + + @staticmethod + @abc.abstractmethod + def _set_optimizer_lr(optimizer: Optimizer, lr: float) -> None: + """Updates the learning rate of the given local optimizer. + + Args: + optimizer: The local optimizer to update the learning rate for. + lr: The new learning rate. + """ + + @staticmethod + @abc.abstractmethod + def _get_clip_function() -> Callable: + """Returns the gradient clipping function to use.""" + + @staticmethod + @abc.abstractmethod + def _get_global_norm_function() -> Callable: + """Returns the global norm function to use, given the framework.""" + + def _log_steps_trained_metrics(self, batch: MultiAgentBatch): + """Logs this iteration's steps trained, based on given `batch`.""" + for mid, module_batch in batch.policy_batches.items(): + # Log weights seq no for this batch. + self.metrics.log_value( + (mid, WEIGHTS_SEQ_NO), + self._weights_seq_no, + window=1, + ) + + module_batch_size = len(module_batch) + # Log average batch size (for each module). + self.metrics.log_value( + key=(mid, MODULE_TRAIN_BATCH_SIZE_MEAN), + value=module_batch_size, + ) + # Log module steps (for each module). + self.metrics.log_value( + key=(mid, NUM_MODULE_STEPS_TRAINED), + value=module_batch_size, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + key=(mid, NUM_MODULE_STEPS_TRAINED_LIFETIME), + value=module_batch_size, + reduce="sum", + with_throughput=True, + ) + # Log module steps (sum of all modules). + self.metrics.log_value( + key=(ALL_MODULES, NUM_MODULE_STEPS_TRAINED), + value=module_batch_size, + reduce="sum", + clear_on_reduce=True, + with_throughput=True, + ) + self.metrics.log_value( + key=(ALL_MODULES, NUM_MODULE_STEPS_TRAINED_LIFETIME), + value=module_batch_size, + reduce="sum", + with_throughput=True, + ) + # Log env steps (all modules). + self.metrics.log_value( + (ALL_MODULES, NUM_ENV_STEPS_TRAINED), + batch.env_steps(), + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (ALL_MODULES, NUM_ENV_STEPS_TRAINED_LIFETIME), + batch.env_steps(), + reduce="sum", + with_throughput=True, + ) + + def _set_learner_index_and_placement_group(self, *, learner_index, placement_group): + self._learner_index = learner_index + self._placement_group = placement_group + + @Deprecated(new="Learner.update(batch=.., ..)", error=False) + def update_from_batch(self, batch, **kwargs): + if isinstance(batch, list): + if isinstance(batch[0], ray.ObjectRef): + return self.update(batches_refs=batch, **kwargs) + else: + return self.update(batches=batch, **kwargs) + else: + return self.update(batch=batch, **kwargs) + + @Deprecated(new="Learner.update(episodes=.., ..)", error=False) + def update_from_episodes(self, episodes, **kwargs): + assert isinstance(episodes, list) + if isinstance(episodes[0], ray.ObjectRef): + return self.update(episodes_refs=episodes, **kwargs) + else: + return self.update(episodes=episodes, **kwargs) + + @Deprecated(new="Learner.compute_losses(...)", error=True) + def compute_loss(self, *args, **kwargs): + pass diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/learner_group.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/learner_group.py new file mode 100644 index 0000000000000000000000000000000000000000..e1d816ff9e195a604a3c47b0a7c670ccbdff8b19 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/learner_group.py @@ -0,0 +1,755 @@ +import copy +from functools import partial +import itertools +import pathlib +from typing import ( + Any, + Callable, + Collection, + Dict, + List, + Optional, + Set, + Type, + TYPE_CHECKING, + Union, +) + +import ray +from ray.rllib.core import ( + COMPONENT_LEARNER, + COMPONENT_RL_MODULE, +) +from ray.rllib.core.learner.learner import Learner +from ray.rllib.core.learner.training_data import TrainingData +from ray.rllib.core.rl_module import validate_module_id +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.policy.policy import PolicySpec +from ray.rllib.policy.sample_batch import MultiAgentBatch +from ray.rllib.utils.actor_manager import ( + FaultTolerantActorManager, + RemoteCallResults, + ResultOrError, +) +from ray.rllib.utils.annotations import override +from ray.rllib.utils.checkpoints import Checkpointable +from ray.rllib.utils.deprecation import Deprecated +from ray.rllib.utils.typing import ( + EpisodeType, + ModuleID, + RLModuleSpecType, + ShouldModuleBeUpdatedFn, + StateDict, + T, +) +from ray.train._internal.backend_executor import BackendExecutor +from ray.util.annotations import PublicAPI + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + from ray.util.placement_group import PlacementGroup + + +def _get_backend_config(learner_class: Type[Learner]) -> str: + if learner_class.framework == "torch": + from ray.train.torch.config import TorchConfig, _TorchBackend + + # Override `_TorchBackend` share_cuda_visible_devices=True setting. + # We need this to be False to make sure Learner actors only see their + # own GPU. There is no need in RLlib's LearnerGroups for 2 different Learner + # actors to communicate with each other through their GPUs. + class _RLlibTorchBackend(_TorchBackend): + share_cuda_visible_devices = False + + class RLlibTorchConfig(TorchConfig): + @property + def backend_cls(self): + return _RLlibTorchBackend + + backend_config = RLlibTorchConfig() + + else: + raise ValueError( + "`learner_class.framework` must be 'torch' (but is " + f"{learner_class.framework}!" + ) + + return backend_config + + +class RLlibBackendExecutor(BackendExecutor): + # Override `BackendExecutor` placement group creation logic. We need to pass our own + # to make sure the one of the Algorithm (Trainable) is used for all the + # Algorithm's actors. + def _create_placement_group(self): + pass + + # TODO (sven): Change this once there is a better (public) API for this in the + # superclass. + def set_placement_group(self, placement_group): + if placement_group is not None: + self._placement_group = placement_group + + +@PublicAPI(stability="alpha") +class LearnerGroup(Checkpointable): + """Coordinator of n (possibly remote) Learner workers. + + Each Learner worker has a copy of the RLModule, the loss function(s), and + one or more optimizers. + """ + + def __init__( + self, + *, + config: "AlgorithmConfig", + # TODO (sven): Rename into `rl_module_spec`. + module_spec: Optional[RLModuleSpecType] = None, + placement_group: Optional["PlacementGroup"] = None, + ): + """Initializes a LearnerGroup instance. + + Args: + config: The AlgorithmConfig object to use to configure this LearnerGroup. + Call the `learners(num_learners=...)` method on your config to + specify the number of learner workers to use. + Call the same method with arguments `num_cpus_per_learner` and/or + `num_gpus_per_learner` to configure the compute used by each + Learner worker in this LearnerGroup. + Call the `training(learner_class=...)` method on your config to specify, + which exact Learner class to use. + Call the `rl_module(rl_module_spec=...)` method on your config to set up + the specifics for your RLModule to be used in each Learner. + module_spec: If not already specified in `config`, a separate overriding + RLModuleSpec may be provided via this argument. + placement_group: An optional `PlacementGroup` instance to set the + `RLlibBackendExecutor`'s `self._placement_group` attribute to. + If run within an Algorithm (tune.Trainable), the placement group of tune + trial actor is passed through here. + """ + self.config = config.copy(copy_frozen=False) + self._module_spec = module_spec + + learner_class = self.config.learner_class + module_spec = module_spec or self.config.get_multi_rl_module_spec() + + self._learner = None + self._workers = None + # If a user calls self.shutdown() on their own then this flag is set to true. + # When del is called the backend executor isn't shutdown twice if this flag is + # true. the backend executor would otherwise log a warning to the console from + # ray train. + self._is_shut_down = False + + # How many timesteps had to be dropped due to a full input queue? + self._ts_dropped = 0 + + # A single local Learner. + if not self.is_remote: + self._learner = learner_class(config=config, module_spec=module_spec) + self._learner.build() + self._worker_manager = None + # N remote Learner workers. + else: + backend_config = _get_backend_config(learner_class) + + num_cpus_per_learner = ( + self.config.num_cpus_per_learner + if self.config.num_cpus_per_learner != "auto" + else 1 + if self.config.num_gpus_per_learner == 0 + else 0 + ) + num_gpus_per_learner = max(0, self.config.num_gpus_per_learner) + resources_per_learner = { + "CPU": num_cpus_per_learner, + "GPU": num_gpus_per_learner, + } + + backend_executor = RLlibBackendExecutor( + backend_config=backend_config, + num_workers=self.config.num_learners, + resources_per_worker=resources_per_learner, + max_retries=0, + ) + # Set the placement group - if any - of the BackendExecutor. + backend_executor.set_placement_group(placement_group) + backend_executor.start( + train_cls=learner_class, + train_cls_kwargs={ + "config": config, + "module_spec": module_spec, + }, + ) + self._backend_executor = backend_executor + + self._workers = [w.actor for w in backend_executor.worker_group.workers] + + ray.get( + [ + worker._set_learner_index_and_placement_group.remote( + learner_index=idx, + placement_group=placement_group, + ) + for idx, worker in enumerate(self._workers) + ] + ) + + # Run the neural network building code on remote workers. + ray.get([w.build.remote() for w in self._workers]) + + self._worker_manager = FaultTolerantActorManager( + self._workers, + max_remote_requests_in_flight_per_actor=( + self.config.max_requests_in_flight_per_learner + ), + ) + + # TODO (sven): Replace this with call to `self.metrics.peek()`? + # Currently LearnerGroup does not have a metrics object. + def get_stats(self) -> Dict[str, Any]: + """Returns the current stats for the input queue for this learner group.""" + return { + "learner_group_ts_dropped_lifetime": self._ts_dropped, + "actor_manager_num_outstanding_async_reqs": ( + 0 + if self.is_local + else self._worker_manager.num_outstanding_async_reqs() + ), + } + + @property + def is_remote(self) -> bool: + return self.config.num_learners > 0 + + @property + def is_local(self) -> bool: + return not self.is_remote + + def update( + self, + *, + batch: Optional[MultiAgentBatch] = None, + batches: Optional[List[MultiAgentBatch]] = None, + batch_refs: Optional[List[ray.ObjectRef]] = None, + episodes: Optional[List[EpisodeType]] = None, + episodes_refs: Optional[List[ray.ObjectRef]] = None, + data_iterators: Optional[List[ray.data.DataIterator]] = None, + training_data: Optional[TrainingData] = None, + timesteps: Optional[Dict[str, Any]] = None, + async_update: bool = False, + return_state: bool = False, + # User kwargs passed onto the Learners. + **kwargs, + ) -> List[Dict[str, Any]]: + """Performs gradient based updates on Learners, based on given training data. + + Args: + batch: A data batch to use for the update. If there are more + than one Learner workers, the batch is split amongst these and one + shard is sent to each Learner. + batch_refs: + episodes: A list of Episodes to process and perform the update + for. If there are more than one Learner workers, the list of episodes + is split amongst these and one list shard is sent to each Learner. + episodes_refs: + timesteps: + async_update: Whether the update request(s) to the Learner workers should be + sent asynchronously. If True, will return NOT the results from the + update on the given data, but all results from prior asynchronous update + requests that have not been returned thus far. + return_state: Whether to include one of the Learner worker's state from + after the update step in the returned results dict (under the + `_rl_module_state_after_update` key). Note that after an update, all + Learner workers' states should be identical, so we use the first + Learner's state here. Useful for avoiding an extra `get_weights()` call, + e.g. for synchronizing EnvRunner weights. + num_epochs: The number of complete passes over the entire train batch. Each + pass might be further split into n minibatches (if `minibatch_size` + provided). + minibatch_size: The size of minibatches to use to further split the train + `batch` into sub-batches. The `batch` is then iterated over n times + where n is `len(batch) // minibatch_size`. + shuffle_batch_per_epoch: Whether to shuffle the train batch once per epoch. + If the train batch has a time rank (axis=1), shuffling will only take + place along the batch axis to not disturb any intact (episode) + trajectories. Also, shuffling is always skipped if `minibatch_size` is + None, meaning the entire train batch is processed each epoch, making it + unnecessary to shuffle. + **kwargs: + + Returns: + If `async_update` is False, a dictionary with the reduced results of the + updates from the Learner(s) or a list of dictionaries of results from the + updates from the Learner(s). + If `async_update` is True, a list of list of dictionaries of results, where + the outer list corresponds to separate previous calls to this method, and + the inner list corresponds to the results from each Learner(s). Or if the + results are reduced, a list of dictionaries of the reduced results from each + call to async_update that is ready. + """ + # Create and validate TrainingData object, if not already provided. + if training_data is None: + training_data = TrainingData( + batch=batch, + batches=batches, + batch_refs=batch_refs, + episodes=episodes, + episodes_refs=episodes_refs, + data_iterators=data_iterators, + ) + training_data.validate() + + # Local Learner instance. + if self.is_local: + if async_update: + raise ValueError( + "Can't call `update(async_update=True)` when running with " + "`num_learners=0`! Set `config.num_learners > 0` to allow async " + "updates." + ) + # Solve all ray refs locally already here. + training_data.solve_refs() + if return_state: + kwargs["return_state"] = return_state + # Return the single Learner's update results. + return [ + self._learner.update( + training_data=training_data, + timesteps=timesteps, + **kwargs, + ) + ] + + # Remote Learner actors' kwargs. + remote_call_kwargs = [ + dict( + training_data=td_shard, + timesteps=timesteps, + # If `return_state=True`, only return it from the first Learner + # actor. + return_state=(return_state and i == 0), + **kw, + **kwargs, + ) + for i, (td_shard, kw) in enumerate( + training_data.shard( + num_shards=len(self), + len_lookback_buffer=self.config.episode_lookback_horizon, + **kwargs, + ) + ) + ] + + # Async updates. + if async_update: + # Retrieve all ready results (kicked off by prior calls to this method). + results = self._worker_manager.fetch_ready_async_reqs(timeout_seconds=0.0) + # Send out new request(s), if there is still capacity on the actors + # (each actor is allowed only some number of max in-flight requests + # at the same time). + num_sent_requests = self._worker_manager.foreach_actor_async( + "update", + kwargs=remote_call_kwargs, + ) + + # Some requests were dropped, record lost ts/data. + if num_sent_requests != len(self): + factor = 1 - (num_sent_requests / len(self)) + # TODO (sven): Move this logic into a TrainingData API as well + # (`TrainingData.env_steps()`). + if training_data.batch_refs is not None: + dropped = ( + len(training_data.batch_refs) + * self.config.train_batch_size_per_learner + ) + elif training_data.batch is not None: + dropped = len(training_data.batch) + # List of Ray ObjectRefs (each object ref is a list of episodes of + # total len=`rollout_fragment_length * num_envs_per_env_runner`) + elif training_data.episodes_refs is not None: + dropped = ( + len(training_data.episodes_refs) + * self.config.get_rollout_fragment_length() + * self.config.num_envs_per_env_runner + ) + else: + assert training_data.episodes is not None + dropped = sum(len(e) for e in training_data.episodes) + + self._ts_dropped += factor * dropped + # Sync updates. + else: + results = self._worker_manager.foreach_actor( + "update", + kwargs=remote_call_kwargs, + ) + + results = self._get_results(results) + return results + + def add_module( + self, + *, + module_id: ModuleID, + module_spec: RLModuleSpec, + config_overrides: Optional[Dict] = None, + new_should_module_be_updated: Optional[ShouldModuleBeUpdatedFn] = None, + ) -> MultiRLModuleSpec: + """Adds a module to the underlying MultiRLModule. + + Changes this Learner's config in order to make this architectural change + permanent wrt. to checkpointing. + + Args: + module_id: The ModuleID of the module to be added. + module_spec: The ModuleSpec of the module to be added. + config_overrides: The `AlgorithmConfig` overrides that should apply to + the new Module, if any. + new_should_module_be_updated: An optional sequence of ModuleIDs or a + callable taking ModuleID and SampleBatchType and returning whether the + ModuleID should be updated (trained). + If None, will keep the existing setup in place. RLModules, + whose IDs are not in the list (or for which the callable + returns False) will not be updated. + + Returns: + The new MultiRLModuleSpec (after the change has been performed). + """ + validate_module_id(module_id, error=True) + + # Force-set inference-only = False. + module_spec = copy.deepcopy(module_spec) + module_spec.inference_only = False + + results = self.foreach_learner( + func=lambda _learner: _learner.add_module( + module_id=module_id, + module_spec=module_spec, + config_overrides=config_overrides, + new_should_module_be_updated=new_should_module_be_updated, + ), + ) + marl_spec = self._get_results(results)[0] + + # Change our config (AlgorithmConfig) to contain the new Module. + # TODO (sven): This is a hack to manipulate the AlgorithmConfig directly, + # but we'll deprecate config.policies soon anyway. + self.config.policies[module_id] = PolicySpec() + if config_overrides is not None: + self.config.multi_agent( + algorithm_config_overrides_per_module={module_id: config_overrides} + ) + self.config.rl_module(rl_module_spec=marl_spec) + if new_should_module_be_updated is not None: + self.config.multi_agent(policies_to_train=new_should_module_be_updated) + + return marl_spec + + def remove_module( + self, + module_id: ModuleID, + *, + new_should_module_be_updated: Optional[ShouldModuleBeUpdatedFn] = None, + ) -> MultiRLModuleSpec: + """Removes a module from the Learner. + + Args: + module_id: The ModuleID of the module to be removed. + new_should_module_be_updated: An optional sequence of ModuleIDs or a + callable taking ModuleID and SampleBatchType and returning whether the + ModuleID should be updated (trained). + If None, will keep the existing setup in place. RLModules, + whose IDs are not in the list (or for which the callable + returns False) will not be updated. + + Returns: + The new MultiRLModuleSpec (after the change has been performed). + """ + results = self.foreach_learner( + func=lambda _learner: _learner.remove_module( + module_id=module_id, + new_should_module_be_updated=new_should_module_be_updated, + ), + ) + marl_spec = self._get_results(results)[0] + + # Change self.config to reflect the new architecture. + # TODO (sven): This is a hack to manipulate the AlgorithmConfig directly, + # but we'll deprecate config.policies soon anyway. + del self.config.policies[module_id] + self.config.algorithm_config_overrides_per_module.pop(module_id, None) + if new_should_module_be_updated is not None: + self.config.multi_agent(policies_to_train=new_should_module_be_updated) + self.config.rl_module(rl_module_spec=marl_spec) + + return marl_spec + + @override(Checkpointable) + def get_state( + self, + components: Optional[Union[str, Collection[str]]] = None, + *, + not_components: Optional[Union[str, Collection[str]]] = None, + **kwargs, + ) -> StateDict: + state = {} + + if self._check_component(COMPONENT_LEARNER, components, not_components): + if self.is_local: + state[COMPONENT_LEARNER] = self._learner.get_state( + components=self._get_subcomponents(COMPONENT_LEARNER, components), + not_components=self._get_subcomponents( + COMPONENT_LEARNER, not_components + ), + **kwargs, + ) + else: + worker = self._worker_manager.healthy_actor_ids()[0] + assert len(self) == self._worker_manager.num_healthy_actors() + _comps = self._get_subcomponents(COMPONENT_LEARNER, components) + _not_comps = self._get_subcomponents(COMPONENT_LEARNER, not_components) + results = self._worker_manager.foreach_actor( + lambda w: w.get_state(_comps, not_components=_not_comps, **kwargs), + remote_actor_ids=[worker], + ) + state[COMPONENT_LEARNER] = self._get_results(results)[0] + + return state + + @override(Checkpointable) + def set_state(self, state: StateDict) -> None: + if COMPONENT_LEARNER in state: + if self.is_local: + self._learner.set_state(state[COMPONENT_LEARNER]) + else: + state_ref = ray.put(state[COMPONENT_LEARNER]) + self.foreach_learner( + lambda _learner, _ref=state_ref: _learner.set_state(ray.get(_ref)) + ) + + def get_weights( + self, module_ids: Optional[Collection[ModuleID]] = None + ) -> StateDict: + """Convenience method instead of self.get_state(components=...). + + Args: + module_ids: An optional collection of ModuleIDs for which to return weights. + If None (default), return weights of all RLModules. + + Returns: + The results of + `self.get_state(components='learner/rl_module')['learner']['rl_module']`. + """ + # Return the entire RLModule state (all possible single-agent RLModules). + if module_ids is None: + components = COMPONENT_LEARNER + "/" + COMPONENT_RL_MODULE + # Return a subset of the single-agent RLModules. + else: + components = [ + "".join(tup) + for tup in itertools.product( + [COMPONENT_LEARNER + "/" + COMPONENT_RL_MODULE + "/"], + list(module_ids), + ) + ] + state = self.get_state(components)[COMPONENT_LEARNER][COMPONENT_RL_MODULE] + return state + + def set_weights(self, weights) -> None: + """Convenience method instead of self.set_state({'learner': {'rl_module': ..}}). + + Args: + weights: The weights dict of the MultiRLModule of a Learner inside this + LearnerGroup. + """ + self.set_state({COMPONENT_LEARNER: {COMPONENT_RL_MODULE: weights}}) + + @override(Checkpointable) + def get_ctor_args_and_kwargs(self): + return ( + (), # *args + { + "config": self.config, + "module_spec": self._module_spec, + }, # **kwargs + ) + + @override(Checkpointable) + def get_checkpointable_components(self): + # Return the entire ActorManager, if remote. Otherwise, return the + # local worker. Also, don't give the component (Learner) a name ("") + # as it's the only component in this LearnerGroup to be saved. + return [ + ( + COMPONENT_LEARNER, + self._learner if self.is_local else self._worker_manager, + ) + ] + + def foreach_learner( + self, + func: Callable[[Learner, Optional[Any]], T], + *, + healthy_only: bool = True, + remote_actor_ids: List[int] = None, + timeout_seconds: Optional[float] = None, + return_obj_refs: bool = False, + mark_healthy: bool = False, + **kwargs, + ) -> RemoteCallResults: + r"""Calls the given function on each Learner L with the args: (L, \*\*kwargs). + + Args: + func: The function to call on each Learner L with args: (L, \*\*kwargs). + healthy_only: If True, applies `func` only to Learner actors currently + tagged "healthy", otherwise to all actors. If `healthy_only=False` and + `mark_healthy=True`, will send `func` to all actors and mark those + actors "healthy" that respond to the request within `timeout_seconds` + and are currently tagged as "unhealthy". + remote_actor_ids: Apply func on a selected set of remote actors. Use None + (default) for all actors. + timeout_seconds: Time to wait (in seconds) for results. Set this to 0.0 for + fire-and-forget. Set this to None (default) to wait infinitely (i.e. for + synchronous execution). + return_obj_refs: whether to return ObjectRef instead of actual results. + Note, for fault tolerance reasons, these returned ObjectRefs should + never be resolved with ray.get() outside of the context of this manager. + mark_healthy: Whether to mark all those actors healthy again that are + currently marked unhealthy AND that returned results from the remote + call (within the given `timeout_seconds`). + Note that actors are NOT set unhealthy, if they simply time out + (only if they return a RayActorError). + Also not that this setting is ignored if `healthy_only=True` (b/c this + setting only affects actors that are currently tagged as unhealthy). + + Returns: + A list of size len(Learners) with the return values of all calls to `func`. + """ + if self.is_local: + results = RemoteCallResults() + results.add_result( + None, + ResultOrError(result=func(self._learner, **kwargs)), + None, + ) + return results + + return self._worker_manager.foreach_actor( + func=partial(func, **kwargs), + healthy_only=healthy_only, + remote_actor_ids=remote_actor_ids, + timeout_seconds=timeout_seconds, + return_obj_refs=return_obj_refs, + mark_healthy=mark_healthy, + ) + + def __len__(self): + return 0 if self.is_local else len(self._workers) + + def shutdown(self): + """Shuts down the LearnerGroup.""" + if self.is_remote and hasattr(self, "_backend_executor"): + self._backend_executor.shutdown(graceful_termination=True) + self._is_shut_down = True + + def __del__(self): + if not self._is_shut_down: + self.shutdown() + + def _get_results(self, results): + processed_results = [] + for result in results: + result_or_error = result.get() + if result.ok: + processed_results.append(result_or_error) + else: + raise result_or_error + return processed_results + + @Deprecated(new="LearnerGroup.update(batch=.., **kwargs)", error=False) + def update_from_batch(self, batch, **kwargs): + return self.update(batch=batch, **kwargs) + + @Deprecated(new="LearnerGroup.update(episodes=.., **kwargs)", error=False) + def update_from_episodes(self, episodes, **kwargs): + return self.update(episodes=episodes, **kwargs) + + @Deprecated(new="LearnerGroup.update_from_batch(async=True)", error=True) + def async_update(self, *args, **kwargs): + pass + + @Deprecated(new="LearnerGroup.load_from_path(path=..., component=...)", error=False) + def load_module_state( + self, + *, + multi_rl_module_ckpt_dir: Optional[str] = None, + modules_to_load: Optional[Set[str]] = None, + rl_module_ckpt_dirs: Optional[Dict[ModuleID, str]] = None, + ) -> None: + """Load the checkpoints of the modules being trained by this LearnerGroup. + + `load_module_state` can be used 3 ways: + 1. Load a checkpoint for the MultiRLModule being trained by this + LearnerGroup. Limit the modules that are loaded from the checkpoint + by specifying the `modules_to_load` argument. + 2. Load the checkpoint(s) for single agent RLModules that + are in the MultiRLModule being trained by this LearnerGroup. + 3. Load a checkpoint for the MultiRLModule being trained by this + LearnerGroup and load the checkpoint(s) for single agent RLModules + that are in the MultiRLModule. The checkpoints for the single + agent RLModules take precedence over the module states in the + MultiRLModule checkpoint. + + NOTE: At lease one of multi_rl_module_ckpt_dir or rl_module_ckpt_dirs is + must be specified. modules_to_load can only be specified if + multi_rl_module_ckpt_dir is specified. + + Args: + multi_rl_module_ckpt_dir: The path to the checkpoint for the + MultiRLModule. + modules_to_load: A set of module ids to load from the checkpoint. + rl_module_ckpt_dirs: A mapping from module ids to the path to a + checkpoint for a single agent RLModule. + """ + if not (multi_rl_module_ckpt_dir or rl_module_ckpt_dirs): + raise ValueError( + "At least one of `multi_rl_module_ckpt_dir` or " + "`rl_module_ckpt_dirs` must be provided!" + ) + if multi_rl_module_ckpt_dir: + multi_rl_module_ckpt_dir = pathlib.Path(multi_rl_module_ckpt_dir) + if rl_module_ckpt_dirs: + for module_id, path in rl_module_ckpt_dirs.items(): + rl_module_ckpt_dirs[module_id] = pathlib.Path(path) + + # MultiRLModule checkpoint is provided. + if multi_rl_module_ckpt_dir: + # Restore the entire MultiRLModule state. + if modules_to_load is None: + self.restore_from_path( + multi_rl_module_ckpt_dir, + component=COMPONENT_LEARNER + "/" + COMPONENT_RL_MODULE, + ) + # Restore individual module IDs. + else: + for module_id in modules_to_load: + self.restore_from_path( + multi_rl_module_ckpt_dir / module_id, + component=( + COMPONENT_LEARNER + + "/" + + COMPONENT_RL_MODULE + + "/" + + module_id + ), + ) + if rl_module_ckpt_dirs: + for module_id, path in rl_module_ckpt_dirs.items(): + self.restore_from_path( + path, + component=( + COMPONENT_LEARNER + "/" + COMPONENT_RL_MODULE + "/" + module_id + ), + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/torch/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/torch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/torch/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/torch/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e63ee473032269771f39d8ca2a8b80ae64d79e1c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/torch/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/torch/__pycache__/torch_differentiable_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/torch/__pycache__/torch_differentiable_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c183ce979d40a9874e19d612327462a64428b7e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/torch/__pycache__/torch_differentiable_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/torch/__pycache__/torch_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/torch/__pycache__/torch_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..edc445898e18bf896792e41527508af80271b016 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/torch/__pycache__/torch_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/torch/__pycache__/torch_meta_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/torch/__pycache__/torch_meta_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb2daa17955d6204626bf5a1945b82a1210523ec Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/torch/__pycache__/torch_meta_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/torch/torch_differentiable_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/torch/torch_differentiable_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..5ceeaf924cec8c1cad2d90b9c8798605716e0cc4 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/torch/torch_differentiable_learner.py @@ -0,0 +1,375 @@ +import contextlib +import logging + +from typing import Any, Dict, Optional, Tuple + +from ray.rllib.algorithms.algorithm_config import ( + TorchCompileWhatToCompile, +) +from ray.rllib.core.columns import Columns +from ray.rllib.core.learner.differentiable_learner import DifferentiableLearner +from ray.rllib.core.rl_module.torch.torch_rl_module import ( + TorchCompileConfig, +) +from ray.rllib.policy.sample_batch import MultiAgentBatch +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.metrics import ( + DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY, + WEIGHTS_SEQ_NO, +) +from ray.rllib.utils.torch_utils import convert_to_torch_tensor +from ray.rllib.utils.typing import DeviceType, ModuleID, NamedParamDict, TensorType + +logger = logging.getLogger("__name__") + +torch, nn = try_import_torch() + + +# TODO (simon): Maybe create again a base class `TorchLearnable`. +class TorchDifferentiableLearner(DifferentiableLearner): + """A `DifferentiableLearner` class leveraging PyTorch for functional updates. + + This class utilizes PyTorch 2.0's `func` module to perform functional + updates on the provided parameters. + """ + + # Set the framework to `"torch"`. + framework: str = "torch" + + def __init__(self, **kwargs): + + # First initialize the `DifferentiableLearner` base class to set + # the configurations and `MultiRLModule`. + super().__init__(**kwargs) + + # Whether to compile the RL Module of this learner. This implies that the. + # forward_train method of the RL Module will be compiled. Further more, + # other forward methods of the RL Module will be compiled on demand. + # This is assumed to not happen, since other forwrad methods are not expected + # to be used during training. + self._torch_compile_forward_train = False + self._torch_compile_cfg = None + # Whether to compile the `_uncompiled_update` method of this learner. This + # implies that everything within `_uncompiled_update` will be compiled, + # not only the forward_train method of the RL Module. + # Note that this is experimental. + # Note that this requires recompiling the forward methods once we add/remove + # RL Modules. + self._torch_compile_complete_update = False + if self.config.torch_compile_learner: + if ( + self.config.torch_compile_learner_what_to_compile + == TorchCompileWhatToCompile.COMPLETE_UPDATE + ): + self._torch_compile_complete_update = True + self._compiled_update_initialized = False + else: + self._torch_compile_forward_train = True + + self._torch_compile_cfg = TorchCompileConfig( + torch_dynamo_backend=self.config.torch_compile_learner_dynamo_backend, + torch_dynamo_mode=self.config.torch_compile_learner_dynamo_mode, + ) + + # TODO (simon): See, if we can include these without a torch optimizer. + # self._lr_schedulers = {} + # self._lr_scheduler_classes = None + # if self.config._torch_lr_scheduler_classes: + # self._lr_scheduler_classes = self.config._torch_lr_scheduler_classes + + def _uncompiled_update( + self, + batch: Dict, + params: Dict[ModuleID, NamedParamDict], + **kwargs, + ) -> Tuple[Any, Any, Dict[ModuleID, NamedParamDict], Any]: + """Performs a single functional update using a batch of data. + + This update operates on parameters passed via a functional call to the + `MultiRLModule` and leverages PyTorch 2.0's `autograd` module. Parameters + are not modified in-place within `self._module`; instead, updates are + applied to the cloned parameters provided. + + Args: + batch: A dictionary (or `MultiAgentBatch`) containing training data for + all modules in the `MultiRLModule` (that should be trained). + params: A dictionary of named parameters for each module id. + + Returns: + A tuple consisting of: + 1) the output of a functional forward call to the RLModule using + `params`, + 2) the `loss_per_module` dictionary mapping module IDs to individual + loss tensors, + 3) the functionally updated parameters in the (dict) format passed in, + 4) a metrics dict mapping module IDs to metrics key/value pairs. + + """ + # TODO (sven): Causes weird cuda error when WandB is used. + # Diagnosis thus far: + # - All peek values during metrics.reduce are non-tensors. + # - However, in impala.py::training_step(), a tensor does arrive after learner + # group.update(), so somehow, there is still a race condition + # possible (learner, which performs the reduce() and learner thread, which + # performs the logging of tensors into metrics logger). + self._compute_off_policyness(batch) + + # Make a functional forward pass with the provided parameters. + fwd_out = self._make_functional_call(params, batch) + loss_per_module = self.compute_losses(fwd_out=fwd_out, batch=batch) + # Compute gradients for the provided parameters. + gradients = self.compute_gradients(loss_per_module, params) + + with contextlib.ExitStack() as stack: + if self.config.num_learners > 1: + for mod in self.module.values(): + # Skip non-torch modules, b/c they may not have the `no_sync` API. + if isinstance(mod, torch.nn.Module): + stack.enter_context(mod.no_sync()) + # TODO (simon): See, if we need here postprocessing of gradients. + # postprocessed_gradients = self.postprocess_gradients(gradients) + # Make a stateless (of `params`) update of the `RLModule` parameters. + params = self.apply_gradients(gradients, params) + + # Deactivate tensor-mode on our MetricsLogger and collect the (tensor) + # results. + return fwd_out, loss_per_module, params, {} + + # TODO (simon): Maybe make type for gradients. + @override(DifferentiableLearner) + def compute_gradients( + self, + loss_per_module: Dict[ModuleID, TensorType], + params: Dict[ModuleID, NamedParamDict], + **kwargs, + ) -> Dict[ModuleID, NamedParamDict]: + """Computes functionally gradients based on the given losses. + + This method uses `torch.autograd.grad` to make the backward pass on the + `MultiRLModule` which enables a functional backward pass. If a PyTorch + optimizer is needed a differentiable one must be used (e.g. `torchopt`). + + Args: + loss_per_module: Dict mapping module IDs to their individual total loss + terms, computed by the individual `compute_loss_for_module()` calls. + The overall total loss (sum of loss terms over all modules) is stored + under `loss_per_module[ALL_MODULES]` + params: A dictionary containing named parameters for each module id. + **kwargs: Forward compatibility kwargs. + + Returns: + The (named) gradients in the same (dict) format as `params`. + """ + + # TODO (simon): Add grad scalers later. + total_loss = sum(loss_per_module.values()) + + # Use `torch`'s `autograd` to compute gradients and create a graph, so we can + # compute higher order gradients. Allow specified inputs not being used in outputs + # as probably not all modules/parameters of a `MultiRLModule` are used in the loss. + # Note, parameters are named parameters as this is needed by the + # `torch.func.functional_call` + # TODO (simon): Make sure this works for `MultiRLModule`s. This here can have + # all parameter tensors in a list. But the `functional_call` above needs named + # parameters for each module. Implement this via `foreach_module`. + grads = torch.autograd.grad( + total_loss, + sum((list(param.values()) for mid, param in params.items()), []), + create_graph=True, + retain_graph=True, + allow_unused=True, + ) + + # Map all gradients to their keys. + named_grads = { + module_id: { + name: grad for (name, _), grad in zip(module_params.items(), grads) + } + for module_id, module_params in params.items() + } + + return named_grads + + @override(DifferentiableLearner) + def apply_gradients( + self, + gradients: Dict[ModuleID, NamedParamDict], + params: Dict[ModuleID, NamedParamDict], + ) -> Dict[ModuleID, NamedParamDict]: + """Applies the given gradients in a functional manner. + + This method requires functional parameter updates, meaning modifications + must not be performed in-place (e.g., using an optimizer or directly within + the `MultiRLModule`). + + Args: + gradients: A dictionary containing named gradients for each module id. + params: A dictionary containing named parameters for each module id. + + Returns: + The updated parameters in the same (dict) format as `params`. + """ + policies_to_update = self.learner_config.policies_to_update or list( + gradients.keys() + ) + # Note, because this is a functional update we cannot apply in-place + # modifications of parameters. + updated_params = {} + for module_id, module_grads in gradients.items(): + if module_id not in policies_to_update: + updated_params[module_id] = params[module_id] + continue + updated_params[module_id] = {} + for name, grad in module_grads.items(): + # If updates should not be skipped turn `nan` and `inf` gradients to zero. + if ( + not self.config.torch_skip_nan_gradients + and not torch.isfinite(grad).all() + ): + # Warn the user about `nan` gradients. + logger.warning(f"Gradients {name} contain `nan/inf` values.") + # If updates should be skipped, do not step the optimizer and return. + if not self.config.torch_skip_nan_gradients: + logger.warning( + "Setting `nan/inf` gradients to zero. If updates with " + "`nan/inf` gradients should not be set to zero and instead " + "the update be skipped entirely set `torch_skip_nan_gradients` " + "to `True`." + ) + # If necessary turn `nan` gradients to zero. Note, this can corrupt the + # internal state of the optimizer, if many `nan` gradients occur. + grad = torch.nan_to_num(grad) + + if self.config.torch_skip_nan_gradients or torch.isfinite(grad).all(): + # Update each parameter, by a simple gradient descent step. + updated_params[module_id][name] = ( + params[module_id][name] - self.learner_config.lr * grad + ) + elif grad is None or not torch.isfinite(grad).all(): + logger.warning( + "Skipping this update. If updates with `nan/inf` gradients " + "should not be skipped entirely and instead `nan/inf` " + "gradients set to `zero` set `torch_skip_nan_gradients` to " + "`False`." + ) + return updated_params + + def _make_functional_call( + self, params: Dict[ModuleID, NamedParamDict], batch: MultiAgentBatch + ) -> Dict[ModuleID, NamedParamDict]: + """Makes a functional call for each module in the `MultiRLModule`.""" + return self._module.foreach_module( + lambda mid, m: torch.func.functional_call(m, params[mid], batch[mid]), + return_dict=True, + ) + + @override(DifferentiableLearner) + def _get_tensor_variable( + self, value, dtype=None, trainable=False + ) -> "torch.Tensor": + tensor = torch.tensor( + value, + requires_grad=trainable, + # TODO (simon): Make GPU-trainable. + # device=self._device, + dtype=( + dtype + or ( + torch.float32 + if isinstance(value, float) + else torch.int32 + if isinstance(value, int) + else None + ) + ), + ) + return nn.Parameter(tensor) if trainable else tensor + + def _convert_batch_type( + self, + batch: MultiAgentBatch, + to_device: bool = True, + pin_memory: bool = False, + use_stream: bool = False, + ) -> MultiAgentBatch: + batch = convert_to_torch_tensor( + batch.policy_batches, + device=self._device if to_device else None, + pin_memory=pin_memory, + use_stream=use_stream, + ) + # TODO (sven): This computation of `env_steps` is not accurate! + length = max(len(b) for b in batch.values()) + batch = MultiAgentBatch(batch, env_steps=length) + return batch + + def _compute_off_policyness(self, batch): + # Log off-policy'ness of this batch wrt the current weights. + off_policyness = { + (mid, DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY): ( + (self._weights_seq_no - module_batch[WEIGHTS_SEQ_NO]).float() + ) + for mid, module_batch in batch.items() + if WEIGHTS_SEQ_NO in module_batch + } + for key in off_policyness.keys(): + mid = key[0] + if Columns.LOSS_MASK not in batch[mid]: + off_policyness[key] = torch.mean(off_policyness[key]) + else: + mask = batch[mid][Columns.LOSS_MASK] + num_valid = torch.sum(mask) + off_policyness[key] = torch.sum(off_policyness[key][mask]) / num_valid + self.metrics.log_dict(off_policyness, window=1) + + @override(DifferentiableLearner) + def build(self, device: Optional[DeviceType] = None) -> None: + """Builds the TorchDifferentiableLearner. + + This method is specific to TorchDifferentiableLearner. Before running super() it will + initialize the device properly based on `self.config`, so that `_make_module()` + can place the created module on the correct device. After running super() it + wraps the module in a TorchDDPRLModule if `config.num_learners > 0`. + Note, in inherited classes it is advisable to call the parent's `build()` + after setting up all variables because `configure_optimizer_for_module` is + called in this `Learner.build()`. + """ + # TODO (simon): Allow different `DifferentiableLearner` instances in a + # `MetaLearner` to run on different GPUs. + + super().build(device=device) + + if self._torch_compile_complete_update: + torch._dynamo.reset() + self._compiled_update_initialized = False + self._possibly_compiled_update = torch.compile( + self._uncompiled_update, + backend=self._torch_compile_cfg.torch_dynamo_backend, + mode=self._torch_compile_cfg.torch_dynamo_mode, + **self._torch_compile_cfg.kwargs, + ) + # Otherwise, we use the possibly compiled `forward_train` in + # the module, compiled in the `MetaLearner`. + else: + # Nothing, to do. + self._possibly_compiled_update = self._uncompiled_update + + @override(DifferentiableLearner) + def _update( + self, batch: Dict[str, Any], params: Dict[ModuleID, NamedParamDict] + ) -> Tuple[Any, Dict[ModuleID, NamedParamDict], Any, Any]: + # The first time we call _update after building the learner or + # adding/removing models, we update with the uncompiled update method. + # This makes it so that any variables that may be created during the first + # update step are already there when compiling. More specifically, + # this avoids errors that occur around using defaultdicts with + # torch.compile(). + if ( + self._torch_compile_complete_update + and not self._compiled_update_initialized + ): + self._compiled_update_initialized = True + return self._uncompiled_update(batch, params) + else: + return self._possibly_compiled_update(batch, params) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/torch/torch_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/torch/torch_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..e49ce42d516867f69f240d19ac90248ff2afc1f3 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/torch/torch_learner.py @@ -0,0 +1,685 @@ +from collections import defaultdict +import contextlib +import logging +from typing import ( + Any, + Callable, + Dict, + Hashable, + Optional, + Sequence, + Tuple, + TYPE_CHECKING, +) + +from ray.rllib.algorithms.algorithm_config import ( + AlgorithmConfig, + TorchCompileWhatToCompile, +) +from ray.rllib.core.columns import Columns +from ray.rllib.core.learner.learner import Learner, LR_KEY +from ray.rllib.core.rl_module.multi_rl_module import ( + MultiRLModule, + MultiRLModuleSpec, +) +from ray.rllib.core.rl_module.rl_module import ( + RLModule, + RLModuleSpec, +) +from ray.rllib.core.rl_module.torch.torch_rl_module import ( + TorchCompileConfig, + TorchDDPRLModule, + TorchRLModule, +) +from ray.rllib.policy.sample_batch import MultiAgentBatch +from ray.rllib.utils.annotations import ( + override, + OverrideToImplementCustomLogic, + OverrideToImplementCustomLogic_CallToSuperRecommended, +) +from ray.rllib.utils.framework import get_device, try_import_torch +from ray.rllib.utils.metrics import ( + ALL_MODULES, + DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY, + NUM_TRAINABLE_PARAMETERS, + NUM_NON_TRAINABLE_PARAMETERS, + WEIGHTS_SEQ_NO, +) +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.torch_utils import convert_to_torch_tensor +from ray.rllib.utils.typing import ( + ModuleID, + Optimizer, + Param, + ParamDict, + ShouldModuleBeUpdatedFn, + StateDict, + TensorType, +) + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + +torch, nn = try_import_torch() +logger = logging.getLogger(__name__) + + +class TorchLearner(Learner): + + framework: str = "torch" + + def __init__(self, **kwargs): + super().__init__(**kwargs) + + # Whether to compile the RL Module of this learner. This implies that the. + # forward_train method of the RL Module will be compiled. Further more, + # other forward methods of the RL Module will be compiled on demand. + # This is assumed to not happen, since other forwrad methods are not expected + # to be used during training. + self._torch_compile_forward_train = False + self._torch_compile_cfg = None + # Whether to compile the `_uncompiled_update` method of this learner. This + # implies that everything within `_uncompiled_update` will be compiled, + # not only the forward_train method of the RL Module. + # Note that this is experimental. + # Note that this requires recompiling the forward methods once we add/remove + # RL Modules. + self._torch_compile_complete_update = False + if self.config.torch_compile_learner: + if ( + self.config.torch_compile_learner_what_to_compile + == TorchCompileWhatToCompile.COMPLETE_UPDATE + ): + self._torch_compile_complete_update = True + self._compiled_update_initialized = False + else: + self._torch_compile_forward_train = True + + self._torch_compile_cfg = TorchCompileConfig( + torch_dynamo_backend=self.config.torch_compile_learner_dynamo_backend, + torch_dynamo_mode=self.config.torch_compile_learner_dynamo_mode, + ) + + # Loss scalers for mixed precision training. Map optimizer names to + # associated torch GradScaler objects. + self._grad_scalers = None + if self.config._torch_grad_scaler_class: + self._grad_scalers = defaultdict( + lambda: self.config._torch_grad_scaler_class() + ) + self._lr_schedulers = {} + self._lr_scheduler_classes = None + if self.config._torch_lr_scheduler_classes: + self._lr_scheduler_classes = self.config._torch_lr_scheduler_classes + + @OverrideToImplementCustomLogic + @override(Learner) + def configure_optimizers_for_module( + self, + module_id: ModuleID, + config: "AlgorithmConfig" = None, + ) -> None: + module = self._module[module_id] + + # For this default implementation, the learning rate is handled by the + # attached lr Scheduler (controlled by self.config.lr, which can be a + # fixed value or a schedule setting). + params = self.get_parameters(module) + optimizer = torch.optim.Adam(params) + + # Register the created optimizer (under the default optimizer name). + self.register_optimizer( + module_id=module_id, + optimizer=optimizer, + params=params, + lr_or_lr_schedule=config.lr, + ) + + def _uncompiled_update( + self, + batch: Dict, + **kwargs, + ): + """Performs a single update given a batch of data.""" + + # TODO (sven): Causes weird cuda error when WandB is used. + # Diagnosis thus far: + # - All peek values during metrics.reduce are non-tensors. + # - However, in impala.py::training_step(), a tensor does arrive after learner + # group.update(), so somehow, there is still a race condition + # possible (learner, which performs the reduce() and learner thread, which + # performs the logging of tensors into metrics logger). + self._compute_off_policyness(batch) + + fwd_out = self.module.forward_train(batch) + loss_per_module = self.compute_losses(fwd_out=fwd_out, batch=batch) + gradients = self.compute_gradients(loss_per_module) + + with contextlib.ExitStack() as stack: + if self.config.num_learners > 1: + for mod in self.module.values(): + # Skip non-torch modules, b/c they may not have the `no_sync` API. + if isinstance(mod, torch.nn.Module): + stack.enter_context(mod.no_sync()) + postprocessed_gradients = self.postprocess_gradients(gradients) + self.apply_gradients(postprocessed_gradients) + + return fwd_out, loss_per_module, {} + + @override(Learner) + def compute_gradients( + self, loss_per_module: Dict[ModuleID, TensorType], **kwargs + ) -> ParamDict: + for optim in self._optimizer_parameters: + # `set_to_none=True` is a faster way to zero out the gradients. + optim.zero_grad(set_to_none=True) + + if self._grad_scalers is not None: + total_loss = sum( + self._grad_scalers[mid].scale(loss) + for mid, loss in loss_per_module.items() + ) + else: + total_loss = sum(loss_per_module.values()) + + # If we don't have any loss computations, `sum` returns 0. + if isinstance(total_loss, int): + assert total_loss == 0 + return {} + + total_loss.backward() + grads = {pid: p.grad for pid, p in self._params.items()} + + return grads + + @override(Learner) + def apply_gradients(self, gradients_dict: ParamDict) -> None: + # Set the gradient of the parameters. + for pid, grad in gradients_dict.items(): + # If updates should not be skipped turn `nan` and `inf` gradients to zero. + if ( + not self.config.torch_skip_nan_gradients + and not torch.isfinite(grad).all() + ): + # Warn the user about `nan` gradients. + logger.warning(f"Gradients {pid} contain `nan/inf` values.") + # If updates should be skipped, do not step the optimizer and return. + if not self.config.torch_skip_nan_gradients: + logger.warning( + "Setting `nan/inf` gradients to zero. If updates with " + "`nan/inf` gradients should not be set to zero and instead " + "the update be skipped entirely set `torch_skip_nan_gradients` " + "to `True`." + ) + # If necessary turn `nan` gradients to zero. Note this can corrupt the + # internal state of the optimizer, if many `nan` gradients occur. + self._params[pid].grad = torch.nan_to_num(grad) + # Otherwise, use the gradient as is. + else: + self._params[pid].grad = grad + + # For each optimizer call its step function. + for module_id, optimizer_names in self._module_optimizers.items(): + for optimizer_name in optimizer_names: + optim = self.get_optimizer(module_id, optimizer_name) + # If we have learning rate schedulers for a module add them, if + # necessary. + if self._lr_scheduler_classes is not None: + if ( + module_id not in self._lr_schedulers + or optimizer_name not in self._lr_schedulers[module_id] + ): + # Set for each module and optimizer a scheduler. + self._lr_schedulers[module_id] = {optimizer_name: []} + # If the classes are in a dictionary each module might have + # a different set of schedulers. + if isinstance(self._lr_scheduler_classes, dict): + scheduler_classes = self._lr_scheduler_classes[module_id] + # Else, each module has the same learning rate schedulers. + else: + scheduler_classes = self._lr_scheduler_classes + # Initialize and add the schedulers. + for scheduler_class in scheduler_classes: + self._lr_schedulers[module_id][optimizer_name].append( + scheduler_class(optim) + ) + + # Step through the scaler (unscales gradients, if applicable). + if self._grad_scalers is not None: + scaler = self._grad_scalers[module_id] + scaler.step(optim) + self.metrics.log_value( + (module_id, "_torch_grad_scaler_current_scale"), + scaler.get_scale(), + window=1, # snapshot in time, no EMA/mean. + ) + # Update the scaler. + scaler.update() + # `step` the optimizer (default), but only if all gradients are finite. + elif self.config.torch_skip_nan_gradients or all( + param.grad is None or torch.isfinite(param.grad).all() + for group in optim.param_groups + for param in group["params"] + ): + optim.step() + # If gradients are not all finite warn the user that the update will be + # skipped. + elif not all( + torch.isfinite(param.grad).all() + for group in optim.param_groups + for param in group["params"] + ): + logger.warning( + "Skipping this update. If updates with `nan/inf` gradients " + "should not be skipped entirely and instead `nan/inf` " + "gradients set to `zero` set `torch_skip_nan_gradients` to " + "`False`." + ) + + @OverrideToImplementCustomLogic_CallToSuperRecommended + @override(Learner) + def after_gradient_based_update(self, *, timesteps: Dict[str, Any]) -> None: + """Called after gradient-based updates are completed. + + Should be overridden to implement custom cleanup-, logging-, or non-gradient- + based Learner/RLModule update logic after(!) gradient-based updates have been + completed. + + Note, for `framework="torch"` users can register + `torch.optim.lr_scheduler.LRScheduler` via + `AlgorithmConfig._torch_lr_scheduler_classes`. These schedulers need to be + stepped here after gradient updates and reported. + + Args: + timesteps: Timesteps dict, which must have the key + `NUM_ENV_STEPS_SAMPLED_LIFETIME`. + # TODO (sven): Make this a more formal structure with its own type. + """ + + # If we have no `torch.optim.lr_scheduler.LRScheduler` registered call the + # `super()`'s method to update RLlib's learning rate schedules. + if not self._lr_schedulers: + return super().after_gradient_based_update(timesteps=timesteps) + + # Only update this optimizer's lr, if a scheduler has been registered + # along with it. + for module_id, optimizer_names in self._module_optimizers.items(): + for optimizer_name in optimizer_names: + # If learning rate schedulers are provided step them here. Note, + # stepping them in `TorchLearner.apply_gradients` updates the + # learning rates during minibatch updates; we want to update + # between whole batch updates. + if ( + module_id in self._lr_schedulers + and optimizer_name in self._lr_schedulers[module_id] + ): + for scheduler in self._lr_schedulers[module_id][optimizer_name]: + scheduler.step() + optimizer = self.get_optimizer(module_id, optimizer_name) + self.metrics.log_value( + # Cut out the module ID from the beginning since it's already + # part of the key sequence: (ModuleID, "[optim name]_lr"). + key=( + module_id, + f"{optimizer_name[len(module_id) + 1:]}_{LR_KEY}", + ), + value=self._get_optimizer_lr(optimizer), + window=1, + ) + + @override(Learner) + def _get_optimizer_state(self) -> StateDict: + ret = {} + for name, optim in self._named_optimizers.items(): + ret[name] = { + "module_id": self._optimizer_name_to_module[name], + "state": convert_to_numpy(optim.state_dict()), + } + return ret + + @override(Learner) + def _set_optimizer_state(self, state: StateDict) -> None: + for name, state_dict in state.items(): + # Ignore updating optimizers matching to submodules not present in this + # Learner's MultiRLModule. + module_id = state_dict["module_id"] + if name not in self._named_optimizers and module_id in self.module: + self.configure_optimizers_for_module( + module_id=module_id, + config=self.config.get_config_for_module(module_id=module_id), + ) + if name in self._named_optimizers: + self._named_optimizers[name].load_state_dict( + convert_to_torch_tensor(state_dict["state"], device=self._device) + ) + + @override(Learner) + def get_param_ref(self, param: Param) -> Hashable: + return param + + @override(Learner) + def get_parameters(self, module: RLModule) -> Sequence[Param]: + return list(module.parameters()) + + @override(Learner) + def _convert_batch_type( + self, + batch: MultiAgentBatch, + to_device: bool = True, + pin_memory: bool = False, + use_stream: bool = False, + ) -> MultiAgentBatch: + batch = convert_to_torch_tensor( + batch.policy_batches, + device=self._device if to_device else None, + pin_memory=pin_memory, + use_stream=use_stream, + ) + # TODO (sven): This computation of `env_steps` is not accurate! + length = max(len(b) for b in batch.values()) + batch = MultiAgentBatch(batch, env_steps=length) + return batch + + @override(Learner) + def add_module( + self, + *, + module_id: ModuleID, + # TODO (sven): Rename to `rl_module_spec`. + module_spec: RLModuleSpec, + config_overrides: Optional[Dict] = None, + new_should_module_be_updated: Optional[ShouldModuleBeUpdatedFn] = None, + ) -> MultiRLModuleSpec: + # Call super's add_module method. + marl_spec = super().add_module( + module_id=module_id, + module_spec=module_spec, + config_overrides=config_overrides, + new_should_module_be_updated=new_should_module_be_updated, + ) + + # we need to ddpify the module that was just added to the pool + module = self._module[module_id] + + if self._torch_compile_forward_train: + module.compile(self._torch_compile_cfg) + elif self._torch_compile_complete_update: + # When compiling the update, we need to reset and recompile + # _uncompiled_update every time we add/remove a module anew. + torch._dynamo.reset() + self._compiled_update_initialized = False + self._possibly_compiled_update = torch.compile( + self._uncompiled_update, + backend=self._torch_compile_cfg.torch_dynamo_backend, + mode=self._torch_compile_cfg.torch_dynamo_mode, + **self._torch_compile_cfg.kwargs, + ) + + if isinstance(module, TorchRLModule): + self._module[module_id].to(self._device) + if self.distributed: + if ( + self._torch_compile_complete_update + or self._torch_compile_forward_train + ): + raise ValueError( + "Using torch distributed and torch compile " + "together tested for now. Please disable " + "torch compile." + ) + self._module.add_module( + module_id, + TorchDDPRLModule(module, **self.config.torch_ddp_kwargs), + override=True, + ) + + self._log_trainable_parameters() + + return marl_spec + + @override(Learner) + def remove_module(self, module_id: ModuleID, **kwargs) -> MultiRLModuleSpec: + marl_spec = super().remove_module(module_id, **kwargs) + + if self._torch_compile_complete_update: + # When compiling the update, we need to reset and recompile + # _uncompiled_update every time we add/remove a module anew. + torch._dynamo.reset() + self._compiled_update_initialized = False + self._possibly_compiled_update = torch.compile( + self._uncompiled_update, + backend=self._torch_compile_cfg.torch_dynamo_backend, + mode=self._torch_compile_cfg.torch_dynamo_mode, + **self._torch_compile_cfg.kwargs, + ) + + self._log_trainable_parameters() + + return marl_spec + + @override(Learner) + def build(self) -> None: + """Builds the TorchLearner. + + This method is specific to TorchLearner. Before running super() it will + initialize the device properly based on `self.config`, so that `_make_module()` + can place the created module on the correct device. After running super() it + wraps the module in a TorchDDPRLModule if `config.num_learners > 0`. + Note, in inherited classes it is advisable to call the parent's `build()` + after setting up all variables because `configure_optimizer_for_module` is + called in this `Learner.build()`. + """ + self._device = get_device(self.config, self.config.num_gpus_per_learner) + + super().build() + + if self._torch_compile_complete_update: + torch._dynamo.reset() + self._compiled_update_initialized = False + self._possibly_compiled_update = torch.compile( + self._uncompiled_update, + backend=self._torch_compile_cfg.torch_dynamo_backend, + mode=self._torch_compile_cfg.torch_dynamo_mode, + **self._torch_compile_cfg.kwargs, + ) + else: + if self._torch_compile_forward_train: + if isinstance(self._module, TorchRLModule): + self._module.compile(self._torch_compile_cfg) + elif isinstance(self._module, MultiRLModule): + for module in self._module._rl_modules.values(): + # Compile only TorchRLModules, e.g. we don't want to compile + # a RandomRLModule. + if isinstance(self._module, TorchRLModule): + module.compile(self._torch_compile_cfg) + else: + raise ValueError( + "Torch compile is only supported for TorchRLModule and " + "MultiRLModule." + ) + + self._possibly_compiled_update = self._uncompiled_update + + self._make_modules_ddp_if_necessary() + + @override(Learner) + def _update(self, batch: Dict[str, Any]) -> Tuple[Any, Any, Any]: + # The first time we call _update after building the learner or + # adding/removing models, we update with the uncompiled update method. + # This makes it so that any variables that may be created during the first + # update step are already there when compiling. More specifically, + # this avoids errors that occur around using defaultdicts with + # torch.compile(). + if ( + self._torch_compile_complete_update + and not self._compiled_update_initialized + ): + self._compiled_update_initialized = True + return self._uncompiled_update(batch) + else: + return self._possibly_compiled_update(batch) + + @OverrideToImplementCustomLogic + def _make_modules_ddp_if_necessary(self) -> None: + """Default logic for (maybe) making all Modules within self._module DDP.""" + + # If the module is a MultiRLModule and nn.Module we can simply assume + # all the submodules are registered. Otherwise, we need to loop through + # each submodule and move it to the correct device. + # TODO (Kourosh): This can result in missing modules if the user does not + # register them in the MultiRLModule. We should find a better way to + # handle this. + if self.config.num_learners > 1: + # Single agent module: Convert to `TorchDDPRLModule`. + if isinstance(self._module, TorchRLModule): + self._module = TorchDDPRLModule( + self._module, **self.config.torch_ddp_kwargs + ) + # Multi agent module: Convert each submodule to `TorchDDPRLModule`. + else: + assert isinstance(self._module, MultiRLModule) + for key in self._module.keys(): + sub_module = self._module[key] + if isinstance(sub_module, TorchRLModule): + # Wrap and override the module ID key in self._module. + self._module.add_module( + key, + TorchDDPRLModule( + sub_module, **self.config.torch_ddp_kwargs + ), + override=True, + ) + + def rl_module_is_compatible(self, module: RLModule) -> bool: + return isinstance(module, nn.Module) + + @override(Learner) + def _check_registered_optimizer( + self, + optimizer: Optimizer, + params: Sequence[Param], + ) -> None: + super()._check_registered_optimizer(optimizer, params) + if not isinstance(optimizer, torch.optim.Optimizer): + raise ValueError( + f"The optimizer ({optimizer}) is not a torch.optim.Optimizer! " + "Only use torch.optim.Optimizer subclasses for TorchLearner." + ) + for param in params: + if not isinstance(param, torch.Tensor): + raise ValueError( + f"One of the parameters ({param}) in the registered optimizer " + "is not a torch.Tensor!" + ) + + @override(Learner) + def _make_module(self) -> MultiRLModule: + module = super()._make_module() + self._map_module_to_device(module) + return module + + def _map_module_to_device(self, module: MultiRLModule) -> None: + """Moves the module to the correct device.""" + if isinstance(module, torch.nn.Module): + module.to(self._device) + else: + for key in module.keys(): + if isinstance(module[key], torch.nn.Module): + module[key].to(self._device) + + @override(Learner) + def _log_trainable_parameters(self) -> None: + # Log number of non-trainable and trainable parameters of our RLModule. + num_trainable_params = defaultdict(int) + num_non_trainable_params = defaultdict(int) + for mid, rlm in self.module._rl_modules.items(): + if isinstance(rlm, TorchRLModule): + for p in rlm.parameters(): + n = p.numel() + if p.requires_grad: + num_trainable_params[(mid, NUM_TRAINABLE_PARAMETERS)] += n + else: + num_non_trainable_params[ + (mid, NUM_NON_TRAINABLE_PARAMETERS) + ] += n + + self.metrics.log_dict( + { + **{ + (ALL_MODULES, NUM_TRAINABLE_PARAMETERS): sum( + num_trainable_params.values() + ), + (ALL_MODULES, NUM_NON_TRAINABLE_PARAMETERS): sum( + num_non_trainable_params.values() + ), + }, + **num_trainable_params, + **num_non_trainable_params, + } + ) + + def _compute_off_policyness(self, batch): + # Log off-policy'ness of this batch wrt the current weights. + off_policyness = { + (mid, DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY): ( + (self._weights_seq_no - module_batch[WEIGHTS_SEQ_NO]).float() + ) + for mid, module_batch in batch.items() + if WEIGHTS_SEQ_NO in module_batch + } + for key in off_policyness.keys(): + mid = key[0] + if Columns.LOSS_MASK not in batch[mid]: + off_policyness[key] = torch.mean(off_policyness[key]) + else: + mask = batch[mid][Columns.LOSS_MASK] + num_valid = torch.sum(mask) + off_policyness[key] = torch.sum(off_policyness[key][mask]) / num_valid + self.metrics.log_dict(off_policyness, window=1) + + @override(Learner) + def _get_tensor_variable( + self, value, dtype=None, trainable=False + ) -> "torch.Tensor": + tensor = torch.tensor( + value, + requires_grad=trainable, + device=self._device, + dtype=( + dtype + or ( + torch.float32 + if isinstance(value, float) + else torch.int32 + if isinstance(value, int) + else None + ) + ), + ) + return nn.Parameter(tensor) if trainable else tensor + + @staticmethod + @override(Learner) + def _get_optimizer_lr(optimizer: "torch.optim.Optimizer") -> float: + for g in optimizer.param_groups: + return g["lr"] + + @staticmethod + @override(Learner) + def _set_optimizer_lr(optimizer: "torch.optim.Optimizer", lr: float) -> None: + for g in optimizer.param_groups: + g["lr"] = lr + + @staticmethod + @override(Learner) + def _get_clip_function() -> Callable: + from ray.rllib.utils.torch_utils import clip_gradients + + return clip_gradients + + @staticmethod + @override(Learner) + def _get_global_norm_function() -> Callable: + from ray.rllib.utils.torch_utils import compute_global_norm + + return compute_global_norm diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/torch/torch_meta_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/torch/torch_meta_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..284a37ee98dce1cb21700baaf625c9e14b607a58 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/torch/torch_meta_learner.py @@ -0,0 +1,455 @@ +import contextlib +import logging +import ray + +from itertools import cycle +from typing import Any, Dict, List, Optional, Tuple + +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig +from ray.rllib.core import ALL_MODULES +from ray.rllib.core.learner.learner import Learner +from ray.rllib.core.learner.torch.torch_differentiable_learner import ( + TorchDifferentiableLearner, +) +from ray.rllib.core.learner.torch.torch_learner import TorchLearner +from ray.rllib.core.learner.training_data import TrainingData +from ray.rllib.core.rl_module.apis import SelfSupervisedLossAPI +from ray.rllib.policy.sample_batch import MultiAgentBatch +from ray.rllib.utils.annotations import ( + override, + OverrideToImplementCustomLogic, + OverrideToImplementCustomLogic_CallToSuperRecommended, +) +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.metrics import ( + DATASET_NUM_ITERS_TRAINED, + DATASET_NUM_ITERS_TRAINED_LIFETIME, + DIFFERENTIABLE_LEARNER_RESULTS, +) +from ray.rllib.utils.metrics.utils import to_snake_case +from ray.rllib.utils.typing import ( + EpisodeType, + ModuleID, + NamedParamDict, + ResultDict, + TensorType, +) + +logger = logging.getLogger("__name__") + +torch, nn = try_import_torch() + + +class TorchMetaLearner(TorchLearner): + """A `TorchLearner` designed for meta-learning with functional updates. + + This `TorchLearner` manages one or more `DifferentiableLearner` instances, + which perform functional updates on the `MultiRLModule`. These updates enable + the computation of higher-order gradients, making this class suitable for + meta-learning applications. + + The `update` method executes one or more update loops on its + `DifferentiableLearner` instances, leveraging the functionally updated + parameters for its own learning process. + """ + + # A list of `TorchDifferentiableLearner`s that run inner functional update + # loops. + others: List[TorchDifferentiableLearner] + + def __init__( + self, + **kwargs, + ): + # First, initialize the `TorchLearner`. + super().__init__(**kwargs) + + # Initialize all configured `TorchDifferentiableLearner`s. + self.others = [ + other_config.learner_class( + config=self.config, + learner_config=other_config, + module=self.module, + ) + for other_config in self.config.differentiable_learner_configs + ] + + @OverrideToImplementCustomLogic_CallToSuperRecommended + @override(TorchLearner) + def build(self) -> None: + """Builds the `TorchMetaLearner`. + + This method should be called before the meta-learner is used. It is + responsible for setting up the `TorchDifferentiableLearner`s. + """ + super().build() + + # Build all `DifferentiableLearner`s. + for other in self.others: + other.build(device=self._device) + + # Ensure 'others' have a module reference. + for other in self.others: + if not other.module: + other.module = self.module + + @OverrideToImplementCustomLogic + @override(Learner) + def update( + self, + batch: Optional[MultiAgentBatch] = None, + batches: Optional[List[MultiAgentBatch]] = None, + batch_refs: Optional[List[ray.ObjectRef]] = None, + episodes: Optional[List[EpisodeType]] = None, + episodes_refs: Optional[List[ray.ObjectRef]] = None, + data_iterators: Optional[List[ray.data.DataIterator]] = None, + training_data: Optional[TrainingData] = None, + *, + # TODO (simon): Maybe defined here other_training_data to provide + # TrainingData for differentiable Learners. List to nest them. + # other_training_data: List[Union[List[Any], TrainingData]] + # TODO (sven): Make this a more formal structure with its own type. + timesteps: Optional[Dict[str, Any]] = None, + num_total_minibatches: int = 0, + num_epochs: int = 1, + minibatch_size: Optional[int] = None, + shuffle_batch_per_epoch: bool = False, + _no_metrics_reduce: bool = False, + others_training_data: Optional[List[TrainingData]] = None, + **kwargs, + ) -> ResultDict: + """Performs a meta-update on the `MultiRLModule`. + + This method allows multiple backward passes on a batch by iteratively + applying functional updates from the `TorchDifferentiableLearner` instances + in `others`. The resulting differentiable parameters are then used in this + learner's own functional forward pass on the `MultiRLModule`, enabling the + computation of higher-order gradients during the backward pass. + """ + self._check_is_built() + + # Call `before_gradient_based_update` to allow for non-gradient based + # preparations-, logging-, and update logic to happen. + self.before_gradient_based_update(timesteps=timesteps or {}) + + if training_data is None: + training_data = TrainingData( + batch=batch, + batches=batches, + batch_refs=batch_refs, + episodes=episodes, + episodes_refs=episodes_refs, + data_iterators=data_iterators, + ) + # Validate training data. + # TODO (simon): Pass in a `TrainingData` list for all differentiable learners. + # to be used if necessary. Some algorithms need it. + training_data.validate() + training_data.solve_refs() + assert training_data.batches is None, "`training_data.batches` must be None!" + + # Increase the _weigths_seq_no in each `update` run. + self._weights_seq_no += 1 + + # Create a batch iterator. + # TODO (simon): Create this method in the `Learner`. + batch_iter = self._create_iterator_if_necessary( + training_data=training_data, + num_total_minibatches=num_total_minibatches, + num_epochs=num_epochs, + minibatch_size=minibatch_size, + shuffle_batch_per_epoch=shuffle_batch_per_epoch, + **kwargs, + ) + + # If no training data for `DifferentiableLearner`s have been passed in, cycle + # over the main training_data for each `DifferentiableLearner`. + if not others_training_data: + others_training_data = cycle([training_data]) + + self.metrics.activate_tensor_mode() + + # Perform the actual looping through the minibatches or the given data iterator. + for iteration, tensor_minibatch in enumerate(batch_iter): + # Check the MultiAgentBatch, whether our RLModule contains all ModuleIDs + # found in this batch. If not, throw an error. + unknown_module_ids = set(tensor_minibatch.policy_batches.keys()) - set( + self.module.keys() + ) + if unknown_module_ids: + raise ValueError( + f"Batch contains one or more ModuleIDs ({unknown_module_ids}) that " + f"are not in this Learner!" + ) + + # Clone the parameters for the differentiable updates. + params = self._clone_named_parameters() + + # Update all differentiable learners. + others_loss_per_module = [] + others_results = {} + for other, other_training_data in zip(self.others, others_training_data): + # TODO (simon): Maybe return all losses from each other's update step. + params, other_loss_per_module, other_results = other.update( + training_data=other_training_data, + params=params, + # TODO (simon): Check, if this is still needed. + _no_metrics_reduce=_no_metrics_reduce, + **kwargs, + ) + others_loss_per_module.append(other_loss_per_module) + # TODO (simon): Find a more elegant way for naming. + others_results[to_snake_case(other.__class__.__name__)] = other_results + + # Log training results from the `DifferentiableLearner`s. + # TODO (simon): Right now metrics are not carried over b/c of + # the double tensormode problem. + self.metrics.aggregate( + stats_dicts=[others_results], key=DIFFERENTIABLE_LEARNER_RESULTS + ) + + # Make the actual in-graph/traced meta-`_update` call. This should return + # all tensor values (no numpy). + fwd_out, loss_per_module, _ = self._update( + tensor_minibatch.policy_batches, + params, + others_loss_per_module, + ) + + # TODO (sven): Maybe move this into loop above to get metrics more accuratcely + # cover the minibatch/epoch logic. + # Log all timesteps (env, agent, modules) based on given episodes/batch. + self._log_steps_trained_metrics(tensor_minibatch) + + self._set_slicing_by_batch_id(tensor_minibatch, value=False) + + if self.iterator: + # Record the number of batches pulled from the dataset. + self.metrics.log_value( + (ALL_MODULES, DATASET_NUM_ITERS_TRAINED), + iteration + 1, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (ALL_MODULES, DATASET_NUM_ITERS_TRAINED_LIFETIME), + iteration + 1, + reduce="sum", + ) + # Log all individual RLModules' loss terms and its registered optimizers' + # current learning rates. + # Note: We do this only once for the last of the minibatch updates, b/c the + # window is only 1 anyways. + for mid, loss in loss_per_module.items(): + self.metrics.log_value( + key=(mid, self.TOTAL_LOSS_KEY), + value=loss, + window=1, + ) + + # Call `after_gradient_based_update` to allow for non-gradient based + # cleanups-, logging-, and update logic to happen. + # TODO (simon): Check, if this should stay here, when running multiple + # gradient steps inside the iterator loop above (could be a complete epoch) + # the target networks might need to be updated earlier. + self.after_gradient_based_update(timesteps=timesteps or {}) + + self.metrics.deactivate_tensor_mode() + + # Reduce results across all minibatch update steps. + if not _no_metrics_reduce: + return self.metrics.reduce() + + def _clone_named_parameters(self): + """Clone named parameters for functional updates.""" + return self.module.foreach_module( + lambda _, m: {name: p.clone() for name, p in m.named_parameters()}, + return_dict=True, + ) + + @OverrideToImplementCustomLogic + @override(TorchLearner) + def _update( + self, + batch: Dict[str, Any], + params: NamedParamDict, + others_loss_per_module: List[Dict[ModuleID, TensorType]] = None, + ) -> Tuple[Any, Any, Any]: + # The first time we call _update after building the learner or + # adding/removing models, we update with the uncompiled update method. + # This makes it so that any variables that may be created during the first + # update step are already there when compiling. More specifically, + # this avoids errors that occur around using defaultdicts with + # torch.compile(). + if ( + self._torch_compile_complete_update + and not self._compiled_update_initialized + ): + self._compiled_update_initialized = True + return self._uncompiled_update(batch, params, others_loss_per_module) + else: + return self._possibly_compiled_update(batch, params, others_loss_per_module) + + def _uncompiled_update( + self, + batch: Dict, + params: NamedParamDict, + others_loss_per_module: List[Dict[ModuleID, TensorType]] = None, + **kwargs, + ): + """Performs a single functional update using a batch of data. + + This update utilizes a functional forward pass via PyTorch 2.0's `func` module. + The updated parameters provided by `TorchDifferentiableLearner` instances are + functions of the `MultiRLModule`'s parameters, allowing for differentiation. + + To ensure compatibility, the `MultiRLModule`'s `forward` method must encapsulate + all logic from `forward_train` and support additional keyword arguments (`kwargs`). + """ + # TODO (sven): Causes weird cuda error when WandB is used. + # Diagnosis thus far: + # - All peek values during metrics.reduce are non-tensors. + # - However, in impala.py::training_step(), a tensor does arrive after learner + # group.update(), so somehow, there is still a race condition + # possible (learner, which performs the reduce() and learner thread, which + # performs the logging of tensors into metrics logger). + self._compute_off_policyness(batch) + + # TODO (simon): For this to work, the `RLModule.forward` must run the + # the `forward_train`. Passing in arguments which makes the `forward` modular + # could be a workaround. + # Make a functional forward call to include higher-order gradients in the meta + # update. + fwd_out = self._make_functional_call(params, batch) + loss_per_module = self.compute_losses( + fwd_out=fwd_out, batch=batch, others_loss_per_module=others_loss_per_module + ) + gradients = self.compute_gradients(loss_per_module) + + with contextlib.ExitStack() as stack: + if self.config.num_learners > 1: + for mod in self.module.values(): + # Skip non-torch modules, b/c they may not have the `no_sync` API. + if isinstance(mod, torch.nn.Module): + stack.enter_context(mod.no_sync()) + postprocessed_gradients = self.postprocess_gradients(gradients) + self.apply_gradients(postprocessed_gradients) + + # Deactivate tensor-mode on our MetricsLogger and collect the (tensor) + # results. + return fwd_out, loss_per_module, {} + + @override(Learner) + def compute_losses( + self, + *, + fwd_out: Dict[str, Any], + batch: Dict[str, Any], + others_loss_per_module: List[Dict[ModuleID, TensorType]] = None, + **kwargs, + ) -> Dict[ModuleID, TensorType]: + """Computes the loss(es) for the module being optimized. + + This method must be overridden by MultiRLModule-specific Learners in order to + define the specific loss computation logic. If the algorithm is single-agent, + only `compute_loss_for_module()` should be overridden instead. If the algorithm + uses independent multi-agent learning (default behavior for RLlib's multi-agent + setups), also only `compute_loss_for_module()` should be overridden, but it will + be called for each individual RLModule inside the MultiRLModule. + For the functional update to work, no `forward` call should be made + within this method, especially not a non-functional one. Instead, use + the model outputs provided by `fwd_out`. + + Losses from `DifferentiableLearner` instances in `others_loss_per_module` + can be leveraged for more advanced module-wise loss calculations. + + Args: + fwd_out: Output from a call to the `forward_train()` method of the + underlying MultiRLModule (`self.module`) during training + (`self.update()`). + batch: The train batch that was used to compute `fwd_out`. + others_loss_per_module: A list of losses per module id from the contained + `DifferentiableLearner` instances in`self.others`. + + Returns: + A dictionary mapping module IDs to individual loss terms. + """ + loss_per_module = {} + for module_id in fwd_out: + module_batch = batch[module_id] + module_fwd_out = fwd_out[module_id] + + module = self.module[module_id].unwrapped() + if isinstance(module, SelfSupervisedLossAPI): + loss = module.compute_self_supervised_loss( + learner=self, + module_id=module_id, + config=self.config.get_config_for_module(module_id), + batch=module_batch, + fwd_out=module_fwd_out, + others_loss_per_module=others_loss_per_module, + ) + else: + loss = self.compute_loss_for_module( + module_id=module_id, + config=self.config.get_config_for_module(module_id), + batch=module_batch, + fwd_out=module_fwd_out, + others_loss_per_module=others_loss_per_module, + ) + loss_per_module[module_id] = loss + + return loss_per_module + + @OverrideToImplementCustomLogic + @override(Learner) + def compute_loss_for_module( + self, + *, + module_id: ModuleID, + config: "AlgorithmConfig", + batch: Dict[str, Any], + fwd_out: Dict[str, TensorType], + others_loss_per_module: List[Dict[ModuleID, TensorType]] = None, + ) -> TensorType: + """Computes the loss for a single module. + + This method calculates the loss for an individual agent. In multi-agent + scenarios requiring more complex loss computations, consider overriding the + `compute_losses` method instead. + + Losses from `DifferentiableLearner` instances in `others_loss_per_module` + can be leveraged for more advanced module-wise loss calculations. + + Args: + module_id: The id of the module. + config: The AlgorithmConfig specific to the given `module_id`. + batch: The train batch for this particular module. + fwd_out: The output of the forward pass for this particular module. + others_loss_per_module: A list of losses per module id from the contained + `DifferentiableLearner` instances in`self.others`. + + Returns: + A single total loss tensor. If you have more than one optimizer on the + provided `module_id` and would like to compute gradients separately using + these different optimizers, simply add up the individual loss terms for + each optimizer and return the sum. Also, for recording/logging any + individual loss terms, you can use the `Learner.metrics.log_value( + key=..., value=...)` or `Learner.metrics.log_dict()` APIs. See: + :py:class:`~ray.rllib.utils.metrics.metrics_logger.MetricsLogger` for more + information. + """ + # By default, `others_loss_per_module` is not used; instead, the superclass + # method is called. + return super().compute_loss_for_module( + module_id=module_id, config=config, batch=batch, fwd_out=fwd_out + ) + + def _make_functional_call( + self, params: Dict[ModuleID, NamedParamDict], batch: MultiAgentBatch + ) -> Dict[ModuleID, NamedParamDict]: + """Make a functional forward call to all modules in the `MultiRLModule`.""" + return self._module.foreach_module( + lambda mid, m: torch.func.functional_call(m, params[mid], batch[mid]), + return_dict=True, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/training_data.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/training_data.py new file mode 100644 index 0000000000000000000000000000000000000000..5561d075d73ec757831d51d44f6d68b9357e7520 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/training_data.py @@ -0,0 +1,157 @@ +from collections import defaultdict +import dataclasses +from typing import List, Optional + +import tree # pip install dm_tree + +import ray +from ray.rllib.env.multi_agent_episode import MultiAgentEpisode +from ray.rllib.policy.sample_batch import MultiAgentBatch +from ray.rllib.utils.minibatch_utils import ( + ShardBatchIterator, + ShardEpisodesIterator, + ShardObjectRefIterator, +) +from ray.rllib.utils.typing import EpisodeType + + +# TODO (sven): Switch to dataclass(slots=True) once on py >= 3.10. +@dataclasses.dataclass +class TrainingData: + batch: Optional[MultiAgentBatch] = None + batches: Optional[List[MultiAgentBatch]] = None + batch_refs: Optional[List[ray.ObjectRef]] = None + + episodes: Optional[List[EpisodeType]] = None + episodes_refs: Optional[List[ray.ObjectRef]] = None + + data_iterators: Optional[List[ray.data.iterator.DataIterator]] = None + + def validate(self): + # Exactly one training data type must be provided. + if ( + sum( + td is not None + for td in [ + self.batch, + self.batches, + self.batch_refs, + self.episodes, + self.episodes_refs, + self.data_iterators, + ] + ) + != 1 + ): + raise ValueError("Exactly one training data type must be provided!") + + def shard( + self, + num_shards: int, + len_lookback_buffer: Optional[int] = None, + **kwargs, + ): + # Single batch -> Split into n smaller batches. + if self.batch is not None: + return [ + (TrainingData(batch=b), {}) + for b in ShardBatchIterator(self.batch, num_shards=num_shards) + ] + + # TODO (sven): Do we need a more sohpisticated shard mechanism for this case? + elif self.batches is not None: + assert num_shards == len(self.batches) + return [(TrainingData(batch=b), {}) for b in self.batches] + + # List of batch refs. + elif self.batch_refs is not None: + return [ + (TrainingData(batch_refs=b), {}) + for b in ShardObjectRefIterator(self.batch_refs, num_shards=num_shards) + ] + + # List of episodes -> Split into n equally sized shards (based on the lengths + # of the episodes). + elif self.episodes is not None: + num_total_minibatches = 0 + if "minibatch_size" in kwargs and num_shards > 1: + num_total_minibatches = self._compute_num_total_minibatches( + self.episodes, + num_shards, + kwargs["minibatch_size"], + kwargs.get("num_epochs", 1), + ) + return [ + ( + TrainingData(episodes=e), + {"num_total_minibatches": num_total_minibatches}, + ) + for e in ShardEpisodesIterator( + self.episodes, + num_shards=num_shards, + len_lookback_buffer=len_lookback_buffer, + ) + ] + # List of episodes refs. + elif self.episodes_refs is not None: + return [ + (TrainingData(episodes_refs=e), {}) + for e in ShardObjectRefIterator(self.episodes_refs, num_shards) + ] + # List of data iterators. + else: + assert self.data_iterators and len(self.data_iterators) == num_shards + return [ + (TrainingData(data_iterators=[di]), {}) for di in self.data_iterators + ] + + def solve_refs(self): + # Batch references. + if self.batch_refs is not None: + # Solve the ray.ObjRefs. + batches = tree.flatten(ray.get(self.batch_refs)) + # If only a single batch, set `self.batch`. + if len(batches) == 1: + self.batch = batches[0] + # Otherwise, set `self.batches`. + else: + self.batches = batches + # Empty `self.batch_refs`. + self.batch_refs = None + + # Episode references. + elif self.episodes_refs is not None: + # It's possible that individual refs are invalid due to the EnvRunner + # that produced the ref has crashed or had its entire node go down. + # In this case, try each ref individually and collect only valid results. + try: + episodes = tree.flatten(ray.get(self.episodes_refs)) + except ray.exceptions.OwnerDiedError: + episode_refs = self.episodes_refs + episodes = [] + for ref in episode_refs: + try: + episodes.extend(ray.get(ref)) + except ray.exceptions.OwnerDiedError: + pass + self.episodes = episodes + self.episodes_refs = None + + @staticmethod + def _compute_num_total_minibatches( + episodes, + num_shards, + minibatch_size, + num_epochs, + ): + # Count total number of timesteps per module ID. + if isinstance(episodes[0], MultiAgentEpisode): + per_mod_ts = defaultdict(int) + for ma_episode in episodes: + for sa_episode in ma_episode.agent_episodes.values(): + per_mod_ts[sa_episode.module_id] += len(sa_episode) + max_ts = max(per_mod_ts.values()) + else: + max_ts = sum(map(len, episodes)) + + return int((num_epochs * max_ts) / (num_shards * minibatch_size)) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7682725cf9a222617968b1b3e578fd36cc2f2595 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/learner/utils.py @@ -0,0 +1,59 @@ +import copy + +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.typing import NetworkType +from ray.util import PublicAPI + + +torch, _ = try_import_torch() + + +def make_target_network(main_net: NetworkType) -> NetworkType: + """Creates a (deep) copy of `main_net` (including synched weights) and returns it. + + Args: + main_net: The main network to return a target network for + + Returns: + The copy of `main_net` that can be used as a target net. Note that the weights + of the returned net are already synched (identical) with `main_net`. + """ + # Deepcopy the main net (this should already take care of synching all weights). + target_net = copy.deepcopy(main_net) + # Make the target net not trainable. + if isinstance(main_net, torch.nn.Module): + target_net.requires_grad_(False) + else: + raise ValueError(f"Unsupported framework for given `main_net` {main_net}!") + + return target_net + + +@PublicAPI(stability="beta") +def update_target_network( + *, + main_net: NetworkType, + target_net: NetworkType, + tau: float, +) -> None: + """Updates a target network (from a "main" network) using Polyak averaging. + + Thereby: + new_target_net_weight = ( + tau * main_net_weight + (1.0 - tau) * current_target_net_weight + ) + + Args: + main_net: The nn.Module to update from. + target_net: The target network to update. + tau: The tau value to use in the Polyak averaging formula. Use 1.0 for a + complete sync of the weights (target and main net will be the exact same + after updating). + """ + if isinstance(main_net, torch.nn.Module): + from ray.rllib.utils.torch_utils import update_target_network as _update_target + + else: + raise ValueError(f"Unsupported framework for given `main_net` {main_net}!") + + _update_target(main_net=main_net, target_net=target_net, tau=tau) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df5d0b8f4917960803c627f2ba621b50db7d1423 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/__pycache__/base.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27bc6d603ae037f9e4e0fd89a834d739b9944adf Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/__pycache__/base.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/__pycache__/catalog.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/__pycache__/catalog.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..905a392807eb8c88c81f63ab1c83bd336f9a22de Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/__pycache__/catalog.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/__pycache__/configs.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/__pycache__/configs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f6a3e179974ae4fb5d9ee59eff64bafcba4f513 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/__pycache__/configs.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/base.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/base.py new file mode 100644 index 0000000000000000000000000000000000000000..d3ad4dd18963ad0eb0047c825ab38c8f2290d583 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/base.py @@ -0,0 +1,445 @@ +import abc +from typing import List, Optional, Tuple, Union + + +from ray.rllib.core.columns import Columns +from ray.rllib.core.models.configs import ModelConfig +from ray.rllib.core.models.specs.specs_base import Spec +from ray.rllib.policy.rnn_sequencing import get_fold_unfold_fns +from ray.rllib.utils.annotations import ExperimentalAPI, override +from ray.rllib.utils.typing import TensorType +from ray.util.annotations import DeveloperAPI + +# Top level keys that unify model i/o. +ENCODER_OUT: str = "encoder_out" +# For Actor-Critic algorithms, these signify data related to the actor and critic +ACTOR: str = "actor" +CRITIC: str = "critic" + + +@ExperimentalAPI +class Model(abc.ABC): + """Framework-agnostic base class for RLlib models. + + Models are low-level neural network components that offer input- and + output-specification, a forward method, and a get_initial_state method. Models + are composed in RLModules. + + Usage Example together with ModelConfig: + + .. testcode:: + + from ray.rllib.core.models.base import Model + from ray.rllib.core.models.configs import ModelConfig + from ray.rllib.core.models.configs import ModelConfig + from dataclasses import dataclass + + class MyModel(Model): + def __init__(self, config): + super().__init__(config) + self.my_param = config.my_param * 2 + + def _forward(self, input_dict): + return input_dict["obs"] * self.my_param + + + @dataclass + class MyModelConfig(ModelConfig): + my_param: int = 42 + + def build(self, framework: str): + if framework == "bork": + return MyModel(self) + + + config = MyModelConfig(my_param=3) + model = config.build(framework="bork") + print(model._forward({"obs": 1})) + + .. testoutput:: + + 6 + + """ + + def __init__(self, config: ModelConfig): + self.config = config + + def __init_subclass__(cls, **kwargs): + # Automatically add a __post_init__ method to all subclasses of Model. + # This method is called after the __init__ method of the subclass. + def init_decorator(previous_init): + def new_init(self, *args, **kwargs): + previous_init(self, *args, **kwargs) + if type(self) is cls: + self.__post_init__() + + return new_init + + cls.__init__ = init_decorator(cls.__init__) + + def __post_init__(self): + """Called automatically after the __init__ method of the subclasses. + + The module first calls the __init__ method of the subclass, With in the + __init__ you should call the super().__init__ method. Then after the __init__ + method of the subclass is called, the __post_init__ method is called. + + This is a good place to do any initialization that requires access to the + subclass's attributes. + """ + self._input_specs = self.get_input_specs() + self._output_specs = self.get_output_specs() + + def get_input_specs(self) -> Optional[Spec]: + """Returns the input specs of this model. + + Override `get_input_specs` to define your own input specs. + This method should not be called often, e.g. every forward pass. + Instead, it should be called once at instantiation to define Model.input_specs. + + Returns: + Spec: The input specs. + """ + return None + + def get_output_specs(self) -> Optional[Spec]: + """Returns the output specs of this model. + + Override `get_output_specs` to define your own output specs. + This method should not be called often, e.g. every forward pass. + Instead, it should be called once at instantiation to define Model.output_specs. + + Returns: + Spec: The output specs. + """ + return None + + @property + def input_specs(self) -> Spec: + """Returns the input spec of this model.""" + return self._input_specs + + @input_specs.setter + def input_specs(self, spec: Spec) -> None: + raise ValueError( + "`input_specs` cannot be set directly. Override " + "Model.get_input_specs() instead. Set Model._input_specs if " + "you want to override this behavior." + ) + + @property + def output_specs(self) -> Spec: + """Returns the output specs of this model.""" + return self._output_specs + + @output_specs.setter + def output_specs(self, spec: Spec) -> None: + raise ValueError( + "`output_specs` cannot be set directly. Override " + "Model.get_output_specs() instead. Set Model._output_specs if " + "you want to override this behavior." + ) + + def get_initial_state(self) -> Union[dict, List[TensorType]]: + """Returns the initial state of the Model. + + It can be left empty if this Model is not stateful. + """ + return dict() + + @abc.abstractmethod + def _forward(self, input_dict: dict, **kwargs) -> dict: + """Returns the output of this model for the given input. + + This method is called by the forwarding method of the respective framework + that is itself wrapped by RLlib in order to check model inputs and outputs. + + Args: + input_dict: The input tensors. + **kwargs: Forward compatibility kwargs. + + Returns: + dict: The output tensors. + """ + + @abc.abstractmethod + def get_num_parameters(self) -> Tuple[int, int]: + """Returns a tuple of (num trainable params, num non-trainable params).""" + + @abc.abstractmethod + def _set_to_dummy_weights(self, value_sequence=(-0.02, -0.01, 0.01, 0.02)) -> None: + """Helper method to set all weights to deterministic dummy values. + + Calling this method on two `Models` that have the same architecture using + the exact same `value_sequence` arg should make both models output the exact + same values on arbitrary inputs. This will work, even if the two `Models` + are of different DL frameworks. + + Args: + value_sequence: Looping through the list of all parameters (weight matrices, + bias tensors, etc..) of this model, in each iteration i, we set all + values in this parameter to `value_sequence[i % len(value_sequence)]` + (round robin). + + Example: + TODO: + """ + + +@ExperimentalAPI +class Encoder(Model, abc.ABC): + """The framework-agnostic base class for all RLlib encoders. + + Encoders are used to transform observations to a latent space. + Therefore, their `input_specs` contains the observation space dimensions. + Similarly, their `output_specs` contains the latent space dimensions. + Encoders can be recurrent, in which case the state should be part of input- and + output_specs. The latent vectors produced by an encoder are fed into subsequent + "heads". Any implementation of Encoder should also be callable. This should be done + by also inheriting from a framework-specific model base-class, s.a. TorchModel or + TfModel. + + Abstract illustration of typical flow of tensors: + + Inputs + | + Encoder + | \ + Head1 Head2 + | / + Outputs + + Outputs of encoders are generally of shape (B, latent_dim) or (B, T, latent_dim). + That is, for time-series data, we encode into the latent space for each time step. + This should be reflected in the `output_specs`. + + Usage example together with a ModelConfig: + + .. testcode:: + + from dataclasses import dataclass + import numpy as np + + from ray.rllib.core.columns import Columns + from ray.rllib.core.models.base import Encoder, ENCODER_OUT + from ray.rllib.core.models.configs import ModelConfig + from ray.rllib.policy.sample_batch import SampleBatch + + class NumpyEncoder(Encoder): + def __init__(self, config): + super().__init__(config) + self.factor = config.factor + + def __call__(self, *args, **kwargs): + # This is a dummy method to do checked forward passes. + return self._forward(*args, **kwargs) + + def _forward(self, input_dict, **kwargs): + obs = input_dict[Columns.OBS] + return { + ENCODER_OUT: np.array(obs) * self.factor, + Columns.STATE_OUT: ( + np.array(input_dict[Columns.STATE_IN]) + * self.factor + ), + } + + @dataclass + class NumpyEncoderConfig(ModelConfig): + factor: int = None + + def build(self, framework: str): + return NumpyEncoder(self) + + config = NumpyEncoderConfig(factor=2) + encoder = NumpyEncoder(config) + print(encoder({Columns.OBS: 1, Columns.STATE_IN: 2})) + + .. testoutput:: + + {'encoder_out': 2, 'state_out': 4} + + """ + + @abc.abstractmethod + def _forward(self, input_dict: dict, **kwargs) -> dict: + """Returns the latent of the encoder for the given inputs. + + This method is called by the forwarding method of the respective framework + that is itself wrapped by RLlib in order to check model inputs and outputs. + + The input dict contains at minimum the observation and the state of the encoder + (None for stateless encoders). + The output dict contains at minimum the latent and the state of the encoder + (None for stateless encoders). + To establish an agreement between the encoder and RLModules, these values + have the fixed keys `Columns.OBS` for the `input_dict`, + and `ACTOR` and `CRITIC` for the returned dict. + + Args: + input_dict: The input tensors. Must contain at a minimum the keys + Columns.OBS and Columns.STATE_IN (which might be None for stateless + encoders). + **kwargs: Forward compatibility kwargs. + + Returns: + The output tensors. Must contain at a minimum the key ENCODER_OUT. + """ + + +@ExperimentalAPI +class ActorCriticEncoder(Encoder): + """An encoder that potentially holds two stateless encoders. + + This is a special case of Encoder that can either enclose a single, + shared encoder or two separate encoders: One for the actor and one for the + critic. The two encoders are of the same type, and we can therefore make the + assumption that they have the same input and output specs. + """ + + framework = None + + def __init__(self, config: ModelConfig) -> None: + super().__init__(config) + + if config.shared: + self.encoder = config.base_encoder_config.build(framework=self.framework) + else: + self.actor_encoder = config.base_encoder_config.build( + framework=self.framework + ) + self.critic_encoder = None + if not config.inference_only: + self.critic_encoder = config.base_encoder_config.build( + framework=self.framework + ) + + @override(Model) + def _forward(self, inputs: dict, **kwargs) -> dict: + if self.config.shared: + encoder_outs = self.encoder(inputs, **kwargs) + return { + ENCODER_OUT: { + ACTOR: encoder_outs[ENCODER_OUT], + **( + {} + if self.config.inference_only + else {CRITIC: encoder_outs[ENCODER_OUT]} + ), + } + } + else: + # Encoders should not modify inputs, so we can pass the same inputs + actor_out = self.actor_encoder(inputs, **kwargs) + if self.critic_encoder: + critic_out = self.critic_encoder(inputs, **kwargs) + + return { + ENCODER_OUT: { + ACTOR: actor_out[ENCODER_OUT], + **( + {} + if self.config.inference_only + else {CRITIC: critic_out[ENCODER_OUT]} + ), + } + } + + +@ExperimentalAPI +class StatefulActorCriticEncoder(Encoder): + """An encoder that potentially holds two potentially stateful encoders. + + This is a special case of Encoder that can either enclose a single, + shared encoder or two separate encoders: One for the actor and one for the + critic. The two encoders are of the same type, and we can therefore make the + assumption that they have the same input and output specs. + + If this encoder wraps a single encoder, state in input- and output dicts + is simply stored under the key `STATE_IN` and `STATE_OUT`, respectively. + If this encoder wraps two encoders, state in input- and output dicts is + stored under the keys `(STATE_IN, ACTOR)` and `(STATE_IN, CRITIC)` and + `(STATE_OUT, ACTOR)` and `(STATE_OUT, CRITIC)`, respectively. + """ + + framework = None + + def __init__(self, config: ModelConfig) -> None: + super().__init__(config) + + if config.shared: + self.encoder = config.base_encoder_config.build(framework=self.framework) + else: + self.actor_encoder = config.base_encoder_config.build( + framework=self.framework + ) + self.critic_encoder = config.base_encoder_config.build( + framework=self.framework + ) + + @override(Model) + def get_initial_state(self): + if self.config.shared: + return self.encoder.get_initial_state() + else: + return { + ACTOR: self.actor_encoder.get_initial_state(), + CRITIC: self.critic_encoder.get_initial_state(), + } + + @override(Model) + def _forward(self, inputs: dict, **kwargs) -> dict: + outputs = {} + + if self.config.shared: + outs = self.encoder(inputs, **kwargs) + encoder_out = outs.pop(ENCODER_OUT) + outputs[ENCODER_OUT] = {ACTOR: encoder_out, CRITIC: encoder_out} + outputs[Columns.STATE_OUT] = outs[Columns.STATE_OUT] + else: + # Shallow copy inputs so that we can add states without modifying + # original dict. + actor_inputs = inputs.copy() + critic_inputs = inputs.copy() + actor_inputs[Columns.STATE_IN] = inputs[Columns.STATE_IN][ACTOR] + critic_inputs[Columns.STATE_IN] = inputs[Columns.STATE_IN][CRITIC] + + actor_out = self.actor_encoder(actor_inputs, **kwargs) + critic_out = self.critic_encoder(critic_inputs, **kwargs) + + outputs[ENCODER_OUT] = { + ACTOR: actor_out[ENCODER_OUT], + CRITIC: critic_out[ENCODER_OUT], + } + + outputs[Columns.STATE_OUT] = { + ACTOR: actor_out[Columns.STATE_OUT], + CRITIC: critic_out[Columns.STATE_OUT], + } + + return outputs + + +@DeveloperAPI +def tokenize(tokenizer: Encoder, inputs: dict, framework: str) -> dict: + """Tokenizes the observations from the input dict. + + Args: + tokenizer: The tokenizer to use. + inputs: The input dict. + + Returns: + The output dict. + """ + # Tokenizer may depend solely on observations. + obs = inputs[Columns.OBS] + tokenizer_inputs = {Columns.OBS: obs} + size = list(obs.size() if framework == "torch" else obs.shape) + b_dim, t_dim = size[:2] + fold, unfold = get_fold_unfold_fns(b_dim, t_dim, framework=framework) + # Push through the tokenizer encoder. + out = tokenizer(fold(tokenizer_inputs)) + out = out[ENCODER_OUT] + # Then unfold batch- and time-dimensions again. + return unfold(out) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/catalog.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/catalog.py new file mode 100644 index 0000000000000000000000000000000000000000..f1bf8c6a3ea526b4f2623b7e2b9751466ee1dd36 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/catalog.py @@ -0,0 +1,649 @@ +import dataclasses +import enum +import functools +from typing import Optional + +import gymnasium as gym +import numpy as np +import tree +from gymnasium.spaces import Box, Dict, Discrete, MultiDiscrete, Tuple + +from ray.rllib.core.models.base import Encoder +from ray.rllib.core.models.configs import ( + CNNEncoderConfig, + MLPEncoderConfig, + RecurrentEncoderConfig, +) +from ray.rllib.core.models.configs import ModelConfig +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.core.distribution.distribution import Distribution +from ray.rllib.models.preprocessors import get_preprocessor, Preprocessor +from ray.rllib.models.utils import get_filter_config +from ray.rllib.utils.deprecation import deprecation_warning, DEPRECATED_VALUE +from ray.rllib.utils.error import UnsupportedSpaceException +from ray.rllib.utils.spaces.simplex import Simplex +from ray.rllib.utils.spaces.space_utils import flatten_space +from ray.rllib.utils.spaces.space_utils import get_base_struct_from_space +from ray.rllib.utils.annotations import ( + OverrideToImplementCustomLogic, + OverrideToImplementCustomLogic_CallToSuperRecommended, +) + + +class Catalog: + """Describes the sub-module-architectures to be used in RLModules. + + RLlib's native RLModules get their Models from a Catalog object. + By default, that Catalog builds the configs it has as attributes. + This component was build to be hackable and extensible. You can inject custom + components into RL Modules by overriding the `build_xxx` methods of this class. + Note that it is recommended to write a custom RL Module for a single use-case. + Modifications to Catalogs mostly make sense if you want to reuse the same + Catalog for different RL Modules. For example if you have written a custom + encoder and want to inject it into different RL Modules (e.g. for PPO, DQN, etc.). + You can influence the decision tree that determines the sub-components by modifying + `Catalog._determine_components_hook`. + + Usage example: + + # Define a custom catalog + + .. testcode:: + + import torch + import gymnasium as gym + from ray.rllib.core.models.configs import MLPHeadConfig + from ray.rllib.core.models.catalog import Catalog + + class MyCatalog(Catalog): + def __init__( + self, + observation_space: gym.Space, + action_space: gym.Space, + model_config_dict: dict, + ): + super().__init__(observation_space, action_space, model_config_dict) + self.my_model_config = MLPHeadConfig( + hidden_layer_dims=[64, 32], + input_dims=[self.observation_space.shape[0]], + ) + + def build_my_head(self, framework: str): + return self.my_model_config.build(framework=framework) + + # With that, RLlib can build and use models from this catalog like this: + catalog = MyCatalog(gym.spaces.Box(0, 1), gym.spaces.Box(0, 1), {}) + my_head = catalog.build_my_head(framework="torch") + + # Make a call to the built model. + out = my_head(torch.Tensor([[1]])) + """ + + # TODO (Sven): Add `framework` arg to c'tor and remove this arg from `build` + # methods. This way, we can already know in the c'tor of Catalog, what the exact + # action distibution objects are and thus what the output dims for e.g. a pi-head + # will be. + def __init__( + self, + observation_space: gym.Space, + action_space: gym.Space, + model_config_dict: dict, + # deprecated args. + view_requirements=DEPRECATED_VALUE, + ): + """Initializes a Catalog with a default encoder config. + + Args: + observation_space: The observation space of the environment. + action_space: The action space of the environment. + model_config_dict: The model config that specifies things like hidden + dimensions and activations functions to use in this Catalog. + """ + if view_requirements != DEPRECATED_VALUE: + deprecation_warning(old="Catalog(view_requirements=..)", error=True) + + # TODO (sven): The following logic won't be needed anymore, once we get rid of + # Catalogs entirely. We will assert directly inside the algo's DefaultRLModule + # class that the `model_config` is a DefaultModelConfig. Thus users won't be + # able to pass in partial config dicts into a default model (alternatively, we + # could automatically augment the user provided dict by the default config + # dataclass object only(!) for default modules). + if dataclasses.is_dataclass(model_config_dict): + model_config_dict = dataclasses.asdict(model_config_dict) + default_config = dataclasses.asdict(DefaultModelConfig()) + # end: TODO + + self.observation_space = observation_space + self.action_space = action_space + + self._model_config_dict = default_config | model_config_dict + self._latent_dims = None + + self._determine_components_hook() + + @OverrideToImplementCustomLogic_CallToSuperRecommended + def _determine_components_hook(self): + """Decision tree hook for subclasses to override. + + By default, this method executes the decision tree that determines the + components that a Catalog builds. You can extend the components by overriding + this or by adding to the constructor of your subclass. + + Override this method if you don't want to use the default components + determined here. If you want to use them but add additional components, you + should call `super()._determine_components()` at the beginning of your + implementation. + + This makes it so that subclasses are not forced to create an encoder config + if the rest of their catalog is not dependent on it or if it breaks. + At the end of this method, an attribute `Catalog.latent_dims` + should be set so that heads can be built using that information. + """ + self._encoder_config = self._get_encoder_config( + observation_space=self.observation_space, + action_space=self.action_space, + model_config_dict=self._model_config_dict, + ) + + # Create a function that can be called when framework is known to retrieve the + # class type for action distributions + self._action_dist_class_fn = functools.partial( + self._get_dist_cls_from_action_space, action_space=self.action_space + ) + + # The dimensions of the latent vector that is output by the encoder and fed + # to the heads. + self.latent_dims = self._encoder_config.output_dims + + @property + def latent_dims(self): + """Returns the latent dimensions of the encoder. + + This establishes an agreement between encoder and heads about the latent + dimensions. Encoders can be built to output a latent tensor with + `latent_dims` dimensions, and heads can be built with tensors of + `latent_dims` dimensions as inputs. This can be safely ignored if this + agreement is not needed in case of modifications to the Catalog. + + Returns: + The latent dimensions of the encoder. + """ + return self._latent_dims + + @latent_dims.setter + def latent_dims(self, value): + self._latent_dims = value + + @OverrideToImplementCustomLogic + def build_encoder(self, framework: str) -> Encoder: + """Builds the encoder. + + By default, this method builds an encoder instance from Catalog._encoder_config. + + You should override this if you want to use RLlib's default RL Modules but + only want to change the encoder. For example, if you want to use a custom + encoder, but want to use RLlib's default heads, action distribution and how + tensors are routed between them. If you want to have full control over the + RL Module, we recommend writing your own RL Module by inheriting from one of + RLlib's RL Modules instead. + + Args: + framework: The framework to use. Either "torch" or "tf2". + + Returns: + The encoder. + """ + assert hasattr(self, "_encoder_config"), ( + "You must define a `Catalog._encoder_config` attribute in your Catalog " + "subclass or override the `Catalog.build_encoder` method. By default, " + "an encoder_config is created in the __post_init__ method." + ) + return self._encoder_config.build(framework=framework) + + @OverrideToImplementCustomLogic + def get_action_dist_cls(self, framework: str): + """Get the action distribution class. + + The default behavior is to get the action distribution from the + `Catalog._action_dist_class_fn`. + + You should override this to have RLlib build your custom action + distribution instead of the default one. For example, if you don't want to + use RLlib's default RLModules with their default models, but only want to + change the distribution that Catalog returns. + + Args: + framework: The framework to use. Either "torch" or "tf2". + + Returns: + The action distribution. + """ + assert hasattr(self, "_action_dist_class_fn"), ( + "You must define a `Catalog._action_dist_class_fn` attribute in your " + "Catalog subclass or override the `Catalog.action_dist_class_fn` method. " + "By default, an action_dist_class_fn is created in the __post_init__ " + "method." + ) + return self._action_dist_class_fn(framework=framework) + + @classmethod + def _get_encoder_config( + cls, + observation_space: gym.Space, + model_config_dict: dict, + action_space: gym.Space = None, + ) -> ModelConfig: + """Returns an EncoderConfig for the given input_space and model_config_dict. + + Encoders are usually used in RLModules to transform the input space into a + latent space that is then fed to the heads. The returned EncoderConfig + objects correspond to the built-in Encoder classes in RLlib. + For example, for a simple 1D-Box input_space, RLlib offers an + MLPEncoder, hence this method returns the MLPEncoderConfig. You can overwrite + this method to produce specific EncoderConfigs for your custom Models. + + The following input spaces lead to the following configs: + - 1D-Box: MLPEncoderConfig + - 3D-Box: CNNEncoderConfig + # TODO (Artur): Support more spaces here + # ... + + Args: + observation_space: The observation space to use. + model_config_dict: The model config to use. + action_space: The action space to use if actions are to be encoded. This + is commonly the case for LSTM models. + + Returns: + The encoder config. + """ + activation = model_config_dict["fcnet_activation"] + output_activation = model_config_dict["fcnet_activation"] + use_lstm = model_config_dict["use_lstm"] + + if use_lstm: + encoder_config = RecurrentEncoderConfig( + input_dims=observation_space.shape, + recurrent_layer_type="lstm", + hidden_dim=model_config_dict["lstm_cell_size"], + hidden_weights_initializer=model_config_dict["lstm_kernel_initializer"], + hidden_weights_initializer_config=model_config_dict[ + "lstm_kernel_initializer_kwargs" + ], + hidden_bias_initializer=model_config_dict["lstm_bias_initializer"], + hidden_bias_initializer_config=model_config_dict[ + "lstm_bias_initializer_kwargs" + ], + batch_major=True, + num_layers=1, + tokenizer_config=cls.get_tokenizer_config( + observation_space, + model_config_dict, + ), + ) + else: + # TODO (Artur): Maybe check for original spaces here + # input_space is a 1D Box + if isinstance(observation_space, Box) and len(observation_space.shape) == 1: + # In order to guarantee backward compatability with old configs, + # we need to check if no latent dim was set and simply reuse the last + # fcnet hidden dim for that purpose. + hidden_layer_dims = model_config_dict["fcnet_hiddens"][:-1] + encoder_latent_dim = model_config_dict["fcnet_hiddens"][-1] + encoder_config = MLPEncoderConfig( + input_dims=observation_space.shape, + hidden_layer_dims=hidden_layer_dims, + hidden_layer_activation=activation, + hidden_layer_weights_initializer=model_config_dict[ + "fcnet_kernel_initializer" + ], + hidden_layer_weights_initializer_config=model_config_dict[ + "fcnet_kernel_initializer_kwargs" + ], + hidden_layer_bias_initializer=model_config_dict[ + "fcnet_bias_initializer" + ], + hidden_layer_bias_initializer_config=model_config_dict[ + "fcnet_bias_initializer_kwargs" + ], + output_layer_dim=encoder_latent_dim, + output_layer_activation=output_activation, + output_layer_weights_initializer=model_config_dict[ + "fcnet_kernel_initializer" + ], + output_layer_weights_initializer_config=model_config_dict[ + "fcnet_kernel_initializer_kwargs" + ], + output_layer_bias_initializer=model_config_dict[ + "fcnet_bias_initializer" + ], + output_layer_bias_initializer_config=model_config_dict[ + "fcnet_bias_initializer_kwargs" + ], + ) + + # input_space is a 3D Box + elif ( + isinstance(observation_space, Box) and len(observation_space.shape) == 3 + ): + if not model_config_dict.get("conv_filters"): + model_config_dict["conv_filters"] = get_filter_config( + observation_space.shape + ) + + encoder_config = CNNEncoderConfig( + input_dims=observation_space.shape, + cnn_filter_specifiers=model_config_dict["conv_filters"], + cnn_activation=model_config_dict["conv_activation"], + cnn_kernel_initializer=model_config_dict["conv_kernel_initializer"], + cnn_kernel_initializer_config=model_config_dict[ + "conv_kernel_initializer_kwargs" + ], + cnn_bias_initializer=model_config_dict["conv_bias_initializer"], + cnn_bias_initializer_config=model_config_dict[ + "conv_bias_initializer_kwargs" + ], + ) + # input_space is a 2D Box + elif ( + isinstance(observation_space, Box) and len(observation_space.shape) == 2 + ): + # RLlib used to support 2D Box spaces by silently flattening them + raise ValueError( + f"No default encoder config for obs space={observation_space}," + f" lstm={use_lstm} found. 2D Box " + f"spaces are not supported. They should be either flattened to a " + f"1D Box space or enhanced to be a 3D box space." + ) + # input_space is a possibly nested structure of spaces. + else: + # NestedModelConfig + raise ValueError( + f"No default encoder config for obs space={observation_space}," + f" lstm={use_lstm} found." + ) + + return encoder_config + + @classmethod + @OverrideToImplementCustomLogic + def get_tokenizer_config( + cls, + observation_space: gym.Space, + model_config_dict: dict, + # deprecated args. + view_requirements=DEPRECATED_VALUE, + ) -> ModelConfig: + """Returns a tokenizer config for the given space. + + This is useful for recurrent / transformer models that need to tokenize their + inputs. By default, RLlib uses the models supported by Catalog out of the box to + tokenize. + + You should override this method if you want to change the custom tokenizer + inside current encoders that Catalog returns without providing the recurrent + network as a whole. For example, if you want to define some custom CNN layers + as a tokenizer for a recurrent encoder that already includes the recurrent + layers and handles the state. + + Args: + observation_space: The observation space to use. + model_config_dict: The model config to use. + """ + if view_requirements != DEPRECATED_VALUE: + deprecation_warning(old="Catalog(view_requirements=..)", error=True) + + return cls._get_encoder_config( + observation_space=observation_space, + # Use model_config_dict without flags that would end up in complex models + model_config_dict={ + **model_config_dict, + **{"use_lstm": False, "use_attention": False}, + }, + ) + + @classmethod + def _get_dist_cls_from_action_space( + cls, + action_space: gym.Space, + *, + framework: Optional[str] = None, + ) -> Distribution: + """Returns a distribution class for the given action space. + + You can get the required input dimension for the distribution by calling + `action_dict_cls.required_input_dim(action_space)` + on the retrieved class. This is useful, because the Catalog needs to find out + about the required input dimension for the distribution before the model that + outputs these inputs is configured. + + Args: + action_space: Action space of the target gym env. + framework: The framework to use. + + Returns: + The distribution class for the given action space. + """ + # If no framework provided, return no action distribution class (None). + if framework is None: + return None + # This method is structured in two steps: + # Firstly, construct a dictionary containing the available distribution classes. + # Secondly, return the correct distribution class for the given action space. + + # Step 1: Construct the dictionary. + + class DistEnum(enum.Enum): + Categorical = "Categorical" + DiagGaussian = "Gaussian" + Deterministic = "Deterministic" + MultiDistribution = "MultiDistribution" + MultiCategorical = "MultiCategorical" + + if framework == "torch": + from ray.rllib.core.distribution.torch.torch_distribution import ( + TorchCategorical, + TorchDeterministic, + TorchDiagGaussian, + ) + + distribution_dicts = { + DistEnum.Deterministic: TorchDeterministic, + DistEnum.DiagGaussian: TorchDiagGaussian, + DistEnum.Categorical: TorchCategorical, + } + else: + raise ValueError( + f"Unknown framework: {framework}. Only 'torch' and 'tf2' are " + "supported for RLModule Catalogs." + ) + + # Only add a MultiAction distribution class to the dict if we can compute its + # components (we need a Tuple/Dict space for this). + if isinstance(action_space, (Tuple, Dict)): + partial_multi_action_distribution_cls = _multi_action_dist_partial_helper( + catalog_cls=cls, + action_space=action_space, + framework=framework, + ) + + distribution_dicts[ + DistEnum.MultiDistribution + ] = partial_multi_action_distribution_cls + + # Only add a MultiCategorical distribution class to the dict if we can compute + # its components (we need a MultiDiscrete space for this). + if isinstance(action_space, MultiDiscrete): + partial_multi_categorical_distribution_cls = ( + _multi_categorical_dist_partial_helper( + action_space=action_space, + framework=framework, + ) + ) + + distribution_dicts[ + DistEnum.MultiCategorical + ] = partial_multi_categorical_distribution_cls + + # Step 2: Return the correct distribution class for the given action space. + + # Box space -> DiagGaussian OR Deterministic. + if isinstance(action_space, Box): + if action_space.dtype.char in np.typecodes["AllInteger"]: + raise ValueError( + "Box(..., `int`) action spaces are not supported. " + "Use MultiDiscrete or Box(..., `float`)." + ) + else: + if len(action_space.shape) > 1: + raise UnsupportedSpaceException( + f"Action space has multiple dimensions {action_space.shape}. " + f"Consider reshaping this into a single dimension, using a " + f"custom action distribution, using a Tuple action space, " + f"or the multi-agent API." + ) + return distribution_dicts[DistEnum.DiagGaussian] + + # Discrete Space -> Categorical. + elif isinstance(action_space, Discrete): + return distribution_dicts[DistEnum.Categorical] + + # Tuple/Dict Spaces -> MultiAction. + elif isinstance(action_space, (Tuple, Dict)): + return distribution_dicts[DistEnum.MultiDistribution] + + # Simplex -> Dirichlet. + elif isinstance(action_space, Simplex): + # TODO(Artur): Supported Simplex (in torch). + raise NotImplementedError("Simplex action space not yet supported.") + + # MultiDiscrete -> MultiCategorical. + elif isinstance(action_space, MultiDiscrete): + return distribution_dicts[DistEnum.MultiCategorical] + + # Unknown type -> Error. + else: + raise NotImplementedError(f"Unsupported action space: `{action_space}`") + + @staticmethod + def get_preprocessor(observation_space: gym.Space, **kwargs) -> Preprocessor: + """Returns a suitable preprocessor for the given observation space. + + Args: + observation_space: The input observation space. + **kwargs: Forward-compatible kwargs. + + Returns: + preprocessor: Preprocessor for the observations. + """ + # TODO(Artur): Since preprocessors have long been @PublicAPI with the options + # kwarg as part of their constructor, we fade out support for this, + # beginning with this entrypoint. + # Next, we should deprecate the `options` kwarg from the Preprocessor itself, + # after deprecating the old catalog and other components that still pass this. + options = kwargs.get("options", {}) + if options: + deprecation_warning( + old="get_preprocessor_for_space(..., options={...})", + help="Override `Catalog.get_preprocessor()` " + "in order to implement custom behaviour.", + error=False, + ) + + if options.get("custom_preprocessor"): + deprecation_warning( + old="model_config['custom_preprocessor']", + help="Custom preprocessors are deprecated, " + "since they sometimes conflict with the built-in " + "preprocessors for handling complex observation spaces. " + "Please use wrapper classes around your environment " + "instead.", + error=True, + ) + else: + # TODO(Artur): Inline the get_preprocessor() call here once we have + # deprecated the old model catalog. + cls = get_preprocessor(observation_space) + prep = cls(observation_space, options) + return prep + + +def _multi_action_dist_partial_helper( + catalog_cls: "Catalog", action_space: gym.Space, framework: str +) -> Distribution: + """Helper method to get a partial of a MultiActionDistribution. + + This is useful for when we want to create MultiActionDistributions from + logits only (!) later, but know the action space now already. + + Args: + catalog_cls: The ModelCatalog class to use. + action_space: The action space to get the child distribution classes for. + framework: The framework to use. + + Returns: + A partial of the TorchMultiActionDistribution class. + """ + action_space_struct = get_base_struct_from_space(action_space) + flat_action_space = flatten_space(action_space) + child_distribution_cls_struct = tree.map_structure( + lambda s: catalog_cls._get_dist_cls_from_action_space( + action_space=s, + framework=framework, + ), + action_space_struct, + ) + flat_distribution_clses = tree.flatten(child_distribution_cls_struct) + + logit_lens = [ + int(dist_cls.required_input_dim(space)) + for dist_cls, space in zip(flat_distribution_clses, flat_action_space) + ] + + if framework == "torch": + from ray.rllib.core.distribution.torch.torch_distribution import ( + TorchMultiDistribution, + ) + + multi_action_dist_cls = TorchMultiDistribution + else: + raise ValueError(f"Unsupported framework: {framework}") + + partial_dist_cls = multi_action_dist_cls.get_partial_dist_cls( + space=action_space, + child_distribution_cls_struct=child_distribution_cls_struct, + input_lens=logit_lens, + ) + return partial_dist_cls + + +def _multi_categorical_dist_partial_helper( + action_space: gym.Space, framework: str +) -> Distribution: + """Helper method to get a partial of a MultiCategorical Distribution. + + This is useful for when we want to create MultiCategorical Distribution from + logits only (!) later, but know the action space now already. + + Args: + action_space: The action space to get the child distribution classes for. + framework: The framework to use. + + Returns: + A partial of the MultiCategorical class. + """ + + if framework == "torch": + from ray.rllib.core.distribution.torch.torch_distribution import ( + TorchMultiCategorical, + ) + + multi_categorical_dist_cls = TorchMultiCategorical + else: + raise ValueError(f"Unsupported framework: {framework}") + + partial_dist_cls = multi_categorical_dist_cls.get_partial_dist_cls( + space=action_space, input_lens=list(action_space.nvec) + ) + + return partial_dist_cls diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/configs.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/configs.py new file mode 100644 index 0000000000000000000000000000000000000000..00acf8ef41328199633fe19b1b5302e41fa665c1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/configs.py @@ -0,0 +1,1058 @@ +import abc +from dataclasses import dataclass, field +import functools +from typing import Callable, Dict, List, Optional, Tuple, TYPE_CHECKING, Union + +import numpy as np + +from ray.rllib.models.torch.misc import ( + same_padding, + same_padding_transpose_after_stride, + valid_padding, +) +from ray.rllib.models.utils import get_activation_fn, get_initializer_fn +from ray.rllib.utils.annotations import ExperimentalAPI + +if TYPE_CHECKING: + from ray.rllib.core.models.base import Model, Encoder + + +@ExperimentalAPI +def _framework_implemented(torch: bool = True, tf2: bool = True): + """Decorator to check if a model was implemented in a framework. + + Args: + torch: Whether we can build this model with torch. + tf2: Whether we can build this model with tf2. + + Returns: + The decorated function. + + Raises: + ValueError: If the framework is not available to build. + """ + accepted = [] + if torch: + accepted.append("torch") + if tf2: + accepted.append("tf2") + + def decorator(fn: Callable) -> Callable: + @functools.wraps(fn) + def checked_build(self, framework, **kwargs): + if framework not in accepted: + raise ValueError( + f"This config does not support framework " + f"{framework}. Only frameworks in {accepted} are " + f"supported." + ) + return fn(self, framework, **kwargs) + + return checked_build + + return decorator + + +@ExperimentalAPI +@dataclass +class ModelConfig(abc.ABC): + """Base class for configuring a `Model` instance. + + ModelConfigs are DL framework-agnostic. + A `Model` (as a sub-component of an `RLModule`) is built via calling the + respective ModelConfig's `build()` method. + RLModules build their sub-components this way after receiving one or more + `ModelConfig` instances from a Catalog object. + + However, `ModelConfig` is not restricted to be used only with Catalog or RLModules. + Usage examples can be found in the individual Model classes', e.g. + see `ray.rllib.core.models.configs::MLPHeadConfig`. + + Attributes: + input_dims: The input dimensions of the network + always_check_shapes: Whether to always check the inputs and outputs of the + model for the specifications. Input specifications are checked on failed + forward passes of the model regardless of this flag. If this flag is set + to `True`, inputs and outputs are checked on every call. This leads to + a slow-down and should only be used for debugging. + """ + + input_dims: Union[List[int], Tuple[int]] = None + always_check_shapes: bool = False + + @abc.abstractmethod + def build(self, framework: str): + """Builds the model. + + Args: + framework: The framework to use for building the model. + """ + raise NotImplementedError + + @property + def output_dims(self) -> Optional[Tuple[int]]: + """Read-only `output_dims` are inferred automatically from other settings.""" + return None + + +@ExperimentalAPI +@dataclass +class _MLPConfig(ModelConfig): + """Generic configuration class for multi-layer-perceptron based Model classes. + + `output_dims` is reached by either the provided `output_layer_dim` setting (int) OR + by the last entry of `hidden_layer_dims`. In the latter case, no special output + layer is added and all layers in the stack behave exactly the same. If + `output_layer_dim` is provided, users might also change this last layer's + activation (`output_layer_activation`) and its bias setting + (`output_layer_use_bias`). + + This is a private class as users should not configure their models directly + through this class, but use one of the sub-classes, e.g. `MLPHeadConfig` or + `MLPEncoderConfig`. + + Attributes: + input_dims: A 1D tensor indicating the input dimension, e.g. `[32]`. + hidden_layer_dims: The sizes of the hidden layers. If an empty list, + `output_layer_dim` must be provided (int) and only a single layer will be + built. + hidden_layer_use_bias: Whether to use bias on all dense layers in the network + (excluding a possible separate output layer defined by `output_layer_dim`). + hidden_layer_activation: The activation function to use after each layer ( + except for the output). The default activation for hidden layers is "relu". + hidden_layer_use_layernorm: Whether to insert a LayerNorm functionality + in between each hidden layer's output and its activation. + hidden_layer_weights_initializer: The initializer function or class to use for + weight initialization in the hidden layers. If `None` the default + initializer of the respective dense layer of a framework (`"torch"` or + `"tf2"`) is used. Note, all initializers defined in the framework `"tf2`) + are allowed. For `"torch"` only the in-place initializers, i.e. ending with + an underscore "_" are allowed. + hidden_layer_weights_initializer_config: Configuration to pass into the + initializer defined in `hidden_layer_weights_initializer`. + hidden_layer_bias_initializer: The initializer function or class to use for + bias initialization in the hidden layers. If `None` the default initializer + of the respective dense layer of a framework (`"torch"` or `"tf2"`) is used. + Note, all initializers defined in the framework `"tf2`) are allowed. For + `"torch"` only the in-place initializers, i.e. ending with an underscore "_" + are allowed. + hidden_layer_bias_initializer_config: Configuration to pass into the + initializer defined in `hidden_layer_bias_initializer`. + output_layer_dim: An int indicating the size of the output layer. This may be + set to `None` in case no extra output layer should be built and only the + layers specified by `hidden_layer_dims` will be part of the network. + output_layer_use_bias: Whether to use bias on the separate output layer, if any. + output_layer_activation: The activation function to use for the output layer, + if any. The default activation for the output layer, if any, is "linear", + meaning no activation. + output_layer_weights_initializer: The initializer function or class to use for + weight initialization in the output layers. If `None` the default + initializer of the respective dense layer of a framework (`"torch"` or ` + "tf2"`) is used. Note, all initializers defined in the framework `"tf2`) are + allowed. For `"torch"` only the in-place initializers, i.e. ending with an + underscore "_" are allowed. + output_layer_weights_initializer_config: Configuration to pass into the + initializer defined in `output_layer_weights_initializer`. + output_layer_bias_initializer: The initializer function or class to use for + bias initialization in the output layers. If `None` the default initializer + of the respective dense layer of a framework (`"torch"` or `"tf2"`) is used. + For `"torch"` only the in-place initializers, i.e. ending with an underscore + "_" are allowed. + output_layer_bias_initializer_config: Configuration to pass into the + initializer defined in `output_layer_bias_initializer`. + clip_log_std: If log std should be clipped by `log_std_clip_param`. This applies + only to the action distribution parameters that encode the log standard + deviation of a `DiagGaussian` distribution. + log_std_clip_param: The clipping parameter for the log std, if clipping should + be applied - i.e. `clip_log_std=True`. The default value is 20, i.e. log + stds are clipped in between -20 and 20. + """ + + hidden_layer_dims: Union[List[int], Tuple[int]] = (256, 256) + hidden_layer_use_bias: bool = True + hidden_layer_activation: str = "relu" + hidden_layer_use_layernorm: bool = False + hidden_layer_weights_initializer: Optional[Union[str, Callable]] = None + hidden_layer_weights_initializer_config: Optional[Dict] = None + hidden_layer_bias_initializer: Optional[Union[str, Callable]] = None + hidden_layer_bias_initializer_config: Optional[Dict] = None + + # Optional last output layer with - possibly - different activation and use_bias + # settings. + output_layer_dim: Optional[int] = None + output_layer_use_bias: bool = True + output_layer_activation: str = "linear" + output_layer_weights_initializer: Optional[Union[str, Callable]] = None + output_layer_weights_initializer_config: Optional[Dict] = None + output_layer_bias_initializer: Optional[Union[str, Callable]] = None + output_layer_bias_initializer_config: Optional[Dict] = None + + # Optional clipping of log standard deviation. + clip_log_std: bool = False + # Optional clip parameter for the log standard deviation. + log_std_clip_param: float = 20.0 + + @property + def output_dims(self): + if self.output_layer_dim is None and not self.hidden_layer_dims: + raise ValueError( + "If `output_layer_dim` is None, you must specify at least one hidden " + "layer dim, e.g. `hidden_layer_dims=[32]`!" + ) + + # Infer `output_dims` automatically. + return (int(self.output_layer_dim or self.hidden_layer_dims[-1]),) + + def _validate(self, framework: str = "torch"): + """Makes sure that settings are valid.""" + if self.input_dims is not None and len(self.input_dims) != 1: + raise ValueError( + f"`input_dims` ({self.input_dims}) of MLPConfig must be 1D, " + "e.g. `[32]`!" + ) + if len(self.output_dims) != 1: + raise ValueError( + f"`output_dims` ({self.output_dims}) of _MLPConfig must be " + "1D, e.g. `[32]`! This is an inferred value, hence other settings might" + " be wrong." + ) + if self.log_std_clip_param is None: + raise ValueError( + "`log_std_clip_param` of _MLPConfig must be a float value, but is " + "`None`." + ) + + # Call these already here to catch errors early on. + get_activation_fn(self.hidden_layer_activation, framework=framework) + get_activation_fn(self.output_layer_activation, framework=framework) + get_initializer_fn(self.hidden_layer_weights_initializer, framework=framework) + get_initializer_fn(self.hidden_layer_bias_initializer, framework=framework) + get_initializer_fn(self.output_layer_weights_initializer, framework=framework) + get_initializer_fn(self.output_layer_bias_initializer, framework=framework) + + +@ExperimentalAPI +@dataclass +class MLPHeadConfig(_MLPConfig): + """Configuration for an MLP head. + + See _MLPConfig for usage details. + + Example: + + .. testcode:: + + # Configuration: + config = MLPHeadConfig( + input_dims=[4], # must be 1D tensor + hidden_layer_dims=[8, 8], + hidden_layer_activation="relu", + hidden_layer_use_layernorm=False, + # final output layer with no activation (linear) + output_layer_dim=2, + output_layer_activation="linear", + ) + model = config.build(framework="tf2") + + # Resulting stack in pseudocode: + # Linear(4, 8, bias=True) + # ReLU() + # Linear(8, 8, bias=True) + # ReLU() + # Linear(8, 2, bias=True) + + Example: + + .. testcode:: + + # Configuration: + config = MLPHeadConfig( + input_dims=[2], + hidden_layer_dims=[10, 4], + hidden_layer_activation="silu", + hidden_layer_use_layernorm=True, + hidden_layer_use_bias=False, + # Initializer for `framework="torch"`. + hidden_layer_weights_initializer="xavier_normal_", + hidden_layer_weights_initializer_config={"gain": 0.8}, + # No final output layer (use last dim in `hidden_layer_dims` + # as the size of the last layer in the stack). + output_layer_dim=None, + ) + model = config.build(framework="torch") + + # Resulting stack in pseudocode: + # Linear(2, 10, bias=False) + # LayerNorm((10,)) # layer norm always before activation + # SiLU() + # Linear(10, 4, bias=False) + # LayerNorm((4,)) # layer norm always before activation + # SiLU() + """ + + @_framework_implemented() + def build(self, framework: str = "torch") -> "Model": + self._validate(framework=framework) + + if framework == "torch": + from ray.rllib.core.models.torch.heads import TorchMLPHead + + return TorchMLPHead(self) + + +@ExperimentalAPI +@dataclass +class FreeLogStdMLPHeadConfig(_MLPConfig): + """Configuration for an MLPHead with a floating second half of outputs. + + This model can be useful together with Gaussian Distributions. + This gaussian distribution would be conditioned as follows: + - The first half of outputs from this model can be used as + state-dependent means when conditioning a gaussian distribution + - The second half are floating free biases that can be used as + state-independent standard deviations to condition a gaussian distribution. + The mean values are produced by an MLPHead, while the standard + deviations are added as floating free biases from a single 1D trainable variable + (not dependent on the net's inputs). + + The output dimensions of the configured MLPHeadConfig must be even and are + divided by two to gain the output dimensions of each the mean-net and the + free std-variable. + + Example: + .. testcode:: + :skipif: True + + # Configuration: + config = FreeLogStdMLPHeadConfig( + input_dims=[2], + hidden_layer_dims=[16], + hidden_layer_activation=None, + hidden_layer_use_layernorm=False, + hidden_layer_use_bias=True, + output_layer_dim=8, # <- this must be an even size + output_layer_use_bias=True, + ) + model = config.build(framework="tf2") + + # Resulting stack in pseudocode: + # Linear(2, 16, bias=True) + # Linear(8, 8, bias=True) # 16 / 2 = 8 -> 8 nodes for the mean + # Extra variable: + # Tensor((8,), float32) # for the free (observation independent) std outputs + + Example: + .. testcode:: + :skipif: True + + # Configuration: + config = FreeLogStdMLPHeadConfig( + input_dims=[2], + hidden_layer_dims=[31, 100], # <- last idx must be an even size + hidden_layer_activation="relu", + hidden_layer_use_layernorm=False, + hidden_layer_use_bias=False, + output_layer_dim=None, # use the last hidden layer as output layer + ) + model = config.build(framework="torch") + + # Resulting stack in pseudocode: + # Linear(2, 31, bias=False) + # ReLu() + # Linear(31, 50, bias=False) # 100 / 2 = 50 -> 50 nodes for the mean + # ReLu() + # Extra variable: + # Tensor((50,), float32) # for the free (observation independent) std outputs + """ + + def _validate(self, framework: str = "torch"): + if len(self.output_dims) > 1 or self.output_dims[0] % 2 == 1: + raise ValueError( + f"`output_layer_dim` ({self.ouput_layer_dim}) or the last value in " + f"`hidden_layer_dims` ({self.hidden_layer_dims}) of a " + "FreeLogStdMLPHeadConfig must be an even int (dividable by 2), " + "e.g. `output_layer_dim=8` or `hidden_layer_dims=[133, 128]`!" + ) + + @_framework_implemented() + def build(self, framework: str = "torch") -> "Model": + self._validate(framework=framework) + + if framework == "torch": + from ray.rllib.core.models.torch.heads import TorchFreeLogStdMLPHead + + return TorchFreeLogStdMLPHead(self) + + +@ExperimentalAPI +@dataclass +class CNNTransposeHeadConfig(ModelConfig): + """Configuration for a convolutional transpose head (decoder) network. + + The configured Model transforms 1D-observations into an image space. + The stack of layers is composed of an initial Dense layer, followed by a sequence + of Conv2DTranspose layers. + `input_dims` describes the shape of the (1D) input tensor, + `initial_image_dims` describes the input into the first Conv2DTranspose + layer, where the translation from `input_dim` to `initial_image_dims` is done + via the initial Dense layer (w/o activation, w/o layer-norm, and w/ bias). + + Beyond that, each layer specified by `cnn_transpose_filter_specifiers` + is followed by an activation function according to `cnn_transpose_activation`. + + `output_dims` is reached after the final Conv2DTranspose layer. + Not that the last Conv2DTranspose layer is never activated and never layer-norm'd + regardless of the other settings. + + An example for a single conv2d operation is as follows: + Input "image" is (4, 4, 24) (not yet strided), padding is "same", stride=2, + kernel=5. + + First, the input "image" is strided (with stride=2): + + Input image (4x4 (x24)): + A B C D + E F G H + I J K L + M N O P + + Stride with stride=2 -> (7x7 (x24)) + A 0 B 0 C 0 D + 0 0 0 0 0 0 0 + E 0 F 0 G 0 H + 0 0 0 0 0 0 0 + I 0 J 0 K 0 L + 0 0 0 0 0 0 0 + M 0 N 0 O 0 P + + Then this strided "image" (strided_size=7x7) is padded (exact padding values will be + computed by the model): + + Padding -> (left=3, right=2, top=3, bottom=2) + + 0 0 0 0 0 0 0 0 0 0 0 0 + 0 0 0 0 0 0 0 0 0 0 0 0 + 0 0 0 0 0 0 0 0 0 0 0 0 + 0 0 0 A 0 B 0 C 0 D 0 0 + 0 0 0 0 0 0 0 0 0 0 0 0 + 0 0 0 E 0 F 0 G 0 H 0 0 + 0 0 0 0 0 0 0 0 0 0 0 0 + 0 0 0 I 0 J 0 K 0 L 0 0 + 0 0 0 0 0 0 0 0 0 0 0 0 + 0 0 0 M 0 N 0 O 0 P 0 0 + 0 0 0 0 0 0 0 0 0 0 0 0 + 0 0 0 0 0 0 0 0 0 0 0 0 + + Then deconvolution with kernel=5 yields an output "image" of 8x8 (x num output + filters). + + Attributes: + input_dims: The input dimensions of the network. This must be a 1D tensor. + initial_image_dims: The shape of the input to the first + Conv2DTranspose layer. We will make sure the input is transformed to + these dims via a preceding initial Dense layer, followed by a reshape, + before entering the Conv2DTranspose stack. + initial_dense_weights_initializer: The initializer function or class to use for + weight initialization in the initial dense layer. If `None` the default + initializer of the respective dense layer of a framework (`"torch"` or + `"tf2"`) is used. Note, all initializers defined in the framework `"tf2`) + are allowed. For `"torch"` only the in-place initializers, i.e. ending with + an underscore "_" are allowed. + initial_dense_weights_initializer_config: Configuration to pass into the + initializer defined in `initial_dense_weights_initializer`. + initial_dense_bias_initializer: The initializer function or class to use for + bias initialization in the initial dense layer. If `None` the default + initializer of the respective CNN layer of a framework (`"torch"` or `"tf2"` + ) is used. For `"torch"` only the in-place initializers, i.e. ending with an + underscore "_" are allowed. + initial_dense_bias_initializer_config: Configuration to pass into the + initializer defined in `initial_dense_bias_initializer`. + cnn_transpose_filter_specifiers: A list of lists, where each element of an inner + list contains elements of the form + `[number of channels/filters, [kernel width, kernel height], stride]` to + specify a convolutional layer stacked in order of the outer list. + cnn_transpose_use_bias: Whether to use bias on all Conv2DTranspose layers. + cnn_transpose_activation: The activation function to use after each layer + (except for the output). + cnn_transpose_use_layernorm: Whether to insert a LayerNorm functionality + in between each Conv2DTranspose layer's output and its activation. + cnn_transpose_kernel_initializer: The initializer function or class to use for + kernel initialization in the CNN layers. If `None` the default initializer + of the respective CNN layer of a framework (`"torch"` or `"tf2"`) is used. + Note, all initializers defined in the framework `"tf2`) are allowed. For + `"torch"` only the in-place initializers, i.e. ending with an underscore "_" + are allowed. + cnn_transpose_kernel_initializer_config: Configuration to pass into the + initializer defined in `cnn_transpose_kernel_initializer`. + cnn_transpose_bias_initializer: The initializer function or class to use for + bias initialization in the CNN layers. If `None` the default initializer of + the respective CNN layer of a framework (`"torch"` or `"tf2"`) is used. + For `"torch"` only the in-place initializers, i.e. ending with an underscore + "_" are allowed. + cnn_transpose_bias_initializer_config: Configuration to pass into the + initializer defined in `cnn_transpose_bias_initializer`. + + Example: + .. testcode:: + :skipif: True + + # Configuration: + config = CNNTransposeHeadConfig( + input_dims=[10], # 1D input vector (possibly coming from another NN) + initial_image_dims=[4, 4, 96], # first image input to deconv stack + # Initializer for TensorFlow. + initial_dense_weights_initializer="HeNormal", + initial_dense_weights_initializer={"seed": 334}, + cnn_transpose_filter_specifiers=[ + [48, [4, 4], 2], + [24, [4, 4], 2], + [3, [4, 4], 2], + ], + cnn_transpose_activation="silu", # or "swish", which is the same + cnn_transpose_use_layernorm=False, + cnn_use_bias=True, + ) + model = config.build(framework="torch) + + # Resulting stack in pseudocode: + # Linear(10, 4*4*24) + # Conv2DTranspose( + # in_channels=96, out_channels=48, + # kernel_size=[4, 4], stride=2, bias=True, + # ) + # Swish() + # Conv2DTranspose( + # in_channels=48, out_channels=24, + # kernel_size=[4, 4], stride=2, bias=True, + # ) + # Swish() + # Conv2DTranspose( + # in_channels=24, out_channels=3, + # kernel_size=[4, 4], stride=2, bias=True, + # ) + + Example: + .. testcode:: + :skipif: True + + # Configuration: + config = CNNTransposeHeadConfig( + input_dims=[128], # 1D input vector (possibly coming from another NN) + initial_image_dims=[4, 4, 32], # first image input to deconv stack + cnn_transpose_filter_specifiers=[ + [16, 4, 2], + [3, 4, 2], + ], + cnn_transpose_activation="relu", + cnn_transpose_use_layernorm=True, + cnn_use_bias=False, + # Initializer for `framework="tf2"`. + # Note, for Torch only in-place initializers are allowed. + cnn_transpose_kernel_initializer="xavier_normal_", + cnn_transpose_kernel_initializer_config={"gain": 0.8}, + ) + model = config.build(framework="torch) + + # Resulting stack in pseudocode: + # Linear(128, 4*4*32, bias=True) # bias always True for initial dense layer + # Conv2DTranspose( + # in_channels=32, out_channels=16, + # kernel_size=[4, 4], stride=2, bias=False, + # ) + # LayerNorm((-3, -2, -1)) # layer normalize over last 3 axes + # ReLU() + # Conv2DTranspose( + # in_channels=16, out_channels=3, + # kernel_size=[4, 4], stride=2, bias=False, + # ) + """ + + input_dims: Union[List[int], Tuple[int]] = None + initial_image_dims: Union[List[int], Tuple[int]] = field( + default_factory=lambda: [4, 4, 96] + ) + initial_dense_weights_initializer: Optional[Union[str, Callable]] = None + initial_dense_weights_initializer_config: Optional[Dict] = None + initial_dense_bias_initializer: Optional[Union[str, Callable]] = None + initial_dense_bias_initializer_config: Optional[Dict] = None + cnn_transpose_filter_specifiers: List[List[Union[int, List[int]]]] = field( + default_factory=lambda: [[48, [4, 4], 2], [24, [4, 4], 2], [3, [4, 4], 2]] + ) + cnn_transpose_use_bias: bool = True + cnn_transpose_activation: str = "relu" + cnn_transpose_use_layernorm: bool = False + cnn_transpose_kernel_initializer: Optional[Union[str, Callable]] = None + cnn_transpose_kernel_initializer_config: Optional[Dict] = None + cnn_transpose_bias_initializer: Optional[Union[str, Callable]] = None + cnn_transpose_bias_initializer_config: Optional[Dict] = None + + @property + def output_dims(self): + # Infer output dims, layer by layer. + dims = self.initial_image_dims + for filter_spec in self.cnn_transpose_filter_specifiers: + # Same padding. + num_filters, kernel, stride = filter_spec + # Compute stride output size first (striding is performed first in a + # conv transpose layer. + stride_w, stride_h = (stride, stride) if isinstance(stride, int) else stride + dims = [ + dims[0] * stride_w - (stride_w - 1), + dims[1] * stride_h - (stride_h - 1), + num_filters, + ] + # TODO (Sven): Support "valid" padding for Conv2DTranspose layers, too. + # Analogous to Conv2D Layers in a CNNEncoder. + # Apply the correct padding. Note that this might be asymetrical, meaning + # left padding might be != right padding, same for top/bottom. + _, padding_out_size = same_padding_transpose_after_stride( + (dims[0], dims[1]), kernel, stride + ) + # Perform conv transpose operation with the kernel. + kernel_w, kernel_h = (kernel, kernel) if isinstance(kernel, int) else kernel + dims = [ + padding_out_size[0] - (kernel_w - 1), + padding_out_size[1] - (kernel_h - 1), + num_filters, + ] + return tuple(dims) + + def _validate(self, framework: str = "torch"): + if len(self.input_dims) != 1: + raise ValueError( + f"`input_dims` ({self.input_dims}) of CNNTransposeHeadConfig must be a " + "3D tensor (image-like) with the dimensions meaning: width x height x " + "num_filters, e.g. `[4, 4, 92]`!" + ) + + @_framework_implemented() + def build(self, framework: str = "torch") -> "Model": + self._validate(framework) + + if framework == "torch": + from ray.rllib.core.models.torch.heads import TorchCNNTransposeHead + + return TorchCNNTransposeHead(self) + + +@ExperimentalAPI +@dataclass +class CNNEncoderConfig(ModelConfig): + """Configuration for a convolutional (encoder) network. + + The configured CNN encodes 3D-observations into a latent space. + The stack of layers is composed of a sequence of convolutional layers. + `input_dims` describes the shape of the input tensor. Beyond that, each layer + specified by `filter_specifiers` is followed by an activation function according + to `filter_activation`. + + `output_dims` is reached by either the final convolutional layer's output directly + OR by flatten this output. + + See ModelConfig for usage details. + + Example: + + .. testcode:: + + # Configuration: + config = CNNEncoderConfig( + input_dims=[84, 84, 3], # must be 3D tensor (image: w x h x C) + cnn_filter_specifiers=[ + [16, [8, 8], 4], + [32, [4, 4], 2], + ], + cnn_activation="relu", + cnn_use_layernorm=False, + cnn_use_bias=True, + ) + model = config.build(framework="torch") + + # Resulting stack in pseudocode: + # Conv2D( + # in_channels=3, out_channels=16, + # kernel_size=[8, 8], stride=[4, 4], bias=True, + # ) + # ReLU() + # Conv2D( + # in_channels=16, out_channels=32, + # kernel_size=[4, 4], stride=[2, 2], bias=True, + # ) + # ReLU() + # Conv2D( + # in_channels=32, out_channels=1, + # kernel_size=[1, 1], stride=[1, 1], bias=True, + # ) + # Flatten() + + Attributes: + input_dims: The input dimension of the network. These must be given in the + form of `(width, height, channels)`. + cnn_filter_specifiers: A list in which each element is another (inner) list + of either the following forms: + `[number of channels/filters, kernel, stride]` + OR: + `[number of channels/filters, kernel, stride, padding]`, where `padding` + can either be "same" or "valid". + When using the first format w/o the `padding` specifier, `padding` is "same" + by default. Also, `kernel` and `stride` may be provided either as single + ints (square) or as a tuple/list of two ints (width- and height dimensions) + for non-squared kernel/stride shapes. + A good rule of thumb for constructing CNN stacks is: + When using padding="same", the input "image" will be reduced in size by + the factor `stride`, e.g. input=(84, 84, 3) stride=2 kernel=x padding="same" + filters=16 -> output=(42, 42, 16). + For example, if you would like to reduce an Atari image from its original + (84, 84, 3) dimensions down to (6, 6, F), you can construct the following + stack and reduce the w x h dimension of the image by 2 in each layer: + [[16, 4, 2], [32, 4, 2], [64, 4, 2], [128, 4, 2]] -> output=(6, 6, 128) + cnn_use_bias: Whether to use bias on all Conv2D layers. + cnn_activation: The activation function to use after each layer ( + except for the output). The default activation for Conv2d layers is "relu". + cnn_use_layernorm: Whether to insert a LayerNorm functionality + in between each CNN layer's output and its activation. Note that + the output layer. + cnn_kernel_initializer: The initializer function or class to use for kernel + initialization in the CNN layers. If `None` the default initializer of the + respective CNN layer of a framework (`"torch"` or `"tf2"`) is used. Note, + all initializers defined in the framework `"tf2`) are allowed. For `"torch"` + only the in-place initializers, i.e. ending with an underscore "_" are + allowed. + cnn_kernel_initializer_config: Configuration to pass into the initializer + defined in `cnn_kernel_initializer`. + cnn_bias_initializer: The initializer function or class to use for bias + initialization in the CNN layers. If `None` the default initializer of + the respective CNN layer of a framework (`"torch"` or `"tf2"`) is used. + For `"torch"` only the in-place initializers, i.e. ending with an underscore + "_" are allowed. + cnn_bias_initializer_config: Configuration to pass into the initializer defined + in `cnn_bias_initializer`. + flatten_at_end: Whether to flatten the output of the last conv 2D layer into + a 1D tensor. By default, this is True. Note that if you set this to False, + you might simply stack another CNNEncoder on top of this one (maybe with + different activation and bias settings). + """ + + input_dims: Union[List[int], Tuple[int]] = None + cnn_filter_specifiers: List[List[Union[int, List[int]]]] = field( + default_factory=lambda: [[16, [4, 4], 2], [32, [4, 4], 2], [64, [8, 8], 2]] + ) + cnn_use_bias: bool = True + cnn_activation: str = "relu" + cnn_use_layernorm: bool = False + cnn_kernel_initializer: Optional[Union[str, Callable]] = None + cnn_kernel_initializer_config: Optional[Dict] = None + cnn_bias_initializer: Optional[Union[str, Callable]] = None + cnn_bias_initializer_config: Optional[Dict] = None + flatten_at_end: bool = True + + @property + def output_dims(self): + if not self.input_dims: + return None + + # Infer output dims, layer by layer. + dims = self.input_dims # Creates a copy (works for tuple/list). + for filter_spec in self.cnn_filter_specifiers: + # Padding not provided, "same" by default. + if len(filter_spec) == 3: + num_filters, kernel, stride = filter_spec + padding = "same" + # Padding option provided, use given value. + else: + num_filters, kernel, stride, padding = filter_spec + + # Same padding. + if padding == "same": + _, dims = same_padding(dims[:2], kernel, stride) + # Valid padding. + else: + dims = valid_padding(dims[:2], kernel, stride) + + # Add depth (num_filters) to the end (our utility functions for same/valid + # only return the image width/height). + dims = [dims[0], dims[1], num_filters] + + # Flatten everything. + if self.flatten_at_end: + return (int(np.prod(dims)),) + + return tuple(dims) + + def _validate(self, framework: str = "torch"): + if len(self.input_dims) != 3: + raise ValueError( + f"`input_dims` ({self.input_dims}) of CNNEncoderConfig must be a 3D " + "tensor (image) with the dimensions meaning: width x height x " + "channels, e.g. `[64, 64, 3]`!" + ) + if not self.flatten_at_end and len(self.output_dims) != 3: + raise ValueError( + f"`output_dims` ({self.output_dims}) of CNNEncoderConfig must be " + "3D, e.g. `[4, 4, 128]`, b/c your `flatten_at_end` setting is False! " + "`output_dims` is an inferred value, hence other settings might be " + "wrong." + ) + elif self.flatten_at_end and len(self.output_dims) != 1: + raise ValueError( + f"`output_dims` ({self.output_dims}) of CNNEncoderConfig must be " + "1D, e.g. `[32]`, b/c your `flatten_at_end` setting is True! " + "`output_dims` is an inferred value, hence other settings might be " + "wrong." + ) + + @_framework_implemented() + def build(self, framework: str = "torch") -> "Model": + self._validate(framework) + + if framework == "torch": + from ray.rllib.core.models.torch.encoder import TorchCNNEncoder + + return TorchCNNEncoder(self) + + +@ExperimentalAPI +@dataclass +class MLPEncoderConfig(_MLPConfig): + """Configuration for an MLP that acts as an encoder. + + See _MLPConfig for usage details. + + Example: + .. testcode:: + + # Configuration: + config = MLPEncoderConfig( + input_dims=[4], # must be 1D tensor + hidden_layer_dims=[16], + hidden_layer_activation="relu", + hidden_layer_use_layernorm=False, + output_layer_dim=None, # maybe None or an int + ) + model = config.build(framework="torch") + + # Resulting stack in pseudocode: + # Linear(4, 16, bias=True) + # ReLU() + + Example: + .. testcode:: + + # Configuration: + config = MLPEncoderConfig( + input_dims=[2], + hidden_layer_dims=[8, 8], + hidden_layer_activation="silu", + hidden_layer_use_layernorm=True, + hidden_layer_use_bias=False, + output_layer_dim=4, + output_layer_activation="tanh", + output_layer_use_bias=False, + ) + model = config.build(framework="tf2") + + # Resulting stack in pseudocode: + # Linear(2, 8, bias=False) + # LayerNorm((8,)) # layernorm always before activation + # SiLU() + # Linear(8, 8, bias=False) + # LayerNorm((8,)) # layernorm always before activation + # SiLU() + # Linear(8, 4, bias=False) + # Tanh() + """ + + @_framework_implemented() + def build(self, framework: str = "torch") -> "Encoder": + self._validate(framework) + + if framework == "torch": + from ray.rllib.core.models.torch.encoder import TorchMLPEncoder + + return TorchMLPEncoder(self) + + +@ExperimentalAPI +@dataclass +class RecurrentEncoderConfig(ModelConfig): + """Configuration for an LSTM-based or a GRU-based encoder. + + The encoder consists of... + - Zero or one tokenizers + - N LSTM/GRU layers stacked on top of each other and feeding + their outputs as inputs to the respective next layer. + + This makes for the following flow of tensors: + + Inputs + | + [Tokenizer if present] + | + LSTM layer 1 + | + (...) + | + LSTM layer n + | + Outputs + + The internal state is structued as (num_layers, B, hidden-size) for all hidden + state components, e.g. + h- and c-states of the LSTM layer(s) or h-state of the GRU layer(s). + For example, the hidden states of an LSTMEncoder with num_layers=2 and hidden_dim=8 + would be: {"h": (2, B, 8), "c": (2, B, 8)}. + + `output_dims` is reached by the last recurrent layer's dimension, which is always + the `hidden_dims` value. + + Example: + .. testcode:: + + # Configuration: + config = RecurrentEncoderConfig( + recurrent_layer_type="lstm", + input_dims=[16], # must be 1D tensor + hidden_dim=128, + num_layers=2, + use_bias=True, + ) + model = config.build(framework="torch") + + # Resulting stack in pseudocode: + # LSTM(16, 128, bias=True) + # LSTM(128, 128, bias=True) + + # Resulting shape of the internal states (c- and h-states): + # (2, B, 128) for each c- and h-states. + + Example: + .. testcode:: + + # Configuration: + config = RecurrentEncoderConfig( + recurrent_layer_type="gru", + input_dims=[32], # must be 1D tensor + hidden_dim=64, + num_layers=1, + use_bias=False, + ) + model = config.build(framework="torch") + + # Resulting stack in pseudocode: + # GRU(32, 64, bias=False) + + # Resulting shape of the internal state: + # (1, B, 64) + + Attributes: + input_dims: The input dimensions. Must be 1D. This is the 1D shape of the tensor + that goes into the first recurrent layer. + recurrent_layer_type: The type of the recurrent layer(s). + Either "lstm" or "gru". + hidden_dim: The size of the hidden internal state(s) of the recurrent layer(s). + For example, for an LSTM, this would be the size of the c- and h-tensors. + num_layers: The number of recurrent (LSTM or GRU) layers to stack. + batch_major: Wether the input is batch major (B, T, ..) or + time major (T, B, ..). + hidden_weights_initializer: The initializer function or class to use for + kernel initialization in the hidden layers. If `None` the default + initializer of the respective recurrent layer of a framework (`"torch"` or + `"tf2"`) is used. Note, all initializers defined in the frameworks ( + `"torch"` or `"tf2`) are allowed. For `"torch"` only the in-place + initializers, i.e. ending with an underscore "_" are allowed. + hidden_weights_initializer_config: Configuration to pass into the + initializer defined in `hidden_weights_initializer`. + use_bias: Whether to use bias on the recurrent layers in the network. + hidden_bias_initializer: The initializer function or class to use for bias + initialization in the hidden layers. If `None` the default initializer of + the respective recurrent layer of a framework (`"torch"` or `"tf2"`) is + used. For `"torch"` only the in-place initializers, i.e. ending with an + underscore "_" are allowed. + hidden_bias_initializer_config: Configuration to pass into the initializer + defined in `hidden_bias_initializer`. + tokenizer_config: A ModelConfig to build tokenizers for observations, + actions and other spaces. + """ + + recurrent_layer_type: str = "lstm" + hidden_dim: int = None + num_layers: int = None + batch_major: bool = True + hidden_weights_initializer: Optional[Union[str, Callable]] = None + hidden_weights_initializer_config: Optional[Dict] = None + use_bias: bool = True + hidden_bias_initializer: Optional[Union[str, Callable]] = None + hidden_bias_initializer_config: Optional[Dict] = None + tokenizer_config: ModelConfig = None + + @property + def output_dims(self): + return (self.hidden_dim,) + + def _validate(self, framework: str = "torch"): + """Makes sure that settings are valid.""" + if self.recurrent_layer_type not in ["gru", "lstm"]: + raise ValueError( + f"`recurrent_layer_type` ({self.recurrent_layer_type}) of " + "RecurrentEncoderConfig must be 'gru' or 'lstm'!" + ) + if self.input_dims is not None and len(self.input_dims) != 1: + raise ValueError( + f"`input_dims` ({self.input_dims}) of RecurrentEncoderConfig must be " + "1D, e.g. `[32]`!" + ) + if len(self.output_dims) != 1: + raise ValueError( + f"`output_dims` ({self.output_dims}) of RecurrentEncoderConfig must be " + "1D, e.g. `[32]`! This is an inferred value, hence other settings might" + " be wrong." + ) + + @_framework_implemented() + def build(self, framework: str = "torch") -> "Encoder": + if framework == "torch": + from ray.rllib.core.models.torch.encoder import ( + TorchGRUEncoder as GRU, + TorchLSTMEncoder as LSTM, + ) + + if self.recurrent_layer_type == "lstm": + return LSTM(self) + else: + return GRU(self) + + +@ExperimentalAPI +@dataclass +class ActorCriticEncoderConfig(ModelConfig): + """Configuration for an ActorCriticEncoder. + + The base encoder functions like other encoders in RLlib. It is wrapped by the + ActorCriticEncoder to provides a shared encoder Model to use in RLModules that + provides twofold outputs: one for the actor and one for the critic. See + ModelConfig for usage details. + + Attributes: + base_encoder_config: The configuration for the wrapped encoder(s). + shared: Whether the base encoder is shared between the actor and critic. + inference_only: Whether the configured encoder will only ever be used as an + actor-encoder, never as a value-function encoder. Thus, if True and `shared` + is False, will only build the actor-related components. + """ + + base_encoder_config: ModelConfig = None + shared: bool = True + inference_only: bool = False + + @_framework_implemented() + def build(self, framework: str = "torch") -> "Encoder": + if framework == "torch": + from ray.rllib.core.models.torch.encoder import ( + TorchActorCriticEncoder, + TorchStatefulActorCriticEncoder, + ) + + if isinstance(self.base_encoder_config, RecurrentEncoderConfig): + return TorchStatefulActorCriticEncoder(self) + else: + return TorchActorCriticEncoder(self) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/specs/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/specs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/specs/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/specs/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0b397492c3c206d95e029cf1c5d1467217e9607 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/specs/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/specs/__pycache__/specs_base.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/specs/__pycache__/specs_base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e1ff49925a32a3459cd8c479aeef8b723119ac1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/specs/__pycache__/specs_base.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/specs/__pycache__/specs_dict.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/specs/__pycache__/specs_dict.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d018b7cb2ba02536e242ec3235c902712c90fe7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/specs/__pycache__/specs_dict.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/specs/specs_base.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/specs/specs_base.py new file mode 100644 index 0000000000000000000000000000000000000000..722267b3dc6d059d56cdef3b2b24d208f6c7faad --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/specs/specs_base.py @@ -0,0 +1,28 @@ +from ray.rllib.utils.deprecation import Deprecated + + +@Deprecated( + help="The Spec checking APIs have been deprecated and cancelled without " + "replacement.", + error=True, +) +class Spec: + pass + + +@Deprecated( + help="The Spec checking APIs have been deprecated and cancelled without " + "replacement.", + error=True, +) +class TypeSpec: + pass + + +@Deprecated( + help="The Spec checking APIs have been deprecated and cancelled without " + "replacement.", + error=True, +) +class TensorSpec: + pass diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/specs/specs_dict.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/specs/specs_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..7d944688eb0eaf3de91bb046fe4304f47124451b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/specs/specs_dict.py @@ -0,0 +1,9 @@ +from ray.rllib.utils.deprecation import Deprecated + + +@Deprecated( + help="The SpecDict API has been deprecated and cancelled without " "replacement.", + error=True, +) +class SpecDict: + pass diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8cda66982c7f4a335d2cb83809af15e832239f9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/__pycache__/base.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82a46b9c5418c0761d6a863a642948c2b7767819 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/__pycache__/base.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/__pycache__/encoder.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/__pycache__/encoder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0895e1b436034469cd68dcf1edf394f1a749ce0c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/__pycache__/encoder.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/__pycache__/heads.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/__pycache__/heads.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec942c831a0435a88e46d4472358a778ac69d53b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/__pycache__/heads.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/__pycache__/primitives.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/__pycache__/primitives.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae8b120f2c4e88f598ecdb9bcdc54288ae3adcf1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/__pycache__/primitives.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/__pycache__/utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..641af68b537650131bccec720070b197bc87fa3a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/__pycache__/utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/base.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ce6a109024b9afd6582d61a141eb44bd15baa34a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/base.py @@ -0,0 +1,101 @@ +import abc +import logging +from typing import Tuple, Union + +from ray.rllib.core.models.base import Model +from ray.rllib.core.models.configs import ModelConfig +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.typing import TensorType + +torch, nn = try_import_torch() + +logger = logging.getLogger(__name__) + + +class TorchModel(nn.Module, Model, abc.ABC): + """Base class for RLlib's PyTorch models. + + This class defines the interface for RLlib's PyTorch models. + + Example usage for a single Flattening layer: + + .. testcode:: + + from ray.rllib.core.models.configs import ModelConfig + from ray.rllib.core.models.torch.base import TorchModel + import torch + + class FlattenModelConfig(ModelConfig): + def build(self, framework: str): + assert framework == "torch" + return TorchFlattenModel(self) + + class TorchFlattenModel(TorchModel): + def __init__(self, config): + TorchModel.__init__(self, config) + self.flatten_layer = torch.nn.Flatten() + + def _forward(self, inputs, **kwargs): + return self.flatten_layer(inputs) + + model = FlattenModelConfig().build("torch") + inputs = torch.Tensor([[[1, 2]]]) + print(model(inputs)) + + .. testoutput:: + + tensor([[1., 2.]]) + + """ + + def __init__(self, config: ModelConfig): + """Initialized a TorchModel. + + Args: + config: The ModelConfig to use. + """ + nn.Module.__init__(self) + Model.__init__(self, config) + + def forward( + self, inputs: Union[dict, TensorType], **kwargs + ) -> Union[dict, TensorType]: + """Returns the output of this model for the given input. + + This method only makes sure that we have a spec-checked _forward() method. + + Args: + inputs: The input tensors. + **kwargs: Forward compatibility kwargs. + + Returns: + dict: The output tensors. + """ + return self._forward(inputs, **kwargs) + + @override(Model) + def get_num_parameters(self) -> Tuple[int, int]: + num_trainable_parameters = 0 + num_frozen_parameters = 0 + for p in self.parameters(): + n = p.numel() + if p.requires_grad: + num_trainable_parameters += n + else: + num_frozen_parameters += n + return num_trainable_parameters, num_frozen_parameters + + @override(Model) + def _set_to_dummy_weights(self, value_sequence=(-0.02, -0.01, 0.01, 0.02)): + trainable_weights = [] + non_trainable_weights = [] + for p in self.parameters(): + if p.requires_grad: + trainable_weights.append(p) + else: + non_trainable_weights.append(p) + for i, w in enumerate(trainable_weights + non_trainable_weights): + fill_val = value_sequence[i % len(value_sequence)] + with torch.no_grad(): + w.fill_(fill_val) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/encoder.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..82812e43fc61ec4dc80f8395735696cc25935493 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/encoder.py @@ -0,0 +1,284 @@ +import tree + +from ray.rllib.core.columns import Columns +from ray.rllib.core.models.base import ( + Encoder, + ActorCriticEncoder, + StatefulActorCriticEncoder, + ENCODER_OUT, +) +from ray.rllib.core.models.base import Model, tokenize +from ray.rllib.core.models.configs import ( + ActorCriticEncoderConfig, + CNNEncoderConfig, + MLPEncoderConfig, + RecurrentEncoderConfig, +) +from ray.rllib.core.models.torch.base import TorchModel +from ray.rllib.core.models.torch.primitives import TorchMLP, TorchCNN +from ray.rllib.models.utils import get_initializer_fn +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch + +torch, nn = try_import_torch() + + +class TorchActorCriticEncoder(TorchModel, ActorCriticEncoder): + """An actor-critic encoder for torch.""" + + framework = "torch" + + def __init__(self, config: ActorCriticEncoderConfig) -> None: + TorchModel.__init__(self, config) + ActorCriticEncoder.__init__(self, config) + + +class TorchStatefulActorCriticEncoder(TorchModel, StatefulActorCriticEncoder): + """A stateful actor-critic encoder for torch.""" + + framework = "torch" + + def __init__(self, config: ActorCriticEncoderConfig) -> None: + TorchModel.__init__(self, config) + StatefulActorCriticEncoder.__init__(self, config) + + +class TorchMLPEncoder(TorchModel, Encoder): + def __init__(self, config: MLPEncoderConfig) -> None: + TorchModel.__init__(self, config) + Encoder.__init__(self, config) + + # Create the neural network. + self.net = TorchMLP( + input_dim=config.input_dims[0], + hidden_layer_dims=config.hidden_layer_dims, + hidden_layer_activation=config.hidden_layer_activation, + hidden_layer_use_layernorm=config.hidden_layer_use_layernorm, + hidden_layer_use_bias=config.hidden_layer_use_bias, + hidden_layer_weights_initializer=config.hidden_layer_weights_initializer, + hidden_layer_weights_initializer_config=( + config.hidden_layer_weights_initializer_config + ), + hidden_layer_bias_initializer=config.hidden_layer_bias_initializer, + hidden_layer_bias_initializer_config=( + config.hidden_layer_bias_initializer_config + ), + output_dim=config.output_layer_dim, + output_activation=config.output_layer_activation, + output_use_bias=config.output_layer_use_bias, + output_weights_initializer=config.output_layer_weights_initializer, + output_weights_initializer_config=( + config.output_layer_weights_initializer_config + ), + output_bias_initializer=config.output_layer_bias_initializer, + output_bias_initializer_config=config.output_layer_bias_initializer_config, + ) + + @override(Model) + def _forward(self, inputs: dict, **kwargs) -> dict: + return {ENCODER_OUT: self.net(inputs[Columns.OBS])} + + +class TorchCNNEncoder(TorchModel, Encoder): + def __init__(self, config: CNNEncoderConfig) -> None: + TorchModel.__init__(self, config) + Encoder.__init__(self, config) + + layers = [] + # The bare-bones CNN (no flatten, no succeeding dense). + cnn = TorchCNN( + input_dims=config.input_dims, + cnn_filter_specifiers=config.cnn_filter_specifiers, + cnn_activation=config.cnn_activation, + cnn_use_layernorm=config.cnn_use_layernorm, + cnn_use_bias=config.cnn_use_bias, + cnn_kernel_initializer=config.cnn_kernel_initializer, + cnn_kernel_initializer_config=config.cnn_kernel_initializer_config, + cnn_bias_initializer=config.cnn_bias_initializer, + cnn_bias_initializer_config=config.cnn_bias_initializer_config, + ) + layers.append(cnn) + + # Add a flatten operation to move from 2/3D into 1D space. + if config.flatten_at_end: + layers.append(nn.Flatten()) + + # Create the network from gathered layers. + self.net = nn.Sequential(*layers) + + @override(Model) + def _forward(self, inputs: dict, **kwargs) -> dict: + return {ENCODER_OUT: self.net(inputs[Columns.OBS])} + + +class TorchGRUEncoder(TorchModel, Encoder): + """A recurrent GRU encoder. + + This encoder has... + - Zero or one tokenizers. + - One or more GRU layers. + """ + + def __init__(self, config: RecurrentEncoderConfig) -> None: + TorchModel.__init__(self, config) + + # Maybe create a tokenizer + if config.tokenizer_config is not None: + self.tokenizer = config.tokenizer_config.build(framework="torch") + gru_input_dims = config.tokenizer_config.output_dims + else: + self.tokenizer = None + gru_input_dims = config.input_dims + + # We only support 1D spaces right now. + assert len(gru_input_dims) == 1 + gru_input_dim = gru_input_dims[0] + + gru_weights_initializer = get_initializer_fn( + config.hidden_weights_initializer, framework="torch" + ) + gru_bias_initializer = get_initializer_fn( + config.hidden_bias_initializer, framework="torch" + ) + + # Create the torch GRU layer. + self.gru = nn.GRU( + gru_input_dim, + config.hidden_dim, + config.num_layers, + batch_first=config.batch_major, + bias=config.use_bias, + ) + + # Initialize, GRU weights, if necessary. + if gru_weights_initializer: + gru_weights_initializer( + self.gru.weight, **config.hidden_weights_initializer_config or {} + ) + # Initialize GRU bias, if necessary. + if gru_bias_initializer: + gru_bias_initializer( + self.gru.weight, **config.hidden_bias_initializer_config or {} + ) + + @override(Model) + def get_initial_state(self): + return { + "h": torch.zeros(self.config.num_layers, self.config.hidden_dim), + } + + @override(Model) + def _forward(self, inputs: dict, **kwargs) -> dict: + outputs = {} + + if self.tokenizer is not None: + # Push observations through the tokenizer encoder if we built one. + out = tokenize(self.tokenizer, inputs, framework="torch") + else: + # Otherwise, just use the raw observations. + out = inputs[Columns.OBS].float() + + # States are batch-first when coming in. Make them layers-first. + states_in = tree.map_structure( + lambda s: s.transpose(0, 1), inputs[Columns.STATE_IN] + ) + + out, states_out = self.gru(out, states_in["h"]) + states_out = {"h": states_out} + + # Insert them into the output dict. + outputs[ENCODER_OUT] = out + outputs[Columns.STATE_OUT] = tree.map_structure( + lambda s: s.transpose(0, 1), states_out + ) + return outputs + + +class TorchLSTMEncoder(TorchModel, Encoder): + """A recurrent LSTM encoder. + + This encoder has... + - Zero or one tokenizers. + - One or more LSTM layers. + """ + + def __init__(self, config: RecurrentEncoderConfig) -> None: + TorchModel.__init__(self, config) + + # Maybe create a tokenizer + if config.tokenizer_config is not None: + self.tokenizer = config.tokenizer_config.build(framework="torch") + lstm_input_dims = config.tokenizer_config.output_dims + else: + self.tokenizer = None + lstm_input_dims = config.input_dims + + # We only support 1D spaces right now. + assert len(lstm_input_dims) == 1 + lstm_input_dim = lstm_input_dims[0] + + lstm_weights_initializer = get_initializer_fn( + config.hidden_weights_initializer, framework="torch" + ) + lstm_bias_initializer = get_initializer_fn( + config.hidden_bias_initializer, framework="torch" + ) + + # Create the torch LSTM layer. + self.lstm = nn.LSTM( + lstm_input_dim, + config.hidden_dim, + config.num_layers, + batch_first=config.batch_major, + bias=config.use_bias, + ) + + # Initialize LSTM layer weigths and biases, if necessary. + for layer in self.lstm.all_weights: + if lstm_weights_initializer: + lstm_weights_initializer( + layer[0], **config.hidden_weights_initializer_config or {} + ) + lstm_weights_initializer( + layer[1], **config.hidden_weights_initializer_config or {} + ) + if lstm_bias_initializer: + lstm_bias_initializer( + layer[2], **config.hidden_bias_initializer_config or {} + ) + lstm_bias_initializer( + layer[3], **config.hidden_bias_initializer_config or {} + ) + + @override(Model) + def get_initial_state(self): + return { + "h": torch.zeros(self.config.num_layers, self.config.hidden_dim), + "c": torch.zeros(self.config.num_layers, self.config.hidden_dim), + } + + @override(Model) + def _forward(self, inputs: dict, **kwargs) -> dict: + outputs = {} + + if self.tokenizer is not None: + # Push observations through the tokenizer encoder if we built one. + out = tokenize(self.tokenizer, inputs, framework="torch") + else: + # Otherwise, just use the raw observations. + out = inputs[Columns.OBS].float() + + # States are batch-first when coming in. Make them layers-first. + states_in = tree.map_structure( + lambda s: s.transpose(0, 1), inputs[Columns.STATE_IN] + ) + + out, states_out = self.lstm(out, (states_in["h"], states_in["c"])) + states_out = {"h": states_out[0], "c": states_out[1]} + + # Insert them into the output dict. + outputs[ENCODER_OUT] = out + outputs[Columns.STATE_OUT] = tree.map_structure( + lambda s: s.transpose(0, 1), states_out + ) + return outputs diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/heads.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/heads.py new file mode 100644 index 0000000000000000000000000000000000000000..844c40c4a44cbe0617c5008b0464acc20ed17653 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/heads.py @@ -0,0 +1,197 @@ +import numpy as np + +from ray.rllib.core.models.base import Model +from ray.rllib.core.models.configs import ( + CNNTransposeHeadConfig, + FreeLogStdMLPHeadConfig, + MLPHeadConfig, +) +from ray.rllib.core.models.torch.base import TorchModel +from ray.rllib.core.models.torch.primitives import TorchCNNTranspose, TorchMLP +from ray.rllib.models.utils import get_initializer_fn +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch + +torch, nn = try_import_torch() + + +class TorchMLPHead(TorchModel): + def __init__(self, config: MLPHeadConfig) -> None: + super().__init__(config) + + self.net = TorchMLP( + input_dim=config.input_dims[0], + hidden_layer_dims=config.hidden_layer_dims, + hidden_layer_activation=config.hidden_layer_activation, + hidden_layer_use_layernorm=config.hidden_layer_use_layernorm, + hidden_layer_use_bias=config.hidden_layer_use_bias, + hidden_layer_weights_initializer=config.hidden_layer_weights_initializer, + hidden_layer_weights_initializer_config=( + config.hidden_layer_weights_initializer_config + ), + hidden_layer_bias_initializer=config.hidden_layer_bias_initializer, + hidden_layer_bias_initializer_config=( + config.hidden_layer_bias_initializer_config + ), + output_dim=config.output_layer_dim, + output_activation=config.output_layer_activation, + output_use_bias=config.output_layer_use_bias, + output_weights_initializer=config.output_layer_weights_initializer, + output_weights_initializer_config=( + config.output_layer_weights_initializer_config + ), + output_bias_initializer=config.output_layer_bias_initializer, + output_bias_initializer_config=config.output_layer_bias_initializer_config, + ) + # If log standard deviations should be clipped. This should be only true for + # policy heads. Value heads should never be clipped. + self.clip_log_std = config.clip_log_std + # The clipping parameter for the log standard deviation. + self.log_std_clip_param = torch.Tensor([config.log_std_clip_param]) + # Register a buffer to handle device mapping. + self.register_buffer("log_std_clip_param_const", self.log_std_clip_param) + + @override(Model) + def _forward(self, inputs: torch.Tensor, **kwargs) -> torch.Tensor: + # Only clip the log standard deviations, if the user wants to clip. This + # avoids also clipping value heads. + if self.clip_log_std: + # Forward pass. + means, log_stds = torch.chunk(self.net(inputs), chunks=2, dim=-1) + # Clip the log standard deviations. + log_stds = torch.clamp( + log_stds, -self.log_std_clip_param_const, self.log_std_clip_param_const + ) + return torch.cat((means, log_stds), dim=-1) + # Otherwise just return the logits. + else: + return self.net(inputs) + + +class TorchFreeLogStdMLPHead(TorchModel): + """An MLPHead that implements floating log stds for Gaussian distributions.""" + + def __init__(self, config: FreeLogStdMLPHeadConfig) -> None: + super().__init__(config) + + assert config.output_dims[0] % 2 == 0, "output_dims must be even for free std!" + self._half_output_dim = config.output_dims[0] // 2 + + self.net = TorchMLP( + input_dim=config.input_dims[0], + hidden_layer_dims=config.hidden_layer_dims, + hidden_layer_activation=config.hidden_layer_activation, + hidden_layer_use_layernorm=config.hidden_layer_use_layernorm, + hidden_layer_use_bias=config.hidden_layer_use_bias, + hidden_layer_weights_initializer=config.hidden_layer_weights_initializer, + hidden_layer_weights_initializer_config=( + config.hidden_layer_weights_initializer_config + ), + hidden_layer_bias_initializer=config.hidden_layer_bias_initializer, + hidden_layer_bias_initializer_config=( + config.hidden_layer_bias_initializer_config + ), + output_dim=self._half_output_dim, + output_activation=config.output_layer_activation, + output_use_bias=config.output_layer_use_bias, + output_weights_initializer=config.output_layer_weights_initializer, + output_weights_initializer_config=( + config.output_layer_weights_initializer_config + ), + output_bias_initializer=config.output_layer_bias_initializer, + output_bias_initializer_config=config.output_layer_bias_initializer_config, + ) + + self.log_std = torch.nn.Parameter( + torch.as_tensor([0.0] * self._half_output_dim) + ) + # If log standard deviations should be clipped. This should be only true for + # policy heads. Value heads should never be clipped. + self.clip_log_std = config.clip_log_std + # The clipping parameter for the log standard deviation. + self.log_std_clip_param = torch.Tensor( + [config.log_std_clip_param], device=self.log_std.device + ) + # Register a buffer to handle device mapping. + self.register_buffer("log_std_clip_param_const", self.log_std_clip_param) + + @override(Model) + def _forward(self, inputs: torch.Tensor, **kwargs) -> torch.Tensor: + # Compute the mean first, then append the log_std. + mean = self.net(inputs) + + # If log standard deviation should be clipped. + if self.clip_log_std: + # Clip the log standard deviation to avoid running into too small + # deviations that factually collapses the policy. + log_std = torch.clamp( + self.log_std, + -self.log_std_clip_param_const, + self.log_std_clip_param_const, + ) + else: + log_std = self.log_std + + return torch.cat([mean, log_std.unsqueeze(0).repeat([len(mean), 1])], axis=1) + + +class TorchCNNTransposeHead(TorchModel): + def __init__(self, config: CNNTransposeHeadConfig) -> None: + super().__init__(config) + + # Initial, inactivated Dense layer (always w/ bias). + # This layer is responsible for getting the incoming tensor into a proper + # initial image shape (w x h x filters) for the suceeding Conv2DTranspose stack. + self.initial_dense = nn.Linear( + in_features=config.input_dims[0], + out_features=int(np.prod(config.initial_image_dims)), + bias=True, + ) + + # Initial Dense layer initializers. + initial_dense_weights_initializer = get_initializer_fn( + config.initial_dense_weights_initializer, framework="torch" + ) + initial_dense_bias_initializer = get_initializer_fn( + config.initial_dense_bias_initializer, framework="torch" + ) + + # Initialize dense layer weights, if necessary. + if initial_dense_weights_initializer: + initial_dense_weights_initializer( + self.initial_dense.weight, + **config.initial_dense_weights_initializer_config or {}, + ) + # Initialized dense layer bais, if necessary. + if initial_dense_bias_initializer: + initial_dense_bias_initializer( + self.initial_dense.bias, + **config.initial_dense_bias_initializer_config or {}, + ) + + # The main CNNTranspose stack. + self.cnn_transpose_net = TorchCNNTranspose( + input_dims=config.initial_image_dims, + cnn_transpose_filter_specifiers=config.cnn_transpose_filter_specifiers, + cnn_transpose_activation=config.cnn_transpose_activation, + cnn_transpose_use_layernorm=config.cnn_transpose_use_layernorm, + cnn_transpose_use_bias=config.cnn_transpose_use_bias, + cnn_transpose_kernel_initializer=config.cnn_transpose_kernel_initializer, + cnn_transpose_kernel_initializer_config=( + config.cnn_transpose_kernel_initializer_config + ), + cnn_transpose_bias_initializer=config.cnn_transpose_bias_initializer, + cnn_transpose_bias_initializer_config=( + config.cnn_transpose_bias_initializer_config + ), + ) + + @override(Model) + def _forward(self, inputs: torch.Tensor, **kwargs) -> torch.Tensor: + out = self.initial_dense(inputs) + # Reshape to initial 3D (image-like) format to enter CNN transpose stack. + out = out.reshape((-1,) + tuple(self.config.initial_image_dims)) + out = self.cnn_transpose_net(out) + # Add 0.5 to center (always non-activated, non-normalized) outputs more + # around 0.0. + return out + 0.5 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/primitives.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/primitives.py new file mode 100644 index 0000000000000000000000000000000000000000..9c4e5574351093e658cf08aa387c172ad4c042a4 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/primitives.py @@ -0,0 +1,479 @@ +from typing import Callable, Dict, List, Optional, Union, Tuple + +from ray.rllib.core.models.torch.utils import Stride2D +from ray.rllib.models.torch.misc import ( + same_padding, + same_padding_transpose_after_stride, + valid_padding, +) +from ray.rllib.models.utils import get_activation_fn, get_initializer_fn +from ray.rllib.utils.framework import try_import_torch + +torch, nn = try_import_torch() + + +class TorchMLP(nn.Module): + """A multi-layer perceptron with N dense layers. + + All layers (except for an optional additional extra output layer) share the same + activation function, bias setup (use bias or not), and LayerNorm setup + (use layer normalization or not). + + If `output_dim` (int) is not None, an additional, extra output dense layer is added, + which might have its own activation function (e.g. "linear"). However, the output + layer does NOT use layer normalization. + """ + + def __init__( + self, + *, + input_dim: int, + hidden_layer_dims: List[int], + hidden_layer_activation: Union[str, Callable] = "relu", + hidden_layer_use_bias: bool = True, + hidden_layer_use_layernorm: bool = False, + hidden_layer_weights_initializer: Optional[Union[str, Callable]] = None, + hidden_layer_weights_initializer_config: Optional[Union[str, Callable]] = None, + hidden_layer_bias_initializer: Optional[Union[str, Callable]] = None, + hidden_layer_bias_initializer_config: Optional[Dict] = None, + output_dim: Optional[int] = None, + output_use_bias: bool = True, + output_activation: Union[str, Callable] = "linear", + output_weights_initializer: Optional[Union[str, Callable]] = None, + output_weights_initializer_config: Optional[Dict] = None, + output_bias_initializer: Optional[Union[str, Callable]] = None, + output_bias_initializer_config: Optional[Dict] = None, + ): + """Initialize a TorchMLP object. + + Args: + input_dim: The input dimension of the network. Must not be None. + hidden_layer_dims: The sizes of the hidden layers. If an empty list, only a + single layer will be built of size `output_dim`. + hidden_layer_use_layernorm: Whether to insert a LayerNormalization + functionality in between each hidden layer's output and its activation. + hidden_layer_use_bias: Whether to use bias on all dense layers (excluding + the possible separate output layer). + hidden_layer_activation: The activation function to use after each layer + (except for the output). Either a torch.nn.[activation fn] callable or + the name thereof, or an RLlib recognized activation name, + e.g. "ReLU", "relu", "tanh", "SiLU", or "linear". + hidden_layer_weights_initializer: The initializer function or class to use + forweights initialization in the hidden layers. If `None` the default + initializer of the respective dense layer is used. Note, only the + in-place initializers, i.e. ending with an underscore "_" are allowed. + hidden_layer_weights_initializer_config: Configuration to pass into the + initializer defined in `hidden_layer_weights_initializer`. + hidden_layer_bias_initializer: The initializer function or class to use for + bias initialization in the hidden layers. If `None` the default + initializer of the respective dense layer is used. Note, only the + in-place initializers, i.e. ending with an underscore "_" are allowed. + hidden_layer_bias_initializer_config: Configuration to pass into the + initializer defined in `hidden_layer_bias_initializer`. + output_dim: The output dimension of the network. If None, no specific output + layer will be added and the last layer in the stack will have + size=`hidden_layer_dims[-1]`. + output_use_bias: Whether to use bias on the separate output layer, + if any. + output_activation: The activation function to use for the output layer + (if any). Either a torch.nn.[activation fn] callable or + the name thereof, or an RLlib recognized activation name, + e.g. "ReLU", "relu", "tanh", "SiLU", or "linear". + output_layer_weights_initializer: The initializer function or class to use + for weights initialization in the output layers. If `None` the default + initializer of the respective dense layer is used. Note, only the + in-place initializers, i.e. ending with an underscore "_" are allowed. + output_layer_weights_initializer_config: Configuration to pass into the + initializer defined in `output_layer_weights_initializer`. + output_layer_bias_initializer: The initializer function or class to use for + bias initialization in the output layers. If `None` the default + initializer of the respective dense layer is used. Note, only the + in-place initializers, i.e. ending with an underscore "_" are allowed. + output_layer_bias_initializer_config: Configuration to pass into the + initializer defined in `output_layer_bias_initializer`. + """ + super().__init__() + assert input_dim > 0 + + self.input_dim = input_dim + + hidden_activation = get_activation_fn( + hidden_layer_activation, framework="torch" + ) + hidden_weights_initializer = get_initializer_fn( + hidden_layer_weights_initializer, framework="torch" + ) + hidden_bias_initializer = get_initializer_fn( + hidden_layer_bias_initializer, framework="torch" + ) + output_weights_initializer = get_initializer_fn( + output_weights_initializer, framework="torch" + ) + output_bias_initializer = get_initializer_fn( + output_bias_initializer, framework="torch" + ) + + layers = [] + dims = ( + [self.input_dim] + + list(hidden_layer_dims) + + ([output_dim] if output_dim else []) + ) + for i in range(0, len(dims) - 1): + # Whether we are already processing the last (special) output layer. + is_output_layer = output_dim is not None and i == len(dims) - 2 + + layer = nn.Linear( + dims[i], + dims[i + 1], + bias=output_use_bias if is_output_layer else hidden_layer_use_bias, + ) + # Initialize layers, if necessary. + if is_output_layer: + # Initialize output layer weigths if necessary. + if output_weights_initializer: + output_weights_initializer( + layer.weight, **output_weights_initializer_config or {} + ) + # Initialize output layer bias if necessary. + if output_bias_initializer: + output_bias_initializer( + layer.bias, **output_bias_initializer_config or {} + ) + # Must be hidden. + else: + # Initialize hidden layer weights if necessary. + if hidden_layer_weights_initializer: + hidden_weights_initializer( + layer.weight, **hidden_layer_weights_initializer_config or {} + ) + # Initialize hidden layer bias if necessary. + if hidden_layer_bias_initializer: + hidden_bias_initializer( + layer.bias, **hidden_layer_bias_initializer_config or {} + ) + + layers.append(layer) + + # We are still in the hidden layer section: Possibly add layernorm and + # hidden activation. + if not is_output_layer: + # Insert a layer normalization in between layer's output and + # the activation. + if hidden_layer_use_layernorm: + # We use an epsilon of 0.001 here to mimick the Tf default behavior. + layers.append(nn.LayerNorm(dims[i + 1], eps=0.001)) + # Add the activation function. + if hidden_activation is not None: + layers.append(hidden_activation()) + + # Add output layer's (if any) activation. + output_activation = get_activation_fn(output_activation, framework="torch") + if output_dim is not None and output_activation is not None: + layers.append(output_activation()) + + self.mlp = nn.Sequential(*layers) + + def forward(self, x): + return self.mlp(x) + + +class TorchCNN(nn.Module): + """A model containing a CNN with N Conv2D layers. + + All layers share the same activation function, bias setup (use bias or not), + and LayerNorm setup (use layer normalization or not). + + Note that there is no flattening nor an additional dense layer at the end of the + stack. The output of the network is a 3D tensor of dimensions + [width x height x num output filters]. + """ + + def __init__( + self, + *, + input_dims: Union[List[int], Tuple[int]], + cnn_filter_specifiers: List[List[Union[int, List]]], + cnn_use_bias: bool = True, + cnn_use_layernorm: bool = False, + cnn_activation: str = "relu", + cnn_kernel_initializer: Optional[Union[str, Callable]] = None, + cnn_kernel_initializer_config: Optional[Dict] = None, + cnn_bias_initializer: Optional[Union[str, Callable]] = None, + cnn_bias_initializer_config: Optional[Dict] = None, + ): + """Initializes a TorchCNN instance. + + Args: + input_dims: The 3D input dimensions of the network (incoming image). + cnn_filter_specifiers: A list in which each element is another (inner) list + of either the following forms: + `[number of channels/filters, kernel, stride]` + OR: + `[number of channels/filters, kernel, stride, padding]`, where `padding` + can either be "same" or "valid". + When using the first format w/o the `padding` specifier, `padding` is + "same" by default. Also, `kernel` and `stride` may be provided either as + single ints (square) or as a tuple/list of two ints (width- and height + dimensions) for non-squared kernel/stride shapes. + A good rule of thumb for constructing CNN stacks is: + When using padding="same", the input "image" will be reduced in size by + the factor `stride`, e.g. input=(84, 84, 3) stride=2 kernel=x + padding="same" filters=16 -> output=(42, 42, 16). + For example, if you would like to reduce an Atari image from its + original (84, 84, 3) dimensions down to (6, 6, F), you can construct the + following stack and reduce the w x h dimension of the image by 2 in each + layer: + [[16, 4, 2], [32, 4, 2], [64, 4, 2], [128, 4, 2]] -> output=(6, 6, 128) + cnn_use_bias: Whether to use bias on all Conv2D layers. + cnn_activation: The activation function to use after each Conv2D layer. + cnn_use_layernorm: Whether to insert a LayerNormalization functionality + in between each Conv2D layer's outputs and its activation. + cnn_kernel_initializer: The initializer function or class to use for kernel + initialization in the CNN layers. If `None` the default initializer of + the respective CNN layer is used. Note, only the in-place + initializers, i.e. ending with an underscore "_" are allowed. + cnn_kernel_initializer_config: Configuration to pass into the initializer + defined in `cnn_kernel_initializer`. + cnn_bias_initializer: The initializer function or class to use for bias + initializationcin the CNN layers. If `None` the default initializer of + the respective CNN layer is used. Note, only the in-place initializers, + i.e. ending with an underscore "_" are allowed. + cnn_bias_initializer_config: Configuration to pass into the initializer + defined in `cnn_bias_initializer`. + """ + super().__init__() + + assert len(input_dims) == 3 + + cnn_activation = get_activation_fn(cnn_activation, framework="torch") + cnn_kernel_initializer = get_initializer_fn( + cnn_kernel_initializer, framework="torch" + ) + cnn_bias_initializer = get_initializer_fn( + cnn_bias_initializer, framework="torch" + ) + layers = [] + + # Add user-specified hidden convolutional layers first + width, height, in_depth = input_dims + in_size = [width, height] + for filter_specs in cnn_filter_specifiers: + # Padding information not provided -> Use "same" as default. + if len(filter_specs) == 3: + out_depth, kernel_size, strides = filter_specs + padding = "same" + # Padding information provided. + else: + out_depth, kernel_size, strides, padding = filter_specs + + # Pad like in tensorflow's SAME/VALID mode. + if padding == "same": + padding_size, out_size = same_padding(in_size, kernel_size, strides) + layers.append(nn.ZeroPad2d(padding_size)) + # No actual padding is performed for "valid" mode, but we will still + # compute the output size (input for the next layer). + else: + out_size = valid_padding(in_size, kernel_size, strides) + + layer = nn.Conv2d( + in_depth, out_depth, kernel_size, strides, bias=cnn_use_bias + ) + + # Initialize CNN layer kernel if necessary. + if cnn_kernel_initializer: + cnn_kernel_initializer( + layer.weight, **cnn_kernel_initializer_config or {} + ) + # Initialize CNN layer bias if necessary. + if cnn_bias_initializer: + cnn_bias_initializer(layer.bias, **cnn_bias_initializer_config or {}) + + layers.append(layer) + + # Layernorm. + if cnn_use_layernorm: + # We use an epsilon of 0.001 here to mimick the Tf default behavior. + layers.append(LayerNorm1D(out_depth, eps=0.001)) + # Activation. + if cnn_activation is not None: + layers.append(cnn_activation()) + + in_size = out_size + in_depth = out_depth + + # Create the CNN. + self.cnn = nn.Sequential(*layers) + + def forward(self, inputs): + # Permute b/c data comes in as channels_last ([B, dim, dim, channels]) -> + # Convert to `channels_first` for torch: + inputs = inputs.permute(0, 3, 1, 2) + out = self.cnn(inputs) + # Permute back to `channels_last`. + return out.permute(0, 2, 3, 1) + + +class TorchCNNTranspose(nn.Module): + """A model containing a CNNTranspose with N Conv2DTranspose layers. + + All layers share the same activation function, bias setup (use bias or not), + and LayerNormalization setup (use layer normalization or not), except for the last + one, which is never activated and never layer norm'd. + + Note that there is no reshaping/flattening nor an additional dense layer at the + beginning or end of the stack. The input as well as output of the network are 3D + tensors of dimensions [width x height x num output filters]. + """ + + def __init__( + self, + *, + input_dims: Union[List[int], Tuple[int]], + cnn_transpose_filter_specifiers: List[List[Union[int, List]]], + cnn_transpose_use_bias: bool = True, + cnn_transpose_activation: str = "relu", + cnn_transpose_use_layernorm: bool = False, + cnn_transpose_kernel_initializer: Optional[Union[str, Callable]] = None, + cnn_transpose_kernel_initializer_config: Optional[Dict] = None, + cnn_transpose_bias_initializer: Optional[Union[str, Callable]] = None, + cnn_transpose_bias_initializer_config: Optional[Dict] = None, + ): + """Initializes a TorchCNNTranspose instance. + + Args: + input_dims: The 3D input dimensions of the network (incoming image). + cnn_transpose_filter_specifiers: A list of lists, where each item represents + one Conv2DTranspose layer. Each such Conv2DTranspose layer is further + specified by the elements of the inner lists. The inner lists follow + the format: `[number of filters, kernel, stride]` to + specify a convolutional-transpose layer stacked in order of the + outer list. + `kernel` as well as `stride` might be provided as width x height tuples + OR as single ints representing both dimension (width and height) + in case of square shapes. + cnn_transpose_use_bias: Whether to use bias on all Conv2DTranspose layers. + cnn_transpose_use_layernorm: Whether to insert a LayerNormalization + functionality in between each Conv2DTranspose layer's outputs and its + activation. + The last Conv2DTranspose layer will not be normed, regardless. + cnn_transpose_activation: The activation function to use after each layer + (except for the last Conv2DTranspose layer, which is always + non-activated). + cnn_transpose_kernel_initializer: The initializer function or class to use + for kernel initialization in the CNN layers. If `None` the default + initializer of the respective CNN layer is used. Note, only the + in-place initializers, i.e. ending with an underscore "_" are allowed. + cnn_transpose_kernel_initializer_config: Configuration to pass into the + initializer defined in `cnn_transpose_kernel_initializer`. + cnn_transpose_bias_initializer: The initializer function or class to use for + bias initialization in the CNN layers. If `None` the default initializer + of the respective CNN layer is used. Note, only the in-place + initializers, i.e. ending with an underscore "_" are allowed. + cnn_transpose_bias_initializer_config: Configuration to pass into the + initializer defined in `cnn_transpose_bias_initializer`. + """ + super().__init__() + + assert len(input_dims) == 3 + + cnn_transpose_activation = get_activation_fn( + cnn_transpose_activation, framework="torch" + ) + cnn_transpose_kernel_initializer = get_initializer_fn( + cnn_transpose_kernel_initializer, framework="torch" + ) + cnn_transpose_bias_initializer = get_initializer_fn( + cnn_transpose_bias_initializer, framework="torch" + ) + + layers = [] + + # Add user-specified hidden convolutional layers first + width, height, in_depth = input_dims + in_size = [width, height] + for i, (out_depth, kernel, stride) in enumerate( + cnn_transpose_filter_specifiers + ): + is_final_layer = i == len(cnn_transpose_filter_specifiers) - 1 + + # Resolve stride and kernel width/height values if only int given (squared). + s_w, s_h = (stride, stride) if isinstance(stride, int) else stride + k_w, k_h = (kernel, kernel) if isinstance(kernel, int) else kernel + + # Stride the incoming image first. + stride_layer = Stride2D(in_size[0], in_size[1], s_w, s_h) + layers.append(stride_layer) + # Then 0-pad (like in tensorflow's SAME mode). + # This will return the necessary padding such that for stride=1, the output + # image has the same size as the input image, for stride=2, the output image + # is 2x the input image, etc.. + padding, out_size = same_padding_transpose_after_stride( + (stride_layer.out_width, stride_layer.out_height), kernel, stride + ) + layers.append(nn.ZeroPad2d(padding)) # left, right, top, bottom + # Then do the Conv2DTranspose operation + # (now that we have padded and strided manually, w/o any more padding using + # stride=1). + + layer = nn.ConvTranspose2d( + in_depth, + out_depth, + kernel, + # Force-set stride to 1 as we already took care of it. + 1, + # Disable torch auto-padding (torch interprets the padding setting + # as: dilation (==1.0) * [`kernel` - 1] - [`padding`]). + padding=(k_w - 1, k_h - 1), + # Last layer always uses bias (b/c has no LayerNorm, regardless of + # config). + bias=cnn_transpose_use_bias or is_final_layer, + ) + + # Initialize CNN Transpose layer kernel if necessary. + if cnn_transpose_kernel_initializer: + cnn_transpose_kernel_initializer( + layer.weight, **cnn_transpose_kernel_initializer_config or {} + ) + # Initialize CNN Transpose layer bias if necessary. + if cnn_transpose_bias_initializer: + cnn_transpose_bias_initializer( + layer.bias, **cnn_transpose_bias_initializer_config or {} + ) + + layers.append(layer) + # Layernorm (never for final layer). + if cnn_transpose_use_layernorm and not is_final_layer: + layers.append(LayerNorm1D(out_depth, eps=0.001)) + # Last layer is never activated (regardless of config). + if cnn_transpose_activation is not None and not is_final_layer: + layers.append(cnn_transpose_activation()) + + in_size = (out_size[0], out_size[1]) + in_depth = out_depth + + # Create the final CNNTranspose network. + self.cnn_transpose = nn.Sequential(*layers) + + def forward(self, inputs): + # Permute b/c data comes in as [B, dim, dim, channels]: + out = inputs.permute(0, 3, 1, 2) + out = self.cnn_transpose(out) + return out.permute(0, 2, 3, 1) + + +class LayerNorm1D(nn.Module): + def __init__(self, num_features, **kwargs): + super().__init__() + self.layer_norm = nn.LayerNorm(num_features, **kwargs) + + def forward(self, x): + # x shape: (B, dim, dim, channels). + batch_size, channels, h, w = x.size() + # Reshape to (batch_size * height * width, channels) for LayerNorm + x = x.permute(0, 2, 3, 1).reshape(-1, channels) + # Apply LayerNorm + x = self.layer_norm(x) + # Reshape back to (batch_size, dim, dim, channels) + x = x.reshape(batch_size, h, w, channels).permute(0, 3, 1, 2) + return x diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1bdbdef016f4c8a7261ff83f14d9c70810d6a90e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/models/torch/utils.py @@ -0,0 +1,85 @@ +from ray.rllib.utils.framework import try_import_torch + +torch, nn = try_import_torch() + + +class Stride2D(nn.Module): + """A striding layer for doing torch Conv2DTranspose operations. + + Using this layer before the 0-padding (on a 3D input "image") and before + the actual ConvTranspose2d allows for a padding="same" behavior that matches + 100% that of a `tf.keras.layers.Conv2DTranspose` layer. + + Examples: + Input image (4x4): + A B C D + E F G H + I J K L + M N O P + + Stride with stride=2 -> output image=(7x7) + A 0 B 0 C 0 D + 0 0 0 0 0 0 0 + E 0 F 0 G 0 H + 0 0 0 0 0 0 0 + I 0 J 0 K 0 L + 0 0 0 0 0 0 0 + M 0 N 0 O 0 P + """ + + def __init__(self, width, height, stride_w, stride_h): + """Initializes a Stride2D instance. + + Args: + width: The width of the 3D input "image". + height: The height of the 3D input "image". + stride_w: The stride in width direction, with which to stride the incoming + image. + stride_h: The stride in height direction, with which to stride the incoming + image. + """ + super().__init__() + + self.width = width + self.height = height + self.stride_w = stride_w + self.stride_h = stride_h + + self.register_buffer( + "zeros", + torch.zeros( + size=( + self.width * self.stride_w - (self.stride_w - 1), + self.height * self.stride_h - (self.stride_h - 1), + ), + dtype=torch.float32, + ), + ) + + self.out_width, self.out_height = self.zeros.shape[0], self.zeros.shape[1] + # Squeeze in batch and channel dims. + self.zeros = self.zeros.unsqueeze(0).unsqueeze(0) + + where_template = torch.zeros( + (self.stride_w, self.stride_h), dtype=torch.float32 + ) + # Set upper/left corner to 1.0. + where_template[0][0] = 1.0 + # then tile across the entire (strided) image size. + where_template = where_template.repeat((self.height, self.width))[ + : -(self.stride_w - 1), : -(self.stride_h - 1) + ] + # Squeeze in batch and channel dims and convert to bool. + where_template = where_template.unsqueeze(0).unsqueeze(0).bool() + self.register_buffer("where_template", where_template) + + def forward(self, x): + # Repeat incoming image stride(w/h) times to match the strided output template. + repeated_x = ( + x.repeat_interleave(self.stride_w, dim=-2).repeat_interleave( + self.stride_h, dim=-1 + ) + )[:, :, : -(self.stride_w - 1), : -(self.stride_h - 1)] + # Where `self.where_template` == 1.0 -> Use image pixel, otherwise use + # zero filler value. + return torch.where(self.where_template, repeated_x, self.zeros) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..490cd7942947d8cc14625fe069893f8347697b12 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/__init__.py @@ -0,0 +1,53 @@ +import logging +import re + +from ray.rllib.core.rl_module.rl_module import RLModule, RLModuleSpec +from ray.rllib.core.rl_module.multi_rl_module import ( + MultiRLModule, + MultiRLModuleSpec, +) +from ray.util import log_once +from ray.util.annotations import DeveloperAPI + +logger = logging.getLogger("ray.rllib") + + +@DeveloperAPI +def validate_module_id(policy_id: str, error: bool = False) -> None: + """Makes sure the given `policy_id` is valid. + + Args: + policy_id: The Policy ID to check. + IMPORTANT: Must not contain characters that + are also not allowed in Unix/Win filesystems, such as: `<>:"/\\|?*` + or a dot `.` or space ` ` at the end of the ID. + error: Whether to raise an error (ValueError) or a warning in case of an + invalid `policy_id`. + + Raises: + ValueError: If the given `policy_id` is not a valid one and `error` is True. + """ + if ( + not isinstance(policy_id, str) + or len(policy_id) == 0 + or re.search('[<>:"/\\\\|?]', policy_id) + or policy_id[-1] in (" ", ".") + ): + msg = ( + f"PolicyID `{policy_id}` not valid! IDs must be a non-empty string, " + "must not contain characters that are also disallowed file- or directory " + "names on Unix/Windows and must not end with a dot `.` or a space ` `." + ) + if error: + raise ValueError(msg) + elif log_once("invalid_policy_id"): + logger.warning(msg) + + +__all__ = [ + "MultiRLModule", + "MultiRLModuleSpec", + "RLModule", + "RLModuleSpec", + "validate_module_id", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..217c1ad7d81d6d65227d32daaa7c3951b0f63ba7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/__pycache__/default_model_config.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/__pycache__/default_model_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3140b6b3ff7175dfda15845ffa02f9deac27af5d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/__pycache__/default_model_config.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/__pycache__/multi_rl_module.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/__pycache__/multi_rl_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37b4af42a06a51f07f2e65cf827d16bf1ba2c5a8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/__pycache__/multi_rl_module.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/__pycache__/rl_module.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/__pycache__/rl_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab75953e4dad35e7fb973bc79584e0601afd1e1e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/__pycache__/rl_module.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4e51e91a1b11e2c0d37a66d8cd7ff904ef2fcf6e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/__init__.py @@ -0,0 +1,18 @@ +from ray.rllib.core.rl_module.apis.inference_only_api import InferenceOnlyAPI +from ray.rllib.core.rl_module.apis.q_net_api import QNetAPI +from ray.rllib.core.rl_module.apis.self_supervised_loss_api import SelfSupervisedLossAPI +from ray.rllib.core.rl_module.apis.target_network_api import ( + TargetNetworkAPI, + TARGET_NETWORK_ACTION_DIST_INPUTS, +) +from ray.rllib.core.rl_module.apis.value_function_api import ValueFunctionAPI + + +__all__ = [ + "InferenceOnlyAPI", + "QNetAPI", + "SelfSupervisedLossAPI", + "TargetNetworkAPI", + "TARGET_NETWORK_ACTION_DIST_INPUTS", + "ValueFunctionAPI", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4fc56dee3487e744ae91ea489de7b7fb9a1136e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/__pycache__/inference_only_api.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/__pycache__/inference_only_api.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1b7f45181c98582501e66fa66e793d25a1e7f8b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/__pycache__/inference_only_api.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/__pycache__/q_net_api.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/__pycache__/q_net_api.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4575d68ff178f8e819cba669772826ade500d172 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/__pycache__/q_net_api.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/__pycache__/self_supervised_loss_api.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/__pycache__/self_supervised_loss_api.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7836d97d09b23573cee4fc88020583c0229ca2c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/__pycache__/self_supervised_loss_api.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/__pycache__/target_network_api.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/__pycache__/target_network_api.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f459b4a7d4cf10f42956c89eb5d8d32aff46565 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/__pycache__/target_network_api.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/__pycache__/value_function_api.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/__pycache__/value_function_api.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ba682cc015084f6ea884d5e6a9c86111be0de05 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/__pycache__/value_function_api.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/inference_only_api.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/inference_only_api.py new file mode 100644 index 0000000000000000000000000000000000000000..723c1e3480c236764828c3e5ef4cd48e6189b46a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/inference_only_api.py @@ -0,0 +1,64 @@ +import abc +from typing import List + +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class InferenceOnlyAPI(abc.ABC): + """An API to be implemented by RLModules that have an inference-only mode. + + Only the `get_non_inference_attributes` method needs to get implemented for + an RLModule to have the following functionality: + - On EnvRunners (or when self.inference_only=True), RLlib will remove + those parts of the model not required for action computation. + - An RLModule on a Learner (where `self.inference_only=False`) will + return only those weights from `get_state()` that are part of its inference-only + version, thus possibly saving network traffic/time. + """ + + @abc.abstractmethod + def get_non_inference_attributes(self) -> List[str]: + """Returns a list of attribute names (str) of components NOT used for inference. + + RLlib will use this information to remove those attributes/components from an + RLModule, whose `config.inference_only` is set to True. This so-called + "inference-only setup" is activated. Normally, all RLModules located on + EnvRunners are constructed this way (because they are only used for computing + actions). Similarly, when deployed into a production environment, users should + consider building their RLModules with this flag set to True as well. + + For example: + + .. code-block:: python + + from ray.rllib.core.rl_module.rl_module import RLModuleSpec + + spec = RLModuleSpec(module_class=..., inference_only=True) + + If an RLModule has the following setup() implementation: + + .. testcode:: + :skipif: True + + class MyRLModule(RLModule): + + def setup(self): + self._policy_head = [some NN component] + self._value_function_head = [some NN component] + + self._encoder = [some NN component with attributes: pol and vf + (policy- and value func. encoder)] + + Then its `get_non_inference_attributes()` should return: + ["_value_function_head", "_encoder.vf"]. + + Note the "." notation to separate attributes and their sub-attributes in case + you need more fine-grained control over which exact sub-attributes to exclude in + the inference-only setup. + + Returns: + A list of names (str) of those attributes (or sub-attributes) that should be + excluded (deleted) from this RLModule in case it's setup in + `inference_only` mode. + """ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/q_net_api.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/q_net_api.py new file mode 100644 index 0000000000000000000000000000000000000000..88fb1a00c0fe7c27e4ca72b594d6f548940fe56f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/q_net_api.py @@ -0,0 +1,56 @@ +import abc +from typing import Dict + +from ray.rllib.utils.typing import TensorType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class QNetAPI(abc.ABC): + """An API to be implemented by RLModules used for (distributional) Q-learning. + + RLModules implementing this API must override the `compute_q_values` and the + `compute_advantage_distribution` methods. + """ + + @abc.abstractmethod + def compute_q_values( + self, + batch: Dict[str, TensorType], + ) -> Dict[str, TensorType]: + """Computes Q-values, given encoder, q-net and (optionally), advantage net. + + Note, these can be accompanied by logits and probabilities + in case of distributional Q-learning, i.e. `self.num_atoms > 1`. + + Args: + batch: The batch received in the forward pass. + + Results: + A dictionary containing the Q-value predictions ("qf_preds") + and in case of distributional Q-learning - in addition to the Q-value + predictions ("qf_preds") - the support atoms ("atoms"), the Q-logits + ("qf_logits"), and the probabilities ("qf_probs"). + """ + + def compute_advantage_distribution( + self, + batch: Dict[str, TensorType], + ) -> Dict[str, TensorType]: + """Computes the advantage distribution. + + Note this distribution is identical to the Q-distribution in case no dueling + architecture is used. + + Args: + batch: A dictionary containing a tensor with the outputs of the + forward pass of the Q-head or advantage stream head. + + Returns: + A `dict` containing the support of the discrete distribution for + either Q-values or advantages (in case of a dueling architecture), + ("atoms"), the logits per action and atom and the probabilities + of the discrete distribution (per action and atom of the support). + """ + # Return the Q-distribution by default. + return self.compute_q_values(batch) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/self_supervised_loss_api.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/self_supervised_loss_api.py new file mode 100644 index 0000000000000000000000000000000000000000..6f1785a426c919cb7c61bf0edea308c44b7bdcb0 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/self_supervised_loss_api.py @@ -0,0 +1,55 @@ +import abc +from typing import Any, Dict, TYPE_CHECKING + +from ray.rllib.utils.typing import ModuleID, TensorType +from ray.util.annotations import PublicAPI + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + from ray.rllib.core.learner.learner import Learner + + +@PublicAPI(stability="alpha") +class SelfSupervisedLossAPI(abc.ABC): + """An API to be implemented by RLModules that bring their own self-supervised loss. + + Learners will call these model's `compute_self_supervised_loss()` method instead of + the Learner's own `compute_loss_for_module()` method. + The call signature is identical to the Learner's `compute_loss_for_module()` method + except of an additional mandatory `learner` kwarg. + """ + + @abc.abstractmethod + def compute_self_supervised_loss( + self, + *, + learner: "Learner", + module_id: ModuleID, + config: "AlgorithmConfig", + batch: Dict[str, Any], + fwd_out: Dict[str, TensorType], + **kwargs, + ) -> TensorType: + """Computes the loss for a single module. + + Think of this as computing loss for a single agent. For multi-agent use-cases + that require more complicated computation for loss, consider overriding the + `compute_losses` method instead. + + Args: + learner: The Learner calling this loss method on the RLModule. + module_id: The ID of the RLModule (within a MultiRLModule). + config: The AlgorithmConfig specific to the given `module_id`. + batch: The sample batch for this particular RLModule. + fwd_out: The output of the forward pass for this particular RLModule. + + Returns: + A single total loss tensor. If you have more than one optimizer on the + provided `module_id` and would like to compute gradients separately using + these different optimizers, simply add up the individual loss terms for + each optimizer and return the sum. Also, for recording/logging any + individual loss terms, you can use the `Learner.metrics.log_value( + key=..., value=...)` or `Learner.metrics.log_dict()` APIs. See: + :py:class:`~ray.rllib.utils.metrics.metrics_logger.MetricsLogger` for more + information. + """ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/target_network_api.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/target_network_api.py new file mode 100644 index 0000000000000000000000000000000000000000..d1615edff1e039236a67bb841e495289fbbdbeb1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/target_network_api.py @@ -0,0 +1,57 @@ +import abc +from typing import Any, Dict, List, Tuple + +from ray.rllib.utils.typing import NetworkType +from ray.util.annotations import PublicAPI + + +TARGET_NETWORK_ACTION_DIST_INPUTS = "target_network_action_dist_inputs" + + +@PublicAPI(stability="alpha") +class TargetNetworkAPI(abc.ABC): + """An API to be implemented by RLModules for handling target networks. + + RLModules implementing this API must override the `make_target_networks`, + `get_target_network_pairs`, and the `forward_target` methods. + + Note that the respective Learner that owns the implementing RLModule handles all + target syncing logic. + """ + + @abc.abstractmethod + def make_target_networks(self) -> None: + """Creates the required target nets for this RLModule. + + Use the convenience `ray.rllib.core.learner.utils.make_target_network()` utility + when implementing this method. Pass in an already existing, corresponding "main" + net (for which you need a target net). + This function already takes care of initialization (from the "main" net). + """ + + @abc.abstractmethod + def get_target_network_pairs(self) -> List[Tuple[NetworkType, NetworkType]]: + """Returns a list of 2-tuples of (main_net, target_net). + + For example, if your RLModule has a property: `self.q_net` and this network + has a corresponding target net `self.target_q_net`, return from this + (overridden) method: [(self.q_net, self.target_q_net)]. + + Note that you need to create all target nets in your overridden + `make_target_networks` method and store the target nets in any properly of your + choice. + + Returns: + A list of 2-tuples of (main_net, target_net) + """ + + @abc.abstractmethod + def forward_target(self, batch: Dict[str, Any]) -> Dict[str, Any]: + """Performs the forward pass through the target net(s). + + Args: + batch: The batch to use for the forward pass. + + Returns: + The results from the forward pass(es) through the target net(s). + """ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/value_function_api.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/value_function_api.py new file mode 100644 index 0000000000000000000000000000000000000000..46e33d2fd315fe75e555e1629d4a1e4a0e44324b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/apis/value_function_api.py @@ -0,0 +1,35 @@ +import abc +from typing import Any, Dict, Optional + +from ray.rllib.utils.typing import TensorType +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class ValueFunctionAPI(abc.ABC): + """An API to be implemented by RLModules for handling value function-based learning. + + RLModules implementing this API must override the `compute_values` method. + """ + + @abc.abstractmethod + def compute_values( + self, + batch: Dict[str, Any], + embeddings: Optional[Any] = None, + ) -> TensorType: + """Computes the value estimates given `batch`. + + Args: + batch: The batch to compute value function estimates for. + embeddings: Optional embeddings already computed from the `batch` (by + another forward pass through the model's encoder (or other subcomponent + that computes an embedding). For example, the caller of thie method + should provide `embeddings` - if available - to avoid duplicate passes + through a shared encoder. + + Returns: + A tensor of shape (B,) or (B, T) (in case the input `batch` has a + time dimension. Note that the last value dimension should already be + squeezed out (not 1!). + """ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/default_model_config.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/default_model_config.py new file mode 100644 index 0000000000000000000000000000000000000000..e53b852a4e7b5ec3c25a2b713e8779d8cdec834e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/default_model_config.py @@ -0,0 +1,204 @@ +from dataclasses import dataclass, field +from typing import Callable, List, Optional, Union + +from ray.rllib.utils.typing import ConvFilterSpec +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +@dataclass +class DefaultModelConfig: + """Dataclass to configure all default RLlib RLModules. + + Users should NOT use this class for configuring their own custom RLModules, but + use a custom `model_config` dict with arbitrary (str) keys passed into the + `RLModuleSpec` used to define the custom RLModule. + For example: + + .. testcode:: + + import gymnasium as gym + import numpy as np + from ray.rllib.core.rl_module.rl_module import RLModuleSpec + from ray.rllib.examples.rl_modules.classes.tiny_atari_cnn_rlm import ( + TinyAtariCNN + ) + + my_rl_module = RLModuleSpec( + module_class=TinyAtariCNN, + observation_space=gym.spaces.Box(-1.0, 1.0, (64, 64, 4), np.float32), + action_space=gym.spaces.Discrete(7), + # DreamerV3-style stack working on a 64x64, color or 4x-grayscale-stacked, + # normalized image. + model_config={ + "conv_filters": [[16, 4, 2], [32, 4, 2], [64, 4, 2], [128, 4, 2]], + }, + ).build() + + Only RLlib's default RLModules (defined by the various algorithms) should use + this dataclass. Pass an instance of it into your algorithm config like so: + + .. testcode:: + + from ray.rllib.algorithms.ppo import PPOConfig + from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig + + config = ( + PPOConfig() + .rl_module( + model_config=DefaultModelConfig(fcnet_hiddens=[32, 32]), + ) + ) + """ + + # ==================================================== + # MLP stacks + # ==================================================== + # __sphinx_doc_default_model_config_fcnet_begin__ + #: List containing the sizes (number of nodes) of a fully connected (MLP) stack. + #: Note that in an encoder-based default architecture with a policy head (and + #: possible value head), this setting only affects the encoder component. To set the + #: policy (and value) head sizes, use `post_fcnet_hiddens`, instead. For example, + #: if you set `fcnet_hiddens=[32, 32]` and `post_fcnet_hiddens=[64]`, you would get + #: an RLModule with a [32, 32] encoder, a [64, act-dim] policy head, and a [64, 1] + #: value head (if applicable). + fcnet_hiddens: List[int] = field(default_factory=lambda: [256, 256]) + #: Activation function descriptor for the stack configured by `fcnet_hiddens`. + #: Supported values are: 'tanh', 'relu', 'swish' (or 'silu', which is the same), + #: and 'linear' (or None). + fcnet_activation: str = "tanh" + #: Initializer function or class descriptor for the weight/kernel matrices in the + #: stack configured by `fcnet_hiddens`. Supported values are the initializer names + #: (str), classes or functions listed by the frameworks (`torch`). See + #: https://pytorch.org/docs/stable/nn.init.html for `torch`. If `None` (default), + #: the default initializer defined by `torch` is used. + fcnet_kernel_initializer: Optional[Union[str, Callable]] = None + #: Kwargs passed into the initializer function defined through + #: `fcnet_kernel_initializer`. + fcnet_kernel_initializer_kwargs: Optional[dict] = None + #: Initializer function or class descriptor for the bias vectors in the stack + #: configured by `fcnet_hiddens`. Supported values are the initializer names (str), + #: classes or functions listed by the frameworks (`torch`). See + #: https://pytorch.org/docs/stable/nn.init.html for `torch`. If `None` (default), + #: the default initializer defined by `torch` is used. + fcnet_bias_initializer: Optional[Union[str, Callable]] = None + #: Kwargs passed into the initializer function defined through + #: `fcnet_bias_initializer`. + fcnet_bias_initializer_kwargs: Optional[dict] = None + # __sphinx_doc_default_model_config_fcnet_end__ + + # ==================================================== + # Conv2D stacks + # ==================================================== + # __sphinx_doc_default_model_config_conv_begin__ + #: List of lists of format [num_out_channels, kernel, stride] defining a Conv2D + #: stack if the input space is 2D. Each item in the outer list represents one Conv2D + #: layer. `kernel` and `stride` may be single ints (width and height have same + #: value) or 2-tuples (int, int) specifying width and height dimensions separately. + #: If None (default) and the input space is 2D, RLlib tries to find a default filter + #: setup given the exact input dimensions. + conv_filters: Optional[ConvFilterSpec] = None + #: Activation function descriptor for the stack configured by `conv_filters`. + #: Supported values are: 'tanh', 'relu', 'swish' (or 'silu', which is the same), and + #: 'linear' (or None). + conv_activation: str = "relu" + #: Initializer function or class descriptor for the weight/kernel matrices in the + #: stack configured by `conv_filters`. Supported values are the initializer names + #: (str), classes or functions listed by the frameworks (`torch`). See + #: https://pytorch.org/docs/stable/nn.init.html for `torch`. If `None` (default), + #: the default initializer defined by `torch` is used. + conv_kernel_initializer: Optional[Union[str, Callable]] = None + #: Kwargs passed into the initializer function defined through + #: `conv_kernel_initializer`. + conv_kernel_initializer_kwargs: Optional[dict] = None + #: Initializer function or class descriptor for the bias vectors in the stack + #: configured by `conv_filters`. Supported values are the initializer names (str), + #: classes or functions listed by the frameworks (`torch`). See + #: https://pytorch.org/docs/stable/nn.init.html for `torch`. If `None` (default), + #: the default initializer defined by `torch` is used. + conv_bias_initializer: Optional[Union[str, Callable]] = None + #: Kwargs passed into the initializer function defined through + #: `conv_bias_initializer`. + conv_bias_initializer_kwargs: Optional[dict] = None + # __sphinx_doc_default_model_config_conv_end__ + + # ==================================================== + # Head configs (e.g. policy- or value function heads) + # ==================================================== + #: List containing the sizes (number of nodes) of a fully connected (MLP) head (ex. + #: policy-, value-, or Q-head). Note that in order to configure the encoder + #: architecture, use `fcnet_hiddens`, instead. + head_fcnet_hiddens: List[int] = field(default_factory=lambda: []) + #: Activation function descriptor for the stack configured by `head_fcnet_hiddens`. + #: Supported values are: 'tanh', 'relu', 'swish' (or 'silu', which is the same), + #: and 'linear' (or None). + head_fcnet_activation: str = "relu" + #: Initializer function or class descriptor for the weight/kernel matrices in the + #: stack configured by `head_fcnet_hiddens`. Supported values are the initializer + #: names (str), classes or functions listed by the frameworks (`torch`). See + #: https://pytorch.org/docs/stable/nn.init.html for `torch`. If `None` (default), + #: the default initializer defined by `torch` is used. + head_fcnet_kernel_initializer: Optional[Union[str, Callable]] = None + #: Kwargs passed into the initializer function defined through + #: `head_fcnet_kernel_initializer`. + head_fcnet_kernel_initializer_kwargs: Optional[dict] = None + #: Initializer function or class descriptor for the bias vectors in the stack + #: configured by `head_fcnet_hiddens`. Supported values are the initializer names + #: (str), classes or functions listed by the frameworks (`torch`). See + #: https://pytorch.org/docs/stable/nn.init.html for `torch`. If `None` (default), + #: the default initializer defined by `torch` is used. + head_fcnet_bias_initializer: Optional[Union[str, Callable]] = None + #: Kwargs passed into the initializer function defined through + #: `head_fcnet_bias_initializer`. + head_fcnet_bias_initializer_kwargs: Optional[dict] = None + + # ==================================================== + # Continuous action settings + # ==================================================== + #: If True, for DiagGaussian action distributions (or any other continuous control + #: distribution), make the second half of the policy's outputs a "free" bias + #: parameter, rather than state-/NN-dependent nodes. In this case, the number of + #: nodes of the policy head have the same dimension as the action space as no slots + #: for log(stddev) are required (only for the mean values). + free_log_std: bool = False + #: Whether to clip the log(stddev) when using a DiagGaussian action distribution + #: (or any other continuous control distribution). This can stabilize training and + #: avoid very small or large log(stddev) values leading to numerical instabilities + #: turning outputs to `nan`. The default is to clamp the log(stddev) in between + #: -20 and 20. Set to float("inf") for no clamping. + log_std_clip_param: float = 20.0 + #: Whether encoder layers (defined by `fcnet_hiddens` or `conv_filters`) should be + #: shared between policy- and value function. + vf_share_layers: bool = True + + # ==================================================== + # LSTM settings + # ==================================================== + #: Whether to wrap the encoder component (defined by `fcnet_hiddens` or + #: `conv_filters`) with an LSTM. + use_lstm: bool = False + #: The maximum seq len for building the train batch for an LSTM model. + #: Defaults to 20. + max_seq_len: int = 20 + #: The size of the LSTM cell. + lstm_cell_size: int = 256 + lstm_use_prev_action: bool = False + lstm_use_prev_reward: bool = False + #: Initializer function or class descriptor for the weight/kernel matrices in the + #: LSTM layer. Supported values are the initializer names (str), classes or + #: functions listed by the frameworks (`torch`). See + #: https://pytorch.org/docs/stable/nn.init.html for `torch`. If `None` (default), + #: the default initializer defined by `torch` is used. + lstm_kernel_initializer: Optional[Union[str, Callable]] = None + #: Kwargs passed into the initializer function defined through + #: `lstm_kernel_initializer`. + lstm_kernel_initializer_kwargs: Optional[dict] = None + #: Initializer function or class descriptor for the bias vectors in the stack + #: configured by the LSTM layer. Supported values are the initializer names (str), + #: classes or functions listed by the frameworks (`torch`). See + #: https://pytorch.org/docs/stable/nn.init.html for `torch`. If `None` (default), + #: the default initializer defined by `torch` is used. + lstm_bias_initializer: Optional[Union[str, Callable]] = None + #: Kwargs passed into the initializer function defined through + #: `lstm_bias_initializer`. + lstm_bias_initializer_kwargs: Optional[dict] = None diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/multi_rl_module.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/multi_rl_module.py new file mode 100644 index 0000000000000000000000000000000000000000..c444f411b45a3d931430b4d2e783e937fa2db5a2 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/multi_rl_module.py @@ -0,0 +1,832 @@ +import copy +import dataclasses +import logging +import pprint +from typing import ( + Any, + Callable, + Collection, + Dict, + ItemsView, + KeysView, + List, + Optional, + Set, + Tuple, + Type, + Union, + ValuesView, +) + +import gymnasium as gym + +from ray.rllib.core.rl_module.rl_module import RLModule, RLModuleSpec +from ray.rllib.utils import force_list +from ray.rllib.utils.annotations import ( + override, + OverrideToImplementCustomLogic, +) +from ray.rllib.utils.checkpoints import Checkpointable +from ray.rllib.utils.deprecation import ( + Deprecated, + DEPRECATED_VALUE, + deprecation_warning, +) +from ray.rllib.utils.serialization import ( + gym_space_from_dict, + gym_space_to_dict, + serialize_type, + deserialize_type, +) +from ray.rllib.utils.typing import ModuleID, StateDict, T +from ray.util.annotations import PublicAPI + +logger = logging.getLogger("ray.rllib") + + +@PublicAPI(stability="alpha") +class MultiRLModule(RLModule): + """Base class for an RLModule that contains n sub-RLModules. + + This class holds a mapping from ModuleID to underlying RLModules. It provides + a convenient way of accessing each individual module, as well as accessing all of + them with only one API call. Whether a given module is trainable is + determined by the caller of this class (not the instance of this class itself). + + The extension of this class can include any arbitrary neural networks as part of + the MultiRLModule. For example, a MultiRLModule can include a shared encoder network + that is used by all the individual (single-agent) RLModules. It is up to the user + to decide how to implement this class. + + The default implementation assumes the data communicated as input and output of + the APIs in this class are `Dict[ModuleID, Dict[str, Any]]` types. The + `MultiRLModule` by default loops through each `module_id`, and runs the forward pass + of the corresponding `RLModule` object with the associated `batch` within the + input. + It also assumes that the underlying RLModules do not share any parameters or + communication with one another. The behavior of modules with such advanced + communication would be undefined by default. To share parameters or communication + between the underlying RLModules, you should implement your own + `MultiRLModule` subclass. + """ + + def __init__( + self, + config=DEPRECATED_VALUE, + *, + observation_space: Optional[gym.Space] = None, + action_space: Optional[gym.Space] = None, + inference_only: Optional[bool] = None, + # TODO (sven): Ignore learner_only setting for now on MultiRLModule. + learner_only: Optional[bool] = None, + model_config: Optional[dict] = None, + rl_module_specs: Optional[Dict[ModuleID, RLModuleSpec]] = None, + **kwargs, + ) -> None: + """Initializes a MultiRLModule instance. + + Args: + observation_space: The MultiRLModule's observation space. + action_space: The MultiRLModule's action space. + inference_only: The MultiRLModule's `inference_only` setting. If True, force + sets all inference_only flags inside `rl_module_specs` also to True. + If None, infers the value for `inference_only` by setting it to True, + iff all `inference_only` flags inside `rl_module_specs`, otherwise to + False. + model_config: The MultiRLModule's `model_config` dict. + rl_module_specs: A dict mapping ModuleIDs to `RLModuleSpec` instances used + to create the submodules. + """ + if config != DEPRECATED_VALUE and isinstance(config, MultiRLModuleConfig): + deprecation_warning( + old="MultiRLModule(config=..)", + new="MultiRLModule(*, observation_space=.., action_space=.., " + "inference_only=.., model_config=.., rl_module_specs=..)", + error=True, + ) + + # Make sure we don't alter incoming module specs in this c'tor. + rl_module_specs = copy.deepcopy(rl_module_specs or {}) + # Figure out global inference_only setting. + # If not provided (None), only if all submodules are + # inference_only, this MultiRLModule will be inference_only. + inference_only = ( + inference_only + if inference_only is not None + else all(spec.inference_only for spec in rl_module_specs.values()) + ) + # If given inference_only=True, make all submodules also inference_only (before + # creating them). + if inference_only is True: + for rl_module_spec in rl_module_specs.values(): + rl_module_spec.inference_only = True + self._check_module_specs(rl_module_specs) + self.rl_module_specs = rl_module_specs + + super().__init__( + observation_space=observation_space, + action_space=action_space, + inference_only=inference_only, + learner_only=None, + catalog_class=None, + model_config=model_config, + **kwargs, + ) + + @OverrideToImplementCustomLogic + @override(RLModule) + def setup(self): + """Sets up the underlying, individual RLModules.""" + self._rl_modules = {} + # Make sure all individual RLModules have the same framework OR framework=None. + framework = None + for module_id, rl_module_spec in self.rl_module_specs.items(): + self._rl_modules[module_id] = rl_module_spec.build() + if framework is None: + framework = self._rl_modules[module_id].framework + else: + assert self._rl_modules[module_id].framework in [None, framework] + self.framework = framework + + @override(RLModule) + def _forward( + self, + batch: Dict[ModuleID, Any], + **kwargs, + ) -> Dict[ModuleID, Dict[str, Any]]: + """Generic forward pass method, used in all phases of training and evaluation. + + If you need a more nuanced distinction between forward passes in the different + phases of training and evaluation, override the following methods instead: + For distinct action computation logic w/o exploration, override the + `self._forward_inference()` method. + For distinct action computation logic with exploration, override the + `self._forward_exploration()` method. + For distinct forward pass logic before loss computation, override the + `self._forward_train()` method. + + Args: + batch: The input batch, a dict mapping from ModuleID to individual modules' + batches. + **kwargs: Additional keyword arguments. + + Returns: + The output of the forward pass. + """ + return { + mid: self._rl_modules[mid]._forward(batch[mid], **kwargs) + for mid in batch.keys() + if mid in self + } + + @override(RLModule) + def _forward_inference( + self, batch: Dict[str, Any], **kwargs + ) -> Union[Dict[str, Any], Dict[ModuleID, Dict[str, Any]]]: + """Forward-pass used for action computation without exploration behavior. + + Override this method only, if you need specific behavior for non-exploratory + action computation behavior. If you have only one generic behavior for all + phases of training and evaluation, override `self._forward()` instead. + + By default, this calls the generic `self._forward()` method. + """ + return { + mid: self._rl_modules[mid]._forward_inference(batch[mid], **kwargs) + for mid in batch.keys() + if mid in self + } + + @override(RLModule) + def _forward_exploration( + self, batch: Dict[str, Any], **kwargs + ) -> Union[Dict[str, Any], Dict[ModuleID, Dict[str, Any]]]: + """Forward-pass used for action computation with exploration behavior. + + Override this method only, if you need specific behavior for exploratory + action computation behavior. If you have only one generic behavior for all + phases of training and evaluation, override `self._forward()` instead. + + By default, this calls the generic `self._forward()` method. + """ + return { + mid: self._rl_modules[mid]._forward_exploration(batch[mid], **kwargs) + for mid in batch.keys() + if mid in self + } + + @override(RLModule) + def _forward_train( + self, batch: Dict[str, Any], **kwargs + ) -> Union[Dict[str, Any], Dict[ModuleID, Dict[str, Any]]]: + """Forward-pass used before the loss computation (training). + + Override this method only, if you need specific behavior and outputs for your + loss computations. If you have only one generic behavior for all + phases of training and evaluation, override `self._forward()` instead. + + By default, this calls the generic `self._forward()` method. + """ + return { + mid: self._rl_modules[mid]._forward_train(batch[mid], **kwargs) + for mid in batch.keys() + if mid in self + } + + @OverrideToImplementCustomLogic + @override(RLModule) + def get_initial_state(self) -> Any: + # TODO (sven): Replace by call to `self.foreach_module`, but only if this method + # supports returning dicts. + ret = {} + for module_id, module in self._rl_modules.items(): + ret[module_id] = module.get_initial_state() + return ret + + @OverrideToImplementCustomLogic + @override(RLModule) + def is_stateful(self) -> bool: + initial_state = self.get_initial_state() + assert isinstance(initial_state, dict), ( + "The initial state of an RLModule must be a dict, but is " + f"{type(initial_state)} instead." + ) + return bool(any(sa_init_state for sa_init_state in initial_state.values())) + + def add_module( + self, + module_id: ModuleID, + module: RLModule, + *, + override: bool = False, + ) -> None: + """Adds a module at run time to the multi-agent module. + + Args: + module_id: The module ID to add. If the module ID already exists and + override is False, an error is raised. If override is True, the module + is replaced. + module: The module to add. + override: Whether to override the module if it already exists. + + Raises: + ValueError: If the module ID already exists and override is False. + Warnings are raised if the module id is not valid according to the + logic of ``validate_module_id()``. + """ + from ray.rllib.core.rl_module import validate_module_id + + validate_module_id(module_id) + + if module_id in self._rl_modules and not override: + raise ValueError( + f"Module ID {module_id} already exists. If your intention is to " + "override, set override=True." + ) + # Set our own inference_only flag to False as soon as any added Module + # has `inference_only=False`. + if not module.inference_only: + self.inference_only = False + + # Check framework of incoming RLModule against `self.framework`. + if module.framework is not None: + if self.framework is None: + self.framework = module.framework + elif module.framework != self.framework: + raise ValueError( + f"Framework ({module.framework}) of incoming RLModule does NOT " + f"match framework ({self.framework}) of MultiRLModule! If the " + f"added module should not be trained, try setting its framework " + f"to None." + ) + + self._rl_modules[module_id] = module + # Update our RLModuleSpecs dict, such that - if written to disk - + # it'll allow for proper restoring this instance through `.from_checkpoint()`. + self.rl_module_specs[module_id] = RLModuleSpec.from_module(module) + + def remove_module( + self, module_id: ModuleID, *, raise_err_if_not_found: bool = True + ) -> None: + """Removes a module at runtime from the multi-agent module. + + Args: + module_id: The module ID to remove. + raise_err_if_not_found: Whether to raise an error if the module ID is not + found. + Raises: + ValueError: If the module ID does not exist and raise_err_if_not_found is + True. + """ + if raise_err_if_not_found: + self._check_module_exists(module_id) + del self._rl_modules[module_id] + del self.rl_module_specs[module_id] + + def foreach_module( + self, + func: Callable[[ModuleID, RLModule, Optional[Any]], T], + *, + return_dict: bool = False, + **kwargs, + ) -> Union[List[T], Dict[ModuleID, T]]: + """Calls the given function with each (module_id, module). + + Args: + func: The function to call with each (module_id, module) tuple. + return_dict: Whether to return a dict mapping ModuleID to the individual + module's return values of calling `func`. If False (default), return + a list. + + Returns: + The list of return values of all calls to + `func([module_id, module, **kwargs])` or a dict (if `return_dict=True`) + mapping ModuleIDs to the respective models' return values. + """ + ret_dict = { + module_id: func(module_id, module.unwrapped(), **kwargs) + for module_id, module in self._rl_modules.items() + } + if return_dict: + return ret_dict + return list(ret_dict.values()) + + def __contains__(self, item) -> bool: + """Returns whether the given `item` (ModuleID) is present in self.""" + return item in self._rl_modules + + def __getitem__(self, module_id: ModuleID) -> RLModule: + """Returns the RLModule with the given module ID. + + Args: + module_id: The module ID to get. + + Returns: + The RLModule with the given module ID. + + Raises: + KeyError: If `module_id` cannot be found in self. + """ + self._check_module_exists(module_id) + return self._rl_modules[module_id] + + def get( + self, + module_id: ModuleID, + default: Optional[RLModule] = None, + ) -> Optional[RLModule]: + """Returns the module with the given module ID or default if not found in self. + + Args: + module_id: The module ID to get. + + Returns: + The RLModule with the given module ID or `default` if `module_id` not found + in `self`. + """ + if module_id not in self._rl_modules: + return default + return self._rl_modules[module_id] + + def items(self) -> ItemsView[ModuleID, RLModule]: + """Returns an ItemsView over the module IDs in this MultiRLModule.""" + return self._rl_modules.items() + + def keys(self) -> KeysView[ModuleID]: + """Returns a KeysView over the module IDs in this MultiRLModule.""" + return self._rl_modules.keys() + + def values(self) -> ValuesView[ModuleID]: + """Returns a ValuesView over the module IDs in this MultiRLModule.""" + return self._rl_modules.values() + + def __len__(self) -> int: + """Returns the number of RLModules within this MultiRLModule.""" + return len(self._rl_modules) + + def __repr__(self) -> str: + return f"MARL({pprint.pformat(self._rl_modules)})" + + @override(RLModule) + def get_state( + self, + components: Optional[Union[str, Collection[str]]] = None, + *, + not_components: Optional[Union[str, Collection[str]]] = None, + inference_only: bool = False, + **kwargs, + ) -> StateDict: + state = {} + + for module_id, rl_module in self.get_checkpointable_components(): + if self._check_component(module_id, components, not_components): + state[module_id] = rl_module.get_state( + components=self._get_subcomponents(module_id, components), + not_components=self._get_subcomponents(module_id, not_components), + inference_only=inference_only, + ) + return state + + @override(RLModule) + def set_state(self, state: StateDict) -> None: + """Sets the state of the multi-agent module. + + It is assumed that the state_dict is a mapping from module IDs to the + corresponding module's state. This method sets the state of each module by + calling their set_state method. If you want to set the state of some of the + RLModules within this MultiRLModule your state_dict can only include the + state of those RLModules. Override this method to customize the state_dict for + custom more advanced multi-agent use cases. + + Args: + state: The state dict to set. + """ + # Now, set the individual states + for module_id, module_state in state.items(): + if module_id in self: + self._rl_modules[module_id].set_state(module_state) + + @override(Checkpointable) + def get_ctor_args_and_kwargs(self): + return ( + (), # *args + { + "observation_space": self.observation_space, + "action_space": self.action_space, + "inference_only": self.inference_only, + "learner_only": self.learner_only, + "model_config": self.model_config, + "rl_module_specs": self.rl_module_specs, + }, # **kwargs + ) + + @override(Checkpointable) + def get_checkpointable_components(self) -> List[Tuple[str, Checkpointable]]: + return list(self._rl_modules.items()) + + @override(RLModule) + def as_multi_rl_module(self) -> "MultiRLModule": + """Returns self in order to match `RLModule.as_multi_rl_module()` behavior. + + This method is overridden to avoid double wrapping. + + Returns: + The instance itself. + """ + return self + + @classmethod + def _check_module_specs(cls, rl_module_specs: Dict[ModuleID, RLModuleSpec]): + """Checks the individual RLModuleSpecs for validity. + + Args: + rl_module_specs: Dict mapping ModuleIDs to the respective RLModuleSpec. + + Raises: + ValueError: If any RLModuleSpec is invalid. + """ + for module_id, rl_module_spec in rl_module_specs.items(): + if not isinstance(rl_module_spec, RLModuleSpec): + raise ValueError(f"Module {module_id} is not a RLModuleSpec object.") + + def _check_module_exists(self, module_id: ModuleID) -> None: + if module_id not in self._rl_modules: + raise KeyError( + f"Module with module_id {module_id} not found. " + f"Available modules: {set(self.keys())}" + ) + + @Deprecated(error=False) + def output_specs_train(self): + pass + + @Deprecated(error=False) + def output_specs_inference(self): + pass + + @Deprecated(error=False) + def output_specs_exploration(self): + pass + + @Deprecated(error=False) + def _default_input_specs(self): + pass + + +@PublicAPI(stability="alpha") +@dataclasses.dataclass +class MultiRLModuleSpec: + """A utility spec class to make it constructing MultiRLModules easier. + + Users can extend this class to modify the behavior of base class. For example to + share neural networks across the modules, the build method can be overridden to + create the shared module first and then pass it to custom module classes that would + then use it as a shared module. + """ + + #: The class of the MultiRLModule to construct. By default, + #: this is the base `MultiRLModule` class. + multi_rl_module_class: Type[MultiRLModule] = MultiRLModule + #: Optional global observation space for the MultiRLModule. + #: Useful for shared network components that live only inside the MultiRLModule + #: and don't have their own ModuleID and own RLModule within + #: `self._rl_modules`. + observation_space: Optional[gym.Space] = None + #: Optional global action space for the MultiRLModule. Useful for + #: shared network components that live only inside the MultiRLModule and don't + #: have their own ModuleID and own RLModule within `self._rl_modules`. + action_space: Optional[gym.Space] = None + #: An optional global inference_only flag. If not set (None by + #: default), considers the MultiRLModule to be inference_only=True, only if all + #: submodules also have their own inference_only flags set to True. + inference_only: Optional[bool] = None + # TODO (sven): Once we support MultiRLModules inside other MultiRLModules, we would + # need this flag in here as well, but for now, we'll leave it out for simplicity. + # learner_only: bool = False + #: An optional global model_config dict. Useful to configure shared + #: network components that only live inside the MultiRLModule and don't have + #: their own ModuleID and own RLModule within `self._rl_modules`. + model_config: Optional[dict] = None + #: The module specs for each individual module. It can be either + #: an RLModuleSpec used for all module_ids or a dictionary mapping from module + #: IDs to RLModuleSpecs for each individual module. + rl_module_specs: Union[RLModuleSpec, Dict[ModuleID, RLModuleSpec]] = None + + # TODO (sven): Deprecate these in favor of using the pure Checkpointable APIs for + # loading and saving state. + load_state_path: Optional[str] = None + modules_to_load: Optional[Set[ModuleID]] = None + + # Deprecated: Do not use anymore. + module_specs: Optional[Union[RLModuleSpec, Dict[ModuleID, RLModuleSpec]]] = None + + def __post_init__(self): + if self.module_specs is not None: + deprecation_warning( + old="MultiRLModuleSpec(module_specs=..)", + new="MultiRLModuleSpec(rl_module_specs=..)", + error=True, + ) + if self.rl_module_specs is None: + raise ValueError( + "Module_specs cannot be None. It should be either a " + "RLModuleSpec or a dictionary mapping from module IDs to " + "RLModuleSpecs for each individual module." + ) + self.module_specs = self.rl_module_specs + # Figure out global inference_only setting. + # If not provided (None), only if all submodules are + # inference_only, this MultiRLModule will be inference_only. + self.inference_only = ( + self.inference_only + if self.inference_only is not None + else all(spec.inference_only for spec in self.rl_module_specs.values()) + ) + + @OverrideToImplementCustomLogic + def build(self, module_id: Optional[ModuleID] = None) -> RLModule: + """Builds either the MultiRLModule or a (single) sub-RLModule under `module_id`. + + Args: + module_id: Optional ModuleID of a single RLModule to be built. If None + (default), builds the MultiRLModule. + + Returns: + The built RLModule if `module_id` is provided, otherwise the built + MultiRLModule. + """ + self._check_before_build() + + # ModuleID provided, return single-agent RLModule. + if module_id: + return self.rl_module_specs[module_id].build() + + # Return MultiRLModule. + try: + module = self.multi_rl_module_class( + observation_space=self.observation_space, + action_space=self.action_space, + inference_only=self.inference_only, + model_config=( + dataclasses.asdict(self.model_config) + if dataclasses.is_dataclass(self.model_config) + else self.model_config + ), + rl_module_specs=self.rl_module_specs, + ) + # Older custom model might still require the old `MultiRLModuleConfig` under + # the `config` arg. + except AttributeError as e: + if self.multi_rl_module_class is not MultiRLModule: + multi_rl_module_config = self.get_rl_module_config() + module = self.multi_rl_module_class(multi_rl_module_config) + else: + raise e + + return module + + def add_modules( + self, + module_specs: Dict[ModuleID, RLModuleSpec], + override: bool = True, + ) -> None: + """Add new module specs to the spec or updates existing ones. + + Args: + module_specs: The mapping for the module_id to the single-agent module + specs to be added to this multi-agent module spec. + override: Whether to override the existing module specs if they already + exist. If False, they are only updated. + """ + if self.rl_module_specs is None: + self.rl_module_specs = {} + for module_id, module_spec in module_specs.items(): + if override or module_id not in self.rl_module_specs: + # Disable our `inference_only` as soon as any single-agent module has + # `inference_only=False`. + if not module_spec.inference_only: + self.inference_only = False + self.rl_module_specs[module_id] = module_spec + else: + self.rl_module_specs[module_id].update(module_spec) + + def remove_modules(self, module_ids: Union[ModuleID, Collection[ModuleID]]) -> None: + """Removes the provided ModuleIDs from this MultiRLModuleSpec. + + Args: + module_ids: Collection of the ModuleIDs to remove from this spec. + """ + for module_id in force_list(module_ids): + self.rl_module_specs.pop(module_id, None) + + @classmethod + def from_module(self, module: MultiRLModule) -> "MultiRLModuleSpec": + """Creates a MultiRLModuleSpec from a MultiRLModule. + + Args: + module: The MultiRLModule to create the spec from. + + Returns: + The MultiRLModuleSpec. + """ + # we want to get the spec of the underlying unwrapped module that way we can + # easily reconstruct it. The only wrappers that we expect to support today are + # wrappers that allow us to do distributed training. Those will be added back + # by the learner if necessary. + rl_module_specs = { + module_id: RLModuleSpec.from_module(rl_module.unwrapped()) + for module_id, rl_module in module._rl_modules.items() + } + multi_rl_module_class = module.__class__ + return MultiRLModuleSpec( + multi_rl_module_class=multi_rl_module_class, + observation_space=module.observation_space, + action_space=module.action_space, + inference_only=module.inference_only, + model_config=module.model_config, + rl_module_specs=rl_module_specs, + ) + + def _check_before_build(self): + if not isinstance(self.rl_module_specs, dict): + raise ValueError( + f"When build() is called on {self.__class__}, the `rl_module_specs` " + "attribute should be a dictionary mapping ModuleIDs to " + "RLModuleSpecs for each individual RLModule." + ) + + def to_dict(self) -> Dict[str, Any]: + """Converts the MultiRLModuleSpec to a dictionary.""" + return { + "multi_rl_module_class": serialize_type(self.multi_rl_module_class), + "observation_space": gym_space_to_dict(self.observation_space), + "action_space": gym_space_to_dict(self.action_space), + "inference_only": self.inference_only, + "model_config": self.model_config, + "rl_module_specs": { + module_id: rl_module_spec.to_dict() + for module_id, rl_module_spec in self.rl_module_specs.items() + }, + } + + @classmethod + def from_dict(cls, d) -> "MultiRLModuleSpec": + """Creates a MultiRLModuleSpec from a dictionary.""" + return MultiRLModuleSpec( + multi_rl_module_class=deserialize_type(d["multi_rl_module_class"]), + observation_space=gym_space_from_dict(d.get("observation_space")), + action_space=gym_space_from_dict(d.get("action_space")), + model_config=d.get("model_config"), + inference_only=d["inference_only"], + rl_module_specs={ + module_id: RLModuleSpec.from_dict(rl_module_spec) + for module_id, rl_module_spec in ( + d.get("rl_module_specs", d.get("module_specs")).items() + ) + }, + ) + + def update( + self, + other: Union["MultiRLModuleSpec", RLModuleSpec], + override: bool = False, + ) -> None: + """Updates this spec with the other spec. + + Traverses this MultiRLModuleSpec's module_specs and updates them with + the module specs from the `other` (Multi)RLModuleSpec. + + Args: + other: The other spec to update this spec with. + override: Whether to override the existing module specs if they already + exist. If False, they are only updated. + """ + if isinstance(other, RLModuleSpec): + # Disable our `inference_only` as soon as any single-agent module has + # `inference_only=False`. + if not other.inference_only: + self.inference_only = False + for mid, spec in self.rl_module_specs.items(): + self.rl_module_specs[mid].update(other, override=False) + elif isinstance(other.module_specs, dict): + self.add_modules(other.rl_module_specs, override=override) + else: + assert isinstance(other, MultiRLModuleSpec) + if not self.rl_module_specs: + self.inference_only = other.inference_only + self.rl_module_specs = other.rl_module_specs + else: + if not other.inference_only: + self.inference_only = False + self.rl_module_specs.update(other.rl_module_specs) + + def as_multi_rl_module_spec(self) -> "MultiRLModuleSpec": + """Returns self in order to match `RLModuleSpec.as_multi_rl_module_spec()`.""" + return self + + def __contains__(self, item) -> bool: + """Returns whether the given `item` (ModuleID) is present in self.""" + return item in self.rl_module_specs + + def __getitem__(self, item) -> RLModuleSpec: + """Returns the RLModuleSpec under the ModuleID.""" + return self.rl_module_specs[item] + + @Deprecated( + new="MultiRLModule(*, module_specs={module1: [RLModuleSpec], " + "module2: [RLModuleSpec], ..}, inference_only=..)", + error=True, + ) + def get_multi_rl_module_config(self): + pass + + @Deprecated(new="MultiRLModuleSpec.as_multi_rl_module_spec()", error=True) + def as_multi_agent(self): + pass + + @Deprecated(new="MultiRLModuleSpec.get_multi_rl_module_config", error=True) + def get_marl_config(self, *args, **kwargs): + pass + + @Deprecated( + new="MultiRLModule(*, observation_space=.., action_space=.., ....)", + error=False, + ) + def get_rl_module_config(self): + return MultiRLModuleConfig( + inference_only=self.inference_only, + modules=self.rl_module_specs, + ) + + +@Deprecated( + new="MultiRLModule(*, rl_module_specs={module1: [RLModuleSpec], " + "module2: [RLModuleSpec], ..}, inference_only=..)", + error=False, +) +@dataclasses.dataclass +class MultiRLModuleConfig: + inference_only: bool = False + modules: Dict[ModuleID, RLModuleSpec] = dataclasses.field(default_factory=dict) + + def to_dict(self): + return { + "inference_only": self.inference_only, + "modules": { + module_id: module_spec.to_dict() + for module_id, module_spec in self.modules.items() + }, + } + + @classmethod + def from_dict(cls, d) -> "MultiRLModuleConfig": + return cls( + inference_only=d["inference_only"], + modules={ + module_id: RLModuleSpec.from_dict(module_spec) + for module_id, module_spec in d["modules"].items() + }, + ) + + def get_catalog(self) -> None: + return None diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/rl_module.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/rl_module.py new file mode 100644 index 0000000000000000000000000000000000000000..644ecae02a465b4252c859c859cb2876119accb7 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/rl_module.py @@ -0,0 +1,821 @@ +import abc +import dataclasses +from dataclasses import dataclass, field +import logging +from typing import Any, Collection, Dict, Optional, Type, TYPE_CHECKING, Union + +import gymnasium as gym + +from ray.rllib.core import DEFAULT_MODULE_ID +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.core.distribution.distribution import Distribution +from ray.rllib.utils.annotations import ( + override, + OverrideToImplementCustomLogic, +) +from ray.rllib.utils.checkpoints import Checkpointable +from ray.rllib.utils.deprecation import ( + Deprecated, + DEPRECATED_VALUE, + deprecation_warning, +) +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.serialization import ( + gym_space_from_dict, + gym_space_to_dict, + serialize_type, + deserialize_type, +) +from ray.rllib.utils.typing import StateDict +from ray.util.annotations import PublicAPI + +if TYPE_CHECKING: + from ray.rllib.core.rl_module.multi_rl_module import ( + MultiRLModule, + MultiRLModuleSpec, + ) + from ray.rllib.core.models.catalog import Catalog + +logger = logging.getLogger("ray.rllib") +torch, _ = try_import_torch() + + +@PublicAPI(stability="beta") +@dataclass +class RLModuleSpec: + """Utility spec class to make constructing RLModules (in single-agent case) easier. + + Args: + module_class: The RLModule class to use. + observation_space: The observation space of the RLModule. This may differ + from the observation space of the environment. For example, a discrete + observation space of an environment, would usually correspond to a + one-hot encoded observation space of the RLModule because of preprocessing. + action_space: The action space of the RLModule. + inference_only: Whether the RLModule should be configured in its inference-only + state, in which those components not needed for action computing (for + example a value function or a target network) might be missing. + Note that `inference_only=True` AND `learner_only=True` is not allowed. + learner_only: Whether this RLModule should only be built on Learner workers, but + NOT on EnvRunners. Useful for RLModules inside a MultiRLModule that are only + used for training, for example a shared value function in a multi-agent + setup or a world model in a curiosity-learning setup. + Note that `inference_only=True` AND `learner_only=True` is not allowed. + model_config: The model config dict or default RLlib dataclass to use. + catalog_class: The Catalog class to use. + load_state_path: The path to the module state to load from. NOTE: This must be + an absolute path. + """ + + module_class: Optional[Type["RLModule"]] = None + observation_space: Optional[gym.Space] = None + action_space: Optional[gym.Space] = None + inference_only: bool = False + learner_only: bool = False + model_config: Optional[Union[Dict[str, Any], DefaultModelConfig]] = None + catalog_class: Optional[Type["Catalog"]] = None + load_state_path: Optional[str] = None + + # Deprecated field. + model_config_dict: Optional[Union[dict, int]] = None + + def __post_init__(self): + if self.model_config_dict is not None: + deprecation_warning( + old="RLModuleSpec(model_config_dict=..)", + new="RLModuleSpec(model_config=..)", + error=True, + ) + + def build(self) -> "RLModule": + """Builds the RLModule from this spec.""" + if self.module_class is None: + raise ValueError("RLModule class is not set.") + if self.observation_space is None: + raise ValueError("Observation space is not set.") + + try: + module = self.module_class( + observation_space=self.observation_space, + action_space=self.action_space, + inference_only=self.inference_only, + model_config=self._get_model_config(), + catalog_class=self.catalog_class, + ) + # Older custom model might still require the old `RLModuleConfig` under + # the `config` arg. + except AttributeError: + module_config = self.get_rl_module_config() + module = self.module_class(module_config) + return module + + @classmethod + def from_module(cls, module: "RLModule") -> "RLModuleSpec": + from ray.rllib.core.rl_module.multi_rl_module import MultiRLModule + + if isinstance(module, MultiRLModule): + raise ValueError("MultiRLModule cannot be converted to RLModuleSpec.") + + # Try instantiating a new RLModule from the spec using the new c'tor args. + try: + rl_module_spec = RLModuleSpec( + module_class=type(module), + observation_space=module.observation_space, + action_space=module.action_space, + inference_only=module.inference_only, + learner_only=module.learner_only, + model_config=module.model_config, + catalog_class=( + type(module.catalog) if module.catalog is not None else None + ), + ) + + # Old path through deprecated `RLModuleConfig` class. Used only if `module` + # still has a valid `config` attribute. + except AttributeError: + rl_module_spec = RLModuleSpec( + module_class=type(module), + observation_space=module.config.observation_space, + action_space=module.config.action_space, + inference_only=module.config.inference_only, + learner_only=module.config.learner_only, + model_config=module.config.model_config_dict, + catalog_class=module.config.catalog_class, + ) + return rl_module_spec + + def to_dict(self): + """Returns a serialized representation of the spec.""" + return { + "module_class": serialize_type(self.module_class), + "observation_space": gym_space_to_dict(self.observation_space), + "action_space": gym_space_to_dict(self.action_space), + "inference_only": self.inference_only, + "learner_only": self.learner_only, + "model_config": self._get_model_config(), + "catalog_class": serialize_type(self.catalog_class) + if self.catalog_class is not None + else None, + } + + @classmethod + def from_dict(cls, d): + """Returns a single agent RLModule spec from a serialized representation.""" + module_class = deserialize_type(d["module_class"]) + try: + spec = RLModuleSpec( + module_class=module_class, + observation_space=gym_space_from_dict(d["observation_space"]), + action_space=gym_space_from_dict(d["action_space"]), + inference_only=d["inference_only"], + learner_only=d["learner_only"], + model_config=d["model_config"], + catalog_class=deserialize_type(d["catalog_class"]) + if d["catalog_class"] is not None + else None, + ) + + # Old path through deprecated `RLModuleConfig` class. + except KeyError: + module_config = RLModuleConfig.from_dict(d["module_config"]) + spec = RLModuleSpec( + module_class=module_class, + observation_space=module_config.observation_space, + action_space=module_config.action_space, + inference_only=module_config.inference_only, + learner_only=module_config.learner_only, + model_config=module_config.model_config_dict, + catalog_class=module_config.catalog_class, + ) + return spec + + def update(self, other, override: bool = True) -> None: + """Updates this spec with the given other spec. Works like dict.update(). + + Args: + other: The other SingleAgentRLModule spec to update this one from. + override: Whether to update all properties in `self` with those of `other. + If False, only update those properties in `self` that are not None. + """ + if not isinstance(other, RLModuleSpec): + raise ValueError("Can only update with another RLModuleSpec.") + + # If the field is None in the other, keep the current field, otherwise update + # with the new value. + if override: + self.module_class = other.module_class or self.module_class + self.observation_space = other.observation_space or self.observation_space + self.action_space = other.action_space or self.action_space + self.inference_only = other.inference_only or self.inference_only + self.learner_only = other.learner_only and self.learner_only + self.model_config = other.model_config or self.model_config + self.catalog_class = other.catalog_class or self.catalog_class + self.load_state_path = other.load_state_path or self.load_state_path + # Only override, if the field is None in `self`. + # Do NOT override the boolean settings: `inference_only` and `learner_only`. + else: + self.module_class = self.module_class or other.module_class + self.observation_space = self.observation_space or other.observation_space + self.action_space = self.action_space or other.action_space + self.model_config = self.model_config or other.model_config + self.catalog_class = self.catalog_class or other.catalog_class + self.load_state_path = self.load_state_path or other.load_state_path + + def as_multi_rl_module_spec(self) -> "MultiRLModuleSpec": + """Returns a MultiRLModuleSpec (`self` under DEFAULT_MODULE_ID key).""" + from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec + + return MultiRLModuleSpec( + rl_module_specs={DEFAULT_MODULE_ID: self}, + load_state_path=self.load_state_path, + ) + + def _get_model_config(self): + return ( + dataclasses.asdict(self.model_config) + if dataclasses.is_dataclass(self.model_config) + else (self.model_config or {}) + ) + + @Deprecated( + new="RLModule(*, observation_space=.., action_space=.., ....)", + error=False, + ) + def get_rl_module_config(self): + return RLModuleConfig( + observation_space=self.observation_space, + action_space=self.action_space, + inference_only=self.inference_only, + learner_only=self.learner_only, + model_config_dict=self._get_model_config(), + catalog_class=self.catalog_class, + ) + + +@PublicAPI(stability="beta") +class RLModule(Checkpointable, abc.ABC): + """Base class for RLlib modules. + + Subclasses should call `super().__init__(observation_space=.., action_space=.., + inference_only=.., learner_only=.., model_config={..})` in their __init__ methods. + + Here is the pseudocode for how the forward methods are called: + + Example for creating a (inference-only) sampling loop: + + .. testcode:: + + from ray.rllib.algorithms.ppo.torch.default_ppo_torch_rl_module import ( + DefaultPPOTorchRLModule + ) + from ray.rllib.algorithms.ppo.ppo_catalog import PPOCatalog + import gymnasium as gym + import torch + + env = gym.make("CartPole-v1") + + # Create an instance of the default RLModule used by PPO. + module = DefaultPPOTorchRLModule( + observation_space=env.observation_space, + action_space=env.action_space, + model_config=DefaultModelConfig(fcnet_hiddens=[128, 128]), + catalog_class=PPOCatalog, + ) + action_dist_class = module.get_inference_action_dist_cls() + obs, info = env.reset() + terminated = False + + while not terminated: + fwd_ins = {"obs": torch.Tensor([obs])} + fwd_outputs = module.forward_exploration(fwd_ins) + # This can be either deterministic or stochastic distribution. + action_dist = action_dist_class.from_logits( + fwd_outputs["action_dist_inputs"] + ) + action = action_dist.sample()[0].numpy() + obs, reward, terminated, truncated, info = env.step(action) + + + Example for training: + + .. testcode:: + + import gymnasium as gym + import torch + + from ray.rllib.algorithms.ppo.torch.default_ppo_torch_rl_module import ( + DefaultPPOTorchRLModule + ) + from ray.rllib.algorithms.ppo.ppo_catalog import PPOCatalog + + env = gym.make("CartPole-v1") + + # Create an instance of the default RLModule used by PPO. + module = DefaultPPOTorchRLModule( + observation_space=env.observation_space, + action_space=env.action_space, + model_config=DefaultModelConfig(fcnet_hiddens=[128, 128]), + catalog_class=PPOCatalog, + ) + + fwd_ins = {"obs": torch.Tensor([obs])} + fwd_outputs = module.forward_train(fwd_ins) + # loss = compute_loss(fwd_outputs, fwd_ins) + # update_params(module, loss) + + Example for inference: + + .. testcode:: + + import gymnasium as gym + import torch + + from ray.rllib.algorithms.ppo.torch.default_ppo_torch_rl_module import ( + DefaultPPOTorchRLModule + ) + from ray.rllib.algorithms.ppo.ppo_catalog import PPOCatalog + + env = gym.make("CartPole-v1") + + # Create an instance of the default RLModule used by PPO. + module = DefaultPPOTorchRLModule( + observation_space=env.observation_space, + action_space=env.action_space, + model_config=DefaultModelConfig(fcnet_hiddens=[128, 128]), + catalog_class=PPOCatalog, + ) + + while not terminated: + fwd_ins = {"obs": torch.Tensor([obs])} + fwd_outputs = module.forward_inference(fwd_ins) + # this can be either deterministic or stochastic distribution + action_dist = action_dist_class.from_logits( + fwd_outputs["action_dist_inputs"] + ) + action = action_dist.sample()[0].numpy() + obs, reward, terminated, truncated, info = env.step(action) + + + Args: + observation_space: The observation space of the model. Note that in multi-agent + setups, this is typically the observation space of an agent that maps to + this RLModule. + action_space: The action space of the model. Note that in multi-agent + setups, this is typically the action space of an agent that maps to + this RLModule. + inference_only: If True, this RLModule should construct itself in an inference- + only fashion. This is done automatically, if the user implements the + `InferenceOnlyAPI` with their custom RLModule subclass. False by default. + learner_only: If True, RLlib won't built this RLModule on EnvRunner actors. + False by default. + model_config: A config dict to specify features of this RLModule. + + Attributes: + action_dist_cls: An optional ray.rllib.core.distribution.distribution. + Distribution subclass to use for sampling actions, given parameters from + a batch (`Columns.ACTION_DIST_INPUTS`). + + Abstract Methods: + ``~_forward_train``: Forward pass during training. + + ``~_forward_exploration``: Forward pass during training for exploration. + + ``~_forward_inference``: Forward pass during inference. + """ + + framework: str = None + + STATE_FILE_NAME = "module_state" + + def __init__( + self, + config=DEPRECATED_VALUE, + *, + observation_space: Optional[gym.Space] = None, + action_space: Optional[gym.Space] = None, + inference_only: Optional[bool] = None, + learner_only: bool = False, + model_config: Optional[Union[dict, DefaultModelConfig]] = None, + catalog_class=None, + **kwargs, + ): + # TODO (sven): Deprecate Catalog and replace with utility functions to create + # primitive components based on obs- and action spaces. + self.catalog = None + self._catalog_ctor_error = None + + # Deprecated + self.config = config + if self.config != DEPRECATED_VALUE: + deprecation_warning( + old="RLModule(config=[RLModuleConfig])", + new="RLModule(observation_space=.., action_space=.., inference_only=..," + " learner_only=.., model_config=..)", + help="See https://github.com/ray-project/ray/blob/master/rllib/examples/rl_modules/custom_cnn_rl_module.py " # noqa + "for how to write a custom RLModule.", + error=True, + ) + else: + self.observation_space = observation_space + self.action_space = action_space + self.inference_only = inference_only + self.learner_only = learner_only + self.model_config = model_config + if catalog_class is not None: + try: + self.catalog = catalog_class( + observation_space=self.observation_space, + action_space=self.action_space, + model_config_dict=self.model_config, + ) + except Exception as e: + logger.warning( + "Didn't create a Catalog object for your RLModule! If you are " + "not using the new API stack yet, make sure to switch it off in" + " your config: `config.api_stack(enable_rl_module_and_learner=" + "False, enable_env_runner_and_connector_v2=False)`. All algos " + "use the new stack by default. Ignore this message, if your " + "RLModule does not use a Catalog to build its sub-components." + ) + self._catalog_ctor_error = e + + # TODO (sven): Deprecate this. We keep it here for now in case users + # still have custom models (or subclasses of RLlib default models) + # into which they pass in a `config` argument. + self.config = RLModuleConfig( + observation_space=self.observation_space, + action_space=self.action_space, + inference_only=self.inference_only, + learner_only=self.learner_only, + model_config_dict=self.model_config, + catalog_class=catalog_class, + ) + + self.action_dist_cls = None + if self.catalog is not None: + self.action_dist_cls = self.catalog.get_action_dist_cls( + framework=self.framework + ) + + # Make sure, `setup()` is only called once, no matter what. + if hasattr(self, "_is_setup") and self._is_setup: + raise RuntimeError( + "`RLModule.setup()` called twice within your RLModule implementation " + f"{self}! Make sure you are using the proper inheritance order " + "(TorchRLModule before [Algo]RLModule) or (TfRLModule before " + "[Algo]RLModule) and that you are NOT overriding the constructor, but " + "only the `setup()` method of your subclass." + ) + try: + self.setup() + except AttributeError as e: + if "'NoneType' object has no attribute " in e.args[0]: + raise (self._catalog_ctor_error or e) + self._is_setup = True + # Cache value for returning from `is_stateful` so we don't have to call + # the module's `get_initial_state()` method all the time (might be expensive). + self._is_stateful = None + + @OverrideToImplementCustomLogic + def setup(self): + """Sets up the components of the module. + + This is called automatically during the __init__ method of this class, + therefore, the subclass should call super.__init__() in its constructor. This + abstraction can be used to create any components (e.g. NN layers) that your + RLModule needs. + """ + pass + + @OverrideToImplementCustomLogic + def get_inference_action_dist_cls(self) -> Type[Distribution]: + """Returns the action distribution class for this RLModule used for inference. + + This class is used to create action distributions from outputs of the forward + inference method. If the case that no action distribution class is needed, + this method can return None. + + Note that RLlib's distribution classes all implement the `Distribution` + interface. This requires two special methods: `Distribution.from_logits()` and + `Distribution.to_deterministic()`. See the documentation of the + :py:class:`~ray.rllib.core.distribution.distribution.Distribution` class for + more details. + """ + raise NotImplementedError + + @OverrideToImplementCustomLogic + def get_exploration_action_dist_cls(self) -> Type[Distribution]: + """Returns the action distribution class for this RLModule used for exploration. + + This class is used to create action distributions from outputs of the + forward_exploration method. If the case that no action distribution class is + needed, this method can return None. + + Note that RLlib's distribution classes all implement the `Distribution` + interface. This requires two special methods: `Distribution.from_logits()` and + `Distribution.to_deterministic()`. See the documentation of the + :py:class:`~ray.rllib.core.distribution.distribution.Distribution` class for + more details. + """ + raise NotImplementedError + + @OverrideToImplementCustomLogic + def get_train_action_dist_cls(self) -> Type[Distribution]: + """Returns the action distribution class for this RLModule used for training. + + This class is used to get the correct action distribution class to be used by + the training components. In case that no action distribution class is needed, + this method can return None. + + Note that RLlib's distribution classes all implement the `Distribution` + interface. This requires two special methods: `Distribution.from_logits()` and + `Distribution.to_deterministic()`. See the documentation of the + :py:class:`~ray.rllib.core.distribution.distribution.Distribution` class for + more details. + """ + raise NotImplementedError + + @OverrideToImplementCustomLogic + def _forward(self, batch: Dict[str, Any], **kwargs) -> Dict[str, Any]: + """Generic forward pass method, used in all phases of training and evaluation. + + If you need a more nuanced distinction between forward passes in the different + phases of training and evaluation, override the following methods instead: + + For distinct action computation logic w/o exploration, override the + `self._forward_inference()` method. + For distinct action computation logic with exploration, override the + `self._forward_exploration()` method. + For distinct forward pass logic before loss computation, override the + `self._forward_train()` method. + + Args: + batch: The input batch. + **kwargs: Additional keyword arguments. + + Returns: + The output of the forward pass. + """ + return {} + + def forward_inference(self, batch: Dict[str, Any], **kwargs) -> Dict[str, Any]: + """DO NOT OVERRIDE! Forward-pass during evaluation, called from the sampler. + + This method should not be overridden. Override the `self._forward_inference()` + method instead. + + Args: + batch: The input batch. + **kwargs: Additional keyword arguments. + + Returns: + The output of the forward pass. This output should comply with the + ouptut_specs_inference(). + """ + return self._forward_inference(batch, **kwargs) + + @OverrideToImplementCustomLogic + def _forward_inference(self, batch: Dict[str, Any], **kwargs) -> Dict[str, Any]: + """Forward-pass used for action computation without exploration behavior. + + Override this method only, if you need specific behavior for non-exploratory + action computation behavior. If you have only one generic behavior for all + phases of training and evaluation, override `self._forward()` instead. + + By default, this calls the generic `self._forward()` method. + """ + return self._forward(batch, **kwargs) + + def forward_exploration(self, batch: Dict[str, Any], **kwargs) -> Dict[str, Any]: + """DO NOT OVERRIDE! Forward-pass during exploration, called from the sampler. + + This method should not be overridden. Override the `self._forward_exploration()` + method instead. + + Args: + batch: The input batch. + **kwargs: Additional keyword arguments. + + Returns: + The output of the forward pass. + """ + return self._forward_exploration(batch, **kwargs) + + @OverrideToImplementCustomLogic + def _forward_exploration(self, batch: Dict[str, Any], **kwargs) -> Dict[str, Any]: + """Forward-pass used for action computation with exploration behavior. + + Override this method only, if you need specific behavior for exploratory + action computation behavior. If you have only one generic behavior for all + phases of training and evaluation, override `self._forward()` instead. + + By default, this calls the generic `self._forward()` method. + """ + return self._forward(batch, **kwargs) + + def forward_train(self, batch: Dict[str, Any], **kwargs) -> Dict[str, Any]: + """DO NOT OVERRIDE! Forward-pass during training called from the learner. + + This method should not be overridden. Override the `self._forward_train()` + method instead. + + Args: + batch: The input batch. + **kwargs: Additional keyword arguments. + + Returns: + The output of the forward pass. + """ + if self.inference_only: + raise RuntimeError( + "Calling `forward_train` on an inference_only module is not allowed! " + "Set the `inference_only=False` flag in the RLModuleSpec (or the " + "RLModule's constructor)." + ) + return self._forward_train(batch, **kwargs) + + @OverrideToImplementCustomLogic + def _forward_train(self, batch: Dict[str, Any], **kwargs) -> Dict[str, Any]: + """Forward-pass used before the loss computation (training). + + Override this method only, if you need specific behavior and outputs for your + loss computations. If you have only one generic behavior for all + phases of training and evaluation, override `self._forward()` instead. + + By default, this calls the generic `self._forward()` method. + """ + return self._forward(batch, **kwargs) + + @OverrideToImplementCustomLogic + def get_initial_state(self) -> Any: + """Returns the initial state of the RLModule, in case this is a stateful module. + + Returns: + A tensor or any nested struct of tensors, representing an initial state for + this (stateful) RLModule. + """ + return {} + + @OverrideToImplementCustomLogic + def is_stateful(self) -> bool: + """By default, returns False if the initial state is an empty dict (or None). + + By default, RLlib assumes that the module is non-recurrent, if the initial + state is an empty dict and recurrent otherwise. + This behavior can be customized by overriding this method. + """ + if self._is_stateful is None: + initial_state = self.get_initial_state() + assert isinstance(initial_state, dict), ( + "The initial state of an RLModule must be a dict, but is " + f"{type(initial_state)} instead." + ) + self._is_stateful = bool(initial_state) + return self._is_stateful + + @OverrideToImplementCustomLogic + @override(Checkpointable) + def get_state( + self, + components: Optional[Union[str, Collection[str]]] = None, + *, + not_components: Optional[Union[str, Collection[str]]] = None, + inference_only: bool = False, + **kwargs, + ) -> StateDict: + """Returns the state dict of the module. + + Args: + inference_only: Whether the returned state should be an inference-only + state (w/o those model components that are not needed for action + computations, such as a value function or a target network). + Note that setting this to `False` might raise an error if + `self.inference_only` is True. + + Returns: + This RLModule's state dict. + """ + return {} + + @OverrideToImplementCustomLogic + @override(Checkpointable) + def set_state(self, state: StateDict) -> None: + pass + + @override(Checkpointable) + def get_ctor_args_and_kwargs(self): + return ( + (), # *args + { + "observation_space": self.observation_space, + "action_space": self.action_space, + "inference_only": self.inference_only, + "learner_only": self.learner_only, + "model_config": self.model_config, + "catalog_class": ( + type(self.catalog) if self.catalog is not None else None + ), + }, # **kwargs + ) + + def as_multi_rl_module(self) -> "MultiRLModule": + """Returns a multi-agent wrapper around this module.""" + from ray.rllib.core.rl_module.multi_rl_module import MultiRLModule + + multi_rl_module = MultiRLModule( + rl_module_specs={DEFAULT_MODULE_ID: RLModuleSpec.from_module(self)} + ) + return multi_rl_module + + def unwrapped(self) -> "RLModule": + """Returns the underlying module if this module is a wrapper. + + An example of a wrapped is the TorchDDPRLModule class, which wraps + a TorchRLModule. + + Returns: + The underlying module. + """ + return self + + @Deprecated(error=False) + def output_specs_train(self): + pass + + @Deprecated(error=False) + def output_specs_inference(self): + pass + + @Deprecated(error=False) + def output_specs_exploration(self): + pass + + @Deprecated(error=False) + def input_specs_inference(self): + pass + + @Deprecated(error=False) + def input_specs_exploration(self): + pass + + @Deprecated(error=False) + def input_specs_train(self): + pass + + @Deprecated(error=False) + def _default_input_specs(self): + pass + + +@Deprecated( + old="RLModule(config=[RLModuleConfig object])", + new="RLModule(observation_space=.., action_space=.., inference_only=.., " + "model_config=.., catalog_class=..)", + error=False, +) +@dataclass +class RLModuleConfig: + observation_space: gym.Space = None + action_space: gym.Space = None + inference_only: bool = False + learner_only: bool = False + model_config_dict: Dict[str, Any] = field(default_factory=dict) + catalog_class: Type["Catalog"] = None + + def get_catalog(self) -> Optional["Catalog"]: + if self.catalog_class is not None: + return self.catalog_class( + observation_space=self.observation_space, + action_space=self.action_space, + model_config_dict=self.model_config_dict, + ) + return None + + def to_dict(self): + catalog_class_path = ( + serialize_type(self.catalog_class) if self.catalog_class else "" + ) + return { + "observation_space": gym_space_to_dict(self.observation_space), + "action_space": gym_space_to_dict(self.action_space), + "inference_only": self.inference_only, + "learner_only": self.learner_only, + "model_config_dict": self.model_config_dict, + "catalog_class_path": catalog_class_path, + } + + @classmethod + def from_dict(cls, d: Dict[str, Any]): + catalog_class = ( + None + if d["catalog_class_path"] == "" + else deserialize_type(d["catalog_class_path"]) + ) + return cls( + observation_space=gym_space_from_dict(d["observation_space"]), + action_space=gym_space_from_dict(d["action_space"]), + inference_only=d["inference_only"], + learner_only=d["learner_only"], + model_config_dict=d["model_config_dict"], + catalog_class=catalog_class, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/torch/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/torch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..217c5a5abc8aa4ec29708e81d0b2884256d8fae7 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/torch/__init__.py @@ -0,0 +1,3 @@ +from .torch_rl_module import TorchRLModule + +__all__ = ["TorchRLModule"] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/torch/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/torch/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..881b301fd6397bf85fa0e20c364a88cc0a203cb4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/torch/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/torch/__pycache__/torch_compile_config.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/torch/__pycache__/torch_compile_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0d9d7f55ca5ed98379b414b846a32d9969240af Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/torch/__pycache__/torch_compile_config.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/torch/__pycache__/torch_rl_module.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/torch/__pycache__/torch_rl_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..865427f887c728d35c598037eb063647ee51de2f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/torch/__pycache__/torch_rl_module.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/torch/torch_compile_config.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/torch/torch_compile_config.py new file mode 100644 index 0000000000000000000000000000000000000000..7c95c62fb52acab3c054c5cce7cc429046f1c84e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/torch/torch_compile_config.py @@ -0,0 +1,39 @@ +import sys +from dataclasses import dataclass, field + + +@dataclass +class TorchCompileConfig: + """Configuration options for RLlib's usage of torch.compile in RLModules. + + # On `torch.compile` in Torch RLModules + `torch.compile` invokes torch's dynamo JIT compiler that can potentially bring + speedups to RL Module's forward methods. + This is a performance optimization that should be disabled for debugging. + + General usage: + - Usually, you only want to `RLModule._forward_train` to be compiled on + instances of RLModule used for learning. (e.g. the learner) + - In some cases, it can bring speedups to also compile + `RLModule._forward_exploration` on instances used for exploration. (e.g. + RolloutWorker) + - In some cases, it can bring speedups to also compile + `RLModule._forward_inference` on instances used for inference. (e.g. + RolloutWorker) + + Note that different backends are available on different platforms. + Also note that the default backend for torch dynamo is "aot_eager" on macOS. + This is a debugging backend that is expected not to improve performance because + the inductor backend is not supported on OSX so far. + + Args: + torch_dynamo_backend: The torch.dynamo backend to use. + torch_dynamo_mode: The torch.dynamo mode to use. + kwargs: Additional keyword arguments to pass to `torch.compile()` + """ + + torch_dynamo_backend: str = ( + "aot_eager" if sys.platform == "darwin" else "cudagraphs" + ) + torch_dynamo_mode: str = None + kwargs: dict = field(default_factory=lambda: dict()) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/torch/torch_rl_module.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/torch/torch_rl_module.py new file mode 100644 index 0000000000000000000000000000000000000000..236e35b4f48b4d87c01bd4ee709b94f62605d011 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/rl_module/torch/torch_rl_module.py @@ -0,0 +1,306 @@ +from typing import Any, Collection, Dict, Optional, Union, Type + +import gymnasium as gym +from packaging import version + +from ray.rllib.core.rl_module.apis import InferenceOnlyAPI +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.core.rl_module.torch.torch_compile_config import TorchCompileConfig +from ray.rllib.core.distribution.torch.torch_distribution import ( + TorchCategorical, + TorchDiagGaussian, + TorchDistribution, +) +from ray.rllib.utils.annotations import override, OverrideToImplementCustomLogic +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.torch_utils import ( + convert_to_torch_tensor, + TORCH_COMPILE_REQUIRED_VERSION, +) +from ray.rllib.utils.typing import StateDict + +torch, nn = try_import_torch() + + +class TorchRLModule(nn.Module, RLModule): + """A base class for RLlib PyTorch RLModules. + + Note that the `_forward` methods of this class can be 'torch.compiled' individually: + - `TorchRLModule._forward_train()` + - `TorchRLModule._forward_inference()` + - `TorchRLModule._forward_exploration()` + + As a rule of thumb, they should only contain torch-native tensor manipulations, + or otherwise they may yield wrong outputs. In particular, the creation of RLlib + distributions inside these methods should be avoided when using `torch.compile`. + When in doubt, you can use `torch.dynamo.explain()` to check whether a compiled + method has broken up into multiple sub-graphs. + + Compiling these methods can bring speedups under certain conditions. + """ + + framework: str = "torch" + + # Stick with torch default. + STATE_FILE_NAME = "module_state" + + def __init__(self, *args, **kwargs) -> None: + nn.Module.__init__(self) + RLModule.__init__(self, *args, **kwargs) + + # If an inference-only class AND self.inference_only is True, + # remove all attributes that are returned by + # `self.get_non_inference_attributes()`. + if self.inference_only and isinstance(self, InferenceOnlyAPI): + for attr in self.get_non_inference_attributes(): + parts = attr.split(".") + if not hasattr(self, parts[0]): + continue + target_name = parts[0] + target_obj = getattr(self, target_name) + # Traverse from the next part on (if nested). + for part in parts[1:]: + if not hasattr(target_obj, part): + target_obj = None + break + target_name = part + target_obj = getattr(target_obj, target_name) + # Delete, if target is valid. + if target_obj is not None: + delattr(self, target_name) + + def compile(self, compile_config: TorchCompileConfig): + """Compile the forward methods of this module. + + This is a convenience method that calls `compile_wrapper` with the given + compile_config. + + Args: + compile_config: The compile config to use. + """ + return compile_wrapper(self, compile_config) + + @OverrideToImplementCustomLogic + def _forward_inference(self, batch: Dict[str, Any], **kwargs) -> Dict[str, Any]: + # By default, calls the generic `_forward()` method, but with a no-grad context + # for performance reasons. + with torch.no_grad(): + return self._forward(batch, **kwargs) + + @OverrideToImplementCustomLogic + def _forward_exploration(self, batch: Dict[str, Any], **kwargs) -> Dict[str, Any]: + # By default, calls the generic `_forward()` method, but with a no-grad context + # for performance reasons. + with torch.no_grad(): + return self._forward(batch, **kwargs) + + @OverrideToImplementCustomLogic + @override(RLModule) + def get_state( + self, + components: Optional[Union[str, Collection[str]]] = None, + *, + not_components: Optional[Union[str, Collection[str]]] = None, + inference_only: bool = False, + **kwargs, + ) -> StateDict: + state_dict = self.state_dict() + # Filter out `inference_only` keys from the state dict if `inference_only` and + # this RLModule is NOT `inference_only` (but does implement the + # InferenceOnlyAPI). + if ( + inference_only + and not self.inference_only + and isinstance(self, InferenceOnlyAPI) + ): + attr = self.get_non_inference_attributes() + for key in list(state_dict.keys()): + if any( + key.startswith(a) and (len(key) == len(a) or key[len(a)] == ".") + for a in attr + ): + del state_dict[key] + return convert_to_numpy(state_dict) + + @OverrideToImplementCustomLogic + @override(RLModule) + def set_state(self, state: StateDict) -> None: + # If state contains more keys than `self.state_dict()`, then we simply ignore + # these keys (strict=False). This is most likely due to `state` coming from + # an `inference_only=False` RLModule, while `self` is an `inference_only=True` + # RLModule. + self.load_state_dict(convert_to_torch_tensor(state), strict=False) + + @OverrideToImplementCustomLogic + @override(RLModule) + def get_inference_action_dist_cls(self) -> Type[TorchDistribution]: + if self.action_dist_cls is not None: + return self.action_dist_cls + elif isinstance(self.action_space, gym.spaces.Discrete): + return TorchCategorical + elif isinstance(self.action_space, gym.spaces.Box): + return TorchDiagGaussian + else: + raise ValueError( + f"Default action distribution for action space " + f"{self.action_space} not supported! Either set the " + f"`self.action_dist_cls` property in your RLModule's `setup()` method " + f"to a subclass of `ray.rllib.core.distribution.torch." + f"torch_distribution.TorchDistribution` or - if you need different " + f"distributions for inference and training - override the three " + f"methods: `get_inference_action_dist_cls`," + f"`get_exploration_action_dist_cls`, and `get_train_action_dist_cls` " + f"in your RLModule." + ) + + @OverrideToImplementCustomLogic + @override(RLModule) + def get_exploration_action_dist_cls(self) -> Type[TorchDistribution]: + return self.get_inference_action_dist_cls() + + @OverrideToImplementCustomLogic + @override(RLModule) + def get_train_action_dist_cls(self) -> Type[TorchDistribution]: + return self.get_inference_action_dist_cls() + + def forward(self, batch: Dict[str, Any], **kwargs) -> Dict[str, Any]: + """DO NOT OVERRIDE! + + This is aliased to `self.forward_train` because Torch DDP requires a forward + method to be implemented for backpropagation to work. + + Instead, override: + `_forward()` to define a generic forward pass for all phases (exploration, + inference, training) + `_forward_inference()` to define the forward pass for action inference in + deployment/production (no exploration). + `_forward_exploration()` to define the forward pass for action inference during + training sample collection (w/ exploration behavior). + `_forward_train()` to define the forward pass prior to loss computation. + """ + # TODO (sven): Experimental to make ONNX exported models work. + if self.config.inference_only: + return self.forward_exploration(batch, **kwargs) + else: + return self.forward_train(batch, **kwargs) + + +class TorchDDPRLModule(RLModule, nn.parallel.DistributedDataParallel): + def __init__(self, *args, **kwargs) -> None: + nn.parallel.DistributedDataParallel.__init__(self, *args, **kwargs) + # We do not want to call RLModule.__init__ here because all we need is + # the interface of that base-class not the actual implementation. + # RLModule.__init__(self, *args, **kwargs) + self.observation_space = self.unwrapped().observation_space + self.action_space = self.unwrapped().action_space + self.inference_only = self.unwrapped().inference_only + self.learner_only = self.unwrapped().learner_only + self.model_config = self.unwrapped().model_config + self.catalog = self.unwrapped().catalog + + # Deprecated. + self.config = self.unwrapped().config + + @override(RLModule) + def get_inference_action_dist_cls(self, *args, **kwargs) -> Type[TorchDistribution]: + return self.unwrapped().get_inference_action_dist_cls(*args, **kwargs) + + @override(RLModule) + def get_exploration_action_dist_cls( + self, *args, **kwargs + ) -> Type[TorchDistribution]: + return self.unwrapped().get_exploration_action_dist_cls(*args, **kwargs) + + @override(RLModule) + def get_train_action_dist_cls(self, *args, **kwargs) -> Type[TorchDistribution]: + return self.unwrapped().get_train_action_dist_cls(*args, **kwargs) + + @override(RLModule) + def get_initial_state(self) -> Any: + return self.unwrapped().get_initial_state() + + @override(RLModule) + def is_stateful(self) -> bool: + return self.unwrapped().is_stateful() + + @override(RLModule) + def _forward(self, *args, **kwargs): + return self.unwrapped()._forward(*args, **kwargs) + + @override(RLModule) + def _forward_inference(self, *args, **kwargs) -> Dict[str, Any]: + return self.unwrapped()._forward_inference(*args, **kwargs) + + @override(RLModule) + def _forward_exploration(self, *args, **kwargs) -> Dict[str, Any]: + return self.unwrapped()._forward_exploration(*args, **kwargs) + + @override(RLModule) + def _forward_train(self, *args, **kwargs): + return self(*args, **kwargs) + + @override(RLModule) + def get_state(self, *args, **kwargs): + return self.unwrapped().get_state(*args, **kwargs) + + @override(RLModule) + def set_state(self, *args, **kwargs): + self.unwrapped().set_state(*args, **kwargs) + + @override(RLModule) + def save_to_path(self, *args, **kwargs): + self.unwrapped().save_to_path(*args, **kwargs) + + @override(RLModule) + def restore_from_path(self, *args, **kwargs): + self.unwrapped().restore_from_path(*args, **kwargs) + + @override(RLModule) + def get_metadata(self, *args, **kwargs): + self.unwrapped().get_metadata(*args, **kwargs) + + @override(RLModule) + def unwrapped(self) -> "RLModule": + return self.module + + +def compile_wrapper(rl_module: "TorchRLModule", compile_config: TorchCompileConfig): + """A wrapper that compiles the forward methods of a TorchRLModule.""" + + # TODO(Artur): Remove this once our requirements enforce torch >= 2.0.0 + # Check if torch framework supports torch.compile. + if ( + torch is not None + and version.parse(torch.__version__) < TORCH_COMPILE_REQUIRED_VERSION + ): + raise ValueError("torch.compile is only supported from torch 2.0.0") + + compiled_forward_train = torch.compile( + rl_module._forward_train, + backend=compile_config.torch_dynamo_backend, + mode=compile_config.torch_dynamo_mode, + **compile_config.kwargs, + ) + + rl_module._forward_train = compiled_forward_train + + compiled_forward_inference = torch.compile( + rl_module._forward_inference, + backend=compile_config.torch_dynamo_backend, + mode=compile_config.torch_dynamo_mode, + **compile_config.kwargs, + ) + + rl_module._forward_inference = compiled_forward_inference + + compiled_forward_exploration = torch.compile( + rl_module._forward_exploration, + backend=compile_config.torch_dynamo_backend, + mode=compile_config.torch_dynamo_mode, + **compile_config.kwargs, + ) + + rl_module._forward_exploration = compiled_forward_exploration + + return rl_module diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81f8fb3d65e174459f28df30138f81d815772f6f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/__pycache__/bc_algorithm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/__pycache__/bc_algorithm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d4b64fad4818c1acb70b692665a6358ccada008 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/__pycache__/bc_algorithm.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/__pycache__/testing_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/__pycache__/testing_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d14f895c73161a1ac3f7c11df602da5583698b6b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/__pycache__/testing_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/bc_algorithm.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/bc_algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..950f2aec87ee17072781997e59cb80a603b7f630 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/bc_algorithm.py @@ -0,0 +1,40 @@ +"""Contains example implementation of a custom algorithm. + +Note: It doesn't include any real use-case functionality; it only serves as an example +to test the algorithm construction and customization. +""" + +from ray.rllib.algorithms import Algorithm, AlgorithmConfig +from ray.rllib.policy.torch_policy_v2 import TorchPolicyV2 +from ray.rllib.core.testing.torch.bc_module import DiscreteBCTorchModule +from ray.rllib.core.testing.torch.bc_learner import BCTorchLearner +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import ResultDict + + +class BCConfigTest(AlgorithmConfig): + def __init__(self, algo_class=None): + super().__init__(algo_class=algo_class or BCAlgorithmTest) + + def get_default_rl_module_spec(self): + if self.framework_str == "torch": + return RLModuleSpec(module_class=DiscreteBCTorchModule) + + def get_default_learner_class(self): + if self.framework_str == "torch": + return BCTorchLearner + + +class BCAlgorithmTest(Algorithm): + @classmethod + def get_default_policy_class(cls, config: AlgorithmConfig): + if config.framework_str == "torch": + return TorchPolicyV2 + else: + raise ValueError("Unknown framework: {}".format(config.framework_str)) + + @override(Algorithm) + def training_step(self) -> ResultDict: + # do nothing. + return {} diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/testing_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/testing_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..a16c0e11ae23fd00f090e375aed08142e05b43bd --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/testing_learner.py @@ -0,0 +1,67 @@ +from typing import Type + +import numpy as np + +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig +from ray.rllib.core import DEFAULT_MODULE_ID +from ray.rllib.core.learner.learner import Learner +from ray.rllib.core.rl_module.multi_rl_module import ( + MultiRLModule, + MultiRLModuleSpec, +) +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.utils.annotations import override +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.typing import RLModuleSpecType + + +class BaseTestingAlgorithmConfig(AlgorithmConfig): + # A test setting to activate metrics on mean weights. + report_mean_weights: bool = True + + @override(AlgorithmConfig) + def get_default_learner_class(self) -> Type["Learner"]: + if self.framework_str == "torch": + from ray.rllib.core.testing.torch.bc_learner import BCTorchLearner + + return BCTorchLearner + else: + raise ValueError(f"Unsupported framework: {self.framework_str}") + + @override(AlgorithmConfig) + def get_default_rl_module_spec(self) -> "RLModuleSpecType": + if self.framework_str == "torch": + from ray.rllib.core.testing.torch.bc_module import DiscreteBCTorchModule + + cls = DiscreteBCTorchModule + else: + raise ValueError(f"Unsupported framework: {self.framework_str}") + + spec = RLModuleSpec( + module_class=cls, + model_config={"fcnet_hiddens": [32]}, + ) + + if self.is_multi_agent: + # TODO (Kourosh): Make this more multi-agent for example with policy ids + # "1" and "2". + return MultiRLModuleSpec( + multi_rl_module_class=MultiRLModule, + rl_module_specs={DEFAULT_MODULE_ID: spec}, + ) + else: + return spec + + +class BaseTestingLearner(Learner): + @override(Learner) + def after_gradient_based_update(self, *, timesteps): + # This is to check if in the multi-gpu case, the weights across workers are + # the same. It is really only needed during testing. + if self.config.report_mean_weights: + for module_id in self.module.keys(): + parameters = convert_to_numpy( + self.get_parameters(self.module[module_id]) + ) + mean_ws = np.mean([w.mean() for w in parameters]) + self.metrics.log_value((module_id, "mean_weight"), mean_ws, window=1) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/torch/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/torch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/torch/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/torch/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be541b5f5605f6d7008a2da96ba016d339bf46c4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/torch/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/torch/__pycache__/bc_learner.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/torch/__pycache__/bc_learner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1eb9a68dfd5d94db622a4d6aca62e7120be33b8d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/torch/__pycache__/bc_learner.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/torch/bc_learner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/torch/bc_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..1c12aee7a1ee84a0d6edf995cae8963b93527aa1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/torch/bc_learner.py @@ -0,0 +1,34 @@ +import torch +from typing import Any, Dict, TYPE_CHECKING + +from ray.rllib.core.columns import Columns +from ray.rllib.core.learner.torch.torch_learner import TorchLearner +from ray.rllib.core.testing.testing_learner import BaseTestingLearner +from ray.rllib.utils.typing import ModuleID, TensorType + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + + +class BCTorchLearner(TorchLearner, BaseTestingLearner): + def compute_loss_for_module( + self, + *, + module_id: ModuleID, + config: "AlgorithmConfig", + batch: Dict[str, Any], + fwd_out: Dict[str, TensorType], + ) -> TensorType: + BaseTestingLearner.compute_loss_for_module( + self, + module_id=module_id, + config=config, + batch=batch, + fwd_out=fwd_out, + ) + action_dist_inputs = fwd_out[Columns.ACTION_DIST_INPUTS] + action_dist_class = self._module[module_id].get_train_action_dist_cls() + action_dist = action_dist_class.from_logits(action_dist_inputs) + loss = -torch.mean(action_dist.logp(batch[Columns.ACTIONS])) + + return loss diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/torch/bc_module.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/torch/bc_module.py new file mode 100644 index 0000000000000000000000000000000000000000..b3fc35556db696154b9f60bc1537beed638ac6fd --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/core/testing/torch/bc_module.py @@ -0,0 +1,149 @@ +from typing import Any, Dict + +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.core.distribution.torch.torch_distribution import TorchCategorical +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModule +from ray.rllib.core.rl_module.torch.torch_rl_module import TorchRLModule +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch + +torch, nn = try_import_torch() + + +class DiscreteBCTorchModule(TorchRLModule): + def setup(self): + input_dim = self.observation_space.shape[0] + hidden_dim = self.model_config["fcnet_hiddens"][0] + output_dim = self.action_space.n + + self.policy = nn.Sequential( + nn.Linear(input_dim, hidden_dim), + nn.ReLU(), + nn.Linear(hidden_dim, output_dim), + ) + + self.input_dim = input_dim + + def get_train_action_dist_cls(self): + return TorchCategorical + + def get_exploration_action_dist_cls(self): + return TorchCategorical + + def get_inference_action_dist_cls(self): + return TorchCategorical + + @override(RLModule) + def _forward_inference(self, batch: Dict[str, Any]) -> Dict[str, Any]: + with torch.no_grad(): + return self._forward_train(batch) + + @override(RLModule) + def _forward_exploration(self, batch: Dict[str, Any]) -> Dict[str, Any]: + with torch.no_grad(): + return self._forward_train(batch) + + @override(RLModule) + def _forward_train(self, batch: Dict[str, Any]) -> Dict[str, Any]: + action_logits = self.policy(batch["obs"]) + return {Columns.ACTION_DIST_INPUTS: action_logits} + + +class BCTorchRLModuleWithSharedGlobalEncoder(TorchRLModule): + """An example of an RLModule that uses an encoder shared with other things. + + For example, we could consider a multi-agent case where for inference each agent + needs to know the global state of the environment, as well as the local state of + itself. For better representation learning we would like to share the encoder + across all the modules. So this module simply accepts the encoder object as its + input argument and uses it to encode the global state. The local state is passed + through as is. The policy head is then a simple MLP that takes the concatenation of + the global and local state as input and outputs the action logits. + + """ + + def __init__( + self, + encoder: nn.Module, + local_dim: int, + hidden_dim: int, + action_dim: int, + config=None, + ) -> None: + super().__init__(config=config) + + self.encoder = encoder + self.policy_head = nn.Sequential( + nn.Linear(hidden_dim + local_dim, hidden_dim), + nn.ReLU(), + nn.Linear(hidden_dim, action_dim), + ) + + def get_train_action_dist_cls(self): + return TorchCategorical + + def get_exploration_action_dist_cls(self): + return TorchCategorical + + def get_inference_action_dist_cls(self): + return TorchCategorical + + @override(RLModule) + def _default_input_specs(self): + return [("obs", "global"), ("obs", "local")] + + @override(RLModule) + def _forward_inference(self, batch): + with torch.no_grad(): + return self._common_forward(batch) + + @override(RLModule) + def _forward_exploration(self, batch): + with torch.no_grad(): + return self._common_forward(batch) + + @override(RLModule) + def _forward_train(self, batch): + return self._common_forward(batch) + + def _common_forward(self, batch): + obs = batch["obs"] + global_enc = self.encoder(obs["global"]) + policy_in = torch.cat([global_enc, obs["local"]], dim=-1) + action_logits = self.policy_head(policy_in) + + return {Columns.ACTION_DIST_INPUTS: action_logits} + + +class BCTorchMultiAgentModuleWithSharedEncoder(MultiRLModule): + def setup(self): + module_specs = self.config.modules + module_spec = next(iter(module_specs.values())) + global_dim = module_spec.observation_space["global"].shape[0] + hidden_dim = module_spec.model_config_dict["fcnet_hiddens"][0] + shared_encoder = nn.Sequential( + nn.Linear(global_dim, hidden_dim), + nn.ReLU(), + nn.Linear(hidden_dim, hidden_dim), + ) + + rl_modules = {} + for module_id, module_spec in module_specs.items(): + rl_modules[module_id] = module_spec.module_class( + config=self.config.modules[module_id].get_rl_module_config(), + encoder=shared_encoder, + local_dim=module_spec.observation_space["local"].shape[0], + hidden_dim=hidden_dim, + action_dim=module_spec.action_space.n, + ) + + self._rl_modules = rl_modules + + def serialize(self): + # TODO (Kourosh): Implement when needed. + raise NotImplementedError + + def deserialize(self, data): + # TODO (Kourosh): Implement when needed. + raise NotImplementedError diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2e48374d784c22e15f6e2b1188afc12e0eff528f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/__init__.py @@ -0,0 +1,40 @@ +from ray.rllib.env.base_env import BaseEnv +from ray.rllib.env.env_context import EnvContext +from ray.rllib.env.external_env import ExternalEnv +from ray.rllib.env.external_multi_agent_env import ExternalMultiAgentEnv +from ray.rllib.env.multi_agent_env import MultiAgentEnv +from ray.rllib.env.policy_client import PolicyClient +from ray.rllib.env.policy_server_input import PolicyServerInput +from ray.rllib.env.remote_base_env import RemoteBaseEnv +from ray.rllib.env.vector_env import VectorEnv + +from ray.rllib.env.wrappers.dm_env_wrapper import DMEnv +from ray.rllib.env.wrappers.dm_control_wrapper import DMCEnv +from ray.rllib.env.wrappers.group_agents_wrapper import GroupAgentsWrapper +from ray.rllib.env.wrappers.pettingzoo_env import PettingZooEnv +from ray.rllib.env.wrappers.pettingzoo_env import ParallelPettingZooEnv +from ray.rllib.env.wrappers.unity3d_env import Unity3DEnv + +INPUT_ENV_SPACES = "__env__" +INPUT_ENV_SINGLE_SPACES = "__env_single__" + + +__all__ = [ + "BaseEnv", + "DMEnv", + "DMCEnv", + "EnvContext", + "ExternalEnv", + "ExternalMultiAgentEnv", + "GroupAgentsWrapper", + "MultiAgentEnv", + "PettingZooEnv", + "ParallelPettingZooEnv", + "PolicyClient", + "PolicyServerInput", + "RemoteBaseEnv", + "Unity3DEnv", + "VectorEnv", + "INPUT_ENV_SPACES", + "INPUT_ENV_SINGLE_SPACES", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/base_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/base_env.py new file mode 100644 index 0000000000000000000000000000000000000000..c67c642e4763f819e1b6143f362cab8ad1aa8472 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/base_env.py @@ -0,0 +1,428 @@ +import logging +from typing import Callable, Tuple, Optional, List, Dict, Any, TYPE_CHECKING, Union, Set + +import gymnasium as gym +import ray +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.typing import AgentID, EnvID, EnvType, MultiEnvDict + +if TYPE_CHECKING: + from ray.rllib.evaluation.rollout_worker import RolloutWorker + +ASYNC_RESET_RETURN = "async_reset_return" + +logger = logging.getLogger(__name__) + + +@OldAPIStack +class BaseEnv: + """The lowest-level env interface used by RLlib for sampling. + + BaseEnv models multiple agents executing asynchronously in multiple + vectorized sub-environments. A call to `poll()` returns observations from + ready agents keyed by their sub-environment ID and agent IDs, and + actions for those agents can be sent back via `send_actions()`. + + All other RLlib supported env types can be converted to BaseEnv. + RLlib handles these conversions internally in RolloutWorker, for example: + + gym.Env => rllib.VectorEnv => rllib.BaseEnv + rllib.MultiAgentEnv (is-a gym.Env) => rllib.VectorEnv => rllib.BaseEnv + rllib.ExternalEnv => rllib.BaseEnv + + .. testcode:: + :skipif: True + + MyBaseEnv = ... + env = MyBaseEnv() + obs, rewards, terminateds, truncateds, infos, off_policy_actions = ( + env.poll() + ) + print(obs) + + env.send_actions({ + "env_0": { + "car_0": 0, + "car_1": 1, + }, ... + }) + obs, rewards, terminateds, truncateds, infos, off_policy_actions = ( + env.poll() + ) + print(obs) + + print(terminateds) + + .. testoutput:: + + { + "env_0": { + "car_0": [2.4, 1.6], + "car_1": [3.4, -3.2], + }, + "env_1": { + "car_0": [8.0, 4.1], + }, + "env_2": { + "car_0": [2.3, 3.3], + "car_1": [1.4, -0.2], + "car_3": [1.2, 0.1], + }, + } + { + "env_0": { + "car_0": [4.1, 1.7], + "car_1": [3.2, -4.2], + }, ... + } + { + "env_0": { + "__all__": False, + "car_0": False, + "car_1": True, + }, ... + } + + """ + + def to_base_env( + self, + make_env: Optional[Callable[[int], EnvType]] = None, + num_envs: int = 1, + remote_envs: bool = False, + remote_env_batch_wait_ms: int = 0, + restart_failed_sub_environments: bool = False, + ) -> "BaseEnv": + """Converts an RLlib-supported env into a BaseEnv object. + + Supported types for the `env` arg are gym.Env, BaseEnv, + VectorEnv, MultiAgentEnv, ExternalEnv, or ExternalMultiAgentEnv. + + The resulting BaseEnv is always vectorized (contains n + sub-environments) to support batched forward passes, where n may also + be 1. BaseEnv also supports async execution via the `poll` and + `send_actions` methods and thus supports external simulators. + + TODO: Support gym3 environments, which are already vectorized. + + Args: + env: An already existing environment of any supported env type + to convert/wrap into a BaseEnv. Supported types are gym.Env, + BaseEnv, VectorEnv, MultiAgentEnv, ExternalEnv, and + ExternalMultiAgentEnv. + make_env: A callable taking an int as input (which indicates the + number of individual sub-environments within the final + vectorized BaseEnv) and returning one individual + sub-environment. + num_envs: The number of sub-environments to create in the + resulting (vectorized) BaseEnv. The already existing `env` + will be one of the `num_envs`. + remote_envs: Whether each sub-env should be a @ray.remote actor. + You can set this behavior in your config via the + `remote_worker_envs=True` option. + remote_env_batch_wait_ms: The wait time (in ms) to poll remote + sub-environments for, if applicable. Only used if + `remote_envs` is True. + policy_config: Optional policy config dict. + + Returns: + The resulting BaseEnv object. + """ + return self + + def poll( + self, + ) -> Tuple[ + MultiEnvDict, + MultiEnvDict, + MultiEnvDict, + MultiEnvDict, + MultiEnvDict, + MultiEnvDict, + ]: + """Returns observations from ready agents. + + All return values are two-level dicts mapping from EnvID to dicts + mapping from AgentIDs to (observation/reward/etc..) values. + The number of agents and sub-environments may vary over time. + + Returns: + Tuple consisting of: + New observations for each ready agent. + Reward values for each ready agent. If the episode is just started, + the value will be None. + Terminated values for each ready agent. The special key "__all__" is used to + indicate episode termination. + Truncated values for each ready agent. The special key "__all__" + is used to indicate episode truncation. + Info values for each ready agent. + Agents may take off-policy actions, in which case, there will be an entry + in this dict that contains the taken action. There is no need to + `send_actions()` for agents that have already chosen off-policy actions. + """ + raise NotImplementedError + + def send_actions(self, action_dict: MultiEnvDict) -> None: + """Called to send actions back to running agents in this env. + + Actions should be sent for each ready agent that returned observations + in the previous poll() call. + + Args: + action_dict: Actions values keyed by env_id and agent_id. + """ + raise NotImplementedError + + def try_reset( + self, + env_id: Optional[EnvID] = None, + *, + seed: Optional[int] = None, + options: Optional[dict] = None, + ) -> Tuple[Optional[MultiEnvDict], Optional[MultiEnvDict]]: + """Attempt to reset the sub-env with the given id or all sub-envs. + + If the environment does not support synchronous reset, a tuple of + (ASYNC_RESET_REQUEST, ASYNC_RESET_REQUEST) can be returned here. + + Note: A MultiAgentDict is returned when using the deprecated wrapper + classes such as `ray.rllib.env.base_env._MultiAgentEnvToBaseEnv`, + however for consistency with the poll() method, a `MultiEnvDict` is + returned from the new wrapper classes, such as + `ray.rllib.env.multi_agent_env.MultiAgentEnvWrapper`. + + Args: + env_id: The sub-environment's ID if applicable. If None, reset + the entire Env (i.e. all sub-environments). + seed: The seed to be passed to the sub-environment(s) when + resetting it. If None, will not reset any existing PRNG. If you pass an + integer, the PRNG will be reset even if it already exists. + options: An options dict to be passed to the sub-environment(s) when + resetting it. + + Returns: + A tuple consisting of a) the reset (multi-env/multi-agent) observation + dict and b) the reset (multi-env/multi-agent) infos dict. Returns the + (ASYNC_RESET_REQUEST, ASYNC_RESET_REQUEST) tuple, if not supported. + """ + return None, None + + def try_restart(self, env_id: Optional[EnvID] = None) -> None: + """Attempt to restart the sub-env with the given id or all sub-envs. + + This could result in the sub-env being completely removed (gc'd) and recreated. + + Args: + env_id: The sub-environment's ID, if applicable. If None, restart + the entire Env (i.e. all sub-environments). + """ + return None + + def get_sub_environments(self, as_dict: bool = False) -> Union[List[EnvType], dict]: + """Return a reference to the underlying sub environments, if any. + + Args: + as_dict: If True, return a dict mapping from env_id to env. + + Returns: + List or dictionary of the underlying sub environments or [] / {}. + """ + if as_dict: + return {} + return [] + + def get_agent_ids(self) -> Set[AgentID]: + """Return the agent ids for the sub_environment. + + Returns: + All agent ids for each the environment. + """ + return {} + + def try_render(self, env_id: Optional[EnvID] = None) -> None: + """Tries to render the sub-environment with the given id or all. + + Args: + env_id: The sub-environment's ID, if applicable. + If None, renders the entire Env (i.e. all sub-environments). + """ + + # By default, do nothing. + pass + + def stop(self) -> None: + """Releases all resources used.""" + + # Try calling `close` on all sub-environments. + for env in self.get_sub_environments(): + if hasattr(env, "close"): + env.close() + + @property + def observation_space(self) -> gym.Space: + """Returns the observation space for each agent. + + Note: samples from the observation space need to be preprocessed into a + `MultiEnvDict` before being used by a policy. + + Returns: + The observation space for each environment. + """ + raise NotImplementedError + + @property + def action_space(self) -> gym.Space: + """Returns the action space for each agent. + + Note: samples from the action space need to be preprocessed into a + `MultiEnvDict` before being passed to `send_actions`. + + Returns: + The observation space for each environment. + """ + raise NotImplementedError + + def last( + self, + ) -> Tuple[MultiEnvDict, MultiEnvDict, MultiEnvDict, MultiEnvDict, MultiEnvDict]: + """Returns the last observations, rewards, done- truncated flags and infos ... + + that were returned by the environment. + + Returns: + The last observations, rewards, done- and truncated flags, and infos + for each sub-environment. + """ + logger.warning("last has not been implemented for this environment.") + return {}, {}, {}, {}, {} + + +# Fixed agent identifier when there is only the single agent in the env +_DUMMY_AGENT_ID = "agent0" + + +@OldAPIStack +def with_dummy_agent_id( + env_id_to_values: Dict[EnvID, Any], dummy_id: "AgentID" = _DUMMY_AGENT_ID +) -> MultiEnvDict: + ret = {} + for (env_id, value) in env_id_to_values.items(): + # If the value (e.g. the observation) is an Exception, publish this error + # under the env ID so the caller of `poll()` knows that the entire episode + # (sub-environment) has crashed. + ret[env_id] = value if isinstance(value, Exception) else {dummy_id: value} + return ret + + +@OldAPIStack +def convert_to_base_env( + env: EnvType, + make_env: Callable[[int], EnvType] = None, + num_envs: int = 1, + remote_envs: bool = False, + remote_env_batch_wait_ms: int = 0, + worker: Optional["RolloutWorker"] = None, + restart_failed_sub_environments: bool = False, +) -> "BaseEnv": + """Converts an RLlib-supported env into a BaseEnv object. + + Supported types for the `env` arg are gym.Env, BaseEnv, + VectorEnv, MultiAgentEnv, ExternalEnv, or ExternalMultiAgentEnv. + + The resulting BaseEnv is always vectorized (contains n + sub-environments) to support batched forward passes, where n may also + be 1. BaseEnv also supports async execution via the `poll` and + `send_actions` methods and thus supports external simulators. + + TODO: Support gym3 environments, which are already vectorized. + + Args: + env: An already existing environment of any supported env type + to convert/wrap into a BaseEnv. Supported types are gym.Env, + BaseEnv, VectorEnv, MultiAgentEnv, ExternalEnv, and + ExternalMultiAgentEnv. + make_env: A callable taking an int as input (which indicates the + number of individual sub-environments within the final + vectorized BaseEnv) and returning one individual + sub-environment. + num_envs: The number of sub-environments to create in the + resulting (vectorized) BaseEnv. The already existing `env` + will be one of the `num_envs`. + remote_envs: Whether each sub-env should be a @ray.remote actor. + You can set this behavior in your config via the + `remote_worker_envs=True` option. + remote_env_batch_wait_ms: The wait time (in ms) to poll remote + sub-environments for, if applicable. Only used if + `remote_envs` is True. + worker: An optional RolloutWorker that owns the env. This is only + used if `remote_worker_envs` is True in your config and the + `on_sub_environment_created` custom callback needs to be called + on each created actor. + restart_failed_sub_environments: If True and any sub-environment (within + a vectorized env) throws any error during env stepping, the + Sampler will try to restart the faulty sub-environment. This is done + without disturbing the other (still intact) sub-environment and without + the RolloutWorker crashing. + + Returns: + The resulting BaseEnv object. + """ + + from ray.rllib.env.remote_base_env import RemoteBaseEnv + from ray.rllib.env.external_env import ExternalEnv + from ray.rllib.env.multi_agent_env import MultiAgentEnv + from ray.rllib.env.vector_env import VectorEnv, VectorEnvWrapper + + if remote_envs and num_envs == 1: + raise ValueError( + "Remote envs only make sense to use if num_envs > 1 " + "(i.e. environment vectorization is enabled)." + ) + + # Given `env` has a `to_base_env` method -> Call that to convert to a BaseEnv type. + if isinstance(env, (BaseEnv, MultiAgentEnv, VectorEnv, ExternalEnv)): + return env.to_base_env( + make_env=make_env, + num_envs=num_envs, + remote_envs=remote_envs, + remote_env_batch_wait_ms=remote_env_batch_wait_ms, + restart_failed_sub_environments=restart_failed_sub_environments, + ) + # `env` is not a BaseEnv yet -> Need to convert/vectorize. + else: + # Sub-environments are ray.remote actors: + if remote_envs: + # Determine, whether the already existing sub-env (could + # be a ray.actor) is multi-agent or not. + multiagent = ( + ray.get(env._is_multi_agent.remote()) + if hasattr(env, "_is_multi_agent") + else False + ) + env = RemoteBaseEnv( + make_env, + num_envs, + multiagent=multiagent, + remote_env_batch_wait_ms=remote_env_batch_wait_ms, + existing_envs=[env], + worker=worker, + restart_failed_sub_environments=restart_failed_sub_environments, + ) + # Sub-environments are not ray.remote actors. + else: + # Convert gym.Env to VectorEnv ... + env = VectorEnv.vectorize_gym_envs( + make_env=make_env, + existing_envs=[env], + num_envs=num_envs, + action_space=env.action_space, + observation_space=env.observation_space, + restart_failed_sub_environments=restart_failed_sub_environments, + ) + # ... then the resulting VectorEnv to a BaseEnv. + env = VectorEnvWrapper(env) + + # Make sure conversion went well. + assert isinstance(env, BaseEnv), env + + return env diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/env_context.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/env_context.py new file mode 100644 index 0000000000000000000000000000000000000000..2dbdae17c6add842021b1b33a4e476c15bfcc86d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/env_context.py @@ -0,0 +1,128 @@ +import copy +from typing import Optional + +from ray.rllib.utils.typing import EnvConfigDict +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +class EnvContext(dict): + """Wraps env configurations to include extra rllib metadata. + + These attributes can be used to parameterize environments per process. + For example, one might use `worker_index` to control which data file an + environment reads in on initialization. + + RLlib auto-sets these attributes when constructing registered envs. + """ + + def __init__( + self, + env_config: EnvConfigDict, + worker_index: int, + vector_index: int = 0, + remote: bool = False, + num_workers: Optional[int] = None, + recreated_worker: bool = False, + ): + """Initializes an EnvContext instance. + + Args: + env_config: The env's configuration defined under the + "env_config" key in the Algorithm's config. + worker_index: When there are multiple workers created, this + uniquely identifies the worker the env is created in. + 0 for local worker, >0 for remote workers. + vector_index: When there are multiple envs per worker, this + uniquely identifies the env index within the worker. + Starts from 0. + remote: Whether individual sub-environments (in a vectorized + env) should be @ray.remote actors or not. + num_workers: The total number of (remote) workers in the set. + 0 if only a local worker exists. + recreated_worker: Whether the worker that holds this env is a recreated one. + This means that it replaced a previous (failed) worker when + `restart_failed_env_runners=True` in the Algorithm's config. + """ + # Store the env_config in the (super) dict. + dict.__init__(self, env_config) + + # Set some metadata attributes. + self.worker_index = worker_index + self.vector_index = vector_index + self.remote = remote + self.num_workers = num_workers + self.recreated_worker = recreated_worker + + def copy_with_overrides( + self, + env_config: Optional[EnvConfigDict] = None, + worker_index: Optional[int] = None, + vector_index: Optional[int] = None, + remote: Optional[bool] = None, + num_workers: Optional[int] = None, + recreated_worker: Optional[bool] = None, + ) -> "EnvContext": + """Returns a copy of this EnvContext with some attributes overridden. + + Args: + env_config: Optional env config to use. None for not overriding + the one from the source (self). + worker_index: Optional worker index to use. None for not + overriding the one from the source (self). + vector_index: Optional vector index to use. None for not + overriding the one from the source (self). + remote: Optional remote setting to use. None for not overriding + the one from the source (self). + num_workers: Optional num_workers to use. None for not overriding + the one from the source (self). + recreated_worker: Optional flag, indicating, whether the worker that holds + the env is a recreated one. This means that it replaced a previous + (failed) worker when `restart_failed_env_runners=True` in the + Algorithm's config. + + Returns: + A new EnvContext object as a copy of self plus the provided + overrides. + """ + return EnvContext( + copy.deepcopy(env_config) if env_config is not None else self, + worker_index if worker_index is not None else self.worker_index, + vector_index if vector_index is not None else self.vector_index, + remote if remote is not None else self.remote, + num_workers if num_workers is not None else self.num_workers, + recreated_worker if recreated_worker is not None else self.recreated_worker, + ) + + def set_defaults(self, defaults: dict) -> None: + """Sets missing keys of self to the values given in `defaults`. + + If `defaults` contains keys that already exist in self, don't override + the values with these defaults. + + Args: + defaults: The key/value pairs to add to self, but only for those + keys in `defaults` that don't exist yet in self. + + .. testcode:: + :skipif: True + + from ray.rllib.env.env_context import EnvContext + env_ctx = EnvContext({"a": 1, "b": 2}, worker_index=0) + env_ctx.set_defaults({"a": -42, "c": 3}) + print(env_ctx) + + .. testoutput:: + + {"a": 1, "b": 2, "c": 3} + """ + for key, value in defaults.items(): + if key not in self: + self[key] = value + + def __str__(self): + return ( + super().__str__()[:-1] + + f", worker={self.worker_index}/{self.num_workers}, " + f"vector_idx={self.vector_index}, remote={self.remote}" + "}" + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/env_runner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/env_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..7d3a7a9d488e76719ecb0009b434bd73a4793633 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/env_runner.py @@ -0,0 +1,255 @@ +import abc +import logging +from typing import Any, Dict, Optional, Tuple, TYPE_CHECKING + +import gymnasium as gym +import tree # pip install dm_tree + +import ray +from ray.rllib.core import COMPONENT_RL_MODULE +from ray.rllib.utils.actor_manager import FaultAwareApply +from ray.rllib.utils.debug import update_global_seed_if_necessary +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.metrics import ENV_RESET_TIMER, ENV_STEP_TIMER +from ray.rllib.utils.metrics.metrics_logger import MetricsLogger +from ray.rllib.utils.torch_utils import convert_to_torch_tensor +from ray.rllib.utils.typing import StateDict, TensorType +from ray.util.annotations import PublicAPI, DeveloperAPI + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + +logger = logging.getLogger("ray.rllib") + +tf1, tf, _ = try_import_tf() + +ENV_RESET_FAILURE = "env_reset_failure" +ENV_STEP_FAILURE = "env_step_failure" + + +# TODO (sven): As soon as RolloutWorker is no longer supported, make this base class +# a Checkpointable. Currently, only some of its subclasses are Checkpointables. +@PublicAPI(stability="alpha") +class EnvRunner(FaultAwareApply, metaclass=abc.ABCMeta): + """Base class for distributed RL-style data collection from an environment. + + The EnvRunner API's core functionalities can be summarized as: + - Gets configured via passing a AlgorithmConfig object to the constructor. + Normally, subclasses of EnvRunner then construct their own environment (possibly + vectorized) copies and RLModules/Policies and use the latter to step through the + environment in order to collect training data. + - Clients of EnvRunner can use the `sample()` method to collect data for training + from the environment(s). + - EnvRunner offers parallelism via creating n remote Ray Actors based on this class. + Use `ray.remote([resources])(EnvRunner)` method to create the corresponding Ray + remote class. Then instantiate n Actors using the Ray `[ctor].remote(...)` syntax. + - EnvRunner clients can get information about the server/node on which the + individual Actors are running. + """ + + def __init__(self, *, config: "AlgorithmConfig", **kwargs): + """Initializes an EnvRunner instance. + + Args: + config: The AlgorithmConfig to use to setup this EnvRunner. + **kwargs: Forward compatibility kwargs. + """ + self.config: AlgorithmConfig = config.copy(copy_frozen=False) + + # Get the worker index on which this instance is running. + + # TODO (sven): We should make these c'tor named args. + self.worker_index: int = kwargs.get("worker_index") + self.num_workers: int = kwargs.get("num_workers", self.config.num_env_runners) + + self.env = None + # Create a MetricsLogger object for logging custom stats. + self.metrics: MetricsLogger = MetricsLogger() + + super().__init__() + + # This eager check is necessary for certain all-framework tests + # that use tf's eager_mode() context generator. + if ( + tf1 + and (self.config.framework_str == "tf2" or config.enable_tf1_exec_eagerly) + and not tf1.executing_eagerly() + ): + tf1.enable_eager_execution() + + # Determine actual seed for this particular worker based on worker index AND + # whether it's an eval worker. + self._seed: Optional[int] = None + if self.config.seed is not None: + self._seed = int( + self.config.seed + + (self.worker_index or 0) + # Eval workers get a +1M seed. + + (1e6 * self.config.in_evaluation) + ) + # Seed everything (random, numpy, torch, tf), if `seed` is provided. + update_global_seed_if_necessary( + framework=self.config.framework_str, + seed=self._seed, + ) + + @abc.abstractmethod + def assert_healthy(self): + """Checks that self.__init__() has been completed properly. + + Useful in case an `EnvRunner` is run as @ray.remote (Actor) and the owner + would like to make sure the Ray Actor has been properly initialized. + + Raises: + AssertionError: If the EnvRunner Actor has NOT been properly initialized. + """ + + # TODO: Make this an abstract method that must be implemented. + def make_env(self): + """Creates the RL environment for this EnvRunner and assigns it to `self.env`. + + Note that users should be able to change the EnvRunner's config (e.g. change + `self.config.env_config`) and then call this method to create new environments + with the updated configuration. + It should also be called after a failure of an earlier env in order to clean up + the existing env (for example `close()` it), re-create a new one, and then + continue sampling with that new env. + """ + pass + + # TODO: Make this an abstract method that must be implemented. + def make_module(self): + """Creates the RLModule for this EnvRunner and assigns it to `self.module`. + + Note that users should be able to change the EnvRunner's config (e.g. change + `self.config.rl_module_spec`) and then call this method to create a new RLModule + with the updated configuration. + """ + pass + + @abc.abstractmethod + def sample(self, **kwargs) -> Any: + """Returns experiences (of any form) sampled from this EnvRunner. + + The exact nature and size of collected data are defined via the EnvRunner's + config and may be overridden by the given arguments. + + Args: + **kwargs: Forward compatibility kwargs. + + Returns: + The collected experience in any form. + """ + + # TODO (sven): Make this an abstract method that must be overridden. + def get_metrics(self) -> Any: + """Returns metrics (in any form) of the thus far collected, completed episodes. + + Returns: + Metrics of any form. + """ + pass + + @DeveloperAPI + def sample_get_state_and_metrics( + self, + ) -> Tuple[ray.ObjectRef, StateDict, StateDict]: + """Convenience method for fast, async algorithms. + + Use this in Algorithms that need to sample Episode lists as ray.ObjectRef, but + also require (in the same remote call) the metrics and the EnvRunner states, + except for the module weights. + """ + _episodes = self.sample() + # Get the EnvRunner's connector states. + _connector_states = self.get_state(not_components=COMPONENT_RL_MODULE) + _metrics = self.get_metrics() + # Return episode lists by reference so we don't have to send them to the + # main algo process, but to the Aggregator- or Learner actors directly. + return ray.put(_episodes), _connector_states, _metrics + + @abc.abstractmethod + def get_spaces(self) -> Dict[str, Tuple[gym.Space, gym.Space]]: + """Returns a dict mapping ModuleIDs to 2-tuples of obs- and action space.""" + + def stop(self) -> None: + """Releases all resources used by this EnvRunner. + + For example, when using a gym.Env in this EnvRunner, you should make sure + that its `close()` method is called. + """ + pass + + def __del__(self) -> None: + """If this Actor is deleted, clears all resources used by it.""" + pass + + def _try_env_reset( + self, + *, + seed: Optional[int] = None, + options: Optional[dict] = None, + ) -> Tuple[Any, Any]: + """Tries resetting the env and - if an error occurs - handles it gracefully. + + Args: + seed: An optional seed (int) to be passed to the Env.reset() call. + options: An optional options-dict to be passed to the Env.reset() call. + + Returns: + The results of calling `Env.reset()`, which is a tuple of observations and + info dicts. + + Raises: + Exception: In case `config.restart_failed_sub_environments` is False and + `Env.reset()` resulted in an error. + """ + # Try to reset. + try: + with self.metrics.log_time(ENV_RESET_TIMER): + obs, infos = self.env.reset(seed=seed, options=options) + # Everything ok -> return. + return obs, infos + # Error. + except Exception as e: + # If user wants to simply restart the env -> recreate env and try again + # (calling this method recursively until success). + if self.config.restart_failed_sub_environments: + logger.exception( + "Resetting the env resulted in an error! The original error " + f"is: {e.args[0]}" + ) + # Recreate the env and simply try again. + self.make_env() + return self._try_env_reset(seed=seed, options=options) + else: + raise e + + def _try_env_step(self, actions): + """Tries stepping the env and - if an error orrurs - handles it gracefully.""" + try: + with self.metrics.log_time(ENV_STEP_TIMER): + results = self.env.step(actions) + return results + except Exception as e: + if self.config.restart_failed_sub_environments: + logger.exception( + "Stepping the env resulted in an error! The original error " + f"is: {e.args[0]}" + ) + # Recreate the env. + self.make_env() + # And return that the stepping failed. The caller will then handle + # specific cleanup operations (for example discarding thus-far collected + # data and repeating the step attempt). + return ENV_STEP_FAILURE + else: + raise e + + def _convert_to_tensor(self, struct) -> TensorType: + """Converts structs to a framework-specific tensor.""" + + if self.config.framework_str == "torch": + return convert_to_torch_tensor(struct) + else: + return tree.map_structure(tf.convert_to_tensor, struct) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/env_runner_group.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/env_runner_group.py new file mode 100644 index 0000000000000000000000000000000000000000..7d49910598dc733d4b4a0d645a1070e56a8ac452 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/env_runner_group.py @@ -0,0 +1,1366 @@ +import functools +import gymnasium as gym +import logging +import importlib.util +import os +from typing import ( + Any, + Callable, + Collection, + Dict, + List, + Optional, + Tuple, + Type, + TYPE_CHECKING, + TypeVar, + Union, +) + +import ray +from ray.actor import ActorHandle +from ray.exceptions import RayActorError +from ray.rllib.core import ( + COMPONENT_ENV_TO_MODULE_CONNECTOR, + COMPONENT_LEARNER, + COMPONENT_MODULE_TO_ENV_CONNECTOR, + COMPONENT_RL_MODULE, +) +from ray.rllib.core.learner import LearnerGroup +from ray.rllib.core.rl_module import validate_module_id +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.evaluation.rollout_worker import RolloutWorker +from ray.rllib.env.base_env import BaseEnv +from ray.rllib.env.env_context import EnvContext +from ray.rllib.env.env_runner import EnvRunner +from ray.rllib.offline import get_dataset_and_shards +from ray.rllib.policy.policy import Policy, PolicyState +from ray.rllib.utils.actor_manager import FaultTolerantActorManager +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.deprecation import ( + Deprecated, + deprecation_warning, + DEPRECATED_VALUE, +) +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.metrics import NUM_ENV_STEPS_SAMPLED_LIFETIME, WEIGHTS_SEQ_NO +from ray.rllib.utils.typing import ( + AgentID, + EnvCreator, + EnvType, + EpisodeID, + PartialAlgorithmConfigDict, + PolicyID, + SampleBatchType, + TensorType, +) +from ray.util.annotations import DeveloperAPI + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + +tf1, tf, tfv = try_import_tf() + +logger = logging.getLogger(__name__) + +# Generic type var for foreach_* methods. +T = TypeVar("T") + + +@DeveloperAPI +class EnvRunnerGroup: + """Set of EnvRunners with n @ray.remote workers and zero or one local worker. + + Where: n >= 0. + """ + + def __init__( + self, + *, + env_creator: Optional[EnvCreator] = None, + validate_env: Optional[Callable[[EnvType], None]] = None, + default_policy_class: Optional[Type[Policy]] = None, + config: Optional["AlgorithmConfig"] = None, + local_env_runner: bool = True, + logdir: Optional[str] = None, + _setup: bool = True, + tune_trial_id: Optional[str] = None, + pg_offset: int = 0, + # Deprecated args. + num_env_runners: Optional[int] = None, + num_workers=DEPRECATED_VALUE, + local_worker=DEPRECATED_VALUE, + ): + """Initializes a EnvRunnerGroup instance. + + Args: + env_creator: Function that returns env given env config. + validate_env: Optional callable to validate the generated + environment (only on worker=0). This callable should raise + an exception if the environment is invalid. + default_policy_class: An optional default Policy class to use inside + the (multi-agent) `policies` dict. In case the PolicySpecs in there + have no class defined, use this `default_policy_class`. + If None, PolicySpecs will be using the Algorithm's default Policy + class. + config: Optional AlgorithmConfig (or config dict). + local_env_runner: Whether to create a local (non @ray.remote) EnvRunner + in the returned set as well (default: True). If `num_env_runners` + is 0, always create a local EnvRunner. + logdir: Optional logging directory for workers. + _setup: Whether to actually set up workers. This is only for testing. + tune_trial_id: The Ray Tune trial ID, if this EnvRunnerGroup is part of + an Algorithm run as a Tune trial. None, otherwise. + """ + if num_workers != DEPRECATED_VALUE or local_worker != DEPRECATED_VALUE: + deprecation_warning( + old="WorkerSet(num_workers=..., local_worker=...)", + new="EnvRunnerGroup(num_env_runners=..., local_env_runner=...)", + error=True, + ) + + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + + # Make sure `config` is an AlgorithmConfig object. + if not config: + config = AlgorithmConfig() + elif isinstance(config, dict): + config = AlgorithmConfig.from_dict(config) + + self._env_creator = env_creator + self._policy_class = default_policy_class + self._remote_config = config + self._remote_config_obj_ref = ray.put(self._remote_config) + self._remote_args = { + "num_cpus": self._remote_config.num_cpus_per_env_runner, + "num_gpus": self._remote_config.num_gpus_per_env_runner, + "resources": self._remote_config.custom_resources_per_env_runner, + "max_restarts": ( + config.max_num_env_runner_restarts + if config.restart_failed_env_runners + else 0 + ), + } + self._tune_trial_id = tune_trial_id + self._pg_offset = pg_offset + + # Set the EnvRunner subclass to be used as "workers". Default: RolloutWorker. + self.env_runner_cls = config.env_runner_cls + if self.env_runner_cls is None: + if config.enable_env_runner_and_connector_v2: + # If experiences should be recorded, use the ` + # OfflineSingleAgentEnvRunner`. + if config.output: + # No multi-agent support. + if config.is_multi_agent: + raise ValueError("Multi-agent recording is not supported, yet.") + # Otherwise, load the single-agent env runner for + # recording. + else: + from ray.rllib.offline.offline_env_runner import ( + OfflineSingleAgentEnvRunner, + ) + + self.env_runner_cls = OfflineSingleAgentEnvRunner + else: + if config.is_multi_agent: + from ray.rllib.env.multi_agent_env_runner import ( + MultiAgentEnvRunner, + ) + + self.env_runner_cls = MultiAgentEnvRunner + else: + from ray.rllib.env.single_agent_env_runner import ( + SingleAgentEnvRunner, + ) + + self.env_runner_cls = SingleAgentEnvRunner + else: + self.env_runner_cls = RolloutWorker + + self._logdir = logdir + self._ignore_ray_errors_on_env_runners = ( + config.ignore_env_runner_failures or config.restart_failed_env_runners + ) + + # Create remote worker manager. + # ID=0 is used by the local worker. + # Starting remote workers from ID=1 to avoid conflicts. + self._worker_manager = FaultTolerantActorManager( + max_remote_requests_in_flight_per_actor=( + config.max_requests_in_flight_per_env_runner + ), + init_id=1, + ) + + if _setup: + try: + self._setup( + validate_env=validate_env, + config=config, + num_env_runners=( + num_env_runners + if num_env_runners is not None + else config.num_env_runners + ), + local_env_runner=local_env_runner, + ) + # EnvRunnerGroup creation possibly fails, if some (remote) workers cannot + # be initialized properly (due to some errors in the EnvRunners's + # constructor). + except RayActorError as e: + # In case of an actor (remote worker) init failure, the remote worker + # may still exist and will be accessible, however, e.g. calling + # its `sample.remote()` would result in strange "property not found" + # errors. + if e.actor_init_failed: + # Raise the original error here that the EnvRunners raised + # during its construction process. This is to enforce transparency + # for the user (better to understand the real reason behind the + # failure). + # - e.args[0]: The RayTaskError (inside the caught RayActorError). + # - e.args[0].args[2]: The original Exception (e.g. a ValueError due + # to a config mismatch) thrown inside the actor. + raise e.args[0].args[2] + # In any other case, raise the RayActorError as-is. + else: + raise e + + def _setup( + self, + *, + validate_env: Optional[Callable[[EnvType], None]] = None, + config: Optional["AlgorithmConfig"] = None, + num_env_runners: int = 0, + local_env_runner: bool = True, + ): + """Sets up an EnvRunnerGroup instance. + Args: + validate_env: Optional callable to validate the generated + environment (only on worker=0). + config: Optional dict that extends the common config of + the Algorithm class. + num_env_runners: Number of remote EnvRunner workers to create. + local_env_runner: Whether to create a local (non @ray.remote) EnvRunner + in the returned set as well (default: True). If `num_env_runners` + is 0, always create a local EnvRunner. + """ + # Force a local worker if num_env_runners == 0 (no remote workers). + # Otherwise, this EnvRunnerGroup would be empty. + self._local_env_runner = None + if num_env_runners == 0: + local_env_runner = True + # Create a local (learner) version of the config for the local worker. + # The only difference is the tf_session_args, which - for the local worker - + # will be `config.tf_session_args` updated/overridden with + # `config.local_tf_session_args`. + local_tf_session_args = config.tf_session_args.copy() + local_tf_session_args.update(config.local_tf_session_args) + self._local_config = config.copy(copy_frozen=False).framework( + tf_session_args=local_tf_session_args + ) + + if config.input_ == "dataset": + # Create the set of dataset readers to be shared by all the + # rollout workers. + self._ds, self._ds_shards = get_dataset_and_shards(config, num_env_runners) + else: + self._ds = None + self._ds_shards = None + + # Create a number of @ray.remote workers. + self.add_workers( + num_env_runners, + validate=config.validate_env_runners_after_construction, + ) + + # If num_env_runners > 0 and we don't have an env on the local worker, + # get the observation- and action spaces for each policy from + # the first remote worker (which does have an env). + if ( + local_env_runner + and self._worker_manager.num_actors() > 0 + and not config.create_env_on_local_worker + and (not config.observation_space or not config.action_space) + ): + spaces = self.get_spaces() + else: + spaces = None + + # Create a local worker, if needed. + if local_env_runner: + self._local_env_runner = self._make_worker( + env_creator=self._env_creator, + validate_env=validate_env, + worker_index=0, + num_workers=num_env_runners, + config=self._local_config, + spaces=spaces, + ) + + def get_spaces(self): + """Infer observation and action spaces from one (local or remote) EnvRunner. + + Returns: + A dict mapping from ModuleID to a 2-tuple containing obs- and action-space. + """ + # Get ID of the first remote worker. + remote_worker_ids = ( + [self._worker_manager.actor_ids()[0]] + if self._worker_manager.actor_ids() + else [] + ) + + spaces = self.foreach_env_runner( + lambda env_runner: env_runner.get_spaces(), + remote_worker_ids=remote_worker_ids, + local_env_runner=not remote_worker_ids, + )[0] + + logger.info( + "Inferred observation/action spaces from remote " + f"worker (local worker has no env): {spaces}" + ) + + return spaces + + @property + def local_env_runner(self) -> EnvRunner: + """Returns the local EnvRunner.""" + return self._local_env_runner + + def healthy_env_runner_ids(self) -> List[int]: + """Returns the list of remote worker IDs.""" + return self._worker_manager.healthy_actor_ids() + + def healthy_worker_ids(self) -> List[int]: + """Returns the list of remote worker IDs.""" + return self.healthy_env_runner_ids() + + def num_remote_env_runners(self) -> int: + """Returns the number of remote EnvRunners.""" + return self._worker_manager.num_actors() + + def num_remote_workers(self) -> int: + """Returns the number of remote EnvRunners.""" + return self.num_remote_env_runners() + + def num_healthy_remote_env_runners(self) -> int: + """Returns the number of healthy remote workers.""" + return self._worker_manager.num_healthy_actors() + + def num_healthy_remote_workers(self) -> int: + """Returns the number of healthy remote workers.""" + return self.num_healthy_remote_env_runners() + + def num_healthy_env_runners(self) -> int: + """Returns the number of all healthy workers, including the local worker.""" + return int(bool(self._local_env_runner)) + self.num_healthy_remote_workers() + + def num_healthy_workers(self) -> int: + """Returns the number of all healthy workers, including the local worker.""" + return self.num_healthy_env_runners() + + def num_in_flight_async_reqs(self) -> int: + """Returns the number of in-flight async requests.""" + return self._worker_manager.num_outstanding_async_reqs() + + def num_remote_worker_restarts(self) -> int: + """Total number of times managed remote workers have been restarted.""" + return self._worker_manager.total_num_restarts() + + def sync_env_runner_states( + self, + *, + config: "AlgorithmConfig", + from_worker: Optional[EnvRunner] = None, + env_steps_sampled: Optional[int] = None, + connector_states: Optional[List[Dict[str, Any]]] = None, + rl_module_state: Optional[Dict[str, Any]] = None, + env_runner_indices_to_update: Optional[List[int]] = None, + env_to_module=None, + module_to_env=None, + ) -> None: + """Synchronizes the connectors of this EnvRunnerGroup's EnvRunners. + + The exact procedure works as follows: + - If `from_worker` is None, set `from_worker=self.local_env_runner`. + - If `config.use_worker_filter_stats` is True, gather all remote EnvRunners' + ConnectorV2 states. Otherwise, only use the ConnectorV2 states of `from_worker`. + - Merge all gathered states into one resulting state. + - Broadcast the resulting state back to all remote EnvRunners AND the local + EnvRunner. + + Args: + config: The AlgorithmConfig object to use to determine, in which + direction(s) we need to synch and what the timeouts are. + from_worker: The EnvRunner from which to synch. If None, will use the local + worker of this EnvRunnerGroup. + env_steps_sampled: The total number of env steps taken thus far by all + workers combined. Used to broadcast this number to all remote workers + if `update_worker_filter_stats` is True in `config`. + env_runner_indices_to_update: The indices of those EnvRunners to update + with the merged state. Use None (default) to update all remote + EnvRunners. + """ + from_worker = from_worker or self.local_env_runner + + merge = ( + not config.enable_env_runner_and_connector_v2 + and config.use_worker_filter_stats + ) or ( + config.enable_env_runner_and_connector_v2 + and ( + config.merge_env_runner_states is True + or ( + config.merge_env_runner_states == "training_only" + and not config.in_evaluation + ) + ) + ) + broadcast = ( + not config.enable_env_runner_and_connector_v2 + and config.update_worker_filter_stats + ) or ( + config.enable_env_runner_and_connector_v2 + and config.broadcast_env_runner_states + ) + + # Early out if the number of (healthy) remote workers is 0. In this case, the + # local worker is the only operating worker and thus of course always holds + # the reference connector state. + if self.num_healthy_remote_workers() == 0 and self.local_env_runner: + self.local_env_runner.set_state( + { + **( + {NUM_ENV_STEPS_SAMPLED_LIFETIME: env_steps_sampled} + if env_steps_sampled is not None + else {} + ), + **(rl_module_state or {}), + } + ) + return + + # Also early out, if we don't merge AND don't broadcast. + if not merge and not broadcast: + return + + # Use states from all remote EnvRunners. + if merge: + if connector_states == []: + env_runner_states = {} + else: + if connector_states is None: + connector_states = self.foreach_env_runner( + lambda w: w.get_state( + components=[ + COMPONENT_ENV_TO_MODULE_CONNECTOR, + COMPONENT_MODULE_TO_ENV_CONNECTOR, + ] + ), + local_env_runner=False, + timeout_seconds=( + config.sync_filters_on_rollout_workers_timeout_s + ), + ) + env_to_module_states = [ + s[COMPONENT_ENV_TO_MODULE_CONNECTOR] + for s in connector_states + if COMPONENT_ENV_TO_MODULE_CONNECTOR in s + ] + module_to_env_states = [ + s[COMPONENT_MODULE_TO_ENV_CONNECTOR] + for s in connector_states + if COMPONENT_MODULE_TO_ENV_CONNECTOR in s + ] + + if ( + self.local_env_runner is not None + and hasattr(self.local_env_runner, "_env_to_module") + and hasattr(self.local_env_runner, "_module_to_env") + ): + assert env_to_module is None + env_to_module = self.local_env_runner._env_to_module + assert module_to_env is None + module_to_env = self.local_env_runner._module_to_env + + env_runner_states = {} + if env_to_module_states: + env_runner_states.update( + { + COMPONENT_ENV_TO_MODULE_CONNECTOR: ( + env_to_module.merge_states(env_to_module_states) + ), + } + ) + if module_to_env_states: + env_runner_states.update( + { + COMPONENT_MODULE_TO_ENV_CONNECTOR: ( + module_to_env.merge_states(module_to_env_states) + ), + } + ) + # Ignore states from remote EnvRunners (use the current `from_worker` states + # only). + else: + if from_worker is None: + env_runner_states = { + COMPONENT_ENV_TO_MODULE_CONNECTOR: env_to_module.get_state(), + COMPONENT_MODULE_TO_ENV_CONNECTOR: module_to_env.get_state(), + } + else: + env_runner_states = from_worker.get_state( + components=[ + COMPONENT_ENV_TO_MODULE_CONNECTOR, + COMPONENT_MODULE_TO_ENV_CONNECTOR, + ] + ) + + # Update the global number of environment steps, if necessary. + # Make sure to divide by the number of env runners (such that each EnvRunner + # knows (roughly) its own(!) lifetime count and can infer the global lifetime + # count from it). + if env_steps_sampled is not None: + env_runner_states[NUM_ENV_STEPS_SAMPLED_LIFETIME] = env_steps_sampled // ( + config.num_env_runners or 1 + ) + + # If we do NOT want remote EnvRunners to get their Connector states updated, + # only update the local worker here (with all state components, except the model + # weights) and then remove the connector components. + if not broadcast: + if self.local_env_runner is not None: + self.local_env_runner.set_state(env_runner_states) + else: + env_to_module.set_state( + env_runner_states.get(COMPONENT_ENV_TO_MODULE_CONNECTOR), {} + ) + module_to_env.set_state( + env_runner_states.get(COMPONENT_MODULE_TO_ENV_CONNECTOR), {} + ) + env_runner_states.pop(COMPONENT_ENV_TO_MODULE_CONNECTOR, None) + env_runner_states.pop(COMPONENT_MODULE_TO_ENV_CONNECTOR, None) + + # If there are components in the state left -> Update remote workers with these + # state components (and maybe the local worker, if it hasn't been updated yet). + if env_runner_states: + # Update the local EnvRunner, but NOT with the weights. If used at all for + # evaluation (through the user calling `self.evaluate`), RLlib would update + # the weights up front either way. + if self.local_env_runner is not None and broadcast: + self.local_env_runner.set_state(env_runner_states) + + # Send the model weights only to remote EnvRunners. + # In case the local EnvRunner is ever needed for evaluation, + # RLlib updates its weight right before such an eval step. + if rl_module_state: + env_runner_states.update(rl_module_state) + + # Broadcast updated states back to all workers. + self.foreach_env_runner( + "set_state", # Call the `set_state()` remote method. + kwargs=dict(state=env_runner_states), + remote_worker_ids=env_runner_indices_to_update, + local_env_runner=False, + timeout_seconds=0.0, # This is a state update -> Fire-and-forget. + ) + + def sync_weights( + self, + policies: Optional[List[PolicyID]] = None, + from_worker_or_learner_group: Optional[Union[EnvRunner, "LearnerGroup"]] = None, + to_worker_indices: Optional[List[int]] = None, + global_vars: Optional[Dict[str, TensorType]] = None, + timeout_seconds: Optional[float] = 0.0, + inference_only: Optional[bool] = False, + ) -> None: + """Syncs model weights from the given weight source to all remote workers. + + Weight source can be either a (local) rollout worker or a learner_group. It + should just implement a `get_weights` method. + + Args: + policies: Optional list of PolicyIDs to sync weights for. + If None (default), sync weights to/from all policies. + from_worker_or_learner_group: Optional (local) EnvRunner instance or + LearnerGroup instance to sync from. If None (default), + sync from this EnvRunnerGroup's local worker. + to_worker_indices: Optional list of worker indices to sync the + weights to. If None (default), sync to all remote workers. + global_vars: An optional global vars dict to set this + worker to. If None, do not update the global_vars. + timeout_seconds: Timeout in seconds to wait for the sync weights + calls to complete. Default is 0.0 (fire-and-forget, do not wait + for any sync calls to finish). Setting this to 0.0 might significantly + improve algorithm performance, depending on the algo's `training_step` + logic. + inference_only: Sync weights with workers that keep inference-only + modules. This is needed for algorithms in the new stack that + use inference-only modules. In this case only a part of the + parameters are synced to the workers. Default is False. + """ + if self.local_env_runner is None and from_worker_or_learner_group is None: + raise TypeError( + "No `local_env_runner` in EnvRunnerGroup! Must provide " + "`from_worker_or_learner_group` arg in `sync_weights()`!" + ) + + # Only sync if we have remote workers or `from_worker_or_trainer` is provided. + rl_module_state = None + if self.num_remote_workers() or from_worker_or_learner_group is not None: + weights_src = ( + from_worker_or_learner_group + if from_worker_or_learner_group is not None + else self.local_env_runner + ) + + if weights_src is None: + raise ValueError( + "`from_worker_or_trainer` is None. In this case, EnvRunnerGroup " + "should have local_env_runner. But local_env_runner is also None." + ) + + modules = ( + [COMPONENT_RL_MODULE + "/" + p for p in policies] + if policies is not None + else [COMPONENT_RL_MODULE] + ) + # LearnerGroup has-a Learner, which has-a RLModule. + if isinstance(weights_src, LearnerGroup): + rl_module_state = weights_src.get_state( + components=[COMPONENT_LEARNER + "/" + m for m in modules], + inference_only=inference_only, + )[COMPONENT_LEARNER] + # EnvRunner (new API stack). + elif self._remote_config.enable_env_runner_and_connector_v2: + # EnvRunner (remote) has-a RLModule. + # TODO (sven): Replace this with a new ActorManager API: + # try_remote_request_till_success("get_state") -> tuple(int, + # remoteresult) + # `weights_src` could be the ActorManager, then. Then RLlib would know + # that it has to ping the manager to try all healthy actors until the + # first returns something. + if isinstance(weights_src, ray.actor.ActorHandle): + rl_module_state = ray.get( + weights_src.get_state.remote( + components=modules, + inference_only=inference_only, + ) + ) + # EnvRunner (local) has-a RLModule. + else: + rl_module_state = weights_src.get_state( + components=modules, + inference_only=inference_only, + ) + # RolloutWorker (old API stack). + else: + rl_module_state = weights_src.get_weights( + policies=policies, + inference_only=inference_only, + ) + + if self._remote_config.enable_env_runner_and_connector_v2: + + # Make sure `rl_module_state` only contains the weights and the + # weight seq no, nothing else. + rl_module_state = { + k: v + for k, v in rl_module_state.items() + if k in [COMPONENT_RL_MODULE, WEIGHTS_SEQ_NO] + } + + # Move weights to the object store to avoid having to make n pickled + # copies of the weights dict for each worker. + rl_module_state_ref = ray.put(rl_module_state) + + # Sync to specified remote workers in this EnvRunnerGroup. + self.foreach_env_runner( + func="set_state", + kwargs=dict(state=rl_module_state_ref), + local_env_runner=False, # Do not sync back to local worker. + remote_worker_ids=to_worker_indices, + timeout_seconds=timeout_seconds, + ) + + else: + rl_module_state_ref = ray.put(rl_module_state) + + def _set_weights(env_runner): + env_runner.set_weights(ray.get(rl_module_state_ref), global_vars) + + # Sync to specified remote workers in this EnvRunnerGroup. + self.foreach_env_runner( + func=_set_weights, + local_env_runner=False, # Do not sync back to local worker. + remote_worker_ids=to_worker_indices, + timeout_seconds=timeout_seconds, + ) + + # If `from_worker_or_learner_group` is provided, also sync to this + # EnvRunnerGroup's local worker. + if self.local_env_runner is not None: + if from_worker_or_learner_group is not None: + if self._remote_config.enable_env_runner_and_connector_v2: + self.local_env_runner.set_state(rl_module_state) + else: + self.local_env_runner.set_weights(rl_module_state) + # If `global_vars` is provided and local worker exists -> Update its + # global_vars. + if global_vars is not None: + self.local_env_runner.set_global_vars(global_vars) + + def add_workers(self, num_workers: int, validate: bool = False) -> None: + """Creates and adds a number of remote workers to this worker set. + + Can be called several times on the same EnvRunnerGroup to add more + EnvRunners to the set. + + Args: + num_workers: The number of remote Workers to add to this + EnvRunnerGroup. + validate: Whether to validate remote workers after their construction + process. + + Raises: + RayError: If any of the constructed remote workers is not up and running + properly. + """ + old_num_workers = self._worker_manager.num_actors() + new_workers = [ + self._make_worker( + env_creator=self._env_creator, + validate_env=None, + worker_index=old_num_workers + i + 1, + num_workers=old_num_workers + num_workers, + # self._remote_config can be large + # and it's best practice to pass it by reference + # instead of value (https://docs.ray.io/en/latest/ray-core/patterns/pass-large-arg-by-value.html) + config=self._remote_config_obj_ref, + ) + for i in range(num_workers) + ] + self._worker_manager.add_actors(new_workers) + + # Validate here, whether all remote workers have been constructed properly + # and are "up and running". Establish initial states. + if validate: + for result in self._worker_manager.foreach_actor( + lambda w: w.assert_healthy() + ): + # Simiply raise the error, which will get handled by the try-except + # clause around the _setup(). + if not result.ok: + e = result.get() + if self._ignore_ray_errors_on_env_runners: + logger.error(f"Validation of EnvRunner failed! Error={str(e)}") + else: + raise e + + def reset(self, new_remote_workers: List[ActorHandle]) -> None: + """Hard overrides the remote EnvRunners in this set with the provided ones. + + Args: + new_remote_workers: A list of new EnvRunners (as `ActorHandles`) to use as + new remote workers. + """ + self._worker_manager.clear() + self._worker_manager.add_actors(new_remote_workers) + + def stop(self) -> None: + """Calls `stop` on all EnvRunners (including the local one).""" + try: + # Make sure we stop all EnvRunners, include the ones that were just + # restarted / recovered or that are tagged unhealthy (at least, we should + # try). + self.foreach_env_runner( + lambda w: w.stop(), healthy_only=False, local_env_runner=True + ) + except Exception: + logger.exception("Failed to stop workers!") + finally: + self._worker_manager.clear() + + def foreach_env_runner( + self, + func: Union[ + Callable[[EnvRunner], T], List[Callable[[EnvRunner], T]], str, List[str] + ], + *, + kwargs=None, + local_env_runner: bool = True, + healthy_only: bool = True, + remote_worker_ids: List[int] = None, + timeout_seconds: Optional[float] = None, + return_obj_refs: bool = False, + mark_healthy: bool = False, + ) -> List[T]: + """Calls the given function with each EnvRunner as its argument. + + Args: + func: The function to call for each EnvRunners. The only call argument is + the respective EnvRunner instance. + local_env_runner: Whether to apply `func` to local EnvRunner, too. + Default is True. + healthy_only: Apply `func` on known-to-be healthy EnvRunners only. + remote_worker_ids: Apply `func` on a selected set of remote EnvRunners. + Use None (default) for all remote EnvRunners. + timeout_seconds: Time to wait (in seconds) for results. Set this to 0.0 for + fire-and-forget. Set this to None (default) to wait infinitely (i.e. for + synchronous execution). + return_obj_refs: Whether to return ObjectRef instead of actual results. + Note, for fault tolerance reasons, these returned ObjectRefs should + never be resolved with ray.get() outside of this EnvRunnerGroup. + mark_healthy: Whether to mark all those EnvRunners healthy again that are + currently marked unhealthy AND that returned results from the remote + call (within the given `timeout_seconds`). + Note that EnvRunners are NOT set unhealthy, if they simply time out + (only if they return a RayActorError). + Also note that this setting is ignored if `healthy_only=True` (b/c + `mark_healthy` only affects EnvRunners that are currently tagged as + unhealthy). + + Returns: + The list of return values of all calls to `func([worker])`. + """ + assert ( + not return_obj_refs or not local_env_runner + ), "Can not return ObjectRef from local worker." + + local_result = [] + if local_env_runner and self.local_env_runner is not None: + assert kwargs is None + if isinstance(func, str): + local_result = [getattr(self.local_env_runner, func)] + else: + local_result = [func(self.local_env_runner)] + + if not self._worker_manager.actor_ids(): + return local_result + + remote_results = self._worker_manager.foreach_actor( + func, + kwargs=kwargs, + healthy_only=healthy_only, + remote_actor_ids=remote_worker_ids, + timeout_seconds=timeout_seconds, + return_obj_refs=return_obj_refs, + mark_healthy=mark_healthy, + ) + + FaultTolerantActorManager.handle_remote_call_result_errors( + remote_results, ignore_ray_errors=self._ignore_ray_errors_on_env_runners + ) + + # With application errors handled, return good results. + remote_results = [r.get() for r in remote_results.ignore_errors()] + + return local_result + remote_results + + # TODO (sven): Deprecate this API. Users can lookup the "worker index" from the + # EnvRunner object directly through `self.worker_index` (besides many other useful + # properties, like `in_evaluation`, `num_env_runners`, etc..). + def foreach_env_runner_with_id( + self, + func: Union[ + Callable[[int, EnvRunner], T], + List[Callable[[int, EnvRunner], T]], + str, + List[str], + ], + *, + local_env_runner: bool = True, + healthy_only: bool = True, + remote_worker_ids: List[int] = None, + timeout_seconds: Optional[float] = None, + return_obj_refs: bool = False, + mark_healthy: bool = False, + ) -> List[T]: + """Calls the given function with each EnvRunner and its ID as its arguments. + + Args: + func: The function to call for each EnvRunners. The call arguments are + the EnvRunner's index (int) and the respective EnvRunner instance + itself. + local_env_runner: Whether to apply `func` to the local EnvRunner, too. + Default is True. + healthy_only: Apply `func` on known-to-be healthy EnvRunners only. + remote_worker_ids: Apply `func` on a selected set of remote EnvRunners. + timeout_seconds: Time to wait for results. Default is None. + return_obj_refs: Whether to return ObjectRef instead of actual results. + Note, for fault tolerance reasons, these returned ObjectRefs should + never be resolved with ray.get() outside of this EnvRunnerGroup. + mark_healthy: Whether to mark all those EnvRunners healthy again that are + currently marked unhealthy AND that returned results from the remote + call (within the given `timeout_seconds`). + Note that workers are NOT set unhealthy, if they simply time out + (only if they return a RayActorError). + Also note that this setting is ignored if `healthy_only=True` (b/c + `mark_healthy` only affects EnvRunners that are currently tagged as + unhealthy). + + Returns: + The list of return values of all calls to `func([worker, id])`. + """ + local_result = [] + if local_env_runner and self.local_env_runner is not None: + local_result = [func(0, self.local_env_runner)] + + if not remote_worker_ids: + remote_worker_ids = self._worker_manager.actor_ids() + + funcs = [functools.partial(func, i) for i in remote_worker_ids] + + remote_results = self._worker_manager.foreach_actor( + funcs, + healthy_only=healthy_only, + remote_actor_ids=remote_worker_ids, + timeout_seconds=timeout_seconds, + return_obj_refs=return_obj_refs, + mark_healthy=mark_healthy, + ) + + FaultTolerantActorManager.handle_remote_call_result_errors( + remote_results, + ignore_ray_errors=self._ignore_ray_errors_on_env_runners, + ) + + remote_results = [r.get() for r in remote_results.ignore_errors()] + + return local_result + remote_results + + def foreach_env_runner_async( + self, + func: Union[ + Callable[[EnvRunner], T], List[Callable[[EnvRunner], T]], str, List[str] + ], + *, + healthy_only: bool = True, + remote_worker_ids: List[int] = None, + ) -> int: + """Calls the given function asynchronously with each EnvRunner as the argument. + + Does not return results directly. Instead, `fetch_ready_async_reqs()` can be + used to pull results in an async manner whenever they are available. + + Args: + func: The function to call for each EnvRunners. The only call argument is + the respective EnvRunner instance. + healthy_only: Apply `func` on known-to-be healthy EnvRunners only. + remote_worker_ids: Apply `func` on a selected set of remote EnvRunners. + + Returns: + The number of async requests that have actually been made. This is the + length of `remote_worker_ids` (or self.num_remote_workers()` if + `remote_worker_ids` is None) minus the number of requests that were NOT + made b/c a remote EnvRunner already had its + `max_remote_requests_in_flight_per_actor` counter reached. + """ + return self._worker_manager.foreach_actor_async( + func, + healthy_only=healthy_only, + remote_actor_ids=remote_worker_ids, + ) + + def fetch_ready_async_reqs( + self, + *, + timeout_seconds: Optional[float] = 0.0, + return_obj_refs: bool = False, + mark_healthy: bool = False, + ) -> List[Tuple[int, T]]: + """Get esults from outstanding asynchronous requests that are ready. + + Args: + timeout_seconds: Time to wait for results. Default is 0, meaning + those requests that are already ready. + return_obj_refs: Whether to return ObjectRef instead of actual results. + mark_healthy: Whether to mark all those workers healthy again that are + currently marked unhealthy AND that returned results from the remote + call (within the given `timeout_seconds`). + Note that workers are NOT set unhealthy, if they simply time out + (only if they return a RayActorError). + Also note that this setting is ignored if `healthy_only=True` (b/c + `mark_healthy` only affects workers that are currently tagged as + unhealthy). + + Returns: + A list of results successfully returned from outstanding remote calls, + paired with the indices of the callee workers. + """ + remote_results = self._worker_manager.fetch_ready_async_reqs( + timeout_seconds=timeout_seconds, + return_obj_refs=return_obj_refs, + mark_healthy=mark_healthy, + ) + + FaultTolerantActorManager.handle_remote_call_result_errors( + remote_results, + ignore_ray_errors=self._ignore_ray_errors_on_env_runners, + ) + + return [(r.actor_id, r.get()) for r in remote_results.ignore_errors()] + + @OldAPIStack + def foreach_env(self, func: Callable[[EnvType], List[T]]) -> List[List[T]]: + """Calls `func` with all workers' sub-environments as args. + + An "underlying sub environment" is a single clone of an env within + a vectorized environment. + `func` takes a single underlying sub environment as arg, e.g. a + gym.Env object. + + Args: + func: A function - taking an EnvType (normally a gym.Env object) + as arg and returning a list of lists of return values, one + value per underlying sub-environment per each worker. + + Returns: + The list (workers) of lists (sub environments) of results. + """ + return list( + self.foreach_env_runner( + lambda w: w.foreach_env(func), + local_env_runner=True, + ) + ) + + @OldAPIStack + def foreach_env_with_context( + self, func: Callable[[BaseEnv, EnvContext], List[T]] + ) -> List[List[T]]: + """Calls `func` with all workers' sub-environments and env_ctx as args. + + An "underlying sub environment" is a single clone of an env within + a vectorized environment. + `func` takes a single underlying sub environment and the env_context + as args. + + Args: + func: A function - taking a BaseEnv object and an EnvContext as + arg - and returning a list of lists of return values over envs + of the worker. + + Returns: + The list (1 item per workers) of lists (1 item per sub-environment) + of results. + """ + return list( + self.foreach_env_runner( + lambda w: w.foreach_env_with_context(func), + local_env_runner=True, + ) + ) + + def probe_unhealthy_env_runners(self) -> List[int]: + """Checks for unhealthy workers and tries restoring their states. + + Returns: + List of IDs of the workers that were restored. + """ + return self._worker_manager.probe_unhealthy_actors( + timeout_seconds=self._remote_config.env_runner_health_probe_timeout_s, + mark_healthy=True, + ) + + @OldAPIStack + def foreach_policy(self, func: Callable[[Policy, PolicyID], T]) -> List[T]: + """Calls `func` with each worker's (policy, PolicyID) tuple. + + Note that in the multi-agent case, each worker may have more than one + policy. + + Args: + func: A function - taking a Policy and its ID - that is + called on all workers' Policies. + + Returns: + The list of return values of func over all workers' policies. The + length of this list is: + (num_workers + 1 (local-worker)) * + [num policies in the multi-agent config dict]. + The local workers' results are first, followed by all remote + workers' results + """ + results = [] + for r in self.foreach_env_runner( + lambda w: w.foreach_policy(func), local_env_runner=True + ): + results.extend(r) + return results + + @OldAPIStack + def foreach_policy_to_train(self, func: Callable[[Policy, PolicyID], T]) -> List[T]: + """Apply `func` to all workers' Policies iff in `policies_to_train`. + + Args: + func: A function - taking a Policy and its ID - that is + called on all workers' Policies, for which + `worker.is_policy_to_train()` returns True. + + Returns: + List[any]: The list of n return values of all + `func([trainable policy], [ID])`-calls. + """ + results = [] + for r in self.foreach_env_runner( + lambda w: w.foreach_policy_to_train(func), local_env_runner=True + ): + results.extend(r) + return results + + @OldAPIStack + def is_policy_to_train( + self, policy_id: PolicyID, batch: Optional[SampleBatchType] = None + ) -> bool: + """Whether given PolicyID (optionally inside some batch) is trainable.""" + if self.local_env_runner: + if self.local_env_runner.is_policy_to_train is None: + return True + return self.local_env_runner.is_policy_to_train(policy_id, batch) + else: + raise NotImplementedError + + @OldAPIStack + def add_policy( + self, + policy_id: PolicyID, + policy_cls: Optional[Type[Policy]] = None, + policy: Optional[Policy] = None, + *, + observation_space: Optional[gym.spaces.Space] = None, + action_space: Optional[gym.spaces.Space] = None, + config: Optional[Union["AlgorithmConfig", PartialAlgorithmConfigDict]] = None, + policy_state: Optional[PolicyState] = None, + policy_mapping_fn: Optional[Callable[[AgentID, EpisodeID], PolicyID]] = None, + policies_to_train: Optional[ + Union[ + Collection[PolicyID], + Callable[[PolicyID, Optional[SampleBatchType]], bool], + ] + ] = None, + module_spec: Optional[RLModuleSpec] = None, + # Deprecated. + workers: Optional[List[Union[EnvRunner, ActorHandle]]] = DEPRECATED_VALUE, + ) -> None: + """Adds a policy to this EnvRunnerGroup's workers or a specific list of workers. + + Args: + policy_id: ID of the policy to add. + policy_cls: The Policy class to use for constructing the new Policy. + Note: Only one of `policy_cls` or `policy` must be provided. + policy: The Policy instance to add to this EnvRunnerGroup. If not None, the + given Policy object will be directly inserted into the + local worker and clones of that Policy will be created on all remote + workers. + Note: Only one of `policy_cls` or `policy` must be provided. + observation_space: The observation space of the policy to add. + If None, try to infer this space from the environment. + action_space: The action space of the policy to add. + If None, try to infer this space from the environment. + config: The config object or overrides for the policy to add. + policy_state: Optional state dict to apply to the new + policy instance, right after its construction. + policy_mapping_fn: An optional (updated) policy mapping function + to use from here on. Note that already ongoing episodes will + not change their mapping but will use the old mapping till + the end of the episode. + policies_to_train: An optional list of policy IDs to be trained + or a callable taking PolicyID and SampleBatchType and + returning a bool (trainable or not?). + If None, will keep the existing setup in place. Policies, + whose IDs are not in the list (or for which the callable + returns False) will not be updated. + module_spec: In the new RLModule API we need to pass in the module_spec for + the new module that is supposed to be added. Knowing the policy spec is + not sufficient. + workers: A list of EnvRunner/ActorHandles (remote + EnvRunners) to add this policy to. If defined, will only + add the given policy to these workers. + + Raises: + KeyError: If the given `policy_id` already exists in this EnvRunnerGroup. + """ + if self.local_env_runner and policy_id in self.local_env_runner.policy_map: + raise KeyError( + f"Policy ID '{policy_id}' already exists in policy map! " + "Make sure you use a Policy ID that has not been taken yet." + " Policy IDs that are already in your policy map: " + f"{list(self.local_env_runner.policy_map.keys())}" + ) + + if workers is not DEPRECATED_VALUE: + deprecation_warning( + old="EnvRunnerGroup.add_policy(.., workers=..)", + help=( + "The `workers` argument to `EnvRunnerGroup.add_policy()` is " + "deprecated! Please do not use it anymore." + ), + error=True, + ) + + if (policy_cls is None) == (policy is None): + raise ValueError( + "Only one of `policy_cls` or `policy` must be provided to " + "staticmethod: `EnvRunnerGroup.add_policy()`!" + ) + validate_module_id(policy_id, error=False) + + # Policy instance not provided: Use the information given here. + if policy_cls is not None: + new_policy_instance_kwargs = dict( + policy_id=policy_id, + policy_cls=policy_cls, + observation_space=observation_space, + action_space=action_space, + config=config, + policy_state=policy_state, + policy_mapping_fn=policy_mapping_fn, + policies_to_train=list(policies_to_train) + if policies_to_train + else None, + module_spec=module_spec, + ) + # Policy instance provided: Create clones of this very policy on the different + # workers (copy all its properties here for the calls to add_policy on the + # remote workers). + else: + new_policy_instance_kwargs = dict( + policy_id=policy_id, + policy_cls=type(policy), + observation_space=policy.observation_space, + action_space=policy.action_space, + config=policy.config, + policy_state=policy.get_state(), + policy_mapping_fn=policy_mapping_fn, + policies_to_train=list(policies_to_train) + if policies_to_train + else None, + module_spec=module_spec, + ) + + def _create_new_policy_fn(worker): + # `foreach_env_runner` function: Adds the policy to the worker (and + # maybe changes its policy_mapping_fn - if provided here). + worker.add_policy(**new_policy_instance_kwargs) + + if self.local_env_runner is not None: + # Add policy directly by (already instantiated) object. + if policy is not None: + self.local_env_runner.add_policy( + policy_id=policy_id, + policy=policy, + policy_mapping_fn=policy_mapping_fn, + policies_to_train=policies_to_train, + module_spec=module_spec, + ) + # Add policy by constructor kwargs. + else: + self.local_env_runner.add_policy(**new_policy_instance_kwargs) + + # Add the policy to all remote workers. + self.foreach_env_runner(_create_new_policy_fn, local_env_runner=False) + + def _make_worker( + self, + *, + env_creator: EnvCreator, + validate_env: Optional[Callable[[EnvType], None]], + worker_index: int, + num_workers: int, + recreated_worker: bool = False, + config: "AlgorithmConfig", + spaces: Optional[ + Dict[PolicyID, Tuple[gym.spaces.Space, gym.spaces.Space]] + ] = None, + ) -> Union[EnvRunner, ActorHandle]: + kwargs = dict( + env_creator=env_creator, + validate_env=validate_env, + default_policy_class=self._policy_class, + config=config, + worker_index=worker_index, + num_workers=num_workers, + recreated_worker=recreated_worker, + log_dir=self._logdir, + spaces=spaces, + dataset_shards=self._ds_shards, + tune_trial_id=self._tune_trial_id, + ) + + if worker_index == 0: + return self.env_runner_cls(**kwargs) + + pg_bundle_idx = ( + -1 + if ray.util.get_current_placement_group() is None + else self._pg_offset + worker_index + ) + return ( + ray.remote(**self._remote_args)(self.env_runner_cls) + .options(placement_group_bundle_index=pg_bundle_idx) + .remote(**kwargs) + ) + + @classmethod + def _valid_module(cls, class_path): + del cls + if ( + isinstance(class_path, str) + and not os.path.isfile(class_path) + and "." in class_path + ): + module_path, class_name = class_path.rsplit(".", 1) + try: + spec = importlib.util.find_spec(module_path) + if spec is not None: + return True + except (ModuleNotFoundError, ValueError): + print( + f"module {module_path} not found while trying to get " + f"input {class_path}" + ) + return False + + @Deprecated(new="EnvRunnerGroup.probe_unhealthy_env_runners", error=False) + def probe_unhealthy_workers(self, *args, **kwargs): + return self.probe_unhealthy_env_runners(*args, **kwargs) + + @Deprecated(new="EnvRunnerGroup.foreach_env_runner", error=False) + def foreach_worker(self, *args, **kwargs): + return self.foreach_env_runner(*args, **kwargs) + + @Deprecated(new="EnvRunnerGroup.foreach_env_runner_with_id", error=False) + def foreach_worker_with_id(self, *args, **kwargs): + return self.foreach_env_runner_with_id(*args, **kwargs) + + @Deprecated(new="EnvRunnerGroup.foreach_env_runner_async", error=False) + def foreach_worker_async(self, *args, **kwargs): + return self.foreach_env_runner_async(*args, **kwargs) + + @Deprecated(new="EnvRunnerGroup.local_env_runner", error=True) + def local_worker(self) -> EnvRunner: + pass + + @property + @Deprecated( + old="_remote_workers", + new="Use either the `foreach_env_runner()`, `foreach_env_runner_with_id()`, or " + "`foreach_env_runner_async()` APIs of `EnvRunnerGroup`, which all handle fault " + "tolerance.", + error=True, + ) + def _remote_workers(self): + pass + + @Deprecated( + old="remote_workers()", + new="Use either the `foreach_env_runner()`, `foreach_env_runner_with_id()`, or " + "`foreach_env_runner_async()` APIs of `EnvRunnerGroup`, which all handle fault " + "tolerance.", + error=True, + ) + def remote_workers(self): + pass diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external_env.py new file mode 100644 index 0000000000000000000000000000000000000000..41eb89d6c471571beca90b9659d262a5283e4519 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external_env.py @@ -0,0 +1,481 @@ +import gymnasium as gym +import queue +import threading +import uuid +from typing import Callable, Tuple, Optional, TYPE_CHECKING + +from ray.rllib.env.base_env import BaseEnv +from ray.rllib.utils.annotations import override, OldAPIStack +from ray.rllib.utils.typing import ( + EnvActionType, + EnvInfoDict, + EnvObsType, + EnvType, + MultiEnvDict, +) +from ray.rllib.utils.deprecation import deprecation_warning + +if TYPE_CHECKING: + from ray.rllib.models.preprocessors import Preprocessor + + +@OldAPIStack +class ExternalEnv(threading.Thread): + """An environment that interfaces with external agents. + + Unlike simulator envs, control is inverted: The environment queries the + policy to obtain actions and in return logs observations and rewards for + training. This is in contrast to gym.Env, where the algorithm drives the + simulation through env.step() calls. + + You can use ExternalEnv as the backend for policy serving (by serving HTTP + requests in the run loop), for ingesting offline logs data (by reading + offline transitions in the run loop), or other custom use cases not easily + expressed through gym.Env. + + ExternalEnv supports both on-policy actions (through self.get_action()), + and off-policy actions (through self.log_action()). + + This env is thread-safe, but individual episodes must be executed serially. + + .. testcode:: + :skipif: True + + from ray.tune import register_env + from ray.rllib.algorithms.dqn import DQN + YourExternalEnv = ... + register_env("my_env", lambda config: YourExternalEnv(config)) + algo = DQN(env="my_env") + while True: + print(algo.train()) + """ + + def __init__( + self, + action_space: gym.Space, + observation_space: gym.Space, + max_concurrent: int = None, + ): + """Initializes an ExternalEnv instance. + + Args: + action_space: Action space of the env. + observation_space: Observation space of the env. + """ + + threading.Thread.__init__(self) + + self.daemon = True + self.action_space = action_space + self.observation_space = observation_space + self._episodes = {} + self._finished = set() + self._results_avail_condition = threading.Condition() + if max_concurrent is not None: + deprecation_warning( + "The `max_concurrent` argument has been deprecated. Please configure" + "the number of episodes using the `rollout_fragment_length` and" + "`batch_mode` arguments. Please raise an issue on the Ray Github if " + "these arguments do not support your expected use case for ExternalEnv", + error=True, + ) + + def run(self): + """Override this to implement the run loop. + + Your loop should continuously: + 1. Call self.start_episode(episode_id) + 2. Call self.[get|log]_action(episode_id, obs, [action]?) + 3. Call self.log_returns(episode_id, reward) + 4. Call self.end_episode(episode_id, obs) + 5. Wait if nothing to do. + + Multiple episodes may be started at the same time. + """ + raise NotImplementedError + + def start_episode( + self, episode_id: Optional[str] = None, training_enabled: bool = True + ) -> str: + """Record the start of an episode. + + Args: + episode_id: Unique string id for the episode or + None for it to be auto-assigned and returned. + training_enabled: Whether to use experiences for this + episode to improve the policy. + + Returns: + Unique string id for the episode. + """ + + if episode_id is None: + episode_id = uuid.uuid4().hex + + if episode_id in self._finished: + raise ValueError("Episode {} has already completed.".format(episode_id)) + + if episode_id in self._episodes: + raise ValueError("Episode {} is already started".format(episode_id)) + + self._episodes[episode_id] = _ExternalEnvEpisode( + episode_id, self._results_avail_condition, training_enabled + ) + + return episode_id + + def get_action(self, episode_id: str, observation: EnvObsType) -> EnvActionType: + """Record an observation and get the on-policy action. + + Args: + episode_id: Episode id returned from start_episode(). + observation: Current environment observation. + + Returns: + Action from the env action space. + """ + + episode = self._get(episode_id) + return episode.wait_for_action(observation) + + def log_action( + self, episode_id: str, observation: EnvObsType, action: EnvActionType + ) -> None: + """Record an observation and (off-policy) action taken. + + Args: + episode_id: Episode id returned from start_episode(). + observation: Current environment observation. + action: Action for the observation. + """ + + episode = self._get(episode_id) + episode.log_action(observation, action) + + def log_returns( + self, episode_id: str, reward: float, info: Optional[EnvInfoDict] = None + ) -> None: + """Records returns (rewards and infos) from the environment. + + The reward will be attributed to the previous action taken by the + episode. Rewards accumulate until the next action. If no reward is + logged before the next action, a reward of 0.0 is assumed. + + Args: + episode_id: Episode id returned from start_episode(). + reward: Reward from the environment. + info: Optional info dict. + """ + + episode = self._get(episode_id) + episode.cur_reward += reward + + if info: + episode.cur_info = info or {} + + def end_episode(self, episode_id: str, observation: EnvObsType) -> None: + """Records the end of an episode. + + Args: + episode_id: Episode id returned from start_episode(). + observation: Current environment observation. + """ + + episode = self._get(episode_id) + self._finished.add(episode.episode_id) + episode.done(observation) + + def _get(self, episode_id: str) -> "_ExternalEnvEpisode": + """Get a started episode by its ID or raise an error.""" + + if episode_id in self._finished: + raise ValueError("Episode {} has already completed.".format(episode_id)) + + if episode_id not in self._episodes: + raise ValueError("Episode {} not found.".format(episode_id)) + + return self._episodes[episode_id] + + def to_base_env( + self, + make_env: Optional[Callable[[int], EnvType]] = None, + num_envs: int = 1, + remote_envs: bool = False, + remote_env_batch_wait_ms: int = 0, + restart_failed_sub_environments: bool = False, + ) -> "BaseEnv": + """Converts an RLlib MultiAgentEnv into a BaseEnv object. + + The resulting BaseEnv is always vectorized (contains n + sub-environments) to support batched forward passes, where n may + also be 1. BaseEnv also supports async execution via the `poll` and + `send_actions` methods and thus supports external simulators. + + Args: + make_env: A callable taking an int as input (which indicates + the number of individual sub-environments within the final + vectorized BaseEnv) and returning one individual + sub-environment. + num_envs: The number of sub-environments to create in the + resulting (vectorized) BaseEnv. The already existing `env` + will be one of the `num_envs`. + remote_envs: Whether each sub-env should be a @ray.remote + actor. You can set this behavior in your config via the + `remote_worker_envs=True` option. + remote_env_batch_wait_ms: The wait time (in ms) to poll remote + sub-environments for, if applicable. Only used if + `remote_envs` is True. + + Returns: + The resulting BaseEnv object. + """ + if num_envs != 1: + raise ValueError( + "External(MultiAgent)Env does not currently support " + "num_envs > 1. One way of solving this would be to " + "treat your Env as a MultiAgentEnv hosting only one " + "type of agent but with several copies." + ) + env = ExternalEnvWrapper(self) + + return env + + +@OldAPIStack +class _ExternalEnvEpisode: + """Tracked state for each active episode.""" + + def __init__( + self, + episode_id: str, + results_avail_condition: threading.Condition, + training_enabled: bool, + multiagent: bool = False, + ): + self.episode_id = episode_id + self.results_avail_condition = results_avail_condition + self.training_enabled = training_enabled + self.multiagent = multiagent + self.data_queue = queue.Queue() + self.action_queue = queue.Queue() + if multiagent: + self.new_observation_dict = None + self.new_action_dict = None + self.cur_reward_dict = {} + self.cur_terminated_dict = {"__all__": False} + self.cur_truncated_dict = {"__all__": False} + self.cur_info_dict = {} + else: + self.new_observation = None + self.new_action = None + self.cur_reward = 0.0 + self.cur_terminated = False + self.cur_truncated = False + self.cur_info = {} + + def get_data(self): + if self.data_queue.empty(): + return None + return self.data_queue.get_nowait() + + def log_action(self, observation, action): + if self.multiagent: + self.new_observation_dict = observation + self.new_action_dict = action + else: + self.new_observation = observation + self.new_action = action + self._send() + self.action_queue.get(True, timeout=60.0) + + def wait_for_action(self, observation): + if self.multiagent: + self.new_observation_dict = observation + else: + self.new_observation = observation + self._send() + return self.action_queue.get(True, timeout=300.0) + + def done(self, observation): + if self.multiagent: + self.new_observation_dict = observation + self.cur_terminated_dict = {"__all__": True} + # TODO(sven): External env API does not currently support truncated, + # but we should deprecate external Env anyways in favor of a client-only + # approach. + self.cur_truncated_dict = {"__all__": False} + else: + self.new_observation = observation + self.cur_terminated = True + self.cur_truncated = False + self._send() + + def _send(self): + if self.multiagent: + if not self.training_enabled: + for agent_id in self.cur_info_dict: + self.cur_info_dict[agent_id]["training_enabled"] = False + item = { + "obs": self.new_observation_dict, + "reward": self.cur_reward_dict, + "terminated": self.cur_terminated_dict, + "truncated": self.cur_truncated_dict, + "info": self.cur_info_dict, + } + if self.new_action_dict is not None: + item["off_policy_action"] = self.new_action_dict + self.new_observation_dict = None + self.new_action_dict = None + self.cur_reward_dict = {} + else: + item = { + "obs": self.new_observation, + "reward": self.cur_reward, + "terminated": self.cur_terminated, + "truncated": self.cur_truncated, + "info": self.cur_info, + } + if self.new_action is not None: + item["off_policy_action"] = self.new_action + self.new_observation = None + self.new_action = None + self.cur_reward = 0.0 + if not self.training_enabled: + item["info"]["training_enabled"] = False + + with self.results_avail_condition: + self.data_queue.put_nowait(item) + self.results_avail_condition.notify() + + +@OldAPIStack +class ExternalEnvWrapper(BaseEnv): + """Internal adapter of ExternalEnv to BaseEnv.""" + + def __init__( + self, external_env: "ExternalEnv", preprocessor: "Preprocessor" = None + ): + from ray.rllib.env.external_multi_agent_env import ExternalMultiAgentEnv + + self.external_env = external_env + self.prep = preprocessor + self.multiagent = issubclass(type(external_env), ExternalMultiAgentEnv) + self._action_space = external_env.action_space + if preprocessor: + self._observation_space = preprocessor.observation_space + else: + self._observation_space = external_env.observation_space + external_env.start() + + @override(BaseEnv) + def poll( + self, + ) -> Tuple[MultiEnvDict, MultiEnvDict, MultiEnvDict, MultiEnvDict, MultiEnvDict]: + with self.external_env._results_avail_condition: + results = self._poll() + while len(results[0]) == 0: + self.external_env._results_avail_condition.wait() + results = self._poll() + if not self.external_env.is_alive(): + raise Exception("Serving thread has stopped.") + return results + + @override(BaseEnv) + def send_actions(self, action_dict: MultiEnvDict) -> None: + from ray.rllib.env.base_env import _DUMMY_AGENT_ID + + if self.multiagent: + for env_id, actions in action_dict.items(): + self.external_env._episodes[env_id].action_queue.put(actions) + else: + for env_id, action in action_dict.items(): + self.external_env._episodes[env_id].action_queue.put( + action[_DUMMY_AGENT_ID] + ) + + def _poll( + self, + ) -> Tuple[ + MultiEnvDict, + MultiEnvDict, + MultiEnvDict, + MultiEnvDict, + MultiEnvDict, + MultiEnvDict, + ]: + from ray.rllib.env.base_env import with_dummy_agent_id + + all_obs, all_rewards, all_terminateds, all_truncateds, all_infos = ( + {}, + {}, + {}, + {}, + {}, + ) + off_policy_actions = {} + for eid, episode in self.external_env._episodes.copy().items(): + data = episode.get_data() + cur_terminated = ( + episode.cur_terminated_dict["__all__"] + if self.multiagent + else episode.cur_terminated + ) + cur_truncated = ( + episode.cur_truncated_dict["__all__"] + if self.multiagent + else episode.cur_truncated + ) + if cur_terminated or cur_truncated: + del self.external_env._episodes[eid] + if data: + if self.prep: + all_obs[eid] = self.prep.transform(data["obs"]) + else: + all_obs[eid] = data["obs"] + all_rewards[eid] = data["reward"] + all_terminateds[eid] = data["terminated"] + all_truncateds[eid] = data["truncated"] + all_infos[eid] = data["info"] + if "off_policy_action" in data: + off_policy_actions[eid] = data["off_policy_action"] + if self.multiagent: + # Ensure a consistent set of keys + # rely on all_obs having all possible keys for now. + for eid, eid_dict in all_obs.items(): + for agent_id in eid_dict.keys(): + + def fix(d, zero_val): + if agent_id not in d[eid]: + d[eid][agent_id] = zero_val + + fix(all_rewards, 0.0) + fix(all_terminateds, False) + fix(all_truncateds, False) + fix(all_infos, {}) + return ( + all_obs, + all_rewards, + all_terminateds, + all_truncateds, + all_infos, + off_policy_actions, + ) + else: + return ( + with_dummy_agent_id(all_obs), + with_dummy_agent_id(all_rewards), + with_dummy_agent_id(all_terminateds, "__all__"), + with_dummy_agent_id(all_truncateds, "__all__"), + with_dummy_agent_id(all_infos), + with_dummy_agent_id(off_policy_actions), + ) + + @property + @override(BaseEnv) + def observation_space(self) -> gym.spaces.Dict: + return self._observation_space + + @property + @override(BaseEnv) + def action_space(self) -> gym.Space: + return self._action_space diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external_multi_agent_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external_multi_agent_env.py new file mode 100644 index 0000000000000000000000000000000000000000..1350d5c7c3563f52a8c2c8a7951369d702a0307f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/external_multi_agent_env.py @@ -0,0 +1,161 @@ +import uuid +import gymnasium as gym +from typing import Optional + +from ray.rllib.utils.annotations import override, OldAPIStack +from ray.rllib.env.external_env import ExternalEnv, _ExternalEnvEpisode +from ray.rllib.utils.typing import MultiAgentDict + + +@OldAPIStack +class ExternalMultiAgentEnv(ExternalEnv): + """This is the multi-agent version of ExternalEnv.""" + + def __init__( + self, + action_space: gym.Space, + observation_space: gym.Space, + ): + """Initializes an ExternalMultiAgentEnv instance. + + Args: + action_space: Action space of the env. + observation_space: Observation space of the env. + """ + ExternalEnv.__init__(self, action_space, observation_space) + + # We require to know all agents' spaces. + if isinstance(self.action_space, dict) or isinstance( + self.observation_space, dict + ): + if not (self.action_space.keys() == self.observation_space.keys()): + raise ValueError( + "Agent ids disagree for action space and obs " + "space dict: {} {}".format( + self.action_space.keys(), self.observation_space.keys() + ) + ) + + def run(self): + """Override this to implement the multi-agent run loop. + + Your loop should continuously: + 1. Call self.start_episode(episode_id) + 2. Call self.get_action(episode_id, obs_dict) + -or- + self.log_action(episode_id, obs_dict, action_dict) + 3. Call self.log_returns(episode_id, reward_dict) + 4. Call self.end_episode(episode_id, obs_dict) + 5. Wait if nothing to do. + + Multiple episodes may be started at the same time. + """ + raise NotImplementedError + + @override(ExternalEnv) + def start_episode( + self, episode_id: Optional[str] = None, training_enabled: bool = True + ) -> str: + if episode_id is None: + episode_id = uuid.uuid4().hex + + if episode_id in self._finished: + raise ValueError("Episode {} has already completed.".format(episode_id)) + + if episode_id in self._episodes: + raise ValueError("Episode {} is already started".format(episode_id)) + + self._episodes[episode_id] = _ExternalEnvEpisode( + episode_id, self._results_avail_condition, training_enabled, multiagent=True + ) + + return episode_id + + @override(ExternalEnv) + def get_action( + self, episode_id: str, observation_dict: MultiAgentDict + ) -> MultiAgentDict: + """Record an observation and get the on-policy action. + + Thereby, observation_dict is expected to contain the observation + of all agents acting in this episode step. + + Args: + episode_id: Episode id returned from start_episode(). + observation_dict: Current environment observation. + + Returns: + action: Action from the env action space. + """ + + episode = self._get(episode_id) + return episode.wait_for_action(observation_dict) + + @override(ExternalEnv) + def log_action( + self, + episode_id: str, + observation_dict: MultiAgentDict, + action_dict: MultiAgentDict, + ) -> None: + """Record an observation and (off-policy) action taken. + + Args: + episode_id: Episode id returned from start_episode(). + observation_dict: Current environment observation. + action_dict: Action for the observation. + """ + + episode = self._get(episode_id) + episode.log_action(observation_dict, action_dict) + + @override(ExternalEnv) + def log_returns( + self, + episode_id: str, + reward_dict: MultiAgentDict, + info_dict: MultiAgentDict = None, + multiagent_done_dict: MultiAgentDict = None, + ) -> None: + """Record returns from the environment. + + The reward will be attributed to the previous action taken by the + episode. Rewards accumulate until the next action. If no reward is + logged before the next action, a reward of 0.0 is assumed. + + Args: + episode_id: Episode id returned from start_episode(). + reward_dict: Reward from the environment agents. + info_dict: Optional info dict. + multiagent_done_dict: Optional done dict for agents. + """ + + episode = self._get(episode_id) + + # Accumulate reward by agent. + # For existing agents, we want to add the reward up. + for agent, rew in reward_dict.items(): + if agent in episode.cur_reward_dict: + episode.cur_reward_dict[agent] += rew + else: + episode.cur_reward_dict[agent] = rew + + if multiagent_done_dict: + for agent, done in multiagent_done_dict.items(): + episode.cur_done_dict[agent] = done + + if info_dict: + episode.cur_info_dict = info_dict or {} + + @override(ExternalEnv) + def end_episode(self, episode_id: str, observation_dict: MultiAgentDict) -> None: + """Record the end of an episode. + + Args: + episode_id: Episode id returned from start_episode(). + observation_dict: Current environment observation. + """ + + episode = self._get(episode_id) + self._finished.add(episode.episode_id) + episode.done(observation_dict) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/multi_agent_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/multi_agent_env.py new file mode 100644 index 0000000000000000000000000000000000000000..843169306dce1235272784cdea0400dab6736d33 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/multi_agent_env.py @@ -0,0 +1,808 @@ +import copy +import gymnasium as gym +import logging +from typing import Callable, Dict, List, Tuple, Optional, Union, Set, Type + +import numpy as np + +from ray.rllib.env.base_env import BaseEnv +from ray.rllib.env.env_context import EnvContext +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.deprecation import Deprecated +from ray.rllib.utils.typing import ( + AgentID, + EnvCreator, + EnvID, + EnvType, + MultiAgentDict, + MultiEnvDict, +) +from ray.util import log_once +from ray.util.annotations import DeveloperAPI, PublicAPI + +# If the obs space is Dict type, look for the global state under this key. +ENV_STATE = "state" + +logger = logging.getLogger(__name__) + + +@PublicAPI(stability="beta") +class MultiAgentEnv(gym.Env): + """An environment that hosts multiple independent agents. + + Agents are identified by AgentIDs (string). + """ + + # Optional mappings from AgentID to individual agents' spaces. + # Set this to an "exhaustive" dictionary, mapping all possible AgentIDs to + # individual agents' spaces. Alternatively, override + # `get_observation_space(agent_id=...)` and `get_action_space(agent_id=...)`, which + # is the API that RLlib uses to get individual spaces and whose default + # implementation is to simply look up `agent_id` in these dicts. + observation_spaces: Optional[Dict[AgentID, gym.Space]] = None + action_spaces: Optional[Dict[AgentID, gym.Space]] = None + + # All agents currently active in the environment. This attribute may change during + # the lifetime of the env or even during an individual episode. + agents: List[AgentID] = [] + # All agents that may appear in the environment, ever. + # This attribute should not be changed during the lifetime of this env. + possible_agents: List[AgentID] = [] + + # @OldAPIStack, use `observation_spaces` and `action_spaces`, instead. + observation_space: Optional[gym.Space] = None + action_space: Optional[gym.Space] = None + + def __init__(self): + super().__init__() + + # @OldAPIStack + if not hasattr(self, "_agent_ids"): + self._agent_ids = set() + + # If these important attributes are not set, try to infer them. + if not self.agents: + self.agents = list(self._agent_ids) + if not self.possible_agents: + self.possible_agents = self.agents.copy() + + def reset( + self, + *, + seed: Optional[int] = None, + options: Optional[dict] = None, + ) -> Tuple[MultiAgentDict, MultiAgentDict]: # type: ignore + """Resets the env and returns observations from ready agents. + + Args: + seed: An optional seed to use for the new episode. + + Returns: + New observations for each ready agent. + + .. testcode:: + :skipif: True + + from ray.rllib.env.multi_agent_env import MultiAgentEnv + class MyMultiAgentEnv(MultiAgentEnv): + # Define your env here. + env = MyMultiAgentEnv() + obs, infos = env.reset(seed=42, options={}) + print(obs) + + .. testoutput:: + + { + "car_0": [2.4, 1.6], + "car_1": [3.4, -3.2], + "traffic_light_1": [0, 3, 5, 1], + } + """ + # Call super's `reset()` method to (maybe) set the given `seed`. + super().reset(seed=seed, options=options) + + def step( + self, action_dict: MultiAgentDict + ) -> Tuple[ + MultiAgentDict, MultiAgentDict, MultiAgentDict, MultiAgentDict, MultiAgentDict + ]: + """Returns observations from ready agents. + + The returns are dicts mapping from agent_id strings to values. The + number of agents in the env can vary over time. + + Returns: + Tuple containing 1) new observations for + each ready agent, 2) reward values for each ready agent. If + the episode is just started, the value will be None. + 3) Terminated values for each ready agent. The special key + "__all__" (required) is used to indicate env termination. + 4) Truncated values for each ready agent. + 5) Info values for each agent id (may be empty dicts). + + .. testcode:: + :skipif: True + + env = ... + obs, rewards, terminateds, truncateds, infos = env.step(action_dict={ + "car_0": 1, "car_1": 0, "traffic_light_1": 2, + }) + print(rewards) + + print(terminateds) + + print(infos) + + .. testoutput:: + + { + "car_0": 3, + "car_1": -1, + "traffic_light_1": 0, + } + { + "car_0": False, # car_0 is still running + "car_1": True, # car_1 is terminated + "__all__": False, # the env is not terminated + } + { + "car_0": {}, # info for car_0 + "car_1": {}, # info for car_1 + } + + """ + raise NotImplementedError + + def render(self) -> None: + """Tries to render the environment.""" + + # By default, do nothing. + pass + + def get_observation_space(self, agent_id: AgentID) -> gym.Space: + if self.observation_spaces is not None: + return self.observation_spaces[agent_id] + + # @OldAPIStack behavior. + # `self.observation_space` is a `gym.spaces.Dict` AND contains `agent_id`. + if ( + isinstance(self.observation_space, gym.spaces.Dict) + and agent_id in self.observation_space.spaces + ): + return self.observation_space[agent_id] + # `self.observation_space` is not a `gym.spaces.Dict` OR doesn't contain + # `agent_id` -> The defined space is most likely meant to be the space + # for all agents. + else: + return self.observation_space + + def get_action_space(self, agent_id: AgentID) -> gym.Space: + if self.action_spaces is not None: + return self.action_spaces[agent_id] + + # @OldAPIStack behavior. + # `self.action_space` is a `gym.spaces.Dict` AND contains `agent_id`. + if ( + isinstance(self.action_space, gym.spaces.Dict) + and agent_id in self.action_space.spaces + ): + return self.action_space[agent_id] + # `self.action_space` is not a `gym.spaces.Dict` OR doesn't contain + # `agent_id` -> The defined space is most likely meant to be the space + # for all agents. + else: + return self.action_space + + @property + def num_agents(self) -> int: + return len(self.agents) + + @property + def max_num_agents(self) -> int: + return len(self.possible_agents) + + # fmt: off + # __grouping_doc_begin__ + def with_agent_groups( + self, + groups: Dict[str, List[AgentID]], + obs_space: gym.Space = None, + act_space: gym.Space = None, + ) -> "MultiAgentEnv": + """Convenience method for grouping together agents in this env. + + An agent group is a list of agent IDs that are mapped to a single + logical agent. All agents of the group must act at the same time in the + environment. The grouped agent exposes Tuple action and observation + spaces that are the concatenated action and obs spaces of the + individual agents. + + The rewards of all the agents in a group are summed. The individual + agent rewards are available under the "individual_rewards" key of the + group info return. + + Agent grouping is required to leverage algorithms such as Q-Mix. + + Args: + groups: Mapping from group id to a list of the agent ids + of group members. If an agent id is not present in any group + value, it will be left ungrouped. The group id becomes a new agent ID + in the final environment. + obs_space: Optional observation space for the grouped + env. Must be a tuple space. If not provided, will infer this to be a + Tuple of n individual agents spaces (n=num agents in a group). + act_space: Optional action space for the grouped env. + Must be a tuple space. If not provided, will infer this to be a Tuple + of n individual agents spaces (n=num agents in a group). + + .. testcode:: + :skipif: True + + from ray.rllib.env.multi_agent_env import MultiAgentEnv + class MyMultiAgentEnv(MultiAgentEnv): + # define your env here + ... + env = MyMultiAgentEnv(...) + grouped_env = env.with_agent_groups(env, { + "group1": ["agent1", "agent2", "agent3"], + "group2": ["agent4", "agent5"], + }) + + """ + + from ray.rllib.env.wrappers.group_agents_wrapper import \ + GroupAgentsWrapper + return GroupAgentsWrapper(self, groups, obs_space, act_space) + + # __grouping_doc_end__ + # fmt: on + + @OldAPIStack + @Deprecated(new="MultiAgentEnv.possible_agents", error=False) + def get_agent_ids(self) -> Set[AgentID]: + if not hasattr(self, "_agent_ids"): + self._agent_ids = set() + if not isinstance(self._agent_ids, set): + self._agent_ids = set(self._agent_ids) + # Make this backward compatible as much as possible. + return self._agent_ids if self._agent_ids else set(self.agents) + + @OldAPIStack + def to_base_env( + self, + make_env: Optional[Callable[[int], EnvType]] = None, + num_envs: int = 1, + remote_envs: bool = False, + remote_env_batch_wait_ms: int = 0, + restart_failed_sub_environments: bool = False, + ) -> "BaseEnv": + """Converts an RLlib MultiAgentEnv into a BaseEnv object. + + The resulting BaseEnv is always vectorized (contains n + sub-environments) to support batched forward passes, where n may + also be 1. BaseEnv also supports async execution via the `poll` and + `send_actions` methods and thus supports external simulators. + + Args: + make_env: A callable taking an int as input (which indicates + the number of individual sub-environments within the final + vectorized BaseEnv) and returning one individual + sub-environment. + num_envs: The number of sub-environments to create in the + resulting (vectorized) BaseEnv. The already existing `env` + will be one of the `num_envs`. + remote_envs: Whether each sub-env should be a @ray.remote + actor. You can set this behavior in your config via the + `remote_worker_envs=True` option. + remote_env_batch_wait_ms: The wait time (in ms) to poll remote + sub-environments for, if applicable. Only used if + `remote_envs` is True. + restart_failed_sub_environments: If True and any sub-environment (within + a vectorized env) throws any error during env stepping, we will try to + restart the faulty sub-environment. This is done + without disturbing the other (still intact) sub-environments. + + Returns: + The resulting BaseEnv object. + """ + from ray.rllib.env.remote_base_env import RemoteBaseEnv + + if remote_envs: + env = RemoteBaseEnv( + make_env, + num_envs, + multiagent=True, + remote_env_batch_wait_ms=remote_env_batch_wait_ms, + restart_failed_sub_environments=restart_failed_sub_environments, + ) + # Sub-environments are not ray.remote actors. + else: + env = MultiAgentEnvWrapper( + make_env=make_env, + existing_envs=[self], + num_envs=num_envs, + restart_failed_sub_environments=restart_failed_sub_environments, + ) + + return env + + +@DeveloperAPI +def make_multi_agent( + env_name_or_creator: Union[str, EnvCreator], +) -> Type["MultiAgentEnv"]: + """Convenience wrapper for any single-agent env to be converted into MA. + + Allows you to convert a simple (single-agent) `gym.Env` class + into a `MultiAgentEnv` class. This function simply stacks n instances + of the given ```gym.Env``` class into one unified ``MultiAgentEnv`` class + and returns this class, thus pretending the agents act together in the + same environment, whereas - under the hood - they live separately from + each other in n parallel single-agent envs. + + Agent IDs in the resulting and are int numbers starting from 0 + (first agent). + + Args: + env_name_or_creator: String specifier or env_maker function taking + an EnvContext object as only arg and returning a gym.Env. + + Returns: + New MultiAgentEnv class to be used as env. + The constructor takes a config dict with `num_agents` key + (default=1). The rest of the config dict will be passed on to the + underlying single-agent env's constructor. + + .. testcode:: + :skipif: True + + from ray.rllib.env.multi_agent_env import make_multi_agent + # By gym string: + ma_cartpole_cls = make_multi_agent("CartPole-v1") + # Create a 2 agent multi-agent cartpole. + ma_cartpole = ma_cartpole_cls({"num_agents": 2}) + obs = ma_cartpole.reset() + print(obs) + + # By env-maker callable: + from ray.rllib.examples.envs.classes.stateless_cartpole import StatelessCartPole + ma_stateless_cartpole_cls = make_multi_agent( + lambda config: StatelessCartPole(config)) + # Create a 3 agent multi-agent stateless cartpole. + ma_stateless_cartpole = ma_stateless_cartpole_cls( + {"num_agents": 3}) + print(obs) + + .. testoutput:: + + {0: [...], 1: [...]} + {0: [...], 1: [...], 2: [...]} + """ + + class MultiEnv(MultiAgentEnv): + def __init__(self, config: EnvContext = None): + super().__init__() + + # Note: Explicitly check for None here, because config + # can have an empty dict but meaningful data fields (worker_index, + # vector_index) etc. + # TODO (sven): Clean this up, so we are not mixing up dict fields + # with data fields. + if config is None: + config = {} + else: + # Note the deepcopy is needed b/c (a) we need to remove the + # `num_agents` keyword and (b) with `num_envs > 0` in the + # `VectorMultiAgentEnv` all following environment creations + # need the same config again. + config = copy.deepcopy(config) + num = config.pop("num_agents", 1) + if isinstance(env_name_or_creator, str): + self.envs = [gym.make(env_name_or_creator) for _ in range(num)] + else: + self.envs = [env_name_or_creator(config) for _ in range(num)] + self.terminateds = set() + self.truncateds = set() + self.observation_spaces = { + i: self.envs[i].observation_space for i in range(num) + } + self.action_spaces = {i: self.envs[i].action_space for i in range(num)} + self.agents = list(range(num)) + self.possible_agents = self.agents.copy() + + @override(MultiAgentEnv) + def reset(self, *, seed: Optional[int] = None, options: Optional[dict] = None): + self.terminateds = set() + self.truncateds = set() + obs, infos = {}, {} + for i, env in enumerate(self.envs): + obs[i], infos[i] = env.reset(seed=seed, options=options) + if not self.observation_spaces[i].contains(obs[i]): + print("===> MultiEnv does not contain obs.") + + return obs, infos + + @override(MultiAgentEnv) + def step(self, action_dict): + obs, rew, terminated, truncated, info = {}, {}, {}, {}, {} + + # The environment is expecting an action for at least one agent. + if len(action_dict) == 0: + raise ValueError( + "The environment is expecting an action for at least one agent." + ) + + for i, action in action_dict.items(): + obs[i], rew[i], terminated[i], truncated[i], info[i] = self.envs[ + i + ].step(action) + if terminated[i]: + self.terminateds.add(i) + if truncated[i]: + self.truncateds.add(i) + # TODO: Flaw in our MultiAgentEnv API wrt. new gymnasium: Need to return + # an additional episode_done bool that covers cases where all agents are + # either terminated or truncated, but not all are truncated and not all are + # terminated. We can then get rid of the aweful `__all__` special keys! + terminated["__all__"] = len(self.terminateds) + len(self.truncateds) == len( + self.envs + ) + truncated["__all__"] = len(self.truncateds) == len(self.envs) + return obs, rew, terminated, truncated, info + + @override(MultiAgentEnv) + def render(self): + # This render method simply renders all n underlying individual single-agent + # envs and concatenates their images (on top of each other if the returned + # images have dims where [width] > [height], otherwise next to each other). + render_images = [e.render() for e in self.envs] + if render_images[0].shape[1] > render_images[0].shape[0]: + concat_dim = 0 + else: + concat_dim = 1 + return np.concatenate(render_images, axis=concat_dim) + + return MultiEnv + + +@OldAPIStack +class MultiAgentEnvWrapper(BaseEnv): + """Internal adapter of MultiAgentEnv to BaseEnv. + + This also supports vectorization if num_envs > 1. + """ + + def __init__( + self, + make_env: Callable[[int], EnvType], + existing_envs: List["MultiAgentEnv"], + num_envs: int, + restart_failed_sub_environments: bool = False, + ): + """Wraps MultiAgentEnv(s) into the BaseEnv API. + + Args: + make_env: Factory that produces a new MultiAgentEnv instance taking the + vector index as only call argument. + Must be defined, if the number of existing envs is less than num_envs. + existing_envs: List of already existing multi-agent envs. + num_envs: Desired num multiagent envs to have at the end in + total. This will include the given (already created) + `existing_envs`. + restart_failed_sub_environments: If True and any sub-environment (within + this vectorized env) throws any error during env stepping, we will try + to restart the faulty sub-environment. This is done + without disturbing the other (still intact) sub-environments. + """ + self.make_env = make_env + self.envs = existing_envs + self.num_envs = num_envs + self.restart_failed_sub_environments = restart_failed_sub_environments + + self.terminateds = set() + self.truncateds = set() + while len(self.envs) < self.num_envs: + self.envs.append(self.make_env(len(self.envs))) + for env in self.envs: + assert isinstance(env, MultiAgentEnv) + self._init_env_state(idx=None) + self._unwrapped_env = self.envs[0].unwrapped + + @override(BaseEnv) + def poll( + self, + ) -> Tuple[ + MultiEnvDict, + MultiEnvDict, + MultiEnvDict, + MultiEnvDict, + MultiEnvDict, + MultiEnvDict, + ]: + obs, rewards, terminateds, truncateds, infos = {}, {}, {}, {}, {} + for i, env_state in enumerate(self.env_states): + ( + obs[i], + rewards[i], + terminateds[i], + truncateds[i], + infos[i], + ) = env_state.poll() + return obs, rewards, terminateds, truncateds, infos, {} + + @override(BaseEnv) + def send_actions(self, action_dict: MultiEnvDict) -> None: + for env_id, agent_dict in action_dict.items(): + if env_id in self.terminateds or env_id in self.truncateds: + raise ValueError( + f"Env {env_id} is already done and cannot accept new actions" + ) + env = self.envs[env_id] + try: + obs, rewards, terminateds, truncateds, infos = env.step(agent_dict) + except Exception as e: + if self.restart_failed_sub_environments: + logger.exception(e.args[0]) + self.try_restart(env_id=env_id) + obs = e + rewards = {} + terminateds = {"__all__": True} + truncateds = {"__all__": False} + infos = {} + else: + raise e + + assert isinstance( + obs, (dict, Exception) + ), "Not a multi-agent obs dict or an Exception!" + assert isinstance(rewards, dict), "Not a multi-agent reward dict!" + assert isinstance(terminateds, dict), "Not a multi-agent terminateds dict!" + assert isinstance(truncateds, dict), "Not a multi-agent truncateds dict!" + assert isinstance(infos, dict), "Not a multi-agent info dict!" + if isinstance(obs, dict): + info_diff = set(infos).difference(set(obs)) + if info_diff and info_diff != {"__common__"}: + raise ValueError( + "Key set for infos must be a subset of obs (plus optionally " + "the '__common__' key for infos concerning all/no agents): " + "{} vs {}".format(infos.keys(), obs.keys()) + ) + if "__all__" not in terminateds: + raise ValueError( + "In multi-agent environments, '__all__': True|False must " + "be included in the 'terminateds' dict: got {}.".format(terminateds) + ) + elif "__all__" not in truncateds: + raise ValueError( + "In multi-agent environments, '__all__': True|False must " + "be included in the 'truncateds' dict: got {}.".format(truncateds) + ) + + if terminateds["__all__"]: + self.terminateds.add(env_id) + if truncateds["__all__"]: + self.truncateds.add(env_id) + self.env_states[env_id].observe( + obs, rewards, terminateds, truncateds, infos + ) + + @override(BaseEnv) + def try_reset( + self, + env_id: Optional[EnvID] = None, + *, + seed: Optional[int] = None, + options: Optional[dict] = None, + ) -> Optional[Tuple[MultiEnvDict, MultiEnvDict]]: + ret_obs = {} + ret_infos = {} + if isinstance(env_id, int): + env_id = [env_id] + if env_id is None: + env_id = list(range(len(self.envs))) + for idx in env_id: + obs, infos = self.env_states[idx].reset(seed=seed, options=options) + + if isinstance(obs, Exception): + if self.restart_failed_sub_environments: + self.env_states[idx].env = self.envs[idx] = self.make_env(idx) + else: + raise obs + else: + assert isinstance(obs, dict), "Not a multi-agent obs dict!" + if obs is not None: + if idx in self.terminateds: + self.terminateds.remove(idx) + if idx in self.truncateds: + self.truncateds.remove(idx) + ret_obs[idx] = obs + ret_infos[idx] = infos + return ret_obs, ret_infos + + @override(BaseEnv) + def try_restart(self, env_id: Optional[EnvID] = None) -> None: + if isinstance(env_id, int): + env_id = [env_id] + if env_id is None: + env_id = list(range(len(self.envs))) + for idx in env_id: + # Try closing down the old (possibly faulty) sub-env, but ignore errors. + try: + self.envs[idx].close() + except Exception as e: + if log_once("close_sub_env"): + logger.warning( + "Trying to close old and replaced sub-environment (at vector " + f"index={idx}), but closing resulted in error:\n{e}" + ) + # Try recreating the sub-env. + logger.warning(f"Trying to restart sub-environment at index {idx}.") + self.env_states[idx].env = self.envs[idx] = self.make_env(idx) + logger.warning(f"Sub-environment at index {idx} restarted successfully.") + + @override(BaseEnv) + def get_sub_environments( + self, as_dict: bool = False + ) -> Union[Dict[str, EnvType], List[EnvType]]: + if as_dict: + return {_id: env_state.env for _id, env_state in enumerate(self.env_states)} + return [state.env for state in self.env_states] + + @override(BaseEnv) + def try_render(self, env_id: Optional[EnvID] = None) -> None: + if env_id is None: + env_id = 0 + assert isinstance(env_id, int) + return self.envs[env_id].render() + + @property + @override(BaseEnv) + def observation_space(self) -> gym.spaces.Dict: + return self.envs[0].observation_space + + @property + @override(BaseEnv) + def action_space(self) -> gym.Space: + return self.envs[0].action_space + + @override(BaseEnv) + def get_agent_ids(self) -> Set[AgentID]: + return self.envs[0].get_agent_ids() + + def _init_env_state(self, idx: Optional[int] = None) -> None: + """Resets all or one particular sub-environment's state (by index). + + Args: + idx: The index to reset at. If None, reset all the sub-environments' states. + """ + # If index is None, reset all sub-envs' states: + if idx is None: + self.env_states = [ + _MultiAgentEnvState(env, self.restart_failed_sub_environments) + for env in self.envs + ] + # Index provided, reset only the sub-env's state at the given index. + else: + assert isinstance(idx, int) + self.env_states[idx] = _MultiAgentEnvState( + self.envs[idx], self.restart_failed_sub_environments + ) + + +@OldAPIStack +class _MultiAgentEnvState: + def __init__(self, env: MultiAgentEnv, return_error_as_obs: bool = False): + assert isinstance(env, MultiAgentEnv) + self.env = env + self.return_error_as_obs = return_error_as_obs + + self.initialized = False + self.last_obs = {} + self.last_rewards = {} + self.last_terminateds = {"__all__": False} + self.last_truncateds = {"__all__": False} + self.last_infos = {} + + def poll( + self, + ) -> Tuple[ + MultiAgentDict, + MultiAgentDict, + MultiAgentDict, + MultiAgentDict, + MultiAgentDict, + ]: + if not self.initialized: + # TODO(sven): Should we make it possible to pass in a seed here? + self.reset() + self.initialized = True + + observations = self.last_obs + rewards = {} + terminateds = {"__all__": self.last_terminateds["__all__"]} + truncateds = {"__all__": self.last_truncateds["__all__"]} + infos = self.last_infos + + # If episode is done or we have an error, release everything we have. + if ( + terminateds["__all__"] + or truncateds["__all__"] + or isinstance(observations, Exception) + ): + rewards = self.last_rewards + self.last_rewards = {} + terminateds = self.last_terminateds + if isinstance(observations, Exception): + terminateds["__all__"] = True + truncateds["__all__"] = False + self.last_terminateds = {} + truncateds = self.last_truncateds + self.last_truncateds = {} + self.last_obs = {} + infos = self.last_infos + self.last_infos = {} + # Only release those agents' rewards/terminateds/truncateds/infos, whose + # observations we have. + else: + for ag in observations.keys(): + if ag in self.last_rewards: + rewards[ag] = self.last_rewards[ag] + del self.last_rewards[ag] + if ag in self.last_terminateds: + terminateds[ag] = self.last_terminateds[ag] + del self.last_terminateds[ag] + if ag in self.last_truncateds: + truncateds[ag] = self.last_truncateds[ag] + del self.last_truncateds[ag] + + self.last_terminateds["__all__"] = False + self.last_truncateds["__all__"] = False + return observations, rewards, terminateds, truncateds, infos + + def observe( + self, + obs: MultiAgentDict, + rewards: MultiAgentDict, + terminateds: MultiAgentDict, + truncateds: MultiAgentDict, + infos: MultiAgentDict, + ): + self.last_obs = obs + for ag, r in rewards.items(): + if ag in self.last_rewards: + self.last_rewards[ag] += r + else: + self.last_rewards[ag] = r + for ag, d in terminateds.items(): + if ag in self.last_terminateds: + self.last_terminateds[ag] = self.last_terminateds[ag] or d + else: + self.last_terminateds[ag] = d + for ag, t in truncateds.items(): + if ag in self.last_truncateds: + self.last_truncateds[ag] = self.last_truncateds[ag] or t + else: + self.last_truncateds[ag] = t + self.last_infos = infos + + def reset( + self, + *, + seed: Optional[int] = None, + options: Optional[dict] = None, + ) -> Tuple[MultiAgentDict, MultiAgentDict]: + try: + obs_and_infos = self.env.reset(seed=seed, options=options) + except Exception as e: + if self.return_error_as_obs: + logger.exception(e.args[0]) + obs_and_infos = e, e + else: + raise e + + self.last_obs, self.last_infos = obs_and_infos + self.last_rewards = {} + self.last_terminateds = {"__all__": False} + self.last_truncateds = {"__all__": False} + + return self.last_obs, self.last_infos diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/multi_agent_env_runner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/multi_agent_env_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..2610d1f1ba2d22823c271ce74549071c464ebd4a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/multi_agent_env_runner.py @@ -0,0 +1,1089 @@ +from collections import defaultdict +from functools import partial +import math +import logging +import time +from typing import Collection, DefaultDict, Dict, List, Optional, Union + +import gymnasium as gym + +import ray +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig +from ray.rllib.callbacks.utils import make_callback +from ray.rllib.core import ( + COMPONENT_ENV_TO_MODULE_CONNECTOR, + COMPONENT_MODULE_TO_ENV_CONNECTOR, + COMPONENT_RL_MODULE, +) +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModule, MultiRLModuleSpec +from ray.rllib.env import INPUT_ENV_SPACES, INPUT_ENV_SINGLE_SPACES +from ray.rllib.env.env_context import EnvContext +from ray.rllib.env.env_runner import EnvRunner, ENV_STEP_FAILURE +from ray.rllib.env.multi_agent_env import MultiAgentEnv +from ray.rllib.env.multi_agent_episode import MultiAgentEpisode +from ray.rllib.env.vector.vector_multi_agent_env import VectorMultiAgentEnv +from ray.rllib.env.vector.registration import make_vec +from ray.rllib.env.utils import _gym_env_creator +from ray.rllib.utils import force_list +from ray.rllib.utils.annotations import override +from ray.rllib.utils.checkpoints import Checkpointable +from ray.rllib.utils.deprecation import Deprecated +from ray.rllib.utils.framework import get_device, try_import_torch +from ray.rllib.utils.metrics import ( + ENV_TO_MODULE_CONNECTOR, + EPISODE_DURATION_SEC_MEAN, + EPISODE_LEN_MAX, + EPISODE_LEN_MEAN, + EPISODE_LEN_MIN, + EPISODE_RETURN_MAX, + EPISODE_RETURN_MEAN, + EPISODE_RETURN_MIN, + MODULE_TO_ENV_CONNECTOR, + NUM_AGENT_STEPS_SAMPLED, + NUM_AGENT_STEPS_SAMPLED_LIFETIME, + NUM_ENV_STEPS_SAMPLED, + NUM_ENV_STEPS_SAMPLED_LIFETIME, + NUM_EPISODES, + NUM_EPISODES_LIFETIME, + NUM_MODULE_STEPS_SAMPLED, + NUM_MODULE_STEPS_SAMPLED_LIFETIME, + RLMODULE_INFERENCE_TIMER, + SAMPLE_TIMER, + TIME_BETWEEN_SAMPLING, + WEIGHTS_SEQ_NO, +) +from ray.rllib.utils.pre_checks.env import check_multiagent_environments +from ray.rllib.utils.typing import EpisodeID, ModelWeights, ResultDict, StateDict +from ray.tune.registry import ENV_CREATOR, _global_registry +from ray.util.annotations import PublicAPI + +torch, _ = try_import_torch() +logger = logging.getLogger("ray.rllib") + + +# TODO (sven): As soon as RolloutWorker is no longer supported, make `EnvRunner` itself +# a Checkpointable. Currently, only some of its subclasses are Checkpointables. +@PublicAPI(stability="alpha") +class MultiAgentEnvRunner(EnvRunner, Checkpointable): + """The genetic environment runner for the multi-agent case.""" + + @override(EnvRunner) + def __init__(self, config: AlgorithmConfig, **kwargs): + """Initializes a MultiAgentEnvRunner instance. + + Args: + config: An `AlgorithmConfig` object containing all settings needed to + build this `EnvRunner` class. + """ + super().__init__(config=config, **kwargs) + + # Raise an Error, if the provided config is not a multi-agent one. + if not self.config.is_multi_agent: + raise ValueError( + f"Cannot use this EnvRunner class ({type(self).__name__}), if your " + "setup is not multi-agent! Try adding multi-agent information to your " + "AlgorithmConfig via calling the `config.multi_agent(policies=..., " + "policy_mapping_fn=...)`." + ) + + self.spaces = kwargs.get("spaces", {}) + + self._setup_metrics() + + # Create our callbacks object. + self._callbacks = [cls() for cls in force_list(self.config.callbacks_class)] + + # Set device. + self._device = get_device( + self.config, + 0 if not self.worker_index else self.config.num_gpus_per_env_runner, + ) + + # Create the vectorized gymnasium env. + self.env: Optional[gym.Wrapper] = None + self.num_envs: int = 0 + if ( + self.worker_index is None + or self.worker_index > 0 + or self.config.create_env_on_local_worker + or self.config.num_env_runners == 0 + ): + self.make_env() + + # Create the env-to-module connector pipeline. + self._env_to_module = self.config.build_env_to_module_connector( + env=self.env, spaces=self.spaces, device=self._device + ) + # Cached env-to-module results taken at the end of a `_sample_timesteps()` + # call to make sure the final observation (before an episode cut) gets properly + # processed (and maybe postprocessed and re-stored into the episode). + # For example, if we had a connector that normalizes observations and directly + # re-inserts these new obs back into the episode, the last observation in each + # sample call would NOT be processed, which could be very harmful in cases, + # in which value function bootstrapping of those (truncation) observations is + # required in the learning step. + self._cached_to_module = None + + # Construct the MultiRLModule. + self.module: Optional[MultiRLModule] = None + self.make_module() + + # Create the module-to-env connector pipeline. + self._module_to_env = self.config.build_module_to_env_connector( + env=self.env.unwrapped if self.env else None, spaces=self.spaces + ) + + self._needs_initial_reset: bool = True + self._episode: Optional[MultiAgentEpisode] = None + self._shared_data = None + + self._weights_seq_no: int = 0 + + # Measures the time passed between returning from `sample()` + # and receiving the next `sample()` request from the user. + self._time_after_sampling = None + + @override(EnvRunner) + def sample( + self, + *, + num_timesteps: int = None, + num_episodes: int = None, + explore: bool = None, + random_actions: bool = False, + force_reset: bool = False, + ) -> List[MultiAgentEpisode]: + """Runs and returns a sample (n timesteps or m episodes) on the env(s). + + Args: + num_timesteps: The number of timesteps to sample during this call. + Note that only one of `num_timetseps` or `num_episodes` may be provided. + num_episodes: The number of episodes to sample during this call. + Note that only one of `num_timetseps` or `num_episodes` may be provided. + explore: If True, will use the RLModule's `forward_exploration()` + method to compute actions. If False, will use the RLModule's + `forward_inference()` method. If None (default), will use the `explore` + boolean setting from `self.config` passed into this EnvRunner's + constructor. You can change this setting in your config via + `config.env_runners(explore=True|False)`. + random_actions: If True, actions will be sampled randomly (from the action + space of the environment). If False (default), actions or action + distribution parameters are computed by the RLModule. + force_reset: Whether to force-reset all (vector) environments before + sampling. Useful if you would like to collect a clean slate of new + episodes via this call. Note that when sampling n episodes + (`num_episodes != None`), this is fixed to True. + + Returns: + A list of `MultiAgentEpisode` instances, carrying the sampled data. + """ + if self.env is None: + raise ValueError( + f"{self} doesn't have an env! Can't call `sample()` on it." + ) + + assert not (num_timesteps is not None and num_episodes is not None) + + # Log time between `sample()` requests. + if self._time_after_sampling is not None: + self.metrics.log_value( + key=TIME_BETWEEN_SAMPLING, + value=time.perf_counter() - self._time_after_sampling, + ) + + # Log current weight seq no. + self.metrics.log_value( + key=WEIGHTS_SEQ_NO, + value=self._weights_seq_no, + window=1, + ) + + with self.metrics.log_time(SAMPLE_TIMER): + # If no execution details are provided, use the config to try to infer the + # desired timesteps/episodes to sample and exploration behavior. + if explore is None: + explore = self.config.explore + if ( + num_timesteps is None + and num_episodes is None + and self.config.batch_mode == "truncate_episodes" + ): + num_timesteps = ( + self.config.get_rollout_fragment_length(self.worker_index) + * self.num_envs + ) + + # Sample n timesteps. + if num_timesteps is not None: + samples = self._sample( + num_timesteps=num_timesteps, + explore=explore, + random_actions=random_actions, + force_reset=force_reset, + ) + # Sample m episodes. + elif num_episodes is not None: + samples = self._sample( + num_episodes=num_episodes, + explore=explore, + random_actions=random_actions, + ) + # For complete episodes mode, sample as long as the number of timesteps + # done is smaller than the `train_batch_size`. + else: + samples = self._sample( + num_episodes=self.num_envs, + explore=explore, + random_actions=random_actions, + ) + + # Make the `on_sample_end` callback. + make_callback( + "on_sample_end", + callbacks_objects=self._callbacks, + callbacks_functions=self.config.callbacks_on_sample_end, + kwargs=dict( + env_runner=self, + metrics_logger=self.metrics, + samples=samples, + ), + ) + + self._time_after_sampling = time.perf_counter() + + return samples + + def _sample( + self, + *, + num_timesteps: Optional[int] = None, + num_episodes: Optional[int] = None, + explore: bool, + random_actions: bool = False, + force_reset: bool = False, + ) -> List[MultiAgentEpisode]: + + done_episodes_to_return: List[MultiAgentEpisode] = [] + + # Have to reset the env (on all vector sub_envs). + if force_reset or num_episodes is not None or self._needs_initial_reset: + episodes = self._episodes = [None for _ in range(self.num_envs)] + + shared_data = self._shared_data = {} + self._reset_envs(episodes, shared_data, explore) + + # We just reset the env. Don't have to force this again in the next + # call to `self._sample_timesteps()`. + self._needs_initial_reset = False + else: + episodes = self._episodes + shared_data = self._shared_data + + if num_episodes is not None: + self._needs_initial_reset = True + + # Loop through `num_timesteps` timesteps or `num_episodes` episodes. + env_ts = 0 + agent_ts = 0 + eps = 0 + while ( + (eps < num_episodes) + if num_timesteps is None + else ( + env_ts < num_timesteps + if self.config.count_steps_by == "env_steps" + else agent_ts < num_timesteps + ) + ): + # Act randomly. + if random_actions: + to_env = { + Columns.ACTIONS: [ + { + # Only act (randomly) for those agents that had an + # observation. + aid: self.env.envs[i] + .unwrapped.get_action_space(aid) + .sample() + for aid in episodes[i].get_agents_to_act() + } + for i in range(self.num_envs) + ] + } + # Compute an action using the RLModule. + else: + # Env-to-module connector (already cached). + to_module = self._cached_to_module + assert to_module is not None + self._cached_to_module = None + + if to_module: + # MultiRLModule forward pass: Explore or not. + if explore: + # Global env steps sampled are (roughly) this EnvRunner's lifetime + # count times the number of env runners in the algo. + global_env_steps_lifetime = ( + self.metrics.peek(NUM_ENV_STEPS_SAMPLED_LIFETIME, default=0) + + env_ts + ) * (self.config.num_env_runners or 1) + with self.metrics.log_time(RLMODULE_INFERENCE_TIMER): + to_env = self.module.forward_exploration( + to_module, t=global_env_steps_lifetime + ) + else: + with self.metrics.log_time(RLMODULE_INFERENCE_TIMER): + to_env = self.module.forward_inference(to_module) + + # Module-to-env connector. + to_env = self._module_to_env( + rl_module=self.module, + batch=to_env, + episodes=episodes, + explore=explore, + shared_data=shared_data, + metrics=self.metrics, + metrics_prefix_key=(MODULE_TO_ENV_CONNECTOR,), + ) + # In case all environments had been terminated `to_module` will be + # empty and no actions are needed b/c we reset all environemnts. + else: + to_env = {} + shared_data["vector_env_episodes_map"] = {} + + # Extract the (vectorized) actions (to be sent to the env) from the + # module/connector output. Note that these actions are fully ready (e.g. + # already unsquashed/clipped) to be sent to the environment) and might not + # be identical to the actions produced by the RLModule/distribution, which + # are the ones stored permanently in the episode objects. + actions = to_env.pop(Columns.ACTIONS, [{} for _ in episodes]) + actions_for_env = to_env.pop(Columns.ACTIONS_FOR_ENV, actions) + # Try stepping the environment. + results = self._try_env_step(actions_for_env) + if results == ENV_STEP_FAILURE: + return self._sample( + num_timesteps=num_timesteps, + num_episodes=num_episodes, + explore=explore, + random_actions=random_actions, + force_reset=True, + ) + observations, rewards, terminateds, truncateds, infos = results + + call_on_episode_start = set() + # Store the data from the last environment step into the + # episodes for all sub-envrironments. + for env_index in range(self.num_envs): + extra_model_outputs = defaultdict(dict) + # `to_env` returns a dictionary with column keys and + # (AgentID, value) tuple values. + for col, ma_dict_list in to_env.items(): + ma_dict = ma_dict_list[env_index] + for agent_id, val in ma_dict.items(): + extra_model_outputs[agent_id][col] = val + extra_model_outputs[agent_id][ + WEIGHTS_SEQ_NO + ] = self._weights_seq_no + extra_model_outputs = dict(extra_model_outputs) + + # Episode has no data in it yet -> Was just reset and needs to be called + # with its `add_env_reset()` method. + if not self._episodes[env_index].is_reset: + # Add the reset step data to the episode. + episodes[env_index].add_env_reset( + observations=observations[env_index], + infos=infos[env_index], + ) + # Call the callback on episode start so users can hook in. + call_on_episode_start.add(env_index) + + # Call `add_env_step()` method on episode. + else: + episodes[env_index].add_env_step( + observations=observations[env_index], + actions=actions[env_index], + rewards=rewards[env_index], + infos=infos[env_index], + terminateds=terminateds[env_index], + truncateds=truncateds[env_index], + extra_model_outputs=extra_model_outputs, + ) + # Only increase ts when we actually stepped (not reset'd as a reset + # does not count as a timestep). + env_ts += self._increase_sampled_metrics( + 1, observations[env_index], episodes[env_index] + ) + agent_ts += len(observations[env_index]) + + done_episodes_to_run_env_to_module = [] + for env_index in range(self.num_envs): + # Call `on_episode_start()` callback (always after reset). + if env_index in call_on_episode_start: + self._make_on_episode_callback( + "on_episode_start", env_index, episodes + ) + # Make the `on_episode_step` callbacks. + else: + self._make_on_episode_callback( + "on_episode_step", env_index, episodes + ) + + # Episode is done. + if episodes[env_index].is_done: + eps += 1 + + # Make the `on_episode_end` callbacks (before finalizing the episode + # object). + self._make_on_episode_callback( + "on_episode_end", env_index, episodes + ) + + # TODO (simon): Check, if needed. I guess not b/c the complete episode is done. + # This needs to be executed here to remove the `SingleAgentEpisode`s + # that are done. + self._prune_zero_len_sa_episodes(episodes[env_index]) + + done_episodes_to_return.append(episodes[env_index]) + # Run a last time the `env_to_module` pipeline for these episodes + # to postprocess artifacts (e.g. observations to one-hot). + done_episodes_to_run_env_to_module.append(episodes[env_index]) + # Also early-out if we reach the number of episodes within this + # for-loop. + if eps == num_episodes: + break + + old_episode_id = episodes[env_index].id_ + # Create a new episode object with no data in it and execute + # `on_episode_created` callback (before the `env.reset()` call). + self._new_episode(env_index, episodes) + # Register the mapping of new episode ID to old episode ID. + shared_data["vector_env_episodes_map"].update( + {old_episode_id: episodes[env_index].id_} + ) + + # Env-to-module connector pass (cache results as we will do the RLModule + # forward pass only in the next `while`-iteration). + # Note, running the pipeline here ensures that we are not executing a + # pipeline run for agents that have died. This increases performance in + # case of environments in which 1000's of agents exist. Because the + # `VectorMultiAgentEnv` calls `reset()` for any terminated/truncated sub- + # environment `observations` and `infos` will always be returned for the + # `MultiAgentEpisode.add_reset_step`. + if self.module is not None: + if done_episodes_to_run_env_to_module: + # Run the env-to-module connector pipeline for all done episodes. + # Note, this is needed to postprocess last-step data, e.g. if the + # user uses a connector that one-hot encodes observations. + # Note, this pipeline run is not timed as the number of episodes + # can differ from `num_envs_per_env_runner` and would bias time + # measurements. + self._env_to_module( + episodes=done_episodes_to_run_env_to_module, + explore=explore, + rl_module=self.module, + shared_data=shared_data, + metrics=None, + ) + self._cached_to_module = self._env_to_module( + episodes=episodes, + explore=explore, + rl_module=self.module, + shared_data=shared_data, + metrics=self.metrics, + metrics_prefix_key=(ENV_TO_MODULE_CONNECTOR,), + ) + + # Numpy'ize the done episodes after running the connector pipeline. Note, + # that we need simple `list` objects in the + # `AddObservationsFromEpisodesToBatch` connector. Furthermore, we spare + # multiple `if` calls. + if self.config.episodes_to_numpy: + for episode in done_episodes_to_return: + # Any possibly compress observations. + episode.to_numpy() + + # Return done episodes ... + self._done_episodes_for_metrics.extend(done_episodes_to_return) + # ... and all ongoing episode chunks. + + # Also, make sure we start new episode chunks (continuing the ongoing episodes + # from the to-be-returned chunks). + ongoing_episodes_to_return = [] + # Only if we are doing individual timesteps: We have to maybe cut an ongoing + # episode and continue building it on the next call to `sample()`. + if num_timesteps is not None: + ongoing_episodes_continuations = [ + eps.cut(len_lookback_buffer=self.config.episode_lookback_horizon) + for eps in self._episodes + ] + + for eps in self._episodes: + # Just started Episodes do not have to be returned. There is no data + # in them anyway. + if eps.env_t == 0: + continue + eps.validate() + self._ongoing_episodes_for_metrics[eps.id_].append(eps) + + self._prune_zero_len_sa_episodes(eps) + + # Numpy'ize the episode. + if self.config.episodes_to_numpy: + # Any possibly compress observations. + ongoing_episodes_to_return.append(eps.to_numpy()) + # Leave episode as lists of individual (obs, action, etc..) items. + else: + ongoing_episodes_to_return.append(eps) + + # Continue collecting into the cut Episode chunks. + self._episodes = ongoing_episodes_continuations + + # Return collected episode data. + return done_episodes_to_return + ongoing_episodes_to_return + + def _reset_envs(self, episodes, shared_data, explore): + for env_index in range(self.num_envs): + self._new_episode(env_index, episodes) + + # Erase all cached ongoing episodes. This EnvRunner never completes or returns + # these from `get_metrics`, causing a memory leak. + self._ongoing_episodes_for_metrics.clear() + + # Try resetting the environment. + observations, infos = self._try_env_reset( + # Only seed (if seed provided) upon initial reset. + seed=self._seed if self._needs_initial_reset else None, + # TODO (sven): Support options? + options=None, + ) + + # Set the initial obs and infos in the episodes. + for env_index in range(self.num_envs): + episodes[env_index].add_env_reset( + observations=observations[env_index], + infos=infos[env_index], + ) + + # Run the env-to-module connector to make sure the reset-obs/infos have + # properly been processed (if applicable). + self._cached_to_module = None + if self.module: + self._cached_to_module = self._env_to_module( + rl_module=self.module, + episodes=episodes, + explore=explore, + shared_data=shared_data, + metrics=self.metrics, + metrics_key_prefix=(ENV_TO_MODULE_CONNECTOR,), + ) + + # Call `on_episode_start()` callbacks (always after reset). + for env_index in range(self.num_envs): + self._make_on_episode_callback("on_episode_start", env_index, episodes) + + @override(EnvRunner) + def get_spaces(self): + if self.env is None: + return self.spaces + # Return the already agent-to-module translated spaces from our connector + # pipeline. + return { + INPUT_ENV_SPACES: (self.env.observation_space, self.env.action_space), + INPUT_ENV_SINGLE_SPACES: ( + self.env.single_observation_space, + self.env.single_action_space, + ), + **{ + mid: (o, self._env_to_module.action_space[mid]) + for mid, o in self._env_to_module.observation_space.spaces.items() + }, + } + + @override(EnvRunner) + def get_metrics(self) -> ResultDict: + # Compute per-episode metrics (only on already completed episodes). + for eps in self._done_episodes_for_metrics: + assert eps.is_done + episode_length = len(eps) + agent_steps = defaultdict( + int, + {str(aid): len(sa_eps) for aid, sa_eps in eps.agent_episodes.items()}, + ) + episode_return = eps.get_return() + episode_duration_s = eps.get_duration_s() + + agent_episode_returns = defaultdict( + float, + { + str(sa_eps.agent_id): sa_eps.get_return() + for sa_eps in eps.agent_episodes.values() + }, + ) + module_episode_returns = defaultdict( + float, + { + sa_eps.module_id: sa_eps.get_return() + for sa_eps in eps.agent_episodes.values() + }, + ) + + # Don't forget about the already returned chunks of this episode. + if eps.id_ in self._ongoing_episodes_for_metrics: + for eps2 in self._ongoing_episodes_for_metrics[eps.id_]: + return_eps2 = eps2.get_return() + episode_length += len(eps2) + episode_return += return_eps2 + episode_duration_s += eps2.get_duration_s() + + for sa_eps in eps2.agent_episodes.values(): + return_sa = sa_eps.get_return() + agent_steps[str(sa_eps.agent_id)] += len(sa_eps) + agent_episode_returns[str(sa_eps.agent_id)] += return_sa + module_episode_returns[sa_eps.module_id] += return_sa + + del self._ongoing_episodes_for_metrics[eps.id_] + + self._log_episode_metrics( + episode_length, + episode_return, + episode_duration_s, + agent_episode_returns, + module_episode_returns, + dict(agent_steps), + ) + + # Now that we have logged everything, clear cache of done episodes. + self._done_episodes_for_metrics.clear() + + # Return reduced metrics. + return self.metrics.reduce() + + @override(Checkpointable) + def get_state( + self, + components: Optional[Union[str, Collection[str]]] = None, + *, + not_components: Optional[Union[str, Collection[str]]] = None, + **kwargs, + ) -> StateDict: + # Basic state dict. + state = { + NUM_ENV_STEPS_SAMPLED_LIFETIME: ( + self.metrics.peek(NUM_ENV_STEPS_SAMPLED_LIFETIME, default=0) + ), + } + + # RLModule (MultiRLModule) component. + if self._check_component(COMPONENT_RL_MODULE, components, not_components): + state[COMPONENT_RL_MODULE] = self.module.get_state( + components=self._get_subcomponents(COMPONENT_RL_MODULE, components), + not_components=self._get_subcomponents( + COMPONENT_RL_MODULE, not_components + ), + **kwargs, + ) + state[WEIGHTS_SEQ_NO] = self._weights_seq_no + + # Env-to-module connector. + if self._check_component( + COMPONENT_ENV_TO_MODULE_CONNECTOR, components, not_components + ): + state[COMPONENT_ENV_TO_MODULE_CONNECTOR] = self._env_to_module.get_state() + # Module-to-env connector. + if self._check_component( + COMPONENT_MODULE_TO_ENV_CONNECTOR, components, not_components + ): + state[COMPONENT_MODULE_TO_ENV_CONNECTOR] = self._module_to_env.get_state() + + return state + + @override(Checkpointable) + def set_state(self, state: StateDict) -> None: + if COMPONENT_ENV_TO_MODULE_CONNECTOR in state: + self._env_to_module.set_state(state[COMPONENT_ENV_TO_MODULE_CONNECTOR]) + if COMPONENT_MODULE_TO_ENV_CONNECTOR in state: + self._module_to_env.set_state(state[COMPONENT_MODULE_TO_ENV_CONNECTOR]) + + # Update RLModule state. + if COMPONENT_RL_MODULE in state: + # A missing value for WEIGHTS_SEQ_NO or a value of 0 means: Force the + # update. + weights_seq_no = state.get(WEIGHTS_SEQ_NO, 0) + + # Only update the weigths, if this is the first synchronization or + # if the weights of this `EnvRunner` lacks behind the actual ones. + if weights_seq_no == 0 or self._weights_seq_no < weights_seq_no: + rl_module_state = state[COMPONENT_RL_MODULE] + if isinstance(rl_module_state, ray.ObjectRef): + rl_module_state = ray.get(rl_module_state) + self.module.set_state(rl_module_state) + + # Update weights_seq_no, if the new one is > 0. + if weights_seq_no > 0: + self._weights_seq_no = weights_seq_no + + # Update lifetime counters. + if NUM_ENV_STEPS_SAMPLED_LIFETIME in state: + self.metrics.set_value( + key=NUM_ENV_STEPS_SAMPLED_LIFETIME, + value=state[NUM_ENV_STEPS_SAMPLED_LIFETIME], + reduce="sum", + with_throughput=True, + ) + + @override(Checkpointable) + def get_ctor_args_and_kwargs(self): + return ( + (), # *args + {"config": self.config}, # **kwargs + ) + + @override(Checkpointable) + def get_metadata(self): + metadata = Checkpointable.get_metadata(self) + metadata.update( + { + # TODO (sven): Maybe add serialized (JSON-writable) config here? + } + ) + return metadata + + @override(Checkpointable) + def get_checkpointable_components(self): + return [ + (COMPONENT_RL_MODULE, self.module), + (COMPONENT_ENV_TO_MODULE_CONNECTOR, self._env_to_module), + (COMPONENT_MODULE_TO_ENV_CONNECTOR, self._module_to_env), + ] + + @override(EnvRunner) + def assert_healthy(self): + """Checks that self.__init__() has been completed properly. + + Ensures that the instances has a `MultiRLModule` and an + environment defined. + + Raises: + AssertionError: If the EnvRunner Actor has NOT been properly initialized. + """ + # Make sure, we have built our gym.vector.Env and RLModule properly. + assert self.env and self.module + + @override(EnvRunner) + def make_env(self): + # If an env already exists, try closing it first (to allow it to properly + # cleanup). + if self.env is not None: + try: + self.env.close() + except Exception as e: + logger.warning( + "Tried closing the existing env (multi-agent), but failed with " + f"error: {e.args[0]}" + ) + del self.env + + env_ctx = self.config.env_config + if not isinstance(env_ctx, EnvContext): + env_ctx = EnvContext( + env_ctx, + worker_index=self.worker_index, + num_workers=self.config.num_env_runners, + remote=self.config.remote_worker_envs, + ) + + # No env provided -> Error. + if not self.config.env: + raise ValueError( + "`config.env` is not provided! You should provide a valid environment " + "to your config through `config.environment([env descriptor e.g. " + "'CartPole-v1'])`." + ) + # Register env for the local context. + # Note, `gym.register` has to be called on each worker. + elif isinstance(self.config.env, str) and _global_registry.contains( + ENV_CREATOR, self.config.env + ): + entry_point = partial( + _global_registry.get(ENV_CREATOR, self.config.env), + env_ctx, + ) + else: + entry_point = partial( + _gym_env_creator, + env_descriptor=self.config.env, + env_context=env_ctx, + ) + gym.register( + "rllib-multi-agent-env-v0", + entry_point=entry_point, + disable_env_checker=True, + ) + vectorize_mode = self.config.gym_env_vectorize_mode + + # Perform actual gym.make call. + self.env = make_vec( + "rllib-multi-agent-env-v0", + num_envs=self.config.num_envs_per_env_runner, + vectorization_mode=( + vectorize_mode + if isinstance(vectorize_mode, gym.envs.registration.VectorizeMode) + else gym.envs.registration.VectorizeMode(vectorize_mode.lower()) + ), + ) + self.num_envs: int = self.env.num_envs + assert self.num_envs == self.config.num_envs_per_env_runner + # self.env: MultiAgentEnv = gym.make("rllib-multi-agent-env-v0") + # self.num_envs = 1 + # If required, check the created MultiAgentEnv instances. + if not self.config.disable_env_checking: + try: + for env in self.env.envs: + check_multiagent_environments(env.unwrapped) + except Exception as e: + logger.exception(e.args[0]) + # If not required, still check the type (must be `VectorMultiAgentEnv``). + else: + try: + assert isinstance(self.env, VectorMultiAgentEnv) + assert isinstance(self.env.envs[0].unwrapped, MultiAgentEnv) + except AssertionError: + logger.exception( + "When using the `MultiAgentEnvRunner`, the environment must " + f"inherit from `ray.rllib.env.vector.vector_multi_agent_env." + f"VectorMultiAgentEnv` (but yours is {self.env}) and the individual" + " envs must inherit from `MultiAgentEnv` (but yours is " + f"{self.env.envs[0].unwrapped})!" + ) + except TypeError: + logger.exception( + "When using the `MultiAgentEnvRunner`, the env must " + "have a subscriptable `self.envs` attribute!" + ) + + # Set the flag to reset all envs upon the next `sample()` call. + self._needs_initial_reset = True + + # Call the `on_environment_created` callback. + make_callback( + "on_environment_created", + callbacks_objects=self._callbacks, + callbacks_functions=self.config.callbacks_on_environment_created, + kwargs=dict( + env_runner=self, + metrics_logger=self.metrics, + env=self.env.unwrapped, + env_context=env_ctx, + ), + ) + + @override(EnvRunner) + def make_module(self): + env = self.env.unwrapped if self.env is not None else None + try: + module_spec: MultiRLModuleSpec = self.config.get_multi_rl_module_spec( + env=env, spaces=self.get_spaces(), inference_only=True + ) + # Build the module from its spec. + self.module = module_spec.build() + # Move the RLModule to our device. + # TODO (sven): In order to make this framework-agnostic, we should maybe + # make the MultiRLModule.build() method accept a device OR create an + # additional `(Multi)RLModule.to()` override. + if torch: + self.module.foreach_module( + lambda mid, mod: ( + mod.to(self._device) + if isinstance(mod, torch.nn.Module) + else mod + ) + ) + + # If `AlgorithmConfig.get_rl_module_spec()` is not implemented, this env runner + # will not have an RLModule, but might still be usable with random actions. + except NotImplementedError: + self.module = None + + @override(EnvRunner) + def stop(self): + # Note, `MultiAgentEnv` inherits `close()`-method from `gym.Env`. + if self.env is not None: + self.env.close() + + def _setup_metrics(self): + self._done_episodes_for_metrics: List[MultiAgentEpisode] = [] + self._ongoing_episodes_for_metrics: DefaultDict[ + EpisodeID, List[MultiAgentEpisode] + ] = defaultdict(list) + + def _new_episode(self, env_index, episodes=None): + episodes = episodes if episodes is not None else self._episodes + episodes[env_index] = MultiAgentEpisode( + observation_space={ + aid: self.env.envs[env_index].unwrapped.get_observation_space(aid) + for aid in self.env.envs[env_index].unwrapped.possible_agents + }, + action_space={ + aid: self.env.envs[env_index].unwrapped.get_action_space(aid) + for aid in self.env.envs[env_index].unwrapped.possible_agents + }, + agent_to_module_mapping_fn=self.config.policy_mapping_fn, + ) + self._make_on_episode_callback("on_episode_created", env_index, episodes) + + def _make_on_episode_callback( + self, which: str, idx: int, episodes: List[MultiAgentEpisode] + ): + kwargs = dict( + episode=episodes[idx], + env_runner=self, + metrics_logger=self.metrics, + env=self.env.unwrapped, + rl_module=self.module, + env_index=idx, + ) + if which == "on_episode_end": + kwargs["prev_episode_chunks"] = self._ongoing_episodes_for_metrics[ + episodes[idx].id_ + ] + + make_callback( + which, + callbacks_objects=self._callbacks, + callbacks_functions=getattr(self.config, f"callbacks_{which}"), + kwargs=kwargs, + ) + + def _increase_sampled_metrics(self, num_steps, next_obs, episode): + # Env steps. + self.metrics.log_value( + NUM_ENV_STEPS_SAMPLED, num_steps, reduce="sum", clear_on_reduce=True + ) + self.metrics.log_value( + NUM_ENV_STEPS_SAMPLED_LIFETIME, + num_steps, + reduce="sum", + with_throughput=True, + ) + # Completed episodes. + if episode.is_done: + self.metrics.log_value(NUM_EPISODES, 1, reduce="sum", clear_on_reduce=True) + self.metrics.log_value(NUM_EPISODES_LIFETIME, 1, reduce="sum") + + # Record agent and module metrics. + for aid in next_obs: + self.metrics.log_value( + (NUM_AGENT_STEPS_SAMPLED, str(aid)), + 1, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_AGENT_STEPS_SAMPLED_LIFETIME, str(aid)), + 1, + reduce="sum", + ) + self.metrics.log_value( + (NUM_MODULE_STEPS_SAMPLED, episode.module_for(aid)), + 1, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_MODULE_STEPS_SAMPLED_LIFETIME, episode.module_for(aid)), + 1, + reduce="sum", + ) + return num_steps + + def _log_episode_metrics( + self, + length, + ret, + sec, + agents=None, + modules=None, + agent_steps=None, + ): + # Log general episode metrics. + + # Use the configured window, but factor in the parallelism of the EnvRunners. + # As a result, we only log the last `window / num_env_runners` steps here, + # b/c everything gets parallel-merged in the Algorithm process. + win = max( + 1, + int( + math.ceil( + self.config.metrics_num_episodes_for_smoothing + / (self.config.num_env_runners or 1) + ) + ), + ) + + self.metrics.log_dict( + { + EPISODE_LEN_MEAN: length, + EPISODE_RETURN_MEAN: ret, + EPISODE_DURATION_SEC_MEAN: sec, + **( + { + # Per-agent returns. + "agent_episode_returns_mean": agents, + # Per-RLModule returns. + "module_episode_returns_mean": modules, + "agent_steps": agent_steps, + } + if agents is not None + else {} + ), + }, + window=win, + ) + # For some metrics, log min/max as well. + self.metrics.log_dict( + { + EPISODE_LEN_MIN: length, + EPISODE_RETURN_MIN: ret, + }, + reduce="min", + window=win, + ) + self.metrics.log_dict( + { + EPISODE_LEN_MAX: length, + EPISODE_RETURN_MAX: ret, + }, + reduce="max", + window=win, + ) + + @staticmethod + def _prune_zero_len_sa_episodes(episode: MultiAgentEpisode): + for agent_id, agent_eps in episode.agent_episodes.copy().items(): + if not agent_eps: + del episode.agent_episodes[agent_id] + + @Deprecated( + new="MultiAgentEnvRunner.get_state(components='rl_module')", + error=False, + ) + def get_weights(self, modules=None): + rl_module_state = self.get_state(components=COMPONENT_RL_MODULE)[ + COMPONENT_RL_MODULE + ] + return rl_module_state + + @Deprecated(new="MultiAgentEnvRunner.set_state()", error=False) + def set_weights( + self, + weights: ModelWeights, + global_vars: Optional[Dict] = None, + weights_seq_no: int = 0, + ) -> None: + assert global_vars is None + return self.set_state( + { + COMPONENT_RL_MODULE: weights, + WEIGHTS_SEQ_NO: weights_seq_no, + } + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/multi_agent_episode.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/multi_agent_episode.py new file mode 100644 index 0000000000000000000000000000000000000000..76b078ef69ff620f669fcaac84fa6e1cd956628d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/multi_agent_episode.py @@ -0,0 +1,2575 @@ +from collections import defaultdict +import copy +import time +from typing import ( + Any, + Callable, + Collection, + DefaultDict, + Dict, + List, + Optional, + Set, + Union, +) +import uuid + +import gymnasium as gym + +from ray.rllib.env.single_agent_episode import SingleAgentEpisode +from ray.rllib.env.utils.infinite_lookback_buffer import InfiniteLookbackBuffer +from ray.rllib.policy.sample_batch import MultiAgentBatch +from ray.rllib.utils import force_list +from ray.rllib.utils.deprecation import Deprecated +from ray.rllib.utils.error import MultiAgentEnvError +from ray.rllib.utils.spaces.space_utils import batch +from ray.rllib.utils.typing import AgentID, ModuleID, MultiAgentDict +from ray.util.annotations import PublicAPI + + +# TODO (simon): Include cases in which the number of agents in an +# episode are shrinking or growing during the episode itself. +@PublicAPI(stability="alpha") +class MultiAgentEpisode: + """Stores multi-agent episode data. + + The central attribute of the class is the timestep mapping + `self.env_t_to_agent_t` that maps AgentIDs to their specific environment steps to + the agent's own scale/timesteps. + + Each AgentID in the `MultiAgentEpisode` has its own `SingleAgentEpisode` object + in which this agent's data is stored. Together with the env_t_to_agent_t mapping, + we can extract information either on any individual agent's time scale or from + the (global) multi-agent environment time scale. + + Extraction of data from a MultiAgentEpisode happens via the getter APIs, e.g. + `get_observations()`, which work analogous to the ones implemented in the + `SingleAgentEpisode` class. + + Note that recorded `terminateds`/`truncateds` come as simple + `MultiAgentDict`s mapping AgentID to bools and thus have no assignment to a + certain timestep (analogous to a SingleAgentEpisode's single `terminated/truncated` + boolean flag). Instead we assign it to the last observation recorded. + Theoretically, there could occur edge cases in some environments + where an agent receives partial rewards and then terminates without + a last observation. In these cases, we duplicate the last observation. + + Also, if no initial observation has been received yet for an agent, but + some rewards for this same agent already occurred, we delete the agent's data + up to here, b/c there is nothing to learn from these "premature" rewards. + """ + + __slots__ = ( + "id_", + "agent_to_module_mapping_fn", + "_agent_to_module_mapping", + "observation_space", + "action_space", + "env_t_started", + "env_t", + "agent_t_started", + "env_t_to_agent_t", + "_hanging_actions_end", + "_hanging_extra_model_outputs_end", + "_hanging_rewards_end", + "_hanging_rewards_begin", + "is_terminated", + "is_truncated", + "agent_episodes", + "_last_step_time", + "_len_lookback_buffers", + "_start_time", + "_custom_data", + ) + + SKIP_ENV_TS_TAG = "S" + + def __init__( + self, + id_: Optional[str] = None, + *, + observations: Optional[List[MultiAgentDict]] = None, + observation_space: Optional[gym.Space] = None, + infos: Optional[List[MultiAgentDict]] = None, + actions: Optional[List[MultiAgentDict]] = None, + action_space: Optional[gym.Space] = None, + rewards: Optional[List[MultiAgentDict]] = None, + terminateds: Union[MultiAgentDict, bool] = False, + truncateds: Union[MultiAgentDict, bool] = False, + extra_model_outputs: Optional[List[MultiAgentDict]] = None, + env_t_started: Optional[int] = None, + agent_t_started: Optional[Dict[AgentID, int]] = None, + len_lookback_buffer: Union[int, str] = "auto", + agent_episode_ids: Optional[Dict[AgentID, str]] = None, + agent_module_ids: Optional[Dict[AgentID, ModuleID]] = None, + agent_to_module_mapping_fn: Optional[ + Callable[[AgentID, "MultiAgentEpisode"], ModuleID] + ] = None, + ): + """Initializes a `MultiAgentEpisode`. + + Args: + id_: Optional. Either a string to identify an episode or None. + If None, a hexadecimal id is created. In case of providing + a string, make sure that it is unique, as episodes get + concatenated via this string. + observations: A list of dictionaries mapping agent IDs to observations. + Can be None. If provided, should match all other episode data + (actions, rewards, etc.) in terms of list lengths and agent IDs. + observation_space: An optional gym.spaces.Dict mapping agent IDs to + individual agents' spaces, which all (individual agents') observations + should abide to. If not None and this MultiAgentEpisode is numpy'ized + (via the `self.to_numpy()` method), and data is appended or set, the new + data will be checked for correctness. + infos: A list of dictionaries mapping agent IDs to info dicts. + Can be None. If provided, should match all other episode data + (observations, rewards, etc.) in terms of list lengths and agent IDs. + actions: A list of dictionaries mapping agent IDs to actions. + Can be None. If provided, should match all other episode data + (observations, rewards, etc.) in terms of list lengths and agent IDs. + action_space: An optional gym.spaces.Dict mapping agent IDs to + individual agents' spaces, which all (individual agents') actions + should abide to. If not None and this MultiAgentEpisode is numpy'ized + (via the `self.to_numpy()` method), and data is appended or set, the new + data will be checked for correctness. + rewards: A list of dictionaries mapping agent IDs to rewards. + Can be None. If provided, should match all other episode data + (actions, rewards, etc.) in terms of list lengths and agent IDs. + terminateds: A boolean defining if an environment has + terminated OR a MultiAgentDict mapping individual agent ids + to boolean flags indicating whether individual agents have terminated. + A special __all__ key in these dicts indicates, whether the episode + is terminated for all agents. + The default is `False`, i.e. the episode has not been terminated. + truncateds: A boolean defining if the environment has been + truncated OR a MultiAgentDict mapping individual agent ids + to boolean flags indicating whether individual agents have been + truncated. A special __all__ key in these dicts indicates, whether the + episode is truncated for all agents. + The default is `False`, i.e. the episode has not been truncated. + extra_model_outputs: A list of dictionaries mapping agent IDs to their + corresponding extra model outputs. Each of these "outputs" is a dict + mapping keys (str) to model output values, for example for + `key=STATE_OUT`, the values would be the internal state outputs for + that agent. + env_t_started: The env timestep (int) that defines the starting point + of the episode. This is only larger zero, if an already ongoing episode + chunk is being created, for example by slicing an ongoing episode or + by calling the `cut()` method on an ongoing episode. + agent_t_started: A dict mapping AgentIDs to the respective agent's (local) + timestep at which its SingleAgentEpisode chunk started. + len_lookback_buffer: The size of the lookback buffers to keep in + front of this Episode for each type of data (observations, actions, + etc..). If larger 0, will interpret the first `len_lookback_buffer` + items in each type of data as NOT part of this actual + episode chunk, but instead serve as "historical" record that may be + viewed and used to derive new data from. For example, it might be + necessary to have a lookback buffer of four if you would like to do + observation frame stacking and your episode has been cut and you are now + operating on a new chunk (continuing from the cut one). Then, for the + first 3 items, you would have to be able to look back into the old + chunk's data. + If `len_lookback_buffer` is "auto" (default), will interpret all + provided data in the constructor as part of the lookback buffers. + agent_episode_ids: An optional dict mapping AgentIDs + to their corresponding `SingleAgentEpisode`. If None, each + `SingleAgentEpisode` in `MultiAgentEpisode.agent_episodes` + will generate a hexadecimal code. If a dictionary is provided, + make sure that IDs are unique, because the agents' `SingleAgentEpisode` + instances are concatenated or recreated by it. + agent_module_ids: An optional dict mapping AgentIDs to their respective + ModuleIDs (these mapping are always valid for an entire episode and + thus won't change during the course of this episode). If a mapping from + agent to module has already been provided via this dict, the (optional) + `agent_to_module_mapping_fn` will NOT be used again to map the same + agent (agents do not change their assigned module in the course of + one episode). + agent_to_module_mapping_fn: A callable taking an AgentID and a + MultiAgentEpisode as args and returning a ModuleID. Used to map agents + that have not been mapped yet (because they just entered this episode) + to a ModuleID. The resulting ModuleID is only stored inside the agent's + SingleAgentEpisode object. + """ + self.id_: str = id_ or uuid.uuid4().hex + if agent_to_module_mapping_fn is None: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + + agent_to_module_mapping_fn = ( + AlgorithmConfig.DEFAULT_AGENT_TO_MODULE_MAPPING_FN + ) + self.agent_to_module_mapping_fn = agent_to_module_mapping_fn + # In case a user - e.g. via callbacks - already forces a mapping to happen + # via the `module_for()` API even before the agent has entered the episode + # (and has its SingleAgentEpisode created), we store all aldeary done mappings + # in this dict here. + self._agent_to_module_mapping: Dict[AgentID, ModuleID] = agent_module_ids or {} + + # Lookback buffer length is not provided. Interpret all provided data as + # lookback buffer. + if len_lookback_buffer == "auto": + len_lookback_buffer = len(rewards or []) + self._len_lookback_buffers = len_lookback_buffer + + self.observation_space = observation_space or {} + self.action_space = action_space or {} + + terminateds = terminateds or {} + truncateds = truncateds or {} + + # The global last timestep of the episode and the timesteps when this chunk + # started (excluding a possible lookback buffer). + self.env_t_started = env_t_started or 0 + self.env_t = ( + (len(rewards) if rewards is not None else 0) + - self._len_lookback_buffers + + self.env_t_started + ) + self.agent_t_started = defaultdict(int, agent_t_started or {}) + + # Keeps track of the correspondence between agent steps and environment steps. + # Under each AgentID as key is a InfiniteLookbackBuffer with the following + # data in it: + # The indices of the items in the data represent environment timesteps, + # starting from index=0 for the `env.reset()` and with each `env.step()` call + # increase by 1. + # The values behind these (env timestep) indices represent the agent timesteps + # happening at these env timesteps and the special value of + # `self.SKIP_ENV_TS_TAG` means that the agent did NOT step at the given env + # timestep. + # Thus, agents that are part of the reset obs, will start their mapping data + # with a [0 ...], all other agents will start their mapping data with: + # [self.SKIP_ENV_TS_TAG, ...]. + self.env_t_to_agent_t: DefaultDict[ + AgentID, InfiniteLookbackBuffer + ] = defaultdict(InfiniteLookbackBuffer) + + # Create caches for hanging actions/rewards/extra_model_outputs. + # When an agent gets an observation (and then sends an action), but does not + # receive immediately a next observation, we store the "hanging" action (and + # related rewards and extra model outputs) in the caches postfixed w/ `_end` + # until the next observation is received. + self._hanging_actions_end = {} + self._hanging_extra_model_outputs_end = defaultdict(dict) + self._hanging_rewards_end = defaultdict(float) + + # In case of a `cut()` or `slice()`, we also need to store the hanging actions, + # rewards, and extra model outputs that were already "hanging" in preceeding + # episode slice. + self._hanging_rewards_begin = defaultdict(float) + + # If this is an ongoing episode than the last `__all__` should be `False` + self.is_terminated: bool = ( + terminateds + if isinstance(terminateds, bool) + else terminateds.get("__all__", False) + ) + + # If this is an ongoing episode than the last `__all__` should be `False` + self.is_truncated: bool = ( + truncateds + if isinstance(truncateds, bool) + else truncateds.get("__all__", False) + ) + + # The individual agent SingleAgentEpisode objects. + self.agent_episodes: Dict[AgentID, SingleAgentEpisode] = {} + self._init_single_agent_episodes( + agent_module_ids=agent_module_ids, + agent_episode_ids=agent_episode_ids, + observations=observations, + infos=infos, + actions=actions, + rewards=rewards, + terminateds=terminateds, + truncateds=truncateds, + extra_model_outputs=extra_model_outputs, + ) + + # Cache for custom data. May be used to store custom metrics from within a + # callback for the ongoing episode (e.g. render images). + self._custom_data = {} + + # Keep timer stats on deltas between steps. + self._start_time = None + self._last_step_time = None + + # Validate ourselves. + self.validate() + + def add_env_reset( + self, + *, + observations: MultiAgentDict, + infos: Optional[MultiAgentDict] = None, + ) -> None: + """Stores initial observation. + + Args: + observations: A dictionary mapping agent IDs to initial observations. + Note that some agents may not have an initial observation. + infos: A dictionary mapping agent IDs to initial info dicts. + Note that some agents may not have an initial info dict. If not None, + the agent IDs in `infos` must be a subset of those in `observations` + meaning it would not be allowed to have an agent with an info dict, + but not with an observation. + """ + assert not self.is_done + # Assume that this episode is completely empty and has not stepped yet. + # Leave self.env_t (and self.env_t_started) at 0. + assert self.env_t == self.env_t_started == 0 + infos = infos or {} + + # Note, all agents will have an initial observation, some may have an initial + # info dict as well. + for agent_id, agent_obs in observations.items(): + # Update env_t_to_agent_t mapping (all agents that are part of the reset + # obs have their first mapping 0 (env_t) -> 0 (agent_t)). + self.env_t_to_agent_t[agent_id].append(0) + # Create SingleAgentEpisode, if necessary. + if agent_id not in self.agent_episodes: + self.agent_episodes[agent_id] = SingleAgentEpisode( + agent_id=agent_id, + module_id=self.module_for(agent_id), + multi_agent_episode_id=self.id_, + observation_space=self.observation_space.get(agent_id), + action_space=self.action_space.get(agent_id), + ) + # Add initial observations (and infos) to the agent's episode. + self.agent_episodes[agent_id].add_env_reset( + observation=agent_obs, + infos=infos.get(agent_id), + ) + + # Validate our data. + self.validate() + + # Start the timer for this episode. + self._start_time = time.perf_counter() + + def add_env_step( + self, + observations: MultiAgentDict, + actions: MultiAgentDict, + rewards: MultiAgentDict, + infos: Optional[MultiAgentDict] = None, + *, + terminateds: Optional[MultiAgentDict] = None, + truncateds: Optional[MultiAgentDict] = None, + extra_model_outputs: Optional[MultiAgentDict] = None, + ) -> None: + """Adds a timestep to the episode. + + Args: + observations: A dictionary mapping agent IDs to their corresponding + next observations. Note that some agents may not have stepped at this + timestep. + actions: Mandatory. A dictionary mapping agent IDs to their + corresponding actions. Note that some agents may not have stepped at + this timestep. + rewards: Mandatory. A dictionary mapping agent IDs to their + corresponding observations. Note that some agents may not have stepped + at this timestep. + infos: A dictionary mapping agent IDs to their + corresponding info. Note that some agents may not have stepped at this + timestep. + terminateds: A dictionary mapping agent IDs to their `terminated` flags, + indicating, whether the environment has been terminated for them. + A special `__all__` key indicates that the episode is terminated for + all agent IDs. + terminateds: A dictionary mapping agent IDs to their `truncated` flags, + indicating, whether the environment has been truncated for them. + A special `__all__` key indicates that the episode is `truncated` for + all agent IDs. + extra_model_outputs: A dictionary mapping agent IDs to their + corresponding specific model outputs (also in a dictionary; e.g. + `vf_preds` for PPO). + """ + # Cannot add data to an already done episode. + if self.is_done: + raise MultiAgentEnvError( + "Cannot call `add_env_step` on a MultiAgentEpisode that is already " + "done!" + ) + + infos = infos or {} + terminateds = terminateds or {} + truncateds = truncateds or {} + extra_model_outputs = extra_model_outputs or {} + + # Increase (global) env step by one. + self.env_t += 1 + + # Find out, whether this episode is terminated/truncated (for all agents). + # Case 1: all agents are terminated or all are truncated. + self.is_terminated = terminateds.get("__all__", False) + self.is_truncated = truncateds.get("__all__", False) + # Find all agents that were done at prior timesteps and add the agents that are + # done at the present timestep. + agents_done = set( + [aid for aid, sa_eps in self.agent_episodes.items() if sa_eps.is_done] + + [aid for aid in terminateds if terminateds[aid]] + + [aid for aid in truncateds if truncateds[aid]] + ) + # Case 2: Some agents are truncated and the others are terminated -> Declare + # this episode as terminated. + if all(aid in set(agents_done) for aid in self.agent_ids): + self.is_terminated = True + + # For all agents that are not stepping in this env step, but that are not done + # yet -> Add a skip tag to their env- to agent-step mappings. + stepped_agent_ids = set(observations.keys()) + for agent_id, env_t_to_agent_t in self.env_t_to_agent_t.items(): + if agent_id not in stepped_agent_ids: + env_t_to_agent_t.append(self.SKIP_ENV_TS_TAG) + + # Loop through all agent IDs that we received data for in this step: + # Those found in observations, actions, and rewards. + agent_ids_with_data = ( + set(observations.keys()) + | set(actions.keys()) + | set(rewards.keys()) + | set(terminateds.keys()) + | set(truncateds.keys()) + | set( + self.agent_episodes.keys() + if terminateds.get("__all__") or truncateds.get("__all__") + else set() + ) + ) - {"__all__"} + for agent_id in agent_ids_with_data: + if agent_id not in self.agent_episodes: + sa_episode = SingleAgentEpisode( + agent_id=agent_id, + module_id=self.module_for(agent_id), + multi_agent_episode_id=self.id_, + observation_space=self.observation_space.get(agent_id), + action_space=self.action_space.get(agent_id), + ) + else: + sa_episode = self.agent_episodes[agent_id] + + # Collect value to be passed (at end of for-loop) into `add_env_step()` + # call. + _observation = observations.get(agent_id) + _action = actions.get(agent_id) + _reward = rewards.get(agent_id) + _infos = infos.get(agent_id) + _terminated = terminateds.get(agent_id, False) or self.is_terminated + _truncated = truncateds.get(agent_id, False) or self.is_truncated + _extra_model_outputs = extra_model_outputs.get(agent_id) + + # The value to place into the env- to agent-step map for this agent ID. + # _agent_step = self.SKIP_ENV_TS_TAG + + # Agents, whose SingleAgentEpisode had already been done before this + # step should NOT have received any data in this step. + if sa_episode.is_done and any( + v is not None + for v in [_observation, _action, _reward, _infos, _extra_model_outputs] + ): + raise MultiAgentEnvError( + f"Agent {agent_id} already had its `SingleAgentEpisode.is_done` " + f"set to True, but still received data in a following step! " + f"obs={_observation} act={_action} rew={_reward} info={_infos} " + f"extra_model_outputs={_extra_model_outputs}." + ) + _reward = _reward or 0.0 + + # CASE 1: A complete agent step is available (in one env step). + # ------------------------------------------------------------- + # We have an observation and an action for this agent -> + # Add the agent step to the single agent episode. + # ... action -> next obs + reward ... + if _observation is not None and _action is not None: + if agent_id not in rewards: + raise MultiAgentEnvError( + f"Agent {agent_id} acted (and received next obs), but did NOT " + f"receive any reward from the env!" + ) + + # CASE 2: Step gets completed with a hanging action OR first observation. + # ------------------------------------------------------------------------ + # We have an observation, but no action -> + # a) Action (and extra model outputs) must be hanging already. Also use + # collected hanging rewards and extra_model_outputs. + # b) The observation is the first observation for this agent ID. + elif _observation is not None and _action is None: + _action = self._hanging_actions_end.pop(agent_id, None) + + # We have a hanging action (the agent had acted after the previous + # observation, but the env had not responded - until now - with another + # observation). + # ...[hanging action] ... ... -> next obs + (reward)? ... + if _action is not None: + # Get the extra model output if available. + _extra_model_outputs = self._hanging_extra_model_outputs_end.pop( + agent_id, None + ) + _reward = self._hanging_rewards_end.pop(agent_id, 0.0) + _reward + # First observation for this agent, we have no hanging action. + # ... [done]? ... -> [1st obs for agent ID] + else: + # The agent is already done -> The agent thus has never stepped once + # and we do not have to create a SingleAgentEpisode for it. + if _terminated or _truncated: + self._del_hanging(agent_id) + continue + # This must be the agent's initial observation. + else: + # Prepend n skip tags to this agent's mapping + the initial [0]. + assert agent_id not in self.env_t_to_agent_t + self.env_t_to_agent_t[agent_id].extend( + [self.SKIP_ENV_TS_TAG] * self.env_t + [0] + ) + self.env_t_to_agent_t[ + agent_id + ].lookback = self._len_lookback_buffers + # Make `add_env_reset` call and continue with next agent. + sa_episode.add_env_reset(observation=_observation, infos=_infos) + # Add possible reward to begin cache. + self._hanging_rewards_begin[agent_id] += _reward + # Now that the SAEps is valid, add it to our dict. + self.agent_episodes[agent_id] = sa_episode + continue + + # CASE 3: Step is started (by an action), but not completed (no next obs). + # ------------------------------------------------------------------------ + # We have no observation, but we have a hanging action (used when we receive + # the next obs for this agent in the future). + elif agent_id not in observations and agent_id in actions: + # Agent got truncated -> Error b/c we would need a last (truncation) + # observation for this (otherwise, e.g. bootstrapping would not work). + # [previous obs] [action] (hanging) ... ... [truncated] + if _truncated: + raise MultiAgentEnvError( + f"Agent {agent_id} acted and then got truncated, but did NOT " + "receive a last (truncation) observation, required for e.g. " + "value function bootstrapping!" + ) + # Agent got terminated. + # [previous obs] [action] (hanging) ... ... [terminated] + elif _terminated: + # If the agent was terminated and no observation is provided, + # duplicate the previous one (this is a technical "fix" to properly + # complete the single agent episode; this last observation is never + # used for learning anyway). + _observation = sa_episode._last_added_observation + _infos = sa_episode._last_added_infos + # Agent is still alive. + # [previous obs] [action] (hanging) ... + else: + # Hanging action, reward, and extra_model_outputs. + assert agent_id not in self._hanging_actions_end + self._hanging_actions_end[agent_id] = _action + self._hanging_rewards_end[agent_id] = _reward + self._hanging_extra_model_outputs_end[ + agent_id + ] = _extra_model_outputs + + # CASE 4: Step has started in the past and is still ongoing (no observation, + # no action). + # -------------------------------------------------------------------------- + # Record reward and terminated/truncated flags. + else: + _action = self._hanging_actions_end.get(agent_id) + + # Agent is done. + if _terminated or _truncated: + # If the agent has NOT stepped, we treat it as not being + # part of this episode. + # ... ... [other agents doing stuff] ... ... [agent done] + if _action is None: + self._del_hanging(agent_id) + continue + + # Agent got truncated -> Error b/c we would need a last (truncation) + # observation for this (otherwise, e.g. bootstrapping would not + # work). + if _truncated: + raise MultiAgentEnvError( + f"Agent {agent_id} acted and then got truncated, but did " + "NOT receive a last (truncation) observation, required " + "for e.g. value function bootstrapping!" + ) + + # [obs] ... ... [hanging action] ... ... [done] + # If the agent was terminated and no observation is provided, + # duplicate the previous one (this is a technical "fix" to properly + # complete the single agent episode; this last observation is never + # used for learning anyway). + _observation = sa_episode._last_added_observation + _infos = sa_episode._last_added_infos + # `_action` is already `get` above. We don't need to pop out from + # the cache as it gets wiped out anyway below b/c the agent is + # done. + _extra_model_outputs = self._hanging_extra_model_outputs_end.pop( + agent_id, None + ) + _reward = self._hanging_rewards_end.pop(agent_id, 0.0) + _reward + # The agent is still alive, just add current reward to cache. + else: + # But has never stepped in this episode -> add to begin cache. + if agent_id not in self.agent_episodes: + self._hanging_rewards_begin[agent_id] += _reward + # Otherwise, add to end cache. + else: + self._hanging_rewards_end[agent_id] += _reward + + # If agent is stepping, add timestep to `SingleAgentEpisode`. + if _observation is not None: + sa_episode.add_env_step( + observation=_observation, + action=_action, + reward=_reward, + infos=_infos, + terminated=_terminated, + truncated=_truncated, + extra_model_outputs=_extra_model_outputs, + ) + # Update the env- to agent-step mapping. + self.env_t_to_agent_t[agent_id].append( + len(sa_episode) + sa_episode.observations.lookback + ) + + # Agent is also done. -> Erase all hanging values for this agent + # (they should be empty at this point anyways). + if _terminated or _truncated: + self._del_hanging(agent_id) + + # Validate our data. + self.validate() + + # Step time stats. + self._last_step_time = time.perf_counter() + if self._start_time is None: + self._start_time = self._last_step_time + + def validate(self) -> None: + """Validates the episode's data. + + This function ensures that the data stored to a `MultiAgentEpisode` is + in order (e.g. that the correct number of observations, actions, rewards + are there). + """ + for eps in self.agent_episodes.values(): + eps.validate() + + # TODO (sven): Validate MultiAgentEpisode specifics, like the timestep mappings, + # action/reward caches, etc.. + + @property + def custom_data(self): + return self._custom_data + + @property + def is_reset(self) -> bool: + """Returns True if `self.add_env_reset()` has already been called.""" + return any( + len(sa_episode.observations) > 0 + for sa_episode in self.agent_episodes.values() + ) + + @property + def is_numpy(self) -> bool: + """True, if the data in this episode is already stored as numpy arrays.""" + is_numpy = next(iter(self.agent_episodes.values())).is_numpy + # Make sure that all single agent's episodes' `is_numpy` flags are the same. + if not all(eps.is_numpy is is_numpy for eps in self.agent_episodes.values()): + raise RuntimeError( + f"Only some SingleAgentEpisode objects in {self} are converted to " + f"numpy, others are not!" + ) + return is_numpy + + @property + def is_done(self): + """Whether the episode is actually done (terminated or truncated). + + A done episode cannot be continued via `self.add_env_step()` or being + concatenated on its right-side with another episode chunk or being + succeeded via `self.cut()`. + + Note that in a multi-agent environment this does not necessarily + correspond to single agents having terminated or being truncated. + + `self.is_terminated` should be `True`, if all agents are terminated and + `self.is_truncated` should be `True`, if all agents are truncated. If + only one or more (but not all!) agents are `terminated/truncated the + `MultiAgentEpisode.is_terminated/is_truncated` should be `False`. This + information about single agent's terminated/truncated states can always + be retrieved from the `SingleAgentEpisode`s inside the 'MultiAgentEpisode` + one. + + If all agents are either terminated or truncated, but in a mixed fashion, + i.e. some are terminated and others are truncated: This is currently + undefined and could potentially be a problem (if a user really implemented + such a multi-agent env that behaves this way). + + Returns: + Boolean defining if an episode has either terminated or truncated. + """ + return self.is_terminated or self.is_truncated + + def to_numpy(self) -> "MultiAgentEpisode": + """Converts this Episode's list attributes to numpy arrays. + + This means in particular that this episodes' lists (per single agent) of + (possibly complex) data (e.g. an agent having a dict obs space) will be + converted to (possibly complex) structs, whose leafs are now numpy arrays. + Each of these leaf numpy arrays will have the same length (batch dimension) + as the length of the original lists. + + Note that Columns.INFOS are NEVER numpy'ized and will remain a list + (normally, a list of the original, env-returned dicts). This is due to the + heterogeneous nature of INFOS returned by envs, which would make it unwieldy to + convert this information to numpy arrays. + + After calling this method, no further data may be added to this episode via + the `self.add_env_step()` method. + + Examples: + + .. testcode:: + + import numpy as np + + from ray.rllib.env.multi_agent_episode import MultiAgentEpisode + from ray.rllib.env.tests.test_multi_agent_episode import ( + TestMultiAgentEpisode + ) + + # Create some multi-agent episode data. + ( + observations, + actions, + rewards, + terminateds, + truncateds, + infos, + ) = TestMultiAgentEpisode._mock_multi_agent_records() + # Define the agent ids. + agent_ids = ["agent_1", "agent_2", "agent_3", "agent_4", "agent_5"] + + episode = MultiAgentEpisode( + observations=observations, + infos=infos, + actions=actions, + rewards=rewards, + # Note: terminated/truncated have nothing to do with an episode + # being converted `to_numpy` or not (via the `self.to_numpy()` method)! + terminateds=terminateds, + truncateds=truncateds, + len_lookback_buffer=0, # no lookback; all data is actually "in" episode + ) + + # Episode has not been numpy'ized yet. + assert not episode.is_numpy + # We are still operating on lists. + assert ( + episode.get_observations( + indices=[1], + agent_ids="agent_1", + ) == {"agent_1": [1]} + ) + + # Numpy'ized the episode. + episode.to_numpy() + assert episode.is_numpy + + # Everything is now numpy arrays (with 0-axis of size + # B=[len of requested slice]). + assert ( + isinstance(episode.get_observations( + indices=[1], + agent_ids="agent_1", + )["agent_1"], np.ndarray) + ) + + Returns: + This `MultiAgentEpisode` object with the converted numpy data. + """ + + for agent_id, agent_eps in self.agent_episodes.copy().items(): + agent_eps.to_numpy() + + return self + + def concat_episode(self, other: "MultiAgentEpisode") -> None: + """Adds the given `other` MultiAgentEpisode to the right side of `self`. + + In order for this to work, both chunks (`self` and `other`) must fit + together. This is checked by the IDs (must be identical), the time step counters + (`self.env_t` must be the same as `episode_chunk.env_t_started`), as well as the + observations/infos of the individual agents at the concatenation boundaries. + Also, `self.is_done` must not be True, meaning `self.is_terminated` and + `self.is_truncated` are both False. + + Args: + other: The other `MultiAgentEpisode` to be concatenated to this one. + + Returns: + A `MultiAgentEpisode` instance containing the concatenated data + from both episodes (`self` and `other`). + """ + # Make sure the IDs match. + assert other.id_ == self.id_ + # NOTE (sven): This is what we agreed on. As the replay buffers must be + # able to concatenate. + assert not self.is_done + # Make sure the timesteps match. + assert self.env_t == other.env_t_started + # Validate `other`. + other.validate() + + # Concatenate the individual SingleAgentEpisodes from both chunks. + all_agent_ids = set(self.agent_ids) | set(other.agent_ids) + for agent_id in all_agent_ids: + sa_episode = self.agent_episodes.get(agent_id) + + # If agent is only in the new episode chunk -> Store all the data of `other` + # wrt agent in `self`. + if sa_episode is None: + self.agent_episodes[agent_id] = other.agent_episodes[agent_id] + self.env_t_to_agent_t[agent_id] = other.env_t_to_agent_t[agent_id] + self.agent_t_started[agent_id] = other.agent_t_started[agent_id] + self._copy_hanging(agent_id, other) + + # If the agent was done in `self`, ignore and continue. There should not be + # any data of that agent in `other`. + elif sa_episode.is_done: + continue + + # If the agent has data in both chunks, concatenate on the single-agent + # level, thereby making sure the hanging values (begin and end) match. + elif agent_id in other.agent_episodes: + # If `other` has hanging (end) values -> Add these to `self`'s agent + # SingleAgentEpisode (as a new timestep) and only then concatenate. + # Otherwise, the concatentaion would fail b/c of missing data. + if agent_id in self._hanging_actions_end: + assert agent_id in self._hanging_extra_model_outputs_end + sa_episode.add_env_step( + observation=other.agent_episodes[agent_id].get_observations(0), + infos=other.agent_episodes[agent_id].get_infos(0), + action=self._hanging_actions_end[agent_id], + reward=( + self._hanging_rewards_end[agent_id] + + other._hanging_rewards_begin[agent_id] + ), + extra_model_outputs=( + self._hanging_extra_model_outputs_end[agent_id] + ), + ) + sa_episode.concat_episode(other.agent_episodes[agent_id]) + # Override `self`'s hanging (end) values with `other`'s hanging (end). + if agent_id in other._hanging_actions_end: + self._hanging_actions_end[agent_id] = copy.deepcopy( + other._hanging_actions_end[agent_id] + ) + self._hanging_rewards_end[agent_id] = other._hanging_rewards_end[ + agent_id + ] + self._hanging_extra_model_outputs_end[agent_id] = copy.deepcopy( + other._hanging_extra_model_outputs_end[agent_id] + ) + + # Concatenate the env- to agent-timestep mappings. + j = self.env_t + for i, val in enumerate(other.env_t_to_agent_t[agent_id][1:]): + if val == self.SKIP_ENV_TS_TAG: + self.env_t_to_agent_t[agent_id].append(self.SKIP_ENV_TS_TAG) + else: + self.env_t_to_agent_t[agent_id].append(i + 1 + j) + + # Otherwise, the agent is only in `self` and not done. All data is stored + # already -> skip + # else: pass + + # Update all timestep counters. + self.env_t = other.env_t + # Check, if the episode is terminated or truncated. + if other.is_terminated: + self.is_terminated = True + elif other.is_truncated: + self.is_truncated = True + + # Merge with `other`'s custom_data, but give `other` priority b/c we assume + # that as a follow-up chunk of `self` other has a more complete version of + # `custom_data`. + self.custom_data.update(other.custom_data) + + # Validate. + self.validate() + + def cut(self, len_lookback_buffer: int = 0) -> "MultiAgentEpisode": + """Returns a successor episode chunk (of len=0) continuing from this Episode. + + The successor will have the same ID as `self`. + If no lookback buffer is requested (len_lookback_buffer=0), the successor's + observations will be the last observation(s) of `self` and its length will + therefore be 0 (no further steps taken yet). If `len_lookback_buffer` > 0, + the returned successor will have `len_lookback_buffer` observations (and + actions, rewards, etc..) taken from the right side (end) of `self`. For example + if `len_lookback_buffer=2`, the returned successor's lookback buffer actions + will be identical to the results of `self.get_actions([-2, -1])`. + + This method is useful if you would like to discontinue building an episode + chunk (b/c you have to return it from somewhere), but would like to have a new + episode instance to continue building the actual gym.Env episode at a later + time. Vie the `len_lookback_buffer` argument, the continuing chunk (successor) + will still be able to "look back" into this predecessor episode's data (at + least to some extend, depending on the value of `len_lookback_buffer`). + + Args: + len_lookback_buffer: The number of environment timesteps to take along into + the new chunk as "lookback buffer". A lookback buffer is additional data + on the left side of the actual episode data for visibility purposes + (but without actually being part of the new chunk). For example, if + `self` ends in actions: agent_1=5,6,7 and agent_2=6,7, and we call + `self.cut(len_lookback_buffer=2)`, the returned chunk will have + actions 6 and 7 for both agents already in it, but still + `t_started`==t==8 (not 7!) and a length of 0. If there is not enough + data in `self` yet to fulfil the `len_lookback_buffer` request, the + value of `len_lookback_buffer` is automatically adjusted (lowered). + + Returns: + The successor Episode chunk of this one with the same ID and state and the + only observation being the last observation in self. + """ + assert len_lookback_buffer >= 0 + if self.is_done: + raise RuntimeError( + "Can't call `MultiAgentEpisode.cut()` when the episode is already done!" + ) + + # If there is hanging data (e.g. actions) in the agents' caches, we might have + # to re-adjust the lookback len further into the past to make sure that these + # agents have at least one observation to look back to. Otherwise, the timestep + # that got cut into will be "lost" for learning from it. + orig_len_lb = len_lookback_buffer + for agent_id, agent_actions in self._hanging_actions_end.items(): + assert self.env_t_to_agent_t[agent_id].get(-1) == self.SKIP_ENV_TS_TAG + for i in range(orig_len_lb, len(self.env_t_to_agent_t[agent_id].data) + 1): + if self.env_t_to_agent_t[agent_id].get(-i) != self.SKIP_ENV_TS_TAG: + len_lookback_buffer = max(len_lookback_buffer, i - 1) + break + + # Initialize this episode chunk with the most recent observations + # and infos (even if lookback is zero). Similar to an initial `env.reset()` + indices_obs_and_infos = slice(-len_lookback_buffer - 1, None) + indices_rest = ( + slice(-len_lookback_buffer, None) + if len_lookback_buffer > 0 + else slice(None, 0) # -> empty slice + ) + + observations = self.get_observations( + indices=indices_obs_and_infos, return_list=True + ) + infos = self.get_infos(indices=indices_obs_and_infos, return_list=True) + actions = self.get_actions(indices=indices_rest, return_list=True) + rewards = self.get_rewards(indices=indices_rest, return_list=True) + extra_model_outputs = self.get_extra_model_outputs( + key=None, # all keys + indices=indices_rest, + return_list=True, + ) + + successor = MultiAgentEpisode( + # Same ID. + id_=self.id_, + observations=observations, + observation_space=self.observation_space, + infos=infos, + actions=actions, + action_space=self.action_space, + rewards=rewards, + # List of MADicts, mapping agent IDs to their respective extra model output + # dicts. + extra_model_outputs=extra_model_outputs, + terminateds=self.get_terminateds(), + truncateds=self.get_truncateds(), + # Continue with `self`'s current timesteps. + env_t_started=self.env_t, + agent_t_started={ + aid: self.agent_episodes[aid].t + for aid in self.agent_ids + if not self.agent_episodes[aid].is_done + }, + # Same AgentIDs and SingleAgentEpisode IDs. + agent_episode_ids=self.agent_episode_ids, + agent_module_ids={ + aid: self.agent_episodes[aid].module_id for aid in self.agent_ids + }, + agent_to_module_mapping_fn=self.agent_to_module_mapping_fn, + # All data we provided to the c'tor goes into the lookback buffer. + len_lookback_buffer="auto", + ) + + # Copy over the hanging (end) values into the hanging (begin) caches of the + # successor. + successor._hanging_rewards_begin = self._hanging_rewards_end.copy() + + # Deepcopy all custom data in `self` to be continued in the cut episode. + successor._custom_data = copy.deepcopy(self.custom_data) + + return successor + + @property + def agent_ids(self) -> Set[AgentID]: + """Returns the agent ids.""" + return set(self.agent_episodes.keys()) + + @property + def agent_episode_ids(self) -> MultiAgentDict: + """Returns ids from each agent's `SingleAgentEpisode`.""" + + return { + agent_id: agent_eps.id_ + for agent_id, agent_eps in self.agent_episodes.items() + } + + def module_for(self, agent_id: AgentID) -> Optional[ModuleID]: + """Returns the ModuleID for a given AgentID. + + Forces the agent-to-module mapping to be performed (via + `self.agent_to_module_mapping_fn`), if this has not been done yet. + Note that all such mappings are stored in the `self._agent_to_module_mapping` + property. + + Args: + agent_id: The AgentID to get a mapped ModuleID for. + + Returns: + The ModuleID mapped to from the given `agent_id`. + """ + if agent_id not in self._agent_to_module_mapping: + module_id = self._agent_to_module_mapping[ + agent_id + ] = self.agent_to_module_mapping_fn(agent_id, self) + return module_id + else: + return self._agent_to_module_mapping[agent_id] + + def get_observations( + self, + indices: Optional[Union[int, List[int], slice]] = None, + agent_ids: Optional[Union[Collection[AgentID], AgentID]] = None, + *, + env_steps: bool = True, + # global_indices: bool = False, + neg_index_as_lookback: bool = False, + fill: Optional[Any] = None, + one_hot_discrete: bool = False, + return_list: bool = False, + ) -> Union[MultiAgentDict, List[MultiAgentDict]]: + """Returns agents' observations or batched ranges thereof from this episode. + + Args: + indices: A single int is interpreted as an index, from which to return the + individual observation stored at this index. + A list of ints is interpreted as a list of indices from which to gather + individual observations in a batch of size len(indices). + A slice object is interpreted as a range of observations to be returned. + Thereby, negative indices by default are interpreted as "before the end" + unless the `neg_index_as_lookback=True` option is used, in which case + negative indices are interpreted as "before ts=0", meaning going back + into the lookback buffer. + If None, will return all observations (from ts=0 to the end). + agent_ids: An optional collection of AgentIDs or a single AgentID to get + observations for. If None, will return observations for all agents in + this episode. + env_steps: Whether `indices` should be interpreted as environment time steps + (True) or per-agent timesteps (False). + neg_index_as_lookback: If True, negative values in `indices` are + interpreted as "before ts=0", meaning going back into the lookback + buffer. For example, an episode with agent A's observations + [4, 5, 6, 7, 8, 9], where [4, 5, 6] is the lookback buffer range + (ts=0 item is 7), will respond to `get_observations(-1, agent_ids=[A], + neg_index_as_lookback=True)` with {A: `6`} and to + `get_observations(slice(-2, 1), agent_ids=[A], + neg_index_as_lookback=True)` with {A: `[5, 6, 7]`}. + fill: An optional value to use for filling up the returned results at + the boundaries. This filling only happens if the requested index range's + start/stop boundaries exceed the episode's boundaries (including the + lookback buffer on the left side). This comes in very handy, if users + don't want to worry about reaching such boundaries and want to zero-pad. + For example, an episode with agent A' observations [10, 11, 12, 13, 14] + and lookback buffer size of 2 (meaning observations `10` and `11` are + part of the lookback buffer) will respond to + `get_observations(slice(-7, -2), agent_ids=[A], fill=0.0)` with + `{A: [0.0, 0.0, 10, 11, 12]}`. + one_hot_discrete: If True, will return one-hot vectors (instead of + int-values) for those sub-components of a (possibly complex) observation + space that are Discrete or MultiDiscrete. Note that if `fill=0` and the + requested `indices` are out of the range of our data, the returned + one-hot vectors will actually be zero-hot (all slots zero). + return_list: Whether to return a list of multi-agent dicts (instead of + a single multi-agent dict of lists/structs). False by default. This + option can only be used when `env_steps` is True due to the fact the + such a list can only be interpreted as one env step per list item + (would not work with agent steps). + + Returns: + A dictionary mapping agent IDs to observations (at the given + `indices`). If `env_steps` is True, only agents that have stepped + (were ready) at the given env step `indices` are returned (i.e. not all + agent IDs are necessarily in the keys). + If `return_list` is True, returns a list of MultiAgentDicts (mapping agent + IDs to observations) instead. + """ + return self._get( + what="observations", + indices=indices, + agent_ids=agent_ids, + env_steps=env_steps, + neg_index_as_lookback=neg_index_as_lookback, + fill=fill, + one_hot_discrete=one_hot_discrete, + return_list=return_list, + ) + + def get_infos( + self, + indices: Optional[Union[int, List[int], slice]] = None, + agent_ids: Optional[Union[Collection[AgentID], AgentID]] = None, + *, + env_steps: bool = True, + neg_index_as_lookback: bool = False, + fill: Optional[Any] = None, + return_list: bool = False, + ) -> Union[MultiAgentDict, List[MultiAgentDict]]: + """Returns agents' info dicts or list (ranges) thereof from this episode. + + Args: + indices: A single int is interpreted as an index, from which to return the + individual info dict stored at this index. + A list of ints is interpreted as a list of indices from which to gather + individual info dicts in a list of size len(indices). + A slice object is interpreted as a range of info dicts to be returned. + Thereby, negative indices by default are interpreted as "before the end" + unless the `neg_index_as_lookback=True` option is used, in which case + negative indices are interpreted as "before ts=0", meaning going back + into the lookback buffer. + If None, will return all infos (from ts=0 to the end). + agent_ids: An optional collection of AgentIDs or a single AgentID to get + info dicts for. If None, will return info dicts for all agents in + this episode. + env_steps: Whether `indices` should be interpreted as environment time steps + (True) or per-agent timesteps (False). + neg_index_as_lookback: If True, negative values in `indices` are + interpreted as "before ts=0", meaning going back into the lookback + buffer. For example, an episode with agent A's info dicts + [{"l":4}, {"l":5}, {"l":6}, {"a":7}, {"b":8}, {"c":9}], where the + first 3 items are the lookback buffer (ts=0 item is {"a": 7}), will + respond to `get_infos(-1, agent_ids=A, neg_index_as_lookback=True)` + with `{A: {"l":6}}` and to + `get_infos(slice(-2, 1), agent_ids=A, neg_index_as_lookback=True)` + with `{A: [{"l":5}, {"l":6}, {"a":7}]}`. + fill: An optional value to use for filling up the returned results at + the boundaries. This filling only happens if the requested index range's + start/stop boundaries exceed the episode's boundaries (including the + lookback buffer on the left side). This comes in very handy, if users + don't want to worry about reaching such boundaries and want to + auto-fill. For example, an episode with agent A's infos being + [{"l":10}, {"l":11}, {"a":12}, {"b":13}, {"c":14}] and lookback buffer + size of 2 (meaning infos {"l":10}, {"l":11} are part of the lookback + buffer) will respond to `get_infos(slice(-7, -2), agent_ids=A, + fill={"o": 0.0})` with + `{A: [{"o":0.0}, {"o":0.0}, {"l":10}, {"l":11}, {"a":12}]}`. + return_list: Whether to return a list of multi-agent dicts (instead of + a single multi-agent dict of lists/structs). False by default. This + option can only be used when `env_steps` is True due to the fact the + such a list can only be interpreted as one env step per list item + (would not work with agent steps). + + Returns: + A dictionary mapping agent IDs to observations (at the given + `indices`). If `env_steps` is True, only agents that have stepped + (were ready) at the given env step `indices` are returned (i.e. not all + agent IDs are necessarily in the keys). + If `return_list` is True, returns a list of MultiAgentDicts (mapping agent + IDs to infos) instead. + """ + return self._get( + what="infos", + indices=indices, + agent_ids=agent_ids, + env_steps=env_steps, + neg_index_as_lookback=neg_index_as_lookback, + fill=fill, + return_list=return_list, + ) + + def get_actions( + self, + indices: Optional[Union[int, List[int], slice]] = None, + agent_ids: Optional[Union[Collection[AgentID], AgentID]] = None, + *, + env_steps: bool = True, + neg_index_as_lookback: bool = False, + fill: Optional[Any] = None, + one_hot_discrete: bool = False, + return_list: bool = False, + ) -> Union[MultiAgentDict, List[MultiAgentDict]]: + """Returns agents' actions or batched ranges thereof from this episode. + + Args: + indices: A single int is interpreted as an index, from which to return the + individual actions stored at this index. + A list of ints is interpreted as a list of indices from which to gather + individual actions in a batch of size len(indices). + A slice object is interpreted as a range of actions to be returned. + Thereby, negative indices by default are interpreted as "before the end" + unless the `neg_index_as_lookback=True` option is used, in which case + negative indices are interpreted as "before ts=0", meaning going back + into the lookback buffer. + If None, will return all actions (from ts=0 to the end). + agent_ids: An optional collection of AgentIDs or a single AgentID to get + actions for. If None, will return actions for all agents in + this episode. + env_steps: Whether `indices` should be interpreted as environment time steps + (True) or per-agent timesteps (False). + neg_index_as_lookback: If True, negative values in `indices` are + interpreted as "before ts=0", meaning going back into the lookback + buffer. For example, an episode with agent A's actions + [4, 5, 6, 7, 8, 9], where [4, 5, 6] is the lookback buffer range + (ts=0 item is 7), will respond to `get_actions(-1, agent_ids=[A], + neg_index_as_lookback=True)` with {A: `6`} and to + `get_actions(slice(-2, 1), agent_ids=[A], + neg_index_as_lookback=True)` with {A: `[5, 6, 7]`}. + fill: An optional value to use for filling up the returned results at + the boundaries. This filling only happens if the requested index range's + start/stop boundaries exceed the episode's boundaries (including the + lookback buffer on the left side). This comes in very handy, if users + don't want to worry about reaching such boundaries and want to zero-pad. + For example, an episode with agent A' actions [10, 11, 12, 13, 14] + and lookback buffer size of 2 (meaning actions `10` and `11` are + part of the lookback buffer) will respond to + `get_actions(slice(-7, -2), agent_ids=[A], fill=0.0)` with + `{A: [0.0, 0.0, 10, 11, 12]}`. + one_hot_discrete: If True, will return one-hot vectors (instead of + int-values) for those sub-components of a (possibly complex) observation + space that are Discrete or MultiDiscrete. Note that if `fill=0` and the + requested `indices` are out of the range of our data, the returned + one-hot vectors will actually be zero-hot (all slots zero). + return_list: Whether to return a list of multi-agent dicts (instead of + a single multi-agent dict of lists/structs). False by default. This + option can only be used when `env_steps` is True due to the fact the + such a list can only be interpreted as one env step per list item + (would not work with agent steps). + + Returns: + A dictionary mapping agent IDs to actions (at the given + `indices`). If `env_steps` is True, only agents that have stepped + (were ready) at the given env step `indices` are returned (i.e. not all + agent IDs are necessarily in the keys). + If `return_list` is True, returns a list of MultiAgentDicts (mapping agent + IDs to actions) instead. + """ + return self._get( + what="actions", + indices=indices, + agent_ids=agent_ids, + env_steps=env_steps, + neg_index_as_lookback=neg_index_as_lookback, + fill=fill, + one_hot_discrete=one_hot_discrete, + return_list=return_list, + ) + + def get_rewards( + self, + indices: Optional[Union[int, List[int], slice]] = None, + agent_ids: Optional[Union[Collection[AgentID], AgentID]] = None, + *, + env_steps: bool = True, + neg_index_as_lookback: bool = False, + fill: Optional[float] = None, + return_list: bool = False, + ) -> Union[MultiAgentDict, List[MultiAgentDict]]: + """Returns agents' rewards or batched ranges thereof from this episode. + + Args: + indices: A single int is interpreted as an index, from which to return the + individual rewards stored at this index. + A list of ints is interpreted as a list of indices from which to gather + individual rewards in a batch of size len(indices). + A slice object is interpreted as a range of rewards to be returned. + Thereby, negative indices by default are interpreted as "before the end" + unless the `neg_index_as_lookback=True` option is used, in which case + negative indices are interpreted as "before ts=0", meaning going back + into the lookback buffer. + If None, will return all rewards (from ts=0 to the end). + agent_ids: An optional collection of AgentIDs or a single AgentID to get + rewards for. If None, will return rewards for all agents in + this episode. + env_steps: Whether `indices` should be interpreted as environment time steps + (True) or per-agent timesteps (False). + neg_index_as_lookback: If True, negative values in `indices` are + interpreted as "before ts=0", meaning going back into the lookback + buffer. For example, an episode with agent A's rewards + [4, 5, 6, 7, 8, 9], where [4, 5, 6] is the lookback buffer range + (ts=0 item is 7), will respond to `get_rewards(-1, agent_ids=[A], + neg_index_as_lookback=True)` with {A: `6`} and to + `get_rewards(slice(-2, 1), agent_ids=[A], + neg_index_as_lookback=True)` with {A: `[5, 6, 7]`}. + fill: An optional float value to use for filling up the returned results at + the boundaries. This filling only happens if the requested index range's + start/stop boundaries exceed the episode's boundaries (including the + lookback buffer on the left side). This comes in very handy, if users + don't want to worry about reaching such boundaries and want to zero-pad. + For example, an episode with agent A' rewards [10, 11, 12, 13, 14] + and lookback buffer size of 2 (meaning rewards `10` and `11` are + part of the lookback buffer) will respond to + `get_rewards(slice(-7, -2), agent_ids=[A], fill=0.0)` with + `{A: [0.0, 0.0, 10, 11, 12]}`. + return_list: Whether to return a list of multi-agent dicts (instead of + a single multi-agent dict of lists/structs). False by default. This + option can only be used when `env_steps` is True due to the fact the + such a list can only be interpreted as one env step per list item + (would not work with agent steps). + + Returns: + A dictionary mapping agent IDs to rewards (at the given + `indices`). If `env_steps` is True, only agents that have stepped + (were ready) at the given env step `indices` are returned (i.e. not all + agent IDs are necessarily in the keys). + If `return_list` is True, returns a list of MultiAgentDicts (mapping agent + IDs to rewards) instead. + """ + return self._get( + what="rewards", + indices=indices, + agent_ids=agent_ids, + env_steps=env_steps, + neg_index_as_lookback=neg_index_as_lookback, + fill=fill, + return_list=return_list, + ) + + def get_extra_model_outputs( + self, + key: Optional[str] = None, + indices: Optional[Union[int, List[int], slice]] = None, + agent_ids: Optional[Union[Collection[AgentID], AgentID]] = None, + *, + env_steps: bool = True, + neg_index_as_lookback: bool = False, + fill: Optional[Any] = None, + return_list: bool = False, + ) -> Union[MultiAgentDict, List[MultiAgentDict]]: + """Returns agents' actions or batched ranges thereof from this episode. + + Args: + key: The `key` within each agents' extra_model_outputs dict to extract + data for. If None, return data of all extra model output keys. + indices: A single int is interpreted as an index, from which to return the + individual extra model outputs stored at this index. + A list of ints is interpreted as a list of indices from which to gather + individual extra model outputs in a batch of size len(indices). + A slice object is interpreted as a range of extra model outputs to be + returned. + Thereby, negative indices by default are interpreted as "before the end" + unless the `neg_index_as_lookback=True` option is used, in which case + negative indices are interpreted as "before ts=0", meaning going back + into the lookback buffer. + If None, will return all extra model outputs (from ts=0 to the end). + agent_ids: An optional collection of AgentIDs or a single AgentID to get + extra model outputs for. If None, will return extra model outputs for + all agents in this episode. + env_steps: Whether `indices` should be interpreted as environment time steps + (True) or per-agent timesteps (False). + neg_index_as_lookback: If True, negative values in `indices` are + interpreted as "before ts=0", meaning going back into the lookback + buffer. For example, an episode with agent A's actions + [4, 5, 6, 7, 8, 9], where [4, 5, 6] is the lookback buffer range + (ts=0 item is 7), will respond to `get_actions(-1, agent_ids=[A], + neg_index_as_lookback=True)` with {A: `6`} and to + `get_actions(slice(-2, 1), agent_ids=[A], + neg_index_as_lookback=True)` with {A: `[5, 6, 7]`}. + fill: An optional value to use for filling up the returned results at + the boundaries. This filling only happens if the requested index range's + start/stop boundaries exceed the episode's boundaries (including the + lookback buffer on the left side). This comes in very handy, if users + don't want to worry about reaching such boundaries and want to zero-pad. + For example, an episode with agent A' actions [10, 11, 12, 13, 14] + and lookback buffer size of 2 (meaning actions `10` and `11` are + part of the lookback buffer) will respond to + `get_actions(slice(-7, -2), agent_ids=[A], fill=0.0)` with + `{A: [0.0, 0.0, 10, 11, 12]}`. + one_hot_discrete: If True, will return one-hot vectors (instead of + int-values) for those sub-components of a (possibly complex) observation + space that are Discrete or MultiDiscrete. Note that if `fill=0` and the + requested `indices` are out of the range of our data, the returned + one-hot vectors will actually be zero-hot (all slots zero). + return_list: Whether to return a list of multi-agent dicts (instead of + a single multi-agent dict of lists/structs). False by default. This + option can only be used when `env_steps` is True due to the fact the + such a list can only be interpreted as one env step per list item + (would not work with agent steps). + + Returns: + A dictionary mapping agent IDs to actions (at the given + `indices`). If `env_steps` is True, only agents that have stepped + (were ready) at the given env step `indices` are returned (i.e. not all + agent IDs are necessarily in the keys). + If `return_list` is True, returns a list of MultiAgentDicts (mapping agent + IDs to extra_model_outputs) instead. + """ + return self._get( + what="extra_model_outputs", + extra_model_outputs_key=key, + indices=indices, + agent_ids=agent_ids, + env_steps=env_steps, + neg_index_as_lookback=neg_index_as_lookback, + fill=fill, + return_list=return_list, + ) + + def get_terminateds(self) -> MultiAgentDict: + """Gets the terminateds at given indices.""" + terminateds = { + agent_id: self.agent_episodes[agent_id].is_terminated + for agent_id in self.agent_ids + } + terminateds.update({"__all__": self.is_terminated}) + return terminateds + + def get_truncateds(self) -> MultiAgentDict: + truncateds = { + agent_id: self.agent_episodes[agent_id].is_truncated + for agent_id in self.agent_ids + } + truncateds.update({"__all__": self.is_terminated}) + return truncateds + + def slice( + self, + slice_: slice, + *, + len_lookback_buffer: Optional[int] = None, + ) -> "MultiAgentEpisode": + """Returns a slice of this episode with the given slice object. + + Works analogous to + :py:meth:`~ray.rllib.env.single_agent_episode.SingleAgentEpisode.slice` + + However, the important differences are: + - `slice_` is provided in (global) env steps, not agent steps. + - In case `slice_` ends - for a certain agent - in an env step, where that + particular agent does not have an observation, the previous observation will + be included, but the next action and sum of rewards until this point will + be stored in the agent's hanging values caches for the returned + MultiAgentEpisode slice. + + .. testcode:: + + from ray.rllib.env.multi_agent_episode import MultiAgentEpisode + from ray.rllib.utils.test_utils import check + + # Generate a simple multi-agent episode. + observations = [ + {"a0": 0, "a1": 0}, # 0 + { "a1": 1}, # 1 + { "a1": 2}, # 2 + {"a0": 3, "a1": 3}, # 3 + {"a0": 4}, # 4 + ] + # Actions are the same as observations (except for last obs, which doesn't + # have an action). + actions = observations[:-1] + # Make up a reward for each action. + rewards = [ + {aid: r / 10 + 0.1 for aid, r in o.items()} + for o in observations + ] + episode = MultiAgentEpisode( + observations=observations, + actions=actions, + rewards=rewards, + len_lookback_buffer=0, + ) + + # Slice the episode and check results. + slice = episode[1:3] + a0 = slice.agent_episodes["a0"] + a1 = slice.agent_episodes["a1"] + check((a0.observations, a1.observations), ([3], [1, 2, 3])) + check((a0.actions, a1.actions), ([], [1, 2])) + check((a0.rewards, a1.rewards), ([], [0.2, 0.3])) + check((a0.is_done, a1.is_done), (False, False)) + + # If a slice ends in a "gap" for an agent, expect actions and rewards to be + # cached for this agent. + slice = episode[:2] + a0 = slice.agent_episodes["a0"] + check(a0.observations, [0]) + check(a0.actions, []) + check(a0.rewards, []) + check(slice._hanging_actions_end["a0"], 0) + check(slice._hanging_rewards_end["a0"], 0.1) + + Args: + slice_: The slice object to use for slicing. This should exclude the + lookback buffer, which will be prepended automatically to the returned + slice. + len_lookback_buffer: If not None, forces the returned slice to try to have + this number of timesteps in its lookback buffer (if available). If None + (default), tries to make the returned slice's lookback as large as the + current lookback buffer of this episode (`self`). + + Returns: + The new MultiAgentEpisode representing the requested slice. + """ + if slice_.step not in [1, None]: + raise NotImplementedError( + "Slicing MultiAgentEnv with a step other than 1 (you used" + f" {slice_.step}) is not supported!" + ) + + # Translate `slice_` into one that only contains 0-or-positive ints and will + # NOT contain any None. + start = slice_.start + stop = slice_.stop + + # Start is None -> 0. + if start is None: + start = 0 + # Start is negative -> Interpret index as counting "from end". + elif start < 0: + start = max(len(self) + start, 0) + # Start is larger than len(self) -> Clip to len(self). + elif start > len(self): + start = len(self) + + # Stop is None -> Set stop to our len (one ts past last valid index). + if stop is None: + stop = len(self) + # Stop is negative -> Interpret index as counting "from end". + elif stop < 0: + stop = max(len(self) + stop, 0) + # Stop is larger than len(self) -> Clip to len(self). + elif stop > len(self): + stop = len(self) + + ref_lookback = None + try: + for aid, sa_episode in self.agent_episodes.items(): + if ref_lookback is None: + ref_lookback = sa_episode.observations.lookback + assert sa_episode.observations.lookback == ref_lookback + assert sa_episode.actions.lookback == ref_lookback + assert sa_episode.rewards.lookback == ref_lookback + assert all( + ilb.lookback == ref_lookback + for ilb in sa_episode.extra_model_outputs.values() + ) + except AssertionError: + raise ValueError( + "Can only slice a MultiAgentEpisode if all lookback buffers in this " + "episode have the exact same size!" + ) + + # Determine terminateds/truncateds and when (in agent timesteps) the + # single-agent episode slices start. + terminateds = {} + truncateds = {} + agent_t_started = {} + for aid, sa_episode in self.agent_episodes.items(): + mapping = self.env_t_to_agent_t[aid] + # If the (agent) timestep directly at the slice stop boundary is equal to + # the length of the single-agent episode of this agent -> Use the + # single-agent episode's terminated/truncated flags. + # If `stop` is already beyond this agent's single-agent episode, then we + # don't have to keep track of this: The MultiAgentEpisode initializer will + # automatically determine that this agent must be done (b/c it has no action + # following its final observation). + if ( + stop < len(mapping) + and mapping[stop] != self.SKIP_ENV_TS_TAG + and len(sa_episode) == mapping[stop] + ): + terminateds[aid] = sa_episode.is_terminated + truncateds[aid] = sa_episode.is_truncated + # Determine this agent's t_started. + if start < len(mapping): + for i in range(start, len(mapping)): + if mapping[i] != self.SKIP_ENV_TS_TAG: + agent_t_started[aid] = sa_episode.t_started + mapping[i] + break + terminateds["__all__"] = all( + terminateds.get(aid) for aid in self.agent_episodes + ) + truncateds["__all__"] = all(truncateds.get(aid) for aid in self.agent_episodes) + + # Determine all other slice contents. + _lb = len_lookback_buffer if len_lookback_buffer is not None else ref_lookback + if start - _lb < 0 and ref_lookback < (_lb - start): + _lb = ref_lookback + start + observations = self.get_observations( + slice(start - _lb, stop + 1), + neg_index_as_lookback=True, + return_list=True, + ) + actions = self.get_actions( + slice(start - _lb, stop), + neg_index_as_lookback=True, + return_list=True, + ) + rewards = self.get_rewards( + slice(start - _lb, stop), + neg_index_as_lookback=True, + return_list=True, + ) + extra_model_outputs = self.get_extra_model_outputs( + indices=slice(start - _lb, stop), + neg_index_as_lookback=True, + return_list=True, + ) + + # Create the actual slice to be returned. + ma_episode = MultiAgentEpisode( + id_=self.id_, + # In the following, offset `start`s automatically by lookbacks. + observations=observations, + observation_space=self.observation_space, + actions=actions, + action_space=self.action_space, + rewards=rewards, + extra_model_outputs=extra_model_outputs, + terminateds=terminateds, + truncateds=truncateds, + len_lookback_buffer=_lb, + env_t_started=self.env_t_started + start, + agent_episode_ids={ + aid: eid.id_ for aid, eid in self.agent_episodes.items() + }, + agent_t_started=agent_t_started, + agent_module_ids=self._agent_to_module_mapping, + agent_to_module_mapping_fn=self.agent_to_module_mapping_fn, + ) + + # Numpy'ize slice if `self` is also finalized. + if self.is_numpy: + ma_episode.to_numpy() + + return ma_episode + + def __len__(self): + """Returns the length of an `MultiAgentEpisode`. + + Note that the length of an episode is defined by the difference + between its actual timestep and the starting point. + + Returns: An integer defining the length of the episode or an + error if the episode has not yet started. + """ + return self.env_t - self.env_t_started + + def __repr__(self): + sa_eps_returns = { + aid: sa_eps.get_return() for aid, sa_eps in self.agent_episodes.items() + } + return ( + f"MAEps(len={len(self)} done={self.is_done} " + f"Rs={sa_eps_returns} id_={self.id_})" + ) + + def print(self) -> None: + """Prints this MultiAgentEpisode as a table of observations for the agents.""" + + # Find the maximum timestep across all agents to determine the grid width. + max_ts = max(ts.len_incl_lookback() for ts in self.env_t_to_agent_t.values()) + lookback = next(iter(self.env_t_to_agent_t.values())).lookback + longest_agent = max(len(aid) for aid in self.agent_ids) + # Construct the header. + header = ( + "ts" + + (" " * longest_agent) + + " ".join(str(i) for i in range(-lookback, max_ts - lookback)) + + "\n" + ) + # Construct each agent's row. + rows = [] + for agent, inf_buffer in self.env_t_to_agent_t.items(): + row = f"{agent} " + (" " * (longest_agent - len(agent))) + for t in inf_buffer.data: + # Two spaces for alignment. + if t == "S": + row += " " + # Mark the step with an x. + else: + row += " x " + # Remove trailing space for alignment. + rows.append(row.rstrip()) + + # Join all components into a final string + print(header + "\n".join(rows)) + + def get_state(self) -> Dict[str, Any]: + """Returns the state of a multi-agent episode. + + Note that from an episode's state the episode itself can + be recreated. + + Returns: A dicitonary containing pickable data for a + `MultiAgentEpisode`. + """ + return { + "id_": self.id_, + "agent_to_module_mapping_fn": self.agent_to_module_mapping_fn, + "_agent_to_module_mapping": self._agent_to_module_mapping, + "observation_space": self.observation_space, + "action_space": self.action_space, + "env_t_started": self.env_t_started, + "env_t": self.env_t, + "agent_t_started": self.agent_t_started, + # TODO (simon): Check, if we can store the `InfiniteLookbackBuffer` + "env_t_to_agent_t": self.env_t_to_agent_t, + "_hanging_actions_end": self._hanging_actions_end, + "_hanging_extra_model_outputs_end": self._hanging_extra_model_outputs_end, + "_hanging_rewards_end": self._hanging_rewards_end, + "_hanging_rewards_begin": self._hanging_rewards_begin, + "is_terminated": self.is_terminated, + "is_truncated": self.is_truncated, + "agent_episodes": list( + { + agent_id: agent_eps.get_state() + for agent_id, agent_eps in self.agent_episodes.items() + }.items() + ), + "_start_time": self._start_time, + "_last_step_time": self._last_step_time, + "custom_data": self.custom_data, + } + + @staticmethod + def from_state(state: Dict[str, Any]) -> "MultiAgentEpisode": + """Creates a multi-agent episode from a state dictionary. + + See `MultiAgentEpisode.get_state()` for creating a state for + a `MultiAgentEpisode` pickable state. For recreating a + `MultiAgentEpisode` from a state, this state has to be complete, + i.e. all data must have been stored in the state. + + Args: + state: A dict containing all data required to recreate a MultiAgentEpisode`. + See `MultiAgentEpisode.get_state()`. + + Returns: + A `MultiAgentEpisode` instance created from the state data. + """ + # Create an empty `MultiAgentEpisode` instance. + episode = MultiAgentEpisode(id_=state["id_"]) + # Fill the instance with the state data. + episode.agent_to_module_mapping_fn = state["agent_to_module_mapping_fn"] + episode._agent_to_module_mapping = state["_agent_to_module_mapping"] + episode.observation_space = state["observation_space"] + episode.action_space = state["action_space"] + episode.env_t_started = state["env_t_started"] + episode.env_t = state["env_t"] + episode.agent_t_started = state["agent_t_started"] + episode.env_t_to_agent_t = state["env_t_to_agent_t"] + episode._hanging_actions_end = state["_hanging_actions_end"] + episode._hanging_extra_model_outputs_end = state[ + "_hanging_extra_model_outputs_end" + ] + episode._hanging_rewards_end = state["_hanging_rewards_end"] + episode._hanging_rewards_begin = state["_hanging_rewards_begin"] + episode.is_terminated = state["is_terminated"] + episode.is_truncated = state["is_truncated"] + episode.agent_episodes = { + agent_id: SingleAgentEpisode.from_state(agent_state) + for agent_id, agent_state in state["agent_episodes"] + } + episode._start_time = state["_start_time"] + episode._last_step_time = state["_last_step_time"] + episode._custom_data = state.get("custom_data", {}) + + # Validate the episode. + episode.validate() + + return episode + + def get_sample_batch(self) -> MultiAgentBatch: + """Converts this `MultiAgentEpisode` into a `MultiAgentBatch`. + + Each `SingleAgentEpisode` instances in `MultiAgentEpisode.agent_epiosdes` + will be converted into a `SampleBatch` and the environment timestep will be + passed as the returned MultiAgentBatch's `env_steps`. + + Returns: + A MultiAgentBatch containing all of this episode's data. + """ + # TODO (simon): Check, if timesteps should be converted into global + # timesteps instead of agent steps. + # Note, only agents that have stepped are included into the batch. + return MultiAgentBatch( + policy_batches={ + agent_id: agent_eps.get_sample_batch() + for agent_id, agent_eps in self.agent_episodes.items() + if agent_eps.t - agent_eps.t_started > 0 + }, + env_steps=self.env_t - self.env_t_started, + ) + + def get_return( + self, + include_hanging_rewards: bool = False, + ) -> float: + """Returns all-agent return. + + Args: + include_hanging_rewards: Whether we should also consider + hanging rewards wehn calculating the overall return. Agents might + have received partial rewards, i.e. rewards without an + observation. These are stored in the "hanging" caches (begin and end) + for each agent and added up until the next observation is received by + that agent. + + Returns: + The sum of all single-agents' returns (maybe including the hanging + rewards per agent). + """ + env_return = sum( + agent_eps.get_return() for agent_eps in self.agent_episodes.values() + ) + if include_hanging_rewards: + for hanging_r in self._hanging_rewards_begin.values(): + env_return += hanging_r + for hanging_r in self._hanging_rewards_end.values(): + env_return += hanging_r + + return env_return + + def get_agents_to_act(self) -> Set[AgentID]: + """Returns a set of agent IDs required to send an action to `env.step()` next. + + Those are generally the agents that received an observation in the most recent + `env.step()` call. + + Returns: + A set of AgentIDs that are supposed to send actions to the next `env.step()` + call. + """ + return { + aid + for aid in self.get_observations(-1).keys() + if not self.agent_episodes[aid].is_done + } + + def get_agents_that_stepped(self) -> Set[AgentID]: + """Returns a set of agent IDs of those agents that just finished stepping. + + These are all the agents that have an observation logged at the last env + timestep, which may include agents, whose single agent episode just terminated + or truncated. + + Returns: + A set of AgentIDs of those agents that just finished stepping (that have a + most recent observation on the env timestep scale), regardless of whether + their single agent episodes are done or not. + """ + return set(self.get_observations(-1).keys()) + + def get_duration_s(self) -> float: + """Returns the duration of this Episode (chunk) in seconds.""" + if self._last_step_time is None: + return 0.0 + return self._last_step_time - self._start_time + + def env_steps(self) -> int: + """Returns the number of environment steps. + + Note, this episode instance could be a chunk of an actual episode. + + Returns: + An integer that counts the number of environment steps this episode instance + has seen. + """ + return len(self) + + def agent_steps(self) -> int: + """Number of agent steps. + + Note, there are >= 1 agent steps per environment step. + + Returns: + An integer counting the number of agent steps executed during the time this + episode instance records. + """ + return sum(len(eps) for eps in self.agent_episodes.values()) + + def __getitem__(self, item: slice) -> "MultiAgentEpisode": + """Enable squared bracket indexing- and slicing syntax, e.g. episode[-4:].""" + if isinstance(item, slice): + return self.slice(slice_=item) + else: + raise NotImplementedError( + f"MultiAgentEpisode does not support getting item '{item}'! " + "Only slice objects allowed with the syntax: `episode[a:b]`." + ) + + def _init_single_agent_episodes( + self, + *, + agent_module_ids: Optional[Dict[AgentID, ModuleID]] = None, + agent_episode_ids: Optional[Dict[AgentID, str]] = None, + observations: Optional[List[MultiAgentDict]] = None, + actions: Optional[List[MultiAgentDict]] = None, + rewards: Optional[List[MultiAgentDict]] = None, + infos: Optional[List[MultiAgentDict]] = None, + terminateds: Union[MultiAgentDict, bool] = False, + truncateds: Union[MultiAgentDict, bool] = False, + extra_model_outputs: Optional[List[MultiAgentDict]] = None, + ): + if observations is None: + return + if actions is None: + assert not rewards + assert not extra_model_outputs + actions = [] + rewards = [] + extra_model_outputs = [] + + # Infos and `extra_model_outputs` are allowed to be None -> Fill them with + # proper dummy values, if so. + if infos is None: + infos = [{} for _ in range(len(observations))] + if extra_model_outputs is None: + extra_model_outputs = [{} for _ in range(len(actions))] + + observations_per_agent = defaultdict(list) + infos_per_agent = defaultdict(list) + actions_per_agent = defaultdict(list) + rewards_per_agent = defaultdict(list) + extra_model_outputs_per_agent = defaultdict(list) + done_per_agent = defaultdict(bool) + len_lookback_buffer_per_agent = defaultdict(lambda: self._len_lookback_buffers) + + all_agent_ids = set( + agent_episode_ids.keys() if agent_episode_ids is not None else [] + ) + agent_module_ids = agent_module_ids or {} + + # Step through all observations and interpret these as the (global) env steps. + for data_idx, (obs, inf) in enumerate(zip(observations, infos)): + # If we do have actions/extra outs/rewards for this timestep, use the data. + # It may be that these lists have the same length as the observations list, + # in which case the data will be cached (agent did step/send an action, + # but the step has not been concluded yet by the env). + act = actions[data_idx] if len(actions) > data_idx else {} + extra_outs = ( + extra_model_outputs[data_idx] + if len(extra_model_outputs) > data_idx + else {} + ) + rew = rewards[data_idx] if len(rewards) > data_idx else {} + + for agent_id, agent_obs in obs.items(): + all_agent_ids.add(agent_id) + + observations_per_agent[agent_id].append(agent_obs) + infos_per_agent[agent_id].append(inf.get(agent_id, {})) + + # Pull out hanging action (if not first obs for this agent) and + # complete step for agent. + if len(observations_per_agent[agent_id]) > 1: + actions_per_agent[agent_id].append( + self._hanging_actions_end.pop(agent_id) + ) + extra_model_outputs_per_agent[agent_id].append( + self._hanging_extra_model_outputs_end.pop(agent_id) + ) + rewards_per_agent[agent_id].append( + self._hanging_rewards_end.pop(agent_id) + ) + # First obs for this agent. Make sure the agent's mapping is + # appropriately prepended with self.SKIP_ENV_TS_TAG tags. + else: + if agent_id not in self.env_t_to_agent_t: + self.env_t_to_agent_t[agent_id].extend( + [self.SKIP_ENV_TS_TAG] * data_idx + ) + len_lookback_buffer_per_agent[agent_id] -= data_idx + + # Agent is still continuing (has an action for the next step). + if agent_id in act: + # Always push actions/extra outputs into cache, then remove them + # from there, once the next observation comes in. Same for rewards. + self._hanging_actions_end[agent_id] = act[agent_id] + self._hanging_extra_model_outputs_end[agent_id] = extra_outs.get( + agent_id, {} + ) + self._hanging_rewards_end[agent_id] += rew.get(agent_id, 0.0) + # Agent is done (has no action for the next step). + elif terminateds.get(agent_id) or truncateds.get(agent_id): + done_per_agent[agent_id] = True + # There is more (global) action/reward data. This agent must therefore + # be done. Automatically add it to `done_per_agent` and `terminateds`. + elif data_idx < len(observations) - 1: + done_per_agent[agent_id] = terminateds[agent_id] = True + + # Update env_t_to_agent_t mapping. + self.env_t_to_agent_t[agent_id].append( + len(observations_per_agent[agent_id]) - 1 + ) + + # Those agents that did NOT step: + # - Get self.SKIP_ENV_TS_TAG added to their env_t_to_agent_t mapping. + # - Get their reward (if any) added up. + for agent_id in all_agent_ids: + if agent_id not in obs and agent_id not in done_per_agent: + self.env_t_to_agent_t[agent_id].append(self.SKIP_ENV_TS_TAG) + # If we are still in the global lookback buffer segment, deduct 1 + # from this agents' lookback buffer, b/c we don't want the agent + # to use this (missing) obs/data in its single-agent lookback. + if ( + len(self.env_t_to_agent_t[agent_id]) + - self._len_lookback_buffers + <= 0 + ): + len_lookback_buffer_per_agent[agent_id] -= 1 + self._hanging_rewards_end[agent_id] += rew.get(agent_id, 0.0) + + # - Validate per-agent data. + # - Fix lookback buffers of env_t_to_agent_t mappings. + for agent_id in list(self.env_t_to_agent_t.keys()): + # Skip agent if it doesn't seem to have any data. + if agent_id not in observations_per_agent: + del self.env_t_to_agent_t[agent_id] + continue + assert ( + len(observations_per_agent[agent_id]) + == len(infos_per_agent[agent_id]) + == len(actions_per_agent[agent_id]) + 1 + == len(extra_model_outputs_per_agent[agent_id]) + 1 + == len(rewards_per_agent[agent_id]) + 1 + ) + self.env_t_to_agent_t[agent_id].lookback = self._len_lookback_buffers + + # Now create the individual episodes from the collected per-agent data. + for agent_id, agent_obs in observations_per_agent.items(): + # If agent only has a single obs AND is already done, remove all its traces + # from this MultiAgentEpisode. + if len(agent_obs) == 1 and done_per_agent.get(agent_id): + self._del_agent(agent_id) + continue + + # Try to figure out the module ID for this agent. + # If not provided explicitly by the user that initializes this episode + # object, try our mapping function. + module_id = agent_module_ids.get( + agent_id, self.agent_to_module_mapping_fn(agent_id, self) + ) + # Create this agent's SingleAgentEpisode. + sa_episode = SingleAgentEpisode( + id_=( + agent_episode_ids.get(agent_id) + if agent_episode_ids is not None + else None + ), + agent_id=agent_id, + module_id=module_id, + multi_agent_episode_id=self.id_, + observations=agent_obs, + observation_space=self.observation_space.get(agent_id), + infos=infos_per_agent[agent_id], + actions=actions_per_agent[agent_id], + action_space=self.action_space.get(agent_id), + rewards=rewards_per_agent[agent_id], + extra_model_outputs=( + { + k: [i[k] for i in extra_model_outputs_per_agent[agent_id]] + for k in extra_model_outputs_per_agent[agent_id][0].keys() + } + if extra_model_outputs_per_agent[agent_id] + else None + ), + terminated=terminateds.get(agent_id, False), + truncated=truncateds.get(agent_id, False), + t_started=self.agent_t_started[agent_id], + len_lookback_buffer=max(len_lookback_buffer_per_agent[agent_id], 0), + ) + # .. and store it. + self.agent_episodes[agent_id] = sa_episode + + def _get( + self, + *, + what, + indices, + agent_ids=None, + env_steps=True, + neg_index_as_lookback=False, + fill=None, + one_hot_discrete=False, + return_list=False, + extra_model_outputs_key=None, + ): + agent_ids = set(force_list(agent_ids)) or self.agent_ids + + kwargs = dict( + what=what, + indices=indices, + agent_ids=agent_ids, + neg_index_as_lookback=neg_index_as_lookback, + fill=fill, + # Rewards and infos do not support one_hot_discrete option. + one_hot_discrete=dict( + {} if not one_hot_discrete else {"one_hot_discrete": one_hot_discrete} + ), + extra_model_outputs_key=extra_model_outputs_key, + ) + + # User specified agent timesteps (indices) -> Simply delegate everything + # to the individual agents' SingleAgentEpisodes. + if env_steps is False: + if return_list: + raise ValueError( + f"`MultiAgentEpisode.get_{what}()` can't be called with both " + "`env_steps=False` and `return_list=True`!" + ) + return self._get_data_by_agent_steps(**kwargs) + # User specified env timesteps (indices) -> We need to translate them for each + # agent into agent-timesteps. + # Return a list of individual per-env-timestep multi-agent dicts. + elif return_list: + return self._get_data_by_env_steps_as_list(**kwargs) + # Return a single multi-agent dict with lists/arrays as leafs. + else: + return self._get_data_by_env_steps(**kwargs) + + def _get_data_by_agent_steps( + self, + *, + what, + indices, + agent_ids, + neg_index_as_lookback, + fill, + one_hot_discrete, + extra_model_outputs_key, + ): + # Return requested data by agent-steps. + ret = {} + # For each agent, we retrieve the data through passing the given indices into + # the SingleAgentEpisode of that agent. + for agent_id, sa_episode in self.agent_episodes.items(): + if agent_id not in agent_ids: + continue + inf_lookback_buffer = getattr(sa_episode, what) + hanging_val = self._get_hanging_value(what, agent_id) + # User wants a specific `extra_model_outputs` key. + if extra_model_outputs_key is not None: + inf_lookback_buffer = inf_lookback_buffer[extra_model_outputs_key] + hanging_val = hanging_val[extra_model_outputs_key] + agent_value = inf_lookback_buffer.get( + indices=indices, + neg_index_as_lookback=neg_index_as_lookback, + fill=fill, + _add_last_ts_value=hanging_val, + **one_hot_discrete, + ) + if agent_value is None or agent_value == []: + continue + ret[agent_id] = agent_value + return ret + + def _get_data_by_env_steps_as_list( + self, + *, + what: str, + indices: Union[int, slice, List[int]], + agent_ids: Collection[AgentID], + neg_index_as_lookback: bool, + fill: Any, + one_hot_discrete, + extra_model_outputs_key: str, + ) -> List[MultiAgentDict]: + # Collect indices for each agent first, so we can construct the list in + # the next step. + agent_indices = {} + for agent_id in self.agent_episodes.keys(): + if agent_id not in agent_ids: + continue + agent_indices[agent_id] = self.env_t_to_agent_t[agent_id].get( + indices, + neg_index_as_lookback=neg_index_as_lookback, + fill=self.SKIP_ENV_TS_TAG, + # For those records where there is no "hanging" last timestep (all + # other than obs and infos), we have to ignore the last entry in + # the env_t_to_agent_t mappings. + _ignore_last_ts=what not in ["observations", "infos"], + ) + if not agent_indices: + return [] + ret = [] + for i in range(len(next(iter(agent_indices.values())))): + ret2 = {} + for agent_id, idxes in agent_indices.items(): + hanging_val = self._get_hanging_value(what, agent_id) + ( + inf_lookback_buffer, + indices_to_use, + ) = self._get_inf_lookback_buffer_or_dict( + agent_id, + what, + extra_model_outputs_key, + hanging_val, + filter_for_skip_indices=idxes[i], + ) + if ( + what == "extra_model_outputs" + and not inf_lookback_buffer + and not hanging_val + ): + continue + agent_value = self._get_single_agent_data_by_index( + what=what, + inf_lookback_buffer=inf_lookback_buffer, + agent_id=agent_id, + index_incl_lookback=indices_to_use, + fill=fill, + one_hot_discrete=one_hot_discrete, + extra_model_outputs_key=extra_model_outputs_key, + hanging_val=hanging_val, + ) + if agent_value is not None: + ret2[agent_id] = agent_value + ret.append(ret2) + return ret + + def _get_data_by_env_steps( + self, + *, + what: str, + indices: Union[int, slice, List[int]], + agent_ids: Collection[AgentID], + neg_index_as_lookback: bool, + fill: Any, + one_hot_discrete: bool, + extra_model_outputs_key: str, + ) -> MultiAgentDict: + ignore_last_ts = what not in ["observations", "infos"] + ret = {} + for agent_id, sa_episode in self.agent_episodes.items(): + if agent_id not in agent_ids: + continue + hanging_val = self._get_hanging_value(what, agent_id) + agent_indices = self.env_t_to_agent_t[agent_id].get( + indices, + neg_index_as_lookback=neg_index_as_lookback, + fill=self.SKIP_ENV_TS_TAG if fill is not None else None, + # For those records where there is no "hanging" last timestep (all + # other than obs and infos), we have to ignore the last entry in + # the env_t_to_agent_t mappings. + _ignore_last_ts=ignore_last_ts, + ) + inf_lookback_buffer, agent_indices = self._get_inf_lookback_buffer_or_dict( + agent_id, + what, + extra_model_outputs_key, + hanging_val, + filter_for_skip_indices=agent_indices, + ) + if isinstance(agent_indices, list): + agent_values = self._get_single_agent_data_by_env_step_indices( + what=what, + agent_id=agent_id, + indices_incl_lookback=agent_indices, + fill=fill, + one_hot_discrete=one_hot_discrete, + hanging_val=hanging_val, + extra_model_outputs_key=extra_model_outputs_key, + ) + if len(agent_values) > 0: + ret[agent_id] = agent_values + else: + agent_values = self._get_single_agent_data_by_index( + what=what, + inf_lookback_buffer=inf_lookback_buffer, + agent_id=agent_id, + index_incl_lookback=agent_indices, + fill=fill, + one_hot_discrete=one_hot_discrete, + extra_model_outputs_key=extra_model_outputs_key, + hanging_val=hanging_val, + ) + if agent_values is not None: + ret[agent_id] = agent_values + return ret + + def _get_single_agent_data_by_index( + self, + *, + what: str, + inf_lookback_buffer: InfiniteLookbackBuffer, + agent_id: AgentID, + index_incl_lookback: Union[int, str], + fill: Any, + one_hot_discrete: dict, + extra_model_outputs_key: str, + hanging_val: Any, + ) -> Any: + sa_episode = self.agent_episodes[agent_id] + + if index_incl_lookback == self.SKIP_ENV_TS_TAG: + # We don't want to fill -> Skip this agent. + if fill is None: + return + # Provide filled value for this agent. + return getattr(sa_episode, f"get_{what}")( + indices=1000000000000, + neg_index_as_lookback=False, + fill=fill, + **dict( + {} + if extra_model_outputs_key is None + else {"key": extra_model_outputs_key} + ), + **one_hot_discrete, + ) + + # No skip timestep -> Provide value at given index for this agent. + + # Special case: extra_model_outputs and key=None (return all keys as + # a dict). Note that `inf_lookback_buffer` is NOT an infinite lookback + # buffer, but a dict mapping keys to individual infinite lookback + # buffers. + elif what == "extra_model_outputs" and extra_model_outputs_key is None: + assert hanging_val is None or isinstance(hanging_val, dict) + ret = {} + if inf_lookback_buffer: + for key, sub_buffer in inf_lookback_buffer.items(): + ret[key] = sub_buffer.get( + indices=index_incl_lookback - sub_buffer.lookback, + neg_index_as_lookback=True, + fill=fill, + _add_last_ts_value=( + None if hanging_val is None else hanging_val[key] + ), + **one_hot_discrete, + ) + else: + for key in hanging_val.keys(): + ret[key] = InfiniteLookbackBuffer().get( + indices=index_incl_lookback, + neg_index_as_lookback=True, + fill=fill, + _add_last_ts_value=hanging_val[key], + **one_hot_discrete, + ) + return ret + + # Extract data directly from the infinite lookback buffer object. + else: + return inf_lookback_buffer.get( + indices=index_incl_lookback - inf_lookback_buffer.lookback, + neg_index_as_lookback=True, + fill=fill, + _add_last_ts_value=hanging_val, + **one_hot_discrete, + ) + + def _get_single_agent_data_by_env_step_indices( + self, + *, + what: str, + agent_id: AgentID, + indices_incl_lookback: Union[int, str], + fill: Optional[Any] = None, + one_hot_discrete: bool = False, + extra_model_outputs_key: Optional[str] = None, + hanging_val: Optional[Any] = None, + ) -> Any: + """Returns single data item from the episode based on given (env step) indices. + + The returned data item will have a batch size that matches the env timesteps + defined via `indices_incl_lookback`. + + Args: + what: A (str) descriptor of what data to collect. Must be one of + "observations", "infos", "actions", "rewards", or "extra_model_outputs". + indices_incl_lookback: A list of ints specifying, which indices + to pull from the InfiniteLookbackBuffer defined by `agent_id` and `what` + (and maybe `extra_model_outputs_key`). Note that these indices + disregard the special logic of the lookback buffer. Meaning if one + index in `indices_incl_lookback` is 0, then the first value in the + lookback buffer should be returned, not the first value after the + lookback buffer (which would be normal behavior for pulling items from + an `InfiniteLookbackBuffer` object). + agent_id: The individual agent ID to pull data for. Used to lookup the + `SingleAgentEpisode` object for this agent in `self`. + fill: An optional float value to use for filling up the returned results at + the boundaries. This filling only happens if the requested index range's + start/stop boundaries exceed the buffer's boundaries (including the + lookback buffer on the left side). This comes in very handy, if users + don't want to worry about reaching such boundaries and want to zero-pad. + For example, a buffer with data [10, 11, 12, 13, 14] and lookback + buffer size of 2 (meaning `10` and `11` are part of the lookback buffer) + will respond to `indices_incl_lookback=[-1, -2, 0]` and `fill=0.0` + with `[0.0, 0.0, 10]`. + one_hot_discrete: If True, will return one-hot vectors (instead of + int-values) for those sub-components of a (possibly complex) space + that are Discrete or MultiDiscrete. Note that if `fill=0` and the + requested `indices_incl_lookback` are out of the range of our data, the + returned one-hot vectors will actually be zero-hot (all slots zero). + extra_model_outputs_key: Only if what is "extra_model_outputs", this + specifies the sub-key (str) inside the extra_model_outputs dict, e.g. + STATE_OUT or ACTION_DIST_INPUTS. + hanging_val: In case we are pulling actions, rewards, or extra_model_outputs + data, there might be information "hanging" (cached). For example, + if an agent receives an observation o0 and then immediately sends an + action a0 back, but then does NOT immediately reveive a next + observation, a0 is now cached (not fully logged yet with this + episode). The currently cached value must be provided here to be able + to return it in case the index is -1 (most recent timestep). + + Returns: + A data item corresponding to the provided args. + """ + sa_episode = self.agent_episodes[agent_id] + + inf_lookback_buffer = getattr(sa_episode, what) + if extra_model_outputs_key is not None: + inf_lookback_buffer = inf_lookback_buffer[extra_model_outputs_key] + + # If there are self.SKIP_ENV_TS_TAG items in `indices_incl_lookback` and user + # wants to fill these (together with outside-episode-bounds indices) -> + # Provide these skipped timesteps as filled values. + if self.SKIP_ENV_TS_TAG in indices_incl_lookback and fill is not None: + single_fill_value = inf_lookback_buffer.get( + indices=1000000000000, + neg_index_as_lookback=False, + fill=fill, + **one_hot_discrete, + ) + ret = [] + for i in indices_incl_lookback: + if i == self.SKIP_ENV_TS_TAG: + ret.append(single_fill_value) + else: + ret.append( + inf_lookback_buffer.get( + indices=i - getattr(sa_episode, what).lookback, + neg_index_as_lookback=True, + fill=fill, + _add_last_ts_value=hanging_val, + **one_hot_discrete, + ) + ) + if self.is_numpy: + ret = batch(ret) + else: + # Filter these indices out up front. + indices = [ + i - inf_lookback_buffer.lookback + for i in indices_incl_lookback + if i != self.SKIP_ENV_TS_TAG + ] + ret = inf_lookback_buffer.get( + indices=indices, + neg_index_as_lookback=True, + fill=fill, + _add_last_ts_value=hanging_val, + **one_hot_discrete, + ) + return ret + + def _get_hanging_value(self, what: str, agent_id: AgentID) -> Any: + """Returns the hanging action/reward/extra_model_outputs for given agent.""" + if what == "actions": + return self._hanging_actions_end.get(agent_id) + elif what == "extra_model_outputs": + return self._hanging_extra_model_outputs_end.get(agent_id) + elif what == "rewards": + return self._hanging_rewards_end.get(agent_id) + + def _copy_hanging(self, agent_id: AgentID, other: "MultiAgentEpisode") -> None: + """Copies hanging action, reward, extra_model_outputs from `other` to `self.""" + if agent_id in other._hanging_rewards_begin: + self._hanging_rewards_begin[agent_id] = other._hanging_rewards_begin[ + agent_id + ] + if agent_id in other._hanging_rewards_end: + self._hanging_actions_end[agent_id] = copy.deepcopy( + other._hanging_actions_end[agent_id] + ) + self._hanging_rewards_end[agent_id] = other._hanging_rewards_end[agent_id] + self._hanging_extra_model_outputs_end[agent_id] = copy.deepcopy( + other._hanging_extra_model_outputs_end[agent_id] + ) + + def _del_hanging(self, agent_id: AgentID) -> None: + """Deletes all hanging action, reward, extra_model_outputs of given agent.""" + self._hanging_rewards_begin.pop(agent_id, None) + + self._hanging_actions_end.pop(agent_id, None) + self._hanging_extra_model_outputs_end.pop(agent_id, None) + self._hanging_rewards_end.pop(agent_id, None) + + def _del_agent(self, agent_id: AgentID) -> None: + """Deletes all data of given agent from this episode.""" + self._del_hanging(agent_id) + self.agent_episodes.pop(agent_id, None) + self.agent_ids.discard(agent_id) + self.env_t_to_agent_t.pop(agent_id, None) + self._agent_to_module_mapping.pop(agent_id, None) + self.agent_t_started.pop(agent_id, None) + + def _get_inf_lookback_buffer_or_dict( + self, + agent_id: AgentID, + what: str, + extra_model_outputs_key: Optional[str] = None, + hanging_val: Optional[Any] = None, + filter_for_skip_indices=None, + ): + """Returns a single InfiniteLookbackBuffer or a dict of such. + + In case `what` is "extra_model_outputs" AND `extra_model_outputs_key` is None, + a dict is returned. In all other cases, a single InfiniteLookbackBuffer is + returned. + """ + inf_lookback_buffer_or_dict = inf_lookback_buffer = getattr( + self.agent_episodes[agent_id], what + ) + if what == "extra_model_outputs": + if extra_model_outputs_key is not None: + inf_lookback_buffer = inf_lookback_buffer_or_dict[ + extra_model_outputs_key + ] + elif inf_lookback_buffer_or_dict: + inf_lookback_buffer = next(iter(inf_lookback_buffer_or_dict.values())) + elif filter_for_skip_indices is not None: + return inf_lookback_buffer_or_dict, filter_for_skip_indices + else: + return inf_lookback_buffer_or_dict + + if filter_for_skip_indices is not None: + inf_lookback_buffer_len = ( + len(inf_lookback_buffer) + + inf_lookback_buffer.lookback + + (hanging_val is not None) + ) + ignore_last_ts = what not in ["observations", "infos"] + if isinstance(filter_for_skip_indices, list): + filter_for_skip_indices = [ + "S" if ignore_last_ts and i == inf_lookback_buffer_len else i + for i in filter_for_skip_indices + ] + elif ignore_last_ts and filter_for_skip_indices == inf_lookback_buffer_len: + filter_for_skip_indices = "S" + return inf_lookback_buffer_or_dict, filter_for_skip_indices + else: + return inf_lookback_buffer_or_dict + + @Deprecated(new="MultiAgentEpisode.custom_data[some-key] = ...", error=True) + def add_temporary_timestep_data(self): + pass + + @Deprecated(new="MultiAgentEpisode.custom_data[some-key]", error=True) + def get_temporary_timestep_data(self): + pass diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/policy_client.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/policy_client.py new file mode 100644 index 0000000000000000000000000000000000000000..e4e2e9ad8a6252698b79d7068904f92485f51f25 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/policy_client.py @@ -0,0 +1,321 @@ +import logging +import threading +import time +from typing import Union, Optional + +import ray.cloudpickle as pickle +from ray.rllib.env.external_env import ExternalEnv +from ray.rllib.env.external_multi_agent_env import ExternalMultiAgentEnv +from ray.rllib.env.multi_agent_env import MultiAgentEnv +from ray.rllib.policy.sample_batch import MultiAgentBatch +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.typing import ( + MultiAgentDict, + EnvInfoDict, + EnvObsType, + EnvActionType, +) + +# Backward compatibility. +from ray.rllib.env.external.rllink import RLlink as Commands + +logger = logging.getLogger(__name__) + +try: + import requests # `requests` is not part of stdlib. +except ImportError: + requests = None + logger.warning( + "Couldn't import `requests` library. Be sure to install it on" + " the client side." + ) + + +@OldAPIStack +class PolicyClient: + """REST client to interact with an RLlib policy server.""" + + def __init__( + self, + address: str, + inference_mode: str = "local", + update_interval: float = 10.0, + session: Optional[requests.Session] = None, + ): + self.address = address + self.session = session + self.env: ExternalEnv = None + if inference_mode == "local": + self.local = True + self._setup_local_rollout_worker(update_interval) + elif inference_mode == "remote": + self.local = False + else: + raise ValueError("inference_mode must be either 'local' or 'remote'") + + def start_episode( + self, episode_id: Optional[str] = None, training_enabled: bool = True + ) -> str: + if self.local: + self._update_local_policy() + return self.env.start_episode(episode_id, training_enabled) + + return self._send( + { + "episode_id": episode_id, + "command": Commands.START_EPISODE, + "training_enabled": training_enabled, + } + )["episode_id"] + + def get_action( + self, episode_id: str, observation: Union[EnvObsType, MultiAgentDict] + ) -> Union[EnvActionType, MultiAgentDict]: + if self.local: + self._update_local_policy() + if isinstance(episode_id, (list, tuple)): + actions = { + eid: self.env.get_action(eid, observation[eid]) + for eid in episode_id + } + return actions + else: + return self.env.get_action(episode_id, observation) + else: + return self._send( + { + "command": Commands.GET_ACTION, + "observation": observation, + "episode_id": episode_id, + } + )["action"] + + def log_action( + self, + episode_id: str, + observation: Union[EnvObsType, MultiAgentDict], + action: Union[EnvActionType, MultiAgentDict], + ) -> None: + if self.local: + self._update_local_policy() + return self.env.log_action(episode_id, observation, action) + + self._send( + { + "command": Commands.LOG_ACTION, + "observation": observation, + "action": action, + "episode_id": episode_id, + } + ) + + def log_returns( + self, + episode_id: str, + reward: float, + info: Union[EnvInfoDict, MultiAgentDict] = None, + multiagent_done_dict: Optional[MultiAgentDict] = None, + ) -> None: + if self.local: + self._update_local_policy() + if multiagent_done_dict is not None: + assert isinstance(reward, dict) + return self.env.log_returns( + episode_id, reward, info, multiagent_done_dict + ) + return self.env.log_returns(episode_id, reward, info) + + self._send( + { + "command": Commands.LOG_RETURNS, + "reward": reward, + "info": info, + "episode_id": episode_id, + "done": multiagent_done_dict, + } + ) + + def end_episode( + self, episode_id: str, observation: Union[EnvObsType, MultiAgentDict] + ) -> None: + if self.local: + self._update_local_policy() + return self.env.end_episode(episode_id, observation) + + self._send( + { + "command": Commands.END_EPISODE, + "observation": observation, + "episode_id": episode_id, + } + ) + + def update_policy_weights(self) -> None: + """Query the server for new policy weights, if local inference is enabled.""" + self._update_local_policy(force=True) + + def _send(self, data): + payload = pickle.dumps(data) + + if self.session is None: + response = requests.post(self.address, data=payload) + else: + response = self.session.post(self.address, data=payload) + + if response.status_code != 200: + logger.error("Request failed {}: {}".format(response.text, data)) + response.raise_for_status() + parsed = pickle.loads(response.content) + return parsed + + def _setup_local_rollout_worker(self, update_interval): + self.update_interval = update_interval + self.last_updated = 0 + + logger.info("Querying server for rollout worker settings.") + kwargs = self._send( + { + "command": Commands.GET_WORKER_ARGS, + } + )["worker_args"] + (self.rollout_worker, self.inference_thread) = _create_embedded_rollout_worker( + kwargs, self._send + ) + self.env = self.rollout_worker.env + + def _update_local_policy(self, force=False): + assert self.inference_thread.is_alive() + if ( + self.update_interval + and time.time() - self.last_updated > self.update_interval + ) or force: + logger.info("Querying server for new policy weights.") + resp = self._send( + { + "command": Commands.GET_WEIGHTS, + } + ) + weights = resp["weights"] + global_vars = resp["global_vars"] + logger.info( + "Updating rollout worker weights and global vars {}.".format( + global_vars + ) + ) + self.rollout_worker.set_weights(weights, global_vars) + self.last_updated = time.time() + + +@OldAPIStack +class _LocalInferenceThread(threading.Thread): + def __init__(self, rollout_worker, send_fn): + super().__init__() + self.daemon = True + self.rollout_worker = rollout_worker + self.send_fn = send_fn + + def run(self): + try: + while True: + logger.info("Generating new batch of experiences.") + samples = self.rollout_worker.sample() + metrics = self.rollout_worker.get_metrics() + if isinstance(samples, MultiAgentBatch): + logger.info( + "Sending batch of {} env steps ({} agent steps) to " + "server.".format(samples.env_steps(), samples.agent_steps()) + ) + else: + logger.info( + "Sending batch of {} steps back to server.".format( + samples.count + ) + ) + self.send_fn( + { + "command": Commands.REPORT_SAMPLES, + "samples": samples, + "metrics": metrics, + } + ) + except Exception as e: + logger.error("Error: inference worker thread died!", e) + + +@OldAPIStack +def _auto_wrap_external(real_env_creator): + def wrapped_creator(env_config): + real_env = real_env_creator(env_config) + if not isinstance(real_env, (ExternalEnv, ExternalMultiAgentEnv)): + logger.info( + "The env you specified is not a supported (sub-)type of " + "ExternalEnv. Attempting to convert it automatically to " + "ExternalEnv." + ) + + if isinstance(real_env, MultiAgentEnv): + external_cls = ExternalMultiAgentEnv + else: + external_cls = ExternalEnv + + class _ExternalEnvWrapper(external_cls): + def __init__(self, real_env): + super().__init__( + observation_space=real_env.observation_space, + action_space=real_env.action_space, + ) + + def run(self): + # Since we are calling methods on this class in the + # client, run doesn't need to do anything. + time.sleep(999999) + + return _ExternalEnvWrapper(real_env) + return real_env + + return wrapped_creator + + +@OldAPIStack +def _create_embedded_rollout_worker(kwargs, send_fn): + # Since the server acts as an input datasource, we have to reset the + # input config to the default, which runs env rollouts. + kwargs = kwargs.copy() + kwargs["config"] = kwargs["config"].copy(copy_frozen=False) + config = kwargs["config"] + config.output = None + config.input_ = "sampler" + config.input_config = {} + + # If server has no env (which is the expected case): + # Generate a dummy ExternalEnv here using RandomEnv and the + # given observation/action spaces. + if config.env is None: + from ray.rllib.examples.envs.classes.random_env import ( + RandomEnv, + RandomMultiAgentEnv, + ) + + env_config = { + "action_space": config.action_space, + "observation_space": config.observation_space, + } + is_ma = config.is_multi_agent + kwargs["env_creator"] = _auto_wrap_external( + lambda _: (RandomMultiAgentEnv if is_ma else RandomEnv)(env_config) + ) + # kwargs["config"].env = True + # Otherwise, use the env specified by the server args. + else: + real_env_creator = kwargs["env_creator"] + kwargs["env_creator"] = _auto_wrap_external(real_env_creator) + + logger.info("Creating rollout worker with kwargs={}".format(kwargs)) + from ray.rllib.evaluation.rollout_worker import RolloutWorker + + rollout_worker = RolloutWorker(**kwargs) + + inference_thread = _LocalInferenceThread(rollout_worker, send_fn) + inference_thread.start() + + return rollout_worker, inference_thread diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/policy_server_input.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/policy_server_input.py new file mode 100644 index 0000000000000000000000000000000000000000..48598a51d9eb9252b366c52e970da98f196746e5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/policy_server_input.py @@ -0,0 +1,270 @@ +from collections import deque +from http.server import HTTPServer, SimpleHTTPRequestHandler +import logging +import queue +from socketserver import ThreadingMixIn +import threading +import time +import traceback + +from typing import List +import ray.cloudpickle as pickle +from ray.rllib.env.policy_client import ( + _create_embedded_rollout_worker, + Commands, +) +from ray.rllib.offline.input_reader import InputReader +from ray.rllib.offline.io_context import IOContext +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.evaluation.metrics import RolloutMetrics +from ray.rllib.evaluation.sampler import SamplerInput +from ray.rllib.utils.typing import SampleBatchType +from ray._common.network_utils import build_address + +logger = logging.getLogger(__name__) + + +@OldAPIStack +class PolicyServerInput(ThreadingMixIn, HTTPServer, InputReader): + def __init__( + self, + ioctx: IOContext, + address: str, + port: int, + idle_timeout: float = 3.0, + max_sample_queue_size: int = 20, + ): + self.rollout_worker = ioctx.worker + # Protect ourselves from having a bottleneck on the server (learning) side. + # Once the queue (deque) is full, we throw away 50% (oldest + # samples first) of the samples, warn, and continue. + self.samples_queue = deque(maxlen=max_sample_queue_size) + self.metrics_queue = queue.Queue() + self.idle_timeout = idle_timeout + + # Forwards client-reported metrics directly into the local rollout + # worker. + if self.rollout_worker.sampler is not None: + # This is a bit of a hack since it is patching the get_metrics + # function of the sampler. + + def get_metrics(): + completed = [] + while True: + try: + completed.append(self.metrics_queue.get_nowait()) + except queue.Empty: + break + + return completed + + self.rollout_worker.sampler.get_metrics = get_metrics + else: + # If there is no sampler, act like if there would be one to collect + # metrics from + class MetricsDummySampler(SamplerInput): + """This sampler only maintains a queue to get metrics from.""" + + def __init__(self, metrics_queue): + """Initializes a MetricsDummySampler instance. + + Args: + metrics_queue: A queue of metrics + """ + self.metrics_queue = metrics_queue + + def get_data(self) -> SampleBatchType: + raise NotImplementedError + + def get_extra_batches(self) -> List[SampleBatchType]: + raise NotImplementedError + + def get_metrics(self) -> List[RolloutMetrics]: + """Returns metrics computed on a policy client rollout worker.""" + completed = [] + while True: + try: + completed.append(self.metrics_queue.get_nowait()) + except queue.Empty: + break + return completed + + self.rollout_worker.sampler = MetricsDummySampler(self.metrics_queue) + + # Create a request handler that receives commands from the clients + # and sends data and metrics into the queues. + handler = _make_handler( + self.rollout_worker, self.samples_queue, self.metrics_queue + ) + try: + import time + + time.sleep(1) + HTTPServer.__init__(self, (address, port), handler) + except OSError: + print(f"Creating a PolicyServer on {build_address(address, port)} failed!") + import time + + time.sleep(1) + raise + + logger.info( + "Starting connector server at " + f"{build_address(self.server_name, self.server_port)}" + ) + + # Start the serving thread, listening on socket and handling commands. + serving_thread = threading.Thread(name="server", target=self.serve_forever) + serving_thread.daemon = True + serving_thread.start() + + # Start a dummy thread that puts empty SampleBatches on the queue, just + # in case we don't receive anything from clients (or there aren't + # any). The latter would block sample collection entirely otherwise, + # even if other workers' PolicyServerInput receive incoming data from + # actual clients. + heart_beat_thread = threading.Thread( + name="heart-beat", target=self._put_empty_sample_batch_every_n_sec + ) + heart_beat_thread.daemon = True + heart_beat_thread.start() + + @override(InputReader) + def next(self): + # Blocking wait until there is something in the deque. + while len(self.samples_queue) == 0: + time.sleep(0.1) + # Utilize last items first in order to remain as closely as possible + # to operating on-policy. + return self.samples_queue.pop() + + def _put_empty_sample_batch_every_n_sec(self): + # Places an empty SampleBatch every `idle_timeout` seconds onto the + # `samples_queue`. This avoids hanging of all RolloutWorkers parallel + # to this one in case this PolicyServerInput does not have incoming + # data (e.g. no client connected) and the driver algorithm uses parallel + # synchronous sampling (e.g. PPO). + while True: + time.sleep(self.idle_timeout) + self.samples_queue.append(SampleBatch()) + + +def _make_handler(rollout_worker, samples_queue, metrics_queue): + # Only used in remote inference mode. We must create a new rollout worker + # then since the original worker doesn't have the env properly wrapped in + # an ExternalEnv interface. + child_rollout_worker = None + inference_thread = None + lock = threading.Lock() + + def setup_child_rollout_worker(): + nonlocal lock + + with lock: + nonlocal child_rollout_worker + nonlocal inference_thread + + if child_rollout_worker is None: + ( + child_rollout_worker, + inference_thread, + ) = _create_embedded_rollout_worker( + rollout_worker.creation_args(), report_data + ) + child_rollout_worker.set_weights(rollout_worker.get_weights()) + + def report_data(data): + nonlocal child_rollout_worker + + batch = data["samples"] + batch.decompress_if_needed() + samples_queue.append(batch) + # Deque is full -> purge 50% (oldest samples) + if len(samples_queue) == samples_queue.maxlen: + logger.warning( + "PolicyServerInput queue is full! Purging half of the samples (oldest)." + ) + for _ in range(samples_queue.maxlen // 2): + samples_queue.popleft() + for rollout_metric in data["metrics"]: + metrics_queue.put(rollout_metric) + + if child_rollout_worker is not None: + child_rollout_worker.set_weights( + rollout_worker.get_weights(), rollout_worker.get_global_vars() + ) + + class Handler(SimpleHTTPRequestHandler): + def __init__(self, *a, **kw): + super().__init__(*a, **kw) + + def do_POST(self): + content_len = int(self.headers.get("Content-Length"), 0) + raw_body = self.rfile.read(content_len) + parsed_input = pickle.loads(raw_body) + try: + response = self.execute_command(parsed_input) + self.send_response(200) + self.end_headers() + self.wfile.write(pickle.dumps(response)) + except Exception: + self.send_error(500, traceback.format_exc()) + + def execute_command(self, args): + command = args["command"] + response = {} + + # Local inference commands: + if command == Commands.GET_WORKER_ARGS: + logger.info("Sending worker creation args to client.") + response["worker_args"] = rollout_worker.creation_args() + elif command == Commands.GET_WEIGHTS: + logger.info("Sending worker weights to client.") + response["weights"] = rollout_worker.get_weights() + response["global_vars"] = rollout_worker.get_global_vars() + elif command == Commands.REPORT_SAMPLES: + logger.info( + "Got sample batch of size {} from client.".format( + args["samples"].count + ) + ) + report_data(args) + + # Remote inference commands: + elif command == Commands.START_EPISODE: + setup_child_rollout_worker() + assert inference_thread.is_alive() + response["episode_id"] = child_rollout_worker.env.start_episode( + args["episode_id"], args["training_enabled"] + ) + elif command == Commands.GET_ACTION: + assert inference_thread.is_alive() + response["action"] = child_rollout_worker.env.get_action( + args["episode_id"], args["observation"] + ) + elif command == Commands.LOG_ACTION: + assert inference_thread.is_alive() + child_rollout_worker.env.log_action( + args["episode_id"], args["observation"], args["action"] + ) + elif command == Commands.LOG_RETURNS: + assert inference_thread.is_alive() + if args["done"]: + child_rollout_worker.env.log_returns( + args["episode_id"], args["reward"], args["info"], args["done"] + ) + else: + child_rollout_worker.env.log_returns( + args["episode_id"], args["reward"], args["info"] + ) + elif command == Commands.END_EPISODE: + assert inference_thread.is_alive() + child_rollout_worker.env.end_episode( + args["episode_id"], args["observation"] + ) + else: + raise ValueError("Unknown command: {}".format(command)) + return response + + return Handler diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/remote_base_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/remote_base_env.py new file mode 100644 index 0000000000000000000000000000000000000000..9ff6537a9d32935ead0188e921da41c3f7947773 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/remote_base_env.py @@ -0,0 +1,462 @@ +import gymnasium as gym +import logging +from typing import Callable, Dict, List, Optional, Set, Tuple, TYPE_CHECKING + +import ray +from ray.util import log_once +from ray.rllib.env.base_env import BaseEnv, _DUMMY_AGENT_ID, ASYNC_RESET_RETURN +from ray.rllib.utils.annotations import override, OldAPIStack +from ray.rllib.utils.typing import AgentID, EnvID, EnvType, MultiEnvDict + +if TYPE_CHECKING: + from ray.rllib.evaluation.rollout_worker import RolloutWorker + +logger = logging.getLogger(__name__) + + +@OldAPIStack +class RemoteBaseEnv(BaseEnv): + """BaseEnv that executes its sub environments as @ray.remote actors. + + This provides dynamic batching of inference as observations are returned + from the remote simulator actors. Both single and multi-agent child envs + are supported, and envs can be stepped synchronously or asynchronously. + + NOTE: This class implicitly assumes that the remote envs are gym.Env's + + You shouldn't need to instantiate this class directly. It's automatically + inserted when you use the `remote_worker_envs=True` option in your + Algorithm's config. + """ + + def __init__( + self, + make_env: Callable[[int], EnvType], + num_envs: int, + multiagent: bool, + remote_env_batch_wait_ms: int, + existing_envs: Optional[List[ray.actor.ActorHandle]] = None, + worker: Optional["RolloutWorker"] = None, + restart_failed_sub_environments: bool = False, + ): + """Initializes a RemoteVectorEnv instance. + + Args: + make_env: Callable that produces a single (non-vectorized) env, + given the vector env index as only arg. + num_envs: The number of sub-environments to create for the + vectorization. + multiagent: Whether this is a multiagent env or not. + remote_env_batch_wait_ms: Time to wait for (ray.remote) + sub-environments to have new observations available when + polled. Only when none of the sub-environments is ready, + repeat the `ray.wait()` call until at least one sub-env + is ready. Then return only the observations of the ready + sub-environment(s). + existing_envs: Optional list of already created sub-environments. + These will be used as-is and only as many new sub-envs as + necessary (`num_envs - len(existing_envs)`) will be created. + worker: An optional RolloutWorker that owns the env. This is only + used if `remote_worker_envs` is True in your config and the + `on_sub_environment_created` custom callback needs to be + called on each created actor. + restart_failed_sub_environments: If True and any sub-environment (within + a vectorized env) throws any error during env stepping, the + Sampler will try to restart the faulty sub-environment. This is done + without disturbing the other (still intact) sub-environment and without + the RolloutWorker crashing. + """ + + # Could be creating local or remote envs. + self.make_env = make_env + self.num_envs = num_envs + self.multiagent = multiagent + self.poll_timeout = remote_env_batch_wait_ms / 1000 + self.worker = worker + self.restart_failed_sub_environments = restart_failed_sub_environments + + # Already existing env objects (generated by the RolloutWorker). + existing_envs = existing_envs or [] + + # Whether the given `make_env` callable already returns ActorHandles + # (@ray.remote class instances) or not. + self.make_env_creates_actors = False + + self._observation_space = None + self._action_space = None + + # List of ray actor handles (each handle points to one @ray.remote + # sub-environment). + self.actors: Optional[List[ray.actor.ActorHandle]] = None + + # `self.make_env` already produces Actors: Use it directly. + if len(existing_envs) > 0 and isinstance( + existing_envs[0], ray.actor.ActorHandle + ): + self.make_env_creates_actors = True + self.actors = existing_envs + while len(self.actors) < self.num_envs: + self.actors.append(self._make_sub_env(len(self.actors))) + + # `self.make_env` produces gym.Envs (or children thereof, such + # as MultiAgentEnv): Need to auto-wrap it here. The problem with + # this is that custom methods wil get lost. If you would like to + # keep your custom methods in your envs, you should provide the + # env class directly in your config (w/o tune.register_env()), + # such that your class can directly be made a @ray.remote + # (w/o the wrapping via `_Remote[Multi|Single]AgentEnv`). + # Also, if `len(existing_envs) > 0`, we have to throw those away + # as we need to create ray actors here. + else: + self.actors = [self._make_sub_env(i) for i in range(self.num_envs)] + # Utilize existing envs for inferring observation/action spaces. + if len(existing_envs) > 0: + self._observation_space = existing_envs[0].observation_space + self._action_space = existing_envs[0].action_space + # Have to call actors' remote methods to get observation/action spaces. + else: + self._observation_space, self._action_space = ray.get( + [ + self.actors[0].observation_space.remote(), + self.actors[0].action_space.remote(), + ] + ) + + # Dict mapping object refs (return values of @ray.remote calls), + # whose actual values we are waiting for (via ray.wait in + # `self.poll()`) to their corresponding actor handles (the actors + # that created these return values). + # Call `reset()` on all @ray.remote sub-environment actors. + self.pending: Dict[ray.actor.ActorHandle] = { + a.reset.remote(): a for a in self.actors + } + + @override(BaseEnv) + def poll( + self, + ) -> Tuple[ + MultiEnvDict, + MultiEnvDict, + MultiEnvDict, + MultiEnvDict, + MultiEnvDict, + MultiEnvDict, + ]: + + # each keyed by env_id in [0, num_remote_envs) + obs, rewards, terminateds, truncateds, infos = {}, {}, {}, {}, {} + ready = [] + + # Wait for at least 1 env to be ready here. + while not ready: + ready, _ = ray.wait( + list(self.pending), + num_returns=len(self.pending), + timeout=self.poll_timeout, + ) + + # Get and return observations for each of the ready envs + env_ids = set() + for obj_ref in ready: + # Get the corresponding actor handle from our dict and remove the + # object ref (we will call `ray.get()` on it and it will no longer + # be "pending"). + actor = self.pending.pop(obj_ref) + env_id = self.actors.index(actor) + env_ids.add(env_id) + # Get the ready object ref (this may be return value(s) of + # `reset()` or `step()`). + try: + ret = ray.get(obj_ref) + except Exception as e: + # Something happened on the actor during stepping/resetting. + # Restart sub-environment (create new actor; close old one). + if self.restart_failed_sub_environments: + logger.exception(e.args[0]) + self.try_restart(env_id) + # Always return multi-agent data. + # Set the observation to the exception, no rewards, + # terminated[__all__]=True (episode will be discarded anyways), + # no infos. + ret = ( + e, + {}, + {"__all__": True}, + {"__all__": False}, + {}, + ) + # Do not try to restart. Just raise the error. + else: + raise e + + # Our sub-envs are simple Actor-turned gym.Envs or MultiAgentEnvs. + if self.make_env_creates_actors: + rew, terminated, truncated, info = None, None, None, None + if self.multiagent: + if isinstance(ret, tuple): + # Gym >= 0.26: `step()` result: Obs, reward, terminated, + # truncated, info. + if len(ret) == 5: + ob, rew, terminated, truncated, info = ret + # Gym >= 0.26: `reset()` result: Obs and infos. + elif len(ret) == 2: + ob = ret[0] + info = ret[1] + # Gym < 0.26? Something went wrong. + else: + raise AssertionError( + "Your gymnasium.Env seems to NOT return the correct " + "number of return values for `step()` (needs to return" + " 5 values: obs, reward, terminated, truncated and " + "info) or `reset()` (needs to return 2 values: obs and " + "info)!" + ) + # Gym < 0.26: `reset()` result: Only obs. + else: + raise AssertionError( + "Your gymnasium.Env seems to only return a single value " + "upon `reset()`! Must return 2 (obs AND infos)." + ) + else: + if isinstance(ret, tuple): + # `step()` result: Obs, reward, terminated, truncated, info. + if len(ret) == 5: + ob = {_DUMMY_AGENT_ID: ret[0]} + rew = {_DUMMY_AGENT_ID: ret[1]} + terminated = {_DUMMY_AGENT_ID: ret[2], "__all__": ret[2]} + truncated = {_DUMMY_AGENT_ID: ret[3], "__all__": ret[3]} + info = {_DUMMY_AGENT_ID: ret[4]} + # `reset()` result: Obs and infos. + elif len(ret) == 2: + ob = {_DUMMY_AGENT_ID: ret[0]} + info = {_DUMMY_AGENT_ID: ret[1]} + # Gym < 0.26? Something went wrong. + else: + raise AssertionError( + "Your gymnasium.Env seems to NOT return the correct " + "number of return values for `step()` (needs to return" + " 5 values: obs, reward, terminated, truncated and " + "info) or `reset()` (needs to return 2 values: obs and " + "info)!" + ) + # Gym < 0.26? + else: + raise AssertionError( + "Your gymnasium.Env seems to only return a single value " + "upon `reset()`! Must return 2 (obs and infos)." + ) + + # If this is a `reset()` return value, we only have the initial + # observations and infos: Set rewards, terminateds, and truncateds to + # dummy values. + if rew is None: + rew = {agent_id: 0 for agent_id in ob.keys()} + terminated = {"__all__": False} + truncated = {"__all__": False} + + # Our sub-envs are auto-wrapped (by `_RemoteSingleAgentEnv` or + # `_RemoteMultiAgentEnv`) and already behave like multi-agent + # envs. + else: + ob, rew, terminated, truncated, info = ret + obs[env_id] = ob + rewards[env_id] = rew + terminateds[env_id] = terminated + truncateds[env_id] = truncated + infos[env_id] = info + + logger.debug(f"Got obs batch for actors {env_ids}") + return obs, rewards, terminateds, truncateds, infos, {} + + @override(BaseEnv) + def send_actions(self, action_dict: MultiEnvDict) -> None: + for env_id, actions in action_dict.items(): + actor = self.actors[env_id] + # `actor` is a simple single-agent (remote) env, e.g. a gym.Env + # that was made a @ray.remote. + if not self.multiagent and self.make_env_creates_actors: + obj_ref = actor.step.remote(actions[_DUMMY_AGENT_ID]) + # `actor` is already a _RemoteSingleAgentEnv or + # _RemoteMultiAgentEnv wrapper + # (handles the multi-agent action_dict automatically). + else: + obj_ref = actor.step.remote(actions) + self.pending[obj_ref] = actor + + @override(BaseEnv) + def try_reset( + self, + env_id: Optional[EnvID] = None, + *, + seed: Optional[int] = None, + options: Optional[dict] = None, + ) -> Tuple[MultiEnvDict, MultiEnvDict]: + actor = self.actors[env_id] + obj_ref = actor.reset.remote(seed=seed, options=options) + + self.pending[obj_ref] = actor + # Because this env type does not support synchronous reset requests (with + # immediate return value), we return ASYNC_RESET_RETURN here to indicate + # that the reset results will be available via the next `poll()` call. + return ASYNC_RESET_RETURN, ASYNC_RESET_RETURN + + @override(BaseEnv) + def try_restart(self, env_id: Optional[EnvID] = None) -> None: + # Try closing down the old (possibly faulty) sub-env, but ignore errors. + try: + # Close the env on the remote side. + self.actors[env_id].close.remote() + except Exception as e: + if log_once("close_sub_env"): + logger.warning( + "Trying to close old and replaced sub-environment (at vector " + f"index={env_id}), but closing resulted in error:\n{e}" + ) + + # Terminate the actor itself to free up its resources. + self.actors[env_id].__ray_terminate__.remote() + + # Re-create a new sub-environment. + self.actors[env_id] = self._make_sub_env(env_id) + + @override(BaseEnv) + def stop(self) -> None: + if self.actors is not None: + for actor in self.actors: + actor.__ray_terminate__.remote() + + @override(BaseEnv) + def get_sub_environments(self, as_dict: bool = False) -> List[EnvType]: + if as_dict: + return dict(enumerate(self.actors)) + return self.actors + + @property + @override(BaseEnv) + def observation_space(self) -> gym.spaces.Dict: + return self._observation_space + + @property + @override(BaseEnv) + def action_space(self) -> gym.Space: + return self._action_space + + def _make_sub_env(self, idx: Optional[int] = None): + """Re-creates a sub-environment at the new index.""" + + # Our `make_env` creates ray actors directly. + if self.make_env_creates_actors: + sub_env = self.make_env(idx) + if self.worker is not None: + self.worker.callbacks.on_sub_environment_created( + worker=self.worker, + sub_environment=self.actors[idx], + env_context=self.worker.env_context.copy_with_overrides( + vector_index=idx + ), + ) + + # Our `make_env` returns actual envs -> Have to convert them into actors + # using our utility wrapper classes. + else: + + def make_remote_env(i): + logger.info("Launching env {} in remote actor".format(i)) + if self.multiagent: + sub_env = _RemoteMultiAgentEnv.remote(self.make_env, i) + else: + sub_env = _RemoteSingleAgentEnv.remote(self.make_env, i) + + if self.worker is not None: + self.worker.callbacks.on_sub_environment_created( + worker=self.worker, + sub_environment=sub_env, + env_context=self.worker.env_context.copy_with_overrides( + vector_index=i + ), + ) + + return sub_env + + sub_env = make_remote_env(idx) + + return sub_env + + @override(BaseEnv) + def get_agent_ids(self) -> Set[AgentID]: + if self.multiagent: + return ray.get(self.actors[0].get_agent_ids.remote()) + else: + return {_DUMMY_AGENT_ID} + + +@ray.remote(num_cpus=0) +class _RemoteMultiAgentEnv: + """Wrapper class for making a multi-agent env a remote actor.""" + + def __init__(self, make_env, i): + self.env = make_env(i) + self.agent_ids = set() + + def reset(self, *, seed: Optional[int] = None, options: Optional[dict] = None): + obs, info = self.env.reset(seed=seed, options=options) + + # each keyed by agent_id in the env + rew = {} + for agent_id in obs.keys(): + self.agent_ids.add(agent_id) + rew[agent_id] = 0.0 + terminated = {"__all__": False} + truncated = {"__all__": False} + return obs, rew, terminated, truncated, info + + def step(self, action_dict): + return self.env.step(action_dict) + + # Defining these 2 functions that way this information can be queried + # with a call to ray.get(). + def observation_space(self): + return self.env.observation_space + + def action_space(self): + return self.env.action_space + + def get_agent_ids(self) -> Set[AgentID]: + return self.agent_ids + + +@ray.remote(num_cpus=0) +class _RemoteSingleAgentEnv: + """Wrapper class for making a gym env a remote actor.""" + + def __init__(self, make_env, i): + self.env = make_env(i) + + def reset(self, *, seed: Optional[int] = None, options: Optional[dict] = None): + obs_and_info = self.env.reset(seed=seed, options=options) + + obs = {_DUMMY_AGENT_ID: obs_and_info[0]} + info = {_DUMMY_AGENT_ID: obs_and_info[1]} + + rew = {_DUMMY_AGENT_ID: 0.0} + terminated = {"__all__": False} + truncated = {"__all__": False} + return obs, rew, terminated, truncated, info + + def step(self, action): + results = self.env.step(action[_DUMMY_AGENT_ID]) + + obs, rew, terminated, truncated, info = [{_DUMMY_AGENT_ID: x} for x in results] + + terminated["__all__"] = terminated[_DUMMY_AGENT_ID] + truncated["__all__"] = truncated[_DUMMY_AGENT_ID] + + return obs, rew, terminated, truncated, info + + # Defining these 2 functions that way this information can be queried + # with a call to ray.get(). + def observation_space(self): + return self.env.observation_space + + def action_space(self): + return self.env.action_space diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/single_agent_env_runner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/single_agent_env_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..05db62932cc31db3954e4bf2cec020c3bbf964c8 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/single_agent_env_runner.py @@ -0,0 +1,894 @@ +from collections import defaultdict +from functools import partial +import logging +import math +import time +from typing import Collection, DefaultDict, List, Optional, Union + +import gymnasium as gym +import ray +from gymnasium.wrappers.vector import DictInfoToList + +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig +from ray.rllib.callbacks.callbacks import RLlibCallback +from ray.rllib.callbacks.utils import make_callback +from ray.rllib.core import ( + COMPONENT_ENV_TO_MODULE_CONNECTOR, + COMPONENT_MODULE_TO_ENV_CONNECTOR, + COMPONENT_RL_MODULE, + DEFAULT_AGENT_ID, + DEFAULT_MODULE_ID, +) +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.rl_module import RLModule, RLModuleSpec +from ray.rllib.env import INPUT_ENV_SPACES, INPUT_ENV_SINGLE_SPACES +from ray.rllib.env.env_context import EnvContext +from ray.rllib.env.env_runner import EnvRunner, ENV_STEP_FAILURE +from ray.rllib.env.single_agent_episode import SingleAgentEpisode +from ray.rllib.env.utils import _gym_env_creator +from ray.rllib.utils import force_list +from ray.rllib.utils.annotations import override +from ray.rllib.utils.checkpoints import Checkpointable +from ray.rllib.utils.deprecation import Deprecated +from ray.rllib.utils.framework import get_device +from ray.rllib.utils.metrics import ( + ENV_TO_MODULE_CONNECTOR, + EPISODE_DURATION_SEC_MEAN, + EPISODE_LEN_MAX, + EPISODE_LEN_MEAN, + EPISODE_LEN_MIN, + EPISODE_RETURN_MAX, + EPISODE_RETURN_MEAN, + EPISODE_RETURN_MIN, + MODULE_TO_ENV_CONNECTOR, + NUM_AGENT_STEPS_SAMPLED, + NUM_AGENT_STEPS_SAMPLED_LIFETIME, + NUM_ENV_STEPS_SAMPLED, + NUM_ENV_STEPS_SAMPLED_LIFETIME, + NUM_EPISODES, + NUM_EPISODES_LIFETIME, + NUM_MODULE_STEPS_SAMPLED, + NUM_MODULE_STEPS_SAMPLED_LIFETIME, + RLMODULE_INFERENCE_TIMER, + SAMPLE_TIMER, + TIME_BETWEEN_SAMPLING, + WEIGHTS_SEQ_NO, +) +from ray.rllib.utils.spaces.space_utils import unbatch +from ray.rllib.utils.typing import EpisodeID, ResultDict, StateDict +from ray.tune.registry import ENV_CREATOR, _global_registry +from ray.util.annotations import PublicAPI + +logger = logging.getLogger("ray.rllib") + + +# TODO (sven): As soon as RolloutWorker is no longer supported, make `EnvRunner` itself +# a Checkpointable. Currently, only some of its subclasses are Checkpointables. +@PublicAPI(stability="alpha") +class SingleAgentEnvRunner(EnvRunner, Checkpointable): + """The generic environment runner for the single agent case.""" + + @override(EnvRunner) + def __init__(self, *, config: AlgorithmConfig, **kwargs): + """Initializes a SingleAgentEnvRunner instance. + + Args: + config: An `AlgorithmConfig` object containing all settings needed to + build this `EnvRunner` class. + """ + super().__init__(config=config, **kwargs) + + self.tune_trial_id: str = kwargs.get("tune_trial_id") + self.spaces = kwargs.get("spaces", {}) + + # Create our callbacks object. + self._callbacks: List[RLlibCallback] = [ + cls() for cls in force_list(self.config.callbacks_class) + ] + + # Set device. + self._device = get_device( + self.config, + 0 if not self.worker_index else self.config.num_gpus_per_env_runner, + ) + + # Create the vectorized gymnasium env. + self.env: Optional[gym.vector.VectorEnvWrapper] = None + self.num_envs: int = 0 + if ( + self.worker_index is None + or self.worker_index > 0 + or self.config.create_env_on_local_worker + or self.config.num_env_runners == 0 + ): + self.make_env() + + # Create the env-to-module connector pipeline. + self._env_to_module = self.config.build_env_to_module_connector( + env=self.env, spaces=self.spaces, device=self._device + ) + # Cached env-to-module results taken at the end of a `_sample_timesteps()` + # call to make sure the final observation (before an episode cut) gets properly + # processed (and maybe postprocessed and re-stored into the episode). + # For example, if we had a connector that normalizes observations and directly + # re-inserts these new obs back into the episode, the last observation in each + # sample call would NOT be processed, which could be very harmful in cases, + # in which value function bootstrapping of those (truncation) observations is + # required in the learning step. + self._cached_to_module = None + + # Create the RLModule. + self.module: Optional[RLModule] = None + self.make_module() + + # Create the module-to-env connector pipeline. + self._module_to_env = self.config.build_module_to_env_connector( + env=self.env, spaces=self.spaces + ) + + # This should be the default. + self._needs_initial_reset: bool = True + self._episodes: List[Optional[SingleAgentEpisode]] = [ + None for _ in range(self.num_envs) + ] + self._shared_data = None + + self._done_episodes_for_metrics: List[SingleAgentEpisode] = [] + self._ongoing_episodes_for_metrics: DefaultDict[ + EpisodeID, List[SingleAgentEpisode] + ] = defaultdict(list) + self._weights_seq_no: int = 0 + + # Measures the time passed between returning from `sample()` + # and receiving the next `sample()` request from the user. + self._time_after_sampling = None + + @override(EnvRunner) + def sample( + self, + *, + num_timesteps: int = None, + num_episodes: int = None, + explore: bool = None, + random_actions: bool = False, + force_reset: bool = False, + ) -> List[SingleAgentEpisode]: + """Runs and returns a sample (n timesteps or m episodes) on the env(s). + + Args: + num_timesteps: The number of timesteps to sample during this call. + Note that only one of `num_timetseps` or `num_episodes` may be provided. + num_episodes: The number of episodes to sample during this call. + Note that only one of `num_timetseps` or `num_episodes` may be provided. + explore: If True, will use the RLModule's `forward_exploration()` + method to compute actions. If False, will use the RLModule's + `forward_inference()` method. If None (default), will use the `explore` + boolean setting from `self.config` passed into this EnvRunner's + constructor. You can change this setting in your config via + `config.env_runners(explore=True|False)`. + random_actions: If True, actions will be sampled randomly (from the action + space of the environment). If False (default), actions or action + distribution parameters are computed by the RLModule. + force_reset: Whether to force-reset all (vector) environments before + sampling. Useful if you would like to collect a clean slate of new + episodes via this call. Note that when sampling n episodes + (`num_episodes != None`), this is fixed to True. + + Returns: + A list of `SingleAgentEpisode` instances, carrying the sampled data. + """ + if self.env is None: + raise ValueError( + f"{self} doesn't have an env! Can't call `sample()` on it." + ) + + assert not (num_timesteps is not None and num_episodes is not None) + + # Log time between `sample()` requests. + if self._time_after_sampling is not None: + self.metrics.log_value( + key=TIME_BETWEEN_SAMPLING, + value=time.perf_counter() - self._time_after_sampling, + ) + + # Log current weight seq no. + self.metrics.log_value( + key=WEIGHTS_SEQ_NO, + value=self._weights_seq_no, + window=1, + ) + + with self.metrics.log_time(SAMPLE_TIMER): + # If no execution details are provided, use the config to try to infer the + # desired timesteps/episodes to sample and exploration behavior. + if explore is None: + explore = self.config.explore + if ( + num_timesteps is None + and num_episodes is None + and self.config.batch_mode == "truncate_episodes" + ): + num_timesteps = ( + self.config.get_rollout_fragment_length(self.worker_index) + * self.num_envs + ) + + # Sample n timesteps. + if num_timesteps is not None: + samples = self._sample( + num_timesteps=num_timesteps, + explore=explore, + random_actions=random_actions, + force_reset=force_reset, + ) + # Sample m episodes. + elif num_episodes is not None: + samples = self._sample( + num_episodes=num_episodes, + explore=explore, + random_actions=random_actions, + ) + # For complete episodes mode, sample as long as the number of timesteps + # done is smaller than the `train_batch_size`. + else: + samples = self._sample( + num_episodes=self.num_envs, + explore=explore, + random_actions=random_actions, + ) + + # Make the `on_sample_end` callback. + make_callback( + "on_sample_end", + callbacks_objects=self._callbacks, + callbacks_functions=self.config.callbacks_on_sample_end, + kwargs=dict( + env_runner=self, + metrics_logger=self.metrics, + samples=samples, + ), + ) + + self._time_after_sampling = time.perf_counter() + + return samples + + def _sample( + self, + *, + num_timesteps: Optional[int] = None, + num_episodes: Optional[int] = None, + explore: bool, + random_actions: bool = False, + force_reset: bool = False, + ) -> List[SingleAgentEpisode]: + """Helper method to sample n timesteps or m episodes.""" + + done_episodes_to_return: List[SingleAgentEpisode] = [] + + # Have to reset the env (on all vector sub_envs). + if force_reset or num_episodes is not None or self._needs_initial_reset: + episodes = self._episodes = [None for _ in range(self.num_envs)] + shared_data = self._shared_data = {} + self._reset_envs(episodes, shared_data, explore) + # We just reset the env. Don't have to force this again in the next + # call to `self._sample_timesteps()`. + self._needs_initial_reset = False + else: + episodes = self._episodes + shared_data = self._shared_data + + if num_episodes is not None: + self._needs_initial_reset = True + + # Loop through `num_timesteps` timesteps or `num_episodes` episodes. + ts = 0 + eps = 0 + while ( + (ts < num_timesteps) if num_timesteps is not None else (eps < num_episodes) + ): + # Act randomly. + if random_actions: + to_env = { + Columns.ACTIONS: self.env.action_space.sample(), + } + # Compute an action using the RLModule. + else: + # Env-to-module connector (already cached). + to_module = self._cached_to_module + assert to_module is not None + self._cached_to_module = None + + # RLModule forward pass: Explore or not. + if explore: + # Global env steps sampled are (roughly) this EnvRunner's lifetime + # count times the number of env runners in the algo. + global_env_steps_lifetime = ( + self.metrics.peek(NUM_ENV_STEPS_SAMPLED_LIFETIME, default=0) + + ts + ) * (self.config.num_env_runners or 1) + with self.metrics.log_time(RLMODULE_INFERENCE_TIMER): + to_env = self.module.forward_exploration( + to_module, t=global_env_steps_lifetime + ) + else: + with self.metrics.log_time(RLMODULE_INFERENCE_TIMER): + to_env = self.module.forward_inference(to_module) + + # Module-to-env connector. + to_env = self._module_to_env( + rl_module=self.module, + batch=to_env, + episodes=episodes, + explore=explore, + shared_data=shared_data, + metrics=self.metrics, + metrics_prefix_key=(MODULE_TO_ENV_CONNECTOR,), + ) + + # Extract the (vectorized) actions (to be sent to the env) from the + # module/connector output. Note that these actions are fully ready (e.g. + # already unsquashed/clipped) to be sent to the environment) and might not + # be identical to the actions produced by the RLModule/distribution, which + # are the ones stored permanently in the episode objects. + actions = to_env.pop(Columns.ACTIONS) + actions_for_env = to_env.pop(Columns.ACTIONS_FOR_ENV, actions) + # Try stepping the environment. + results = self._try_env_step(actions_for_env) + if results == ENV_STEP_FAILURE: + return self._sample( + num_timesteps=num_timesteps, + num_episodes=num_episodes, + explore=explore, + random_actions=random_actions, + force_reset=True, + ) + observations, rewards, terminateds, truncateds, infos = results + observations, actions = unbatch(observations), unbatch(actions) + + call_on_episode_start = set() + for env_index in range(self.num_envs): + extra_model_output = {k: v[env_index] for k, v in to_env.items()} + extra_model_output[WEIGHTS_SEQ_NO] = self._weights_seq_no + + # Episode has no data in it yet -> Was just reset and needs to be called + # with its `add_env_reset()` method. + if not self._episodes[env_index].is_reset: + episodes[env_index].add_env_reset( + observation=observations[env_index], + infos=infos[env_index], + ) + call_on_episode_start.add(env_index) + + # Call `add_env_step()` method on episode. + else: + # Only increase ts when we actually stepped (not reset'd as a reset + # does not count as a timestep). + ts += 1 + episodes[env_index].add_env_step( + observation=observations[env_index], + action=actions[env_index], + reward=rewards[env_index], + infos=infos[env_index], + terminated=terminateds[env_index], + truncated=truncateds[env_index], + extra_model_outputs=extra_model_output, + ) + + # Env-to-module connector pass (cache results as we will do the RLModule + # forward pass only in the next `while`-iteration. + if self.module is not None: + self._cached_to_module = self._env_to_module( + episodes=episodes, + explore=explore, + rl_module=self.module, + shared_data=shared_data, + metrics=self.metrics, + metrics_prefix_key=(ENV_TO_MODULE_CONNECTOR,), + ) + + for env_index in range(self.num_envs): + # Call `on_episode_start()` callback (always after reset). + if env_index in call_on_episode_start: + self._make_on_episode_callback( + "on_episode_start", env_index, episodes + ) + # Make the `on_episode_step` callbacks. + else: + self._make_on_episode_callback( + "on_episode_step", env_index, episodes + ) + + # Episode is done. + if episodes[env_index].is_done: + eps += 1 + + # Make the `on_episode_end` callbacks (before finalizing the episode + # object). + self._make_on_episode_callback( + "on_episode_end", env_index, episodes + ) + + # Numpy'ize the episode. + if self.config.episodes_to_numpy: + # Any possibly compress observations. + done_episodes_to_return.append(episodes[env_index].to_numpy()) + # Leave episode as lists of individual (obs, action, etc..) items. + else: + done_episodes_to_return.append(episodes[env_index]) + + # Also early-out if we reach the number of episodes within this + # for-loop. + if eps == num_episodes: + break + + # Create a new episode object with no data in it and execute + # `on_episode_created` callback (before the `env.reset()` call). + self._new_episode(env_index, episodes) + + # Return done episodes ... + self._done_episodes_for_metrics.extend(done_episodes_to_return) + # ... and all ongoing episode chunks. + + # Also, make sure we start new episode chunks (continuing the ongoing episodes + # from the to-be-returned chunks). + ongoing_episodes_to_return = [] + # Only if we are doing individual timesteps: We have to maybe cut an ongoing + # episode and continue building it on the next call to `sample()`. + if num_timesteps is not None: + ongoing_episodes_continuations = [ + eps.cut(len_lookback_buffer=self.config.episode_lookback_horizon) + for eps in self._episodes + ] + + for eps in self._episodes: + # Just started Episodes do not have to be returned. There is no data + # in them anyway. + if eps.t == 0: + continue + eps.validate() + self._ongoing_episodes_for_metrics[eps.id_].append(eps) + + # Numpy'ize the episode. + if self.config.episodes_to_numpy: + # Any possibly compress observations. + ongoing_episodes_to_return.append(eps.to_numpy()) + # Leave episode as lists of individual (obs, action, etc..) items. + else: + ongoing_episodes_to_return.append(eps) + + # Continue collecting into the cut Episode chunks. + self._episodes = ongoing_episodes_continuations + + self._increase_sampled_metrics(ts, len(done_episodes_to_return)) + + # Return collected episode data. + return done_episodes_to_return + ongoing_episodes_to_return + + @override(EnvRunner) + def get_spaces(self): + if self.env is None: + return self.spaces + return { + INPUT_ENV_SPACES: (self.env.observation_space, self.env.action_space), + INPUT_ENV_SINGLE_SPACES: ( + self.env.single_observation_space, + self.env.single_action_space, + ), + DEFAULT_MODULE_ID: ( + self._env_to_module.observation_space, + self.env.single_action_space, + ), + } + + @override(EnvRunner) + def get_metrics(self) -> ResultDict: + # Compute per-episode metrics (only on already completed episodes). + for eps in self._done_episodes_for_metrics: + assert eps.is_done + episode_length = len(eps) + episode_return = eps.get_return() + episode_duration_s = eps.get_duration_s() + # Don't forget about the already returned chunks of this episode. + if eps.id_ in self._ongoing_episodes_for_metrics: + for eps2 in self._ongoing_episodes_for_metrics[eps.id_]: + episode_length += len(eps2) + episode_return += eps2.get_return() + episode_duration_s += eps2.get_duration_s() + del self._ongoing_episodes_for_metrics[eps.id_] + + self._log_episode_metrics( + episode_length, episode_return, episode_duration_s + ) + + # Now that we have logged everything, clear cache of done episodes. + self._done_episodes_for_metrics.clear() + + # Return reduced metrics. + return self.metrics.reduce() + + @override(Checkpointable) + def get_state( + self, + components: Optional[Union[str, Collection[str]]] = None, + *, + not_components: Optional[Union[str, Collection[str]]] = None, + **kwargs, + ) -> StateDict: + state = { + NUM_ENV_STEPS_SAMPLED_LIFETIME: ( + self.metrics.peek(NUM_ENV_STEPS_SAMPLED_LIFETIME, default=0) + ), + } + + if self._check_component(COMPONENT_RL_MODULE, components, not_components): + state[COMPONENT_RL_MODULE] = self.module.get_state( + components=self._get_subcomponents(COMPONENT_RL_MODULE, components), + not_components=self._get_subcomponents( + COMPONENT_RL_MODULE, not_components + ), + **kwargs, + ) + state[WEIGHTS_SEQ_NO] = self._weights_seq_no + if self._check_component( + COMPONENT_ENV_TO_MODULE_CONNECTOR, components, not_components + ): + state[COMPONENT_ENV_TO_MODULE_CONNECTOR] = self._env_to_module.get_state() + if self._check_component( + COMPONENT_MODULE_TO_ENV_CONNECTOR, components, not_components + ): + state[COMPONENT_MODULE_TO_ENV_CONNECTOR] = self._module_to_env.get_state() + + return state + + @override(Checkpointable) + def set_state(self, state: StateDict) -> None: + if COMPONENT_ENV_TO_MODULE_CONNECTOR in state: + self._env_to_module.set_state(state[COMPONENT_ENV_TO_MODULE_CONNECTOR]) + if COMPONENT_MODULE_TO_ENV_CONNECTOR in state: + self._module_to_env.set_state(state[COMPONENT_MODULE_TO_ENV_CONNECTOR]) + + # Update the RLModule state. + if COMPONENT_RL_MODULE in state: + # A missing value for WEIGHTS_SEQ_NO or a value of 0 means: Force the + # update. + weights_seq_no = state.get(WEIGHTS_SEQ_NO, 0) + + # Only update the weigths, if this is the first synchronization or + # if the weights of this `EnvRunner` lacks behind the actual ones. + if weights_seq_no == 0 or self._weights_seq_no < weights_seq_no: + rl_module_state = state[COMPONENT_RL_MODULE] + if isinstance(rl_module_state, ray.ObjectRef): + rl_module_state = ray.get(rl_module_state) + if ( + isinstance(rl_module_state, dict) + and DEFAULT_MODULE_ID in rl_module_state + ): + rl_module_state = rl_module_state[DEFAULT_MODULE_ID] + self.module.set_state(rl_module_state) + + # Update our weights_seq_no, if the new one is > 0. + if weights_seq_no > 0: + self._weights_seq_no = weights_seq_no + + # Update our lifetime counters. + if NUM_ENV_STEPS_SAMPLED_LIFETIME in state: + self.metrics.set_value( + key=NUM_ENV_STEPS_SAMPLED_LIFETIME, + value=state[NUM_ENV_STEPS_SAMPLED_LIFETIME], + reduce="sum", + with_throughput=True, + ) + + @override(Checkpointable) + def get_ctor_args_and_kwargs(self): + return ( + (), # *args + {"config": self.config}, # **kwargs + ) + + @override(Checkpointable) + def get_metadata(self): + metadata = Checkpointable.get_metadata(self) + metadata.update( + { + # TODO (sven): Maybe add serialized (JSON-writable) config here? + } + ) + return metadata + + @override(Checkpointable) + def get_checkpointable_components(self): + return [ + (COMPONENT_RL_MODULE, self.module), + (COMPONENT_ENV_TO_MODULE_CONNECTOR, self._env_to_module), + (COMPONENT_MODULE_TO_ENV_CONNECTOR, self._module_to_env), + ] + + @override(EnvRunner) + def assert_healthy(self): + """Checks that self.__init__() has been completed properly. + + Ensures that the instances has a `MultiRLModule` and an + environment defined. + + Raises: + AssertionError: If the EnvRunner Actor has NOT been properly initialized. + """ + # Make sure, we have built our gym.vector.Env and RLModule properly. + assert self.env and hasattr(self, "module") + + @override(EnvRunner) + def make_env(self) -> None: + """Creates a vectorized gymnasium env and stores it in `self.env`. + + Note that users can change the EnvRunner's config (e.g. change + `self.config.env_config`) and then call this method to create new environments + with the updated configuration. + """ + # If an env already exists, try closing it first (to allow it to properly + # cleanup). + if self.env is not None: + try: + self.env.close() + except Exception as e: + logger.warning( + "Tried closing the existing env, but failed with error: " + f"{e.args[0]}" + ) + + env_ctx = self.config.env_config + if not isinstance(env_ctx, EnvContext): + env_ctx = EnvContext( + env_ctx, + worker_index=self.worker_index, + num_workers=self.num_workers, + remote=self.config.remote_worker_envs, + ) + + # No env provided -> Error. + if not self.config.env: + raise ValueError( + "`config.env` is not provided! You should provide a valid environment " + "to your config through `config.environment([env descriptor e.g. " + "'CartPole-v1'])`." + ) + # Register env for the local context. + # Note, `gym.register` has to be called on each worker. + elif isinstance(self.config.env, str) and _global_registry.contains( + ENV_CREATOR, self.config.env + ): + entry_point = partial( + _global_registry.get(ENV_CREATOR, self.config.env), + env_ctx, + ) + else: + entry_point = partial( + _gym_env_creator, + env_descriptor=self.config.env, + env_context=env_ctx, + ) + gym.register("rllib-single-agent-env-v0", entry_point=entry_point) + vectorize_mode = self.config.gym_env_vectorize_mode + + self.env = DictInfoToList( + gym.make_vec( + "rllib-single-agent-env-v0", + num_envs=self.config.num_envs_per_env_runner, + vectorization_mode=( + vectorize_mode + if isinstance(vectorize_mode, gym.envs.registration.VectorizeMode) + else gym.envs.registration.VectorizeMode(vectorize_mode.lower()) + ), + ) + ) + + self.num_envs: int = self.env.num_envs + assert self.num_envs == self.config.num_envs_per_env_runner + + # Set the flag to reset all envs upon the next `sample()` call. + self._needs_initial_reset = True + + # Call the `on_environment_created` callback. + make_callback( + "on_environment_created", + callbacks_objects=self._callbacks, + callbacks_functions=self.config.callbacks_on_environment_created, + kwargs=dict( + env_runner=self, + metrics_logger=self.metrics, + env=self.env.unwrapped, + env_context=env_ctx, + ), + ) + + @override(EnvRunner) + def make_module(self): + env = self.env.unwrapped if self.env is not None else None + try: + module_spec: RLModuleSpec = self.config.get_rl_module_spec( + env=env, spaces=self.get_spaces(), inference_only=True + ) + # Build the module from its spec. + self.module = module_spec.build() + + # Move the RLModule to our device. + # TODO (sven): In order to make this framework-agnostic, we should maybe + # make the RLModule.build() method accept a device OR create an additional + # `RLModule.to()` override. + self.module.to(self._device) + + # If `AlgorithmConfig.get_rl_module_spec()` is not implemented, this env runner + # will not have an RLModule, but might still be usable with random actions. + except NotImplementedError: + self.module = None + + @override(EnvRunner) + def stop(self): + # Close our env object via gymnasium's API. + if self.env is not None: + self.env.close() + + def _reset_envs(self, episodes, shared_data, explore): + # Create n new episodes and make the `on_episode_created` callbacks. + for env_index in range(self.num_envs): + self._new_episode(env_index, episodes) + + # Erase all cached ongoing episodes (these will never be completed and + # would thus never be returned/cleaned by `get_metrics` and cause a memory + # leak). + self._ongoing_episodes_for_metrics.clear() + + # Try resetting the environment. + observations, infos = self._try_env_reset( + # Only seed (if seed provided) upon initial reset. + seed=self._seed if self._needs_initial_reset else None, + # TODO (sven): Support options? + options=None, + ) + observations = unbatch(observations) + + # Set initial obs and infos in the episodes. + for env_index in range(self.num_envs): + episodes[env_index].add_env_reset( + observation=observations[env_index], + infos=infos[env_index], + ) + + # Run the env-to-module connector to make sure the reset-obs/infos have + # properly been processed (if applicable). + self._cached_to_module = None + if self.module: + self._cached_to_module = self._env_to_module( + rl_module=self.module, + episodes=episodes, + explore=explore, + shared_data=shared_data, + metrics=self.metrics, + metrics_prefix_key=(ENV_TO_MODULE_CONNECTOR,), + ) + + # Call `on_episode_start()` callbacks (always after reset). + for env_index in range(self.num_envs): + self._make_on_episode_callback("on_episode_start", env_index, episodes) + + def _new_episode(self, env_index, episodes=None): + episodes = episodes if episodes is not None else self._episodes + episodes[env_index] = SingleAgentEpisode( + observation_space=self.env.single_observation_space, + action_space=self.env.single_action_space, + ) + self._make_on_episode_callback("on_episode_created", env_index, episodes) + + def _make_on_episode_callback( + self, which: str, idx: int, episodes: List[SingleAgentEpisode] + ): + kwargs = dict( + episode=episodes[idx], + env_runner=self, + metrics_logger=self.metrics, + env=self.env.unwrapped, + rl_module=self.module, + env_index=idx, + ) + if which == "on_episode_end": + kwargs["prev_episode_chunks"] = self._ongoing_episodes_for_metrics[ + episodes[idx].id_ + ] + + make_callback( + which, + callbacks_objects=self._callbacks, + callbacks_functions=getattr(self.config, f"callbacks_{which}"), + kwargs=kwargs, + ) + + def _increase_sampled_metrics(self, num_steps, num_episodes_completed): + # Per sample cycle stats. + self.metrics.log_value( + NUM_ENV_STEPS_SAMPLED, num_steps, reduce="sum", clear_on_reduce=True + ) + self.metrics.log_value( + (NUM_AGENT_STEPS_SAMPLED, DEFAULT_AGENT_ID), + num_steps, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (NUM_MODULE_STEPS_SAMPLED, DEFAULT_MODULE_ID), + num_steps, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + NUM_EPISODES, + num_episodes_completed, + reduce="sum", + clear_on_reduce=True, + ) + # Lifetime stats. + self.metrics.log_value( + NUM_ENV_STEPS_SAMPLED_LIFETIME, + num_steps, + reduce="sum", + with_throughput=True, + ) + self.metrics.log_value( + (NUM_AGENT_STEPS_SAMPLED_LIFETIME, DEFAULT_AGENT_ID), + num_steps, + reduce="sum", + ) + self.metrics.log_value( + (NUM_MODULE_STEPS_SAMPLED_LIFETIME, DEFAULT_MODULE_ID), + num_steps, + reduce="sum", + ) + self.metrics.log_value( + NUM_EPISODES_LIFETIME, + num_episodes_completed, + reduce="sum", + ) + return num_steps + + def _log_episode_metrics(self, length, ret, sec): + # Log general episode metrics. + # Use the configured window, but factor in the parallelism of the EnvRunners. + # As a result, we only log the last `window / num_env_runners` steps here, + # b/c everything gets parallel-merged in the Algorithm process. + win = max( + 1, + int( + math.ceil( + self.config.metrics_num_episodes_for_smoothing + / (self.config.num_env_runners or 1) + ) + ), + ) + self.metrics.log_value(EPISODE_LEN_MEAN, length, window=win) + self.metrics.log_value(EPISODE_RETURN_MEAN, ret, window=win) + self.metrics.log_value(EPISODE_DURATION_SEC_MEAN, sec, window=win) + # Per-agent returns. + self.metrics.log_value( + ("agent_episode_return_mean", DEFAULT_AGENT_ID), ret, window=win + ) + # Per-RLModule returns. + self.metrics.log_value( + ("module_episode_return_mean", DEFAULT_MODULE_ID), ret, window=win + ) + + # For some metrics, log min/max as well. + self.metrics.log_value(EPISODE_LEN_MIN, length, reduce="min", window=win) + self.metrics.log_value(EPISODE_RETURN_MIN, ret, reduce="min", window=win) + self.metrics.log_value(EPISODE_LEN_MAX, length, reduce="max", window=win) + self.metrics.log_value(EPISODE_RETURN_MAX, ret, reduce="max", window=win) + + @Deprecated( + new="SingleAgentEnvRunner.get_state(components='rl_module')", + error=True, + ) + def get_weights(self, *args, **kwargs): + pass + + @Deprecated(new="SingleAgentEnvRunner.set_state()", error=True) + def set_weights(self, *args, **kwargs): + pass diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/single_agent_episode.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/single_agent_episode.py new file mode 100644 index 0000000000000000000000000000000000000000..7056ff5c43b394674f59e0cdf332fa53dc165cca --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/single_agent_episode.py @@ -0,0 +1,1822 @@ +from collections import defaultdict +import copy +import functools +import numpy as np +import time +import uuid + +import gymnasium as gym +from gymnasium.core import ActType, ObsType +from typing import Any, Dict, List, Optional, SupportsFloat, Union + +from ray.rllib.core.columns import Columns +from ray.rllib.env.utils.infinite_lookback_buffer import InfiniteLookbackBuffer +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.serialization import gym_space_from_dict, gym_space_to_dict +from ray.rllib.utils.deprecation import Deprecated +from ray.rllib.utils.typing import AgentID, ModuleID +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class SingleAgentEpisode: + """A class representing RL environment episodes for individual agents. + + SingleAgentEpisode stores observations, info dicts, actions, rewards, and all + module outputs (e.g. state outs, action logp, etc..) for an individual agent within + some single-agent or multi-agent environment. + The two main APIs to add data to an ongoing episode are the `add_env_reset()` + and `add_env_step()` methods, which should be called passing the outputs of the + respective gym.Env API calls: `env.reset()` and `env.step()`. + + A SingleAgentEpisode might also only represent a chunk of an episode, which is + useful for cases, in which partial (non-complete episode) sampling is performed + and collected episode data has to be returned before the actual gym.Env episode has + finished (see `SingleAgentEpisode.cut()`). In order to still maintain visibility + onto past experiences within such a "cut" episode, SingleAgentEpisode instances + can have a "lookback buffer" of n timesteps at their beginning (left side), which + solely exists for the purpose of compiling extra data (e.g. "prev. reward"), but + is not considered part of the finished/packaged episode (b/c the data in the + lookback buffer is already part of a previous episode chunk). + + Powerful getter methods, such as `get_observations()` help collect different types + of data from the episode at individual time indices or time ranges, including the + "lookback buffer" range described above. For example, to extract the last 4 rewards + of an ongoing episode, one can call `self.get_rewards(slice(-4, None))` or + `self.rewards[-4:]`. This would work, even if the ongoing SingleAgentEpisode is + a continuation chunk from a much earlier started episode, as long as it has a + lookback buffer size of sufficient size. + + Examples: + + .. testcode:: + + import gymnasium as gym + import numpy as np + + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + + # Construct a new episode (without any data in it yet). + episode = SingleAgentEpisode() + assert len(episode) == 0 + + # Fill the episode with some data (10 timesteps). + env = gym.make("CartPole-v1") + obs, infos = env.reset() + episode.add_env_reset(obs, infos) + + # Even with the initial obs/infos, the episode is still considered len=0. + assert len(episode) == 0 + for _ in range(5): + action = env.action_space.sample() + obs, reward, term, trunc, infos = env.step(action) + episode.add_env_step( + observation=obs, + action=action, + reward=reward, + terminated=term, + truncated=trunc, + infos=infos, + ) + assert len(episode) == 5 + + # We can now access information from the episode via the getter APIs. + + # Get the last 3 rewards (in a batch of size 3). + episode.get_rewards(slice(-3, None)) # same as `episode.rewards[-3:]` + + # Get the most recent action (single item, not batched). + # This works regardless of the action space or whether the episode has + # been numpy'ized or not (see below). + episode.get_actions(-1) # same as episode.actions[-1] + + # Looking back from ts=1, get the previous 4 rewards AND fill with 0.0 + # in case we go over the beginning (ts=0). So we would expect + # [0.0, 0.0, 0.0, r0] to be returned here, where r0 is the very first received + # reward in the episode: + episode.get_rewards(slice(-4, 0), neg_index_as_lookback=True, fill=0.0) + + # Note the use of fill=0.0 here (fill everything that's out of range with this + # value) AND the argument `neg_index_as_lookback=True`, which interprets + # negative indices as being left of ts=0 (e.g. -1 being the timestep before + # ts=0). + + # Assuming we had a complex action space (nested gym.spaces.Dict) with one or + # more elements being Discrete or MultiDiscrete spaces: + # 1) The `fill=...` argument would still work, filling all spaces (Boxes, + # Discrete) with that provided value. + # 2) Setting the flag `one_hot_discrete=True` would convert those discrete + # sub-components automatically into one-hot (or multi-one-hot) tensors. + # This simplifies the task of having to provide the previous 4 (nested and + # partially discrete/multi-discrete) actions for each timestep within a training + # batch, thereby filling timesteps before the episode started with 0.0s and + # one-hot'ing the discrete/multi-discrete components in these actions: + episode = SingleAgentEpisode(action_space=gym.spaces.Dict({ + "a": gym.spaces.Discrete(3), + "b": gym.spaces.MultiDiscrete([2, 3]), + "c": gym.spaces.Box(-1.0, 1.0, (2,)), + })) + + # ... fill episode with data ... + episode.add_env_reset(observation=0) + # ... from a few steps. + episode.add_env_step( + observation=1, + action={"a":0, "b":np.array([1, 2]), "c":np.array([.5, -.5], np.float32)}, + reward=1.0, + ) + + # In your connector + prev_4_a = [] + # Note here that len(episode) does NOT include the lookback buffer. + for ts in range(len(episode)): + prev_4_a.append( + episode.get_actions( + indices=slice(ts - 4, ts), + # Make sure negative indices are interpreted as + # "into lookback buffer" + neg_index_as_lookback=True, + # Zero-out everything even further before the lookback buffer. + fill=0.0, + # Take care of discrete components (get ready as NN input). + one_hot_discrete=True, + ) + ) + + # Finally, convert from list of batch items to a struct (same as action space) + # of batched (numpy) arrays, in which all leafs have B==len(prev_4_a). + from ray.rllib.utils.spaces.space_utils import batch + + prev_4_actions_col = batch(prev_4_a) + """ + + __slots__ = ( + "actions", + "agent_id", + "extra_model_outputs", + "id_", + "infos", + "is_terminated", + "is_truncated", + "module_id", + "multi_agent_episode_id", + "observations", + "rewards", + "t", + "t_started", + "_action_space", + "_last_added_observation", + "_last_added_infos", + "_last_step_time", + "_observation_space", + "_start_time", + "_custom_data", + ) + + def __init__( + self, + id_: Optional[str] = None, + *, + observations: Optional[Union[List[ObsType], InfiniteLookbackBuffer]] = None, + observation_space: Optional[gym.Space] = None, + infos: Optional[Union[List[Dict], InfiniteLookbackBuffer]] = None, + actions: Optional[Union[List[ActType], InfiniteLookbackBuffer]] = None, + action_space: Optional[gym.Space] = None, + rewards: Optional[Union[List[SupportsFloat], InfiniteLookbackBuffer]] = None, + terminated: bool = False, + truncated: bool = False, + extra_model_outputs: Optional[Dict[str, Any]] = None, + t_started: Optional[int] = None, + len_lookback_buffer: Union[int, str] = "auto", + agent_id: Optional[AgentID] = None, + module_id: Optional[ModuleID] = None, + multi_agent_episode_id: Optional[int] = None, + ): + """Initializes a SingleAgentEpisode instance. + + This constructor can be called with or without already sampled data, part of + which might then go into the lookback buffer. + + Args: + id_: Unique identifier for this episode. If no ID is provided the + constructor generates a unique hexadecimal code for the id. + observations: Either a list of individual observations from a sampling or + an already instantiated `InfiniteLookbackBuffer` object (possibly + with observation data in it). If a list, will construct the buffer + automatically (given the data and the `len_lookback_buffer` argument). + observation_space: An optional gym.Space, which all individual observations + should abide to. If not None and this SingleAgentEpisode is numpy'ized + (via the `self.to_numpy()` method), and data is appended or set, the new + data will be checked for correctness. + infos: Either a list of individual info dicts from a sampling or + an already instantiated `InfiniteLookbackBuffer` object (possibly + with info dicts in it). If a list, will construct the buffer + automatically (given the data and the `len_lookback_buffer` argument). + actions: Either a list of individual info dicts from a sampling or + an already instantiated `InfiniteLookbackBuffer` object (possibly + with info dict] data in it). If a list, will construct the buffer + automatically (given the data and the `len_lookback_buffer` argument). + action_space: An optional gym.Space, which all individual actions + should abide to. If not None and this SingleAgentEpisode is numpy'ized + (via the `self.to_numpy()` method), and data is appended or set, the new + data will be checked for correctness. + rewards: Either a list of individual rewards from a sampling or + an already instantiated `InfiniteLookbackBuffer` object (possibly + with reward data in it). If a list, will construct the buffer + automatically (given the data and the `len_lookback_buffer` argument). + extra_model_outputs: A dict mapping string keys to either lists of + individual extra model output tensors (e.g. `action_logp` or + `state_outs`) from a sampling or to already instantiated + `InfiniteLookbackBuffer` object (possibly with extra model output data + in it). If mapping is to lists, will construct the buffers automatically + (given the data and the `len_lookback_buffer` argument). + terminated: A boolean indicating, if the episode is already terminated. + truncated: A boolean indicating, if the episode has been truncated. + t_started: Optional. The starting timestep of the episode. The default + is zero. If data is provided, the starting point is from the last + observation onwards (i.e. `t_started = len(observations) - 1`). If + this parameter is provided the episode starts at the provided value. + len_lookback_buffer: The size of the (optional) lookback buffers to keep in + front of this Episode for each type of data (observations, actions, + etc..). If larger 0, will interpret the first `len_lookback_buffer` + items in each type of data as NOT part of this actual + episode chunk, but instead serve as "historical" record that may be + viewed and used to derive new data from. For example, it might be + necessary to have a lookback buffer of four if you would like to do + observation frame stacking and your episode has been cut and you are now + operating on a new chunk (continuing from the cut one). Then, for the + first 3 items, you would have to be able to look back into the old + chunk's data. + If `len_lookback_buffer` is "auto" (default), will interpret all + provided data in the constructor as part of the lookback buffers. + agent_id: An optional AgentID indicating which agent this episode belongs + to. This information is stored under `self.agent_id` and only serves + reference purposes. + module_id: An optional ModuleID indicating which RLModule this episode + belongs to. Normally, this information is obtained by querying an + `agent_to_module_mapping_fn` with a given agent ID. This information + is stored under `self.module_id` and only serves reference purposes. + multi_agent_episode_id: An optional EpisodeID of the encapsulating + `MultiAgentEpisode` that this `SingleAgentEpisode` belongs to. + """ + self.id_ = id_ or uuid.uuid4().hex + + self.agent_id = agent_id + self.module_id = module_id + self.multi_agent_episode_id = multi_agent_episode_id + + # Lookback buffer length is not provided. Interpret already given data as + # lookback buffer lengths for all data types. + len_rewards = len(rewards) if rewards is not None else 0 + if len_lookback_buffer == "auto" or len_lookback_buffer > len_rewards: + len_lookback_buffer = len_rewards + + infos = infos or [{} for _ in range(len(observations or []))] + + # Observations: t0 (initial obs) to T. + self._observation_space = None + if isinstance(observations, InfiniteLookbackBuffer): + self.observations = observations + else: + self.observations = InfiniteLookbackBuffer( + data=observations, + lookback=len_lookback_buffer, + ) + self.observation_space = observation_space + # Infos: t0 (initial info) to T. + if isinstance(infos, InfiniteLookbackBuffer): + self.infos = infos + else: + self.infos = InfiniteLookbackBuffer( + data=infos, + lookback=len_lookback_buffer, + ) + # Actions: t1 to T. + self._action_space = None + if isinstance(actions, InfiniteLookbackBuffer): + self.actions = actions + else: + self.actions = InfiniteLookbackBuffer( + data=actions, + lookback=len_lookback_buffer, + ) + self.action_space = action_space + # Rewards: t1 to T. + if isinstance(rewards, InfiniteLookbackBuffer): + self.rewards = rewards + else: + self.rewards = InfiniteLookbackBuffer( + data=rewards, + lookback=len_lookback_buffer, + space=gym.spaces.Box(float("-inf"), float("inf"), (), np.float32), + ) + + # obs[-1] is the final observation in the episode. + self.is_terminated = terminated + # obs[-1] is the last obs in a truncated-by-the-env episode (there will no more + # observations in following chunks for this episode). + self.is_truncated = truncated + + # Extra model outputs, e.g. `action_dist_input` needed in the batch. + self.extra_model_outputs = {} + for k, v in (extra_model_outputs or {}).items(): + if isinstance(v, InfiniteLookbackBuffer): + self.extra_model_outputs[k] = v + else: + # We cannot use the defaultdict's own constructor here as this would + # auto-set the lookback buffer to 0 (there is no data passed to that + # constructor). Then, when we manually have to set the data property, + # the lookback buffer would still be (incorrectly) 0. + self.extra_model_outputs[k] = InfiniteLookbackBuffer( + data=v, lookback=len_lookback_buffer + ) + + # The (global) timestep when this episode (possibly an episode chunk) started, + # excluding a possible lookback buffer. + self.t_started = t_started or 0 + # The current (global) timestep in the episode (possibly an episode chunk). + self.t = len(self.rewards) + self.t_started + + # Cache for custom data. May be used to store custom metrics from within a + # callback for the ongoing episode (e.g. render images). + self._custom_data = {} + + # Keep timer stats on deltas between steps. + self._start_time = None + self._last_step_time = None + + self._last_added_observation = None + self._last_added_infos = None + + # Validate the episode data thus far. + self.validate() + + def add_env_reset( + self, + observation: ObsType, + infos: Optional[Dict] = None, + ) -> None: + """Adds the initial data (after an `env.reset()`) to the episode. + + This data consists of initial observations and initial infos. + + Args: + observation: The initial observation returned by `env.reset()`. + infos: An (optional) info dict returned by `env.reset()`. + """ + assert not self.is_reset + assert not self.is_done + assert len(self.observations) == 0 + # Assume that this episode is completely empty and has not stepped yet. + # Leave self.t (and self.t_started) at 0. + assert self.t == self.t_started == 0 + + infos = infos or {} + + self.observations.append(observation) + self.infos.append(infos) + + self._last_added_observation = observation + self._last_added_infos = infos + + # Validate our data. + self.validate() + + # Start the timer for this episode. + self._start_time = time.perf_counter() + + def add_env_step( + self, + observation: ObsType, + action: ActType, + reward: SupportsFloat, + infos: Optional[Dict[str, Any]] = None, + *, + terminated: bool = False, + truncated: bool = False, + extra_model_outputs: Optional[Dict[str, Any]] = None, + ) -> None: + """Adds results of an `env.step()` call (including the action) to this episode. + + This data consists of an observation and info dict, an action, a reward, + terminated/truncated flags, and extra model outputs (e.g. action probabilities + or RNN internal state outputs). + + Args: + observation: The next observation received from the environment after(!) + taking `action`. + action: The last action used by the agent during the call to `env.step()`. + reward: The last reward received by the agent after taking `action`. + infos: The last info received from the environment after taking `action`. + terminated: A boolean indicating, if the environment has been + terminated (after taking `action`). + truncated: A boolean indicating, if the environment has been + truncated (after taking `action`). + extra_model_outputs: The last timestep's specific model outputs. + These are normally outputs of an RLModule that were computed along with + `action`, e.g. `action_logp` or `action_dist_inputs`. + """ + # Cannot add data to an already done episode. + assert ( + not self.is_done + ), "The agent is already done: no data can be added to its episode." + + self.observations.append(observation) + self.actions.append(action) + self.rewards.append(reward) + infos = infos or {} + self.infos.append(infos) + self.t += 1 + if extra_model_outputs is not None: + for k, v in extra_model_outputs.items(): + if k not in self.extra_model_outputs: + self.extra_model_outputs[k] = InfiniteLookbackBuffer([v]) + else: + self.extra_model_outputs[k].append(v) + self.is_terminated = terminated + self.is_truncated = truncated + + self._last_added_observation = observation + self._last_added_infos = infos + + # Only check spaces if numpy'ized AND every n timesteps. + if self.is_numpy and self.t % 100: + if self.observation_space is not None: + assert self.observation_space.contains(observation), ( + f"`observation` {observation} does NOT fit SingleAgentEpisode's " + f"observation_space: {self.observation_space}!" + ) + if self.action_space is not None: + assert self.action_space.contains(action), ( + f"`action` {action} does NOT fit SingleAgentEpisode's " + f"action_space: {self.action_space}!" + ) + + # Validate our data. + self.validate() + + # Step time stats. + self._last_step_time = time.perf_counter() + if self._start_time is None: + self._start_time = self._last_step_time + + def validate(self) -> None: + """Validates the episode's data. + + This function ensures that the data stored to a `SingleAgentEpisode` is + in order (e.g. that the correct number of observations, actions, rewards + are there). + """ + assert len(self.observations) == len(self.infos) + if len(self.observations) == 0: + assert len(self.infos) == len(self.rewards) == len(self.actions) == 0 + for k, v in self.extra_model_outputs.items(): + assert len(v) == 0, (k, v, v.data, len(v)) + # Make sure we always have one more obs stored than rewards (and actions) + # due to the reset/last-obs logic of an MDP. + else: + assert ( + len(self.observations) + == len(self.infos) + == len(self.rewards) + 1 + == len(self.actions) + 1 + ), ( + len(self.observations), + len(self.infos), + len(self.rewards), + len(self.actions), + ) + for k, v in self.extra_model_outputs.items(): + assert len(v) == len(self.observations) - 1 + + @property + def custom_data(self): + return self._custom_data + + @property + def is_reset(self) -> bool: + """Returns True if `self.add_env_reset()` has already been called.""" + return len(self.observations) > 0 + + @property + def is_numpy(self) -> bool: + """True, if the data in this episode is already stored as numpy arrays.""" + # If rewards are still a list, return False. + # Otherwise, rewards should already be a (1D) numpy array. + return self.rewards.finalized + + @property + def is_done(self) -> bool: + """Whether the episode is actually done (terminated or truncated). + + A done episode cannot be continued via `self.add_timestep()` or being + concatenated on its right-side with another episode chunk or being + succeeded via `self.create_successor()`. + """ + return self.is_terminated or self.is_truncated + + def to_numpy(self) -> "SingleAgentEpisode": + """Converts this Episode's list attributes to numpy arrays. + + This means in particular that this episodes' lists of (possibly complex) + data (e.g. if we have a dict obs space) will be converted to (possibly complex) + structs, whose leafs are now numpy arrays. Each of these leaf numpy arrays will + have the same length (batch dimension) as the length of the original lists. + + Note that the data under the Columns.INFOS are NEVER numpy'ized and will remain + a list (normally, a list of the original, env-returned dicts). This is due to + the herterogenous nature of INFOS returned by envs, which would make it unwieldy + to convert this information to numpy arrays. + + After calling this method, no further data may be added to this episode via + the `self.add_env_step()` method. + + Examples: + + .. testcode:: + + import numpy as np + + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + + episode = SingleAgentEpisode( + observations=[0, 1, 2, 3], + actions=[1, 2, 3], + rewards=[1, 2, 3], + # Note: terminated/truncated have nothing to do with an episode + # being numpy'ized or not (via the `self.to_numpy()` method)! + terminated=False, + len_lookback_buffer=0, # no lookback; all data is actually "in" episode + ) + # Episode has not been numpy'ized yet. + assert not episode.is_numpy + # We are still operating on lists. + assert episode.get_observations([1]) == [1] + assert episode.get_observations(slice(None, 2)) == [0, 1] + # We can still add data (and even add the terminated=True flag). + episode.add_env_step( + observation=4, + action=4, + reward=4, + terminated=True, + ) + # Still NOT numpy'ized. + assert not episode.is_numpy + + # Numpy'ized the episode. + episode.to_numpy() + assert episode.is_numpy + + # We cannot add data anymore. The following would crash. + # episode.add_env_step(observation=5, action=5, reward=5) + + # Everything is now numpy arrays (with 0-axis of size + # B=[len of requested slice]). + assert isinstance(episode.get_observations([1]), np.ndarray) # B=1 + assert isinstance(episode.actions[0:2], np.ndarray) # B=2 + assert isinstance(episode.rewards[1:4], np.ndarray) # B=3 + + Returns: + This `SingleAgentEpisode` object with the converted numpy data. + """ + + self.observations.finalize() + if len(self) > 0: + self.actions.finalize() + self.rewards.finalize() + for k, v in self.extra_model_outputs.items(): + self.extra_model_outputs[k].finalize() + + return self + + def concat_episode(self, other: "SingleAgentEpisode") -> None: + """Adds the given `other` SingleAgentEpisode to the right side of `self`. + + In order for this to work, both chunks (`self` and `other`) must fit + together. This is checked by the IDs (must be identical), the time step counters + (`self.env_t` must be the same as `episode_chunk.env_t_started`), as well as the + observations/infos at the concatenation boundaries. Also, `self.is_done` must + not be True, meaning `self.is_terminated` and `self.is_truncated` are both + False. + + Args: + other: The other `SingleAgentEpisode` to be concatenated to this one. + + Returns: + A `SingleAgentEpisode` instance containing the concatenated data + from both episodes (`self` and `other`). + """ + assert other.id_ == self.id_ + # NOTE (sven): This is what we agreed on. As the replay buffers must be + # able to concatenate. + assert not self.is_done + # Make sure the timesteps match. + assert self.t == other.t_started + # Validate `other`. + other.validate() + + # Make sure, end matches other episode chunk's beginning. + assert np.all(other.observations[0] == self.observations[-1]) + # Pop out our last observations and infos (as these are identical + # to the first obs and infos in the next episode). + self.observations.pop() + self.infos.pop() + + # Extend ourselves. In case, episode_chunk is already terminated and numpy'ized + # we need to convert to lists (as we are ourselves still filling up lists). + self.observations.extend(other.get_observations()) + self.actions.extend(other.get_actions()) + self.rewards.extend(other.get_rewards()) + self.infos.extend(other.get_infos()) + self.t = other.t + + if other.is_terminated: + self.is_terminated = True + elif other.is_truncated: + self.is_truncated = True + + for key in other.extra_model_outputs.keys(): + assert key in self.extra_model_outputs + self.extra_model_outputs[key].extend(other.get_extra_model_outputs(key)) + + # Merge with `other`'s custom_data, but give `other` priority b/c we assume + # that as a follow-up chunk of `self` other has a more complete version of + # `custom_data`. + self.custom_data.update(other.custom_data) + + # Validate. + self.validate() + + def cut(self, len_lookback_buffer: int = 0) -> "SingleAgentEpisode": + """Returns a successor episode chunk (of len=0) continuing from this Episode. + + The successor will have the same ID as `self`. + If no lookback buffer is requested (len_lookback_buffer=0), the successor's + observations will be the last observation(s) of `self` and its length will + therefore be 0 (no further steps taken yet). If `len_lookback_buffer` > 0, + the returned successor will have `len_lookback_buffer` observations (and + actions, rewards, etc..) taken from the right side (end) of `self`. For example + if `len_lookback_buffer=2`, the returned successor's lookback buffer actions + will be identical to `self.actions[-2:]`. + + This method is useful if you would like to discontinue building an episode + chunk (b/c you have to return it from somewhere), but would like to have a new + episode instance to continue building the actual gym.Env episode at a later + time. Vie the `len_lookback_buffer` argument, the continuing chunk (successor) + will still be able to "look back" into this predecessor episode's data (at + least to some extend, depending on the value of `len_lookback_buffer`). + + Args: + len_lookback_buffer: The number of timesteps to take along into the new + chunk as "lookback buffer". A lookback buffer is additional data on + the left side of the actual episode data for visibility purposes + (but without actually being part of the new chunk). For example, if + `self` ends in actions 5, 6, 7, and 8, and we call + `self.cut(len_lookback_buffer=2)`, the returned chunk will have + actions 7 and 8 already in it, but still `t_started`==t==8 (not 7!) and + a length of 0. If there is not enough data in `self` yet to fulfil + the `len_lookback_buffer` request, the value of `len_lookback_buffer` + is automatically adjusted (lowered). + + Returns: + The successor Episode chunk of this one with the same ID and state and the + only observation being the last observation in self. + """ + assert not self.is_done and len_lookback_buffer >= 0 + + # Initialize this chunk with the most recent obs and infos (even if lookback is + # 0). Similar to an initial `env.reset()`. + indices_obs_and_infos = slice(-len_lookback_buffer - 1, None) + indices_rest = ( + slice(-len_lookback_buffer, None) + if len_lookback_buffer > 0 + else slice(None, 0) + ) + + sa_episode = SingleAgentEpisode( + # Same ID. + id_=self.id_, + observations=self.get_observations(indices=indices_obs_and_infos), + observation_space=self.observation_space, + infos=self.get_infos(indices=indices_obs_and_infos), + actions=self.get_actions(indices=indices_rest), + action_space=self.action_space, + rewards=self.get_rewards(indices=indices_rest), + extra_model_outputs={ + k: self.get_extra_model_outputs(k, indices_rest) + for k in self.extra_model_outputs.keys() + }, + # Continue with self's current timestep. + t_started=self.t, + # Use the length of the provided data as lookback buffer. + len_lookback_buffer="auto", + ) + # Deepcopy all custom data in `self` to be continued in the cut episode. + sa_episode._custom_data = copy.deepcopy(self.custom_data) + + return sa_episode + + # TODO (sven): Distinguish between: + # - global index: This is the absolute, global timestep whose values always + # start from 0 (at the env reset). So doing get_observations(0, global_ts=True) + # should always return the exact 1st observation (reset obs), no matter what. In + # case we are in an episode chunk and `fill` or a sufficient lookback buffer is + # provided, this should yield a result. Otherwise, error. + # - global index=False -> indices are relative to the chunk start. If a chunk has + # t_started=6 and we ask for index=0, then return observation at timestep 6 + # (t_started). + def get_observations( + self, + indices: Optional[Union[int, List[int], slice]] = None, + *, + neg_index_as_lookback: bool = False, + fill: Optional[Any] = None, + one_hot_discrete: bool = False, + ) -> Any: + """Returns individual observations or batched ranges thereof from this episode. + + Args: + indices: A single int is interpreted as an index, from which to return the + individual observation stored at this index. + A list of ints is interpreted as a list of indices from which to gather + individual observations in a batch of size len(indices). + A slice object is interpreted as a range of observations to be returned. + Thereby, negative indices by default are interpreted as "before the end" + unless the `neg_index_as_lookback=True` option is used, in which case + negative indices are interpreted as "before ts=0", meaning going back + into the lookback buffer. + If None, will return all observations (from ts=0 to the end). + neg_index_as_lookback: If True, negative values in `indices` are + interpreted as "before ts=0", meaning going back into the lookback + buffer. For example, an episode with observations [4, 5, 6, 7, 8, 9], + where [4, 5, 6] is the lookback buffer range (ts=0 item is 7), will + respond to `get_observations(-1, neg_index_as_lookback=True)` + with `6` and to + `get_observations(slice(-2, 1), neg_index_as_lookback=True)` with + `[5, 6, 7]`. + fill: An optional value to use for filling up the returned results at + the boundaries. This filling only happens if the requested index range's + start/stop boundaries exceed the episode's boundaries (including the + lookback buffer on the left side). This comes in very handy, if users + don't want to worry about reaching such boundaries and want to zero-pad. + For example, an episode with observations [10, 11, 12, 13, 14] and + lookback buffer size of 2 (meaning observations `10` and `11` are part + of the lookback buffer) will respond to + `get_observations(slice(-7, -2), fill=0.0)` with + `[0.0, 0.0, 10, 11, 12]`. + one_hot_discrete: If True, will return one-hot vectors (instead of + int-values) for those sub-components of a (possibly complex) observation + space that are Discrete or MultiDiscrete. Note that if `fill=0` and the + requested `indices` are out of the range of our data, the returned + one-hot vectors will actually be zero-hot (all slots zero). + + Examples: + + .. testcode:: + + import gymnasium as gym + + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + from ray.rllib.utils.test_utils import check + + episode = SingleAgentEpisode( + # Discrete(4) observations (ints between 0 and 4 (excl.)) + observation_space=gym.spaces.Discrete(4), + observations=[0, 1, 2, 3], + actions=[1, 2, 3], rewards=[1, 2, 3], # <- not relevant for this demo + len_lookback_buffer=0, # no lookback; all data is actually "in" episode + ) + # Plain usage (`indices` arg only). + check(episode.get_observations(-1), 3) + check(episode.get_observations(0), 0) + check(episode.get_observations([0, 2]), [0, 2]) + check(episode.get_observations([-1, 0]), [3, 0]) + check(episode.get_observations(slice(None, 2)), [0, 1]) + check(episode.get_observations(slice(-2, None)), [2, 3]) + # Using `fill=...` (requesting slices beyond the boundaries). + check(episode.get_observations(slice(-6, -2), fill=-9), [-9, -9, 0, 1]) + check(episode.get_observations(slice(2, 5), fill=-7), [2, 3, -7]) + # Using `one_hot_discrete=True`. + check(episode.get_observations(2, one_hot_discrete=True), [0, 0, 1, 0]) + check(episode.get_observations(3, one_hot_discrete=True), [0, 0, 0, 1]) + check(episode.get_observations( + slice(0, 3), + one_hot_discrete=True, + ), [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]]) + # Special case: Using `fill=0.0` AND `one_hot_discrete=True`. + check(episode.get_observations( + -1, + neg_index_as_lookback=True, # -1 means one left of ts=0 + fill=0.0, + one_hot_discrete=True, + ), [0, 0, 0, 0]) # <- all 0s one-hot tensor (note difference to [1 0 0 0]!) + + Returns: + The collected observations. + As a 0-axis batch, if there are several `indices` or a list of exactly one + index provided OR `indices` is a slice object. + As single item (B=0 -> no additional 0-axis) if `indices` is a single int. + """ + return self.observations.get( + indices=indices, + neg_index_as_lookback=neg_index_as_lookback, + fill=fill, + one_hot_discrete=one_hot_discrete, + ) + + def get_infos( + self, + indices: Optional[Union[int, List[int], slice]] = None, + *, + neg_index_as_lookback: bool = False, + fill: Optional[Any] = None, + ) -> Any: + """Returns individual info dicts or list (ranges) thereof from this episode. + + Args: + indices: A single int is interpreted as an index, from which to return the + individual info dict stored at this index. + A list of ints is interpreted as a list of indices from which to gather + individual info dicts in a list of size len(indices). + A slice object is interpreted as a range of info dicts to be returned. + Thereby, negative indices by default are interpreted as "before the end" + unless the `neg_index_as_lookback=True` option is used, in which case + negative indices are interpreted as "before ts=0", meaning going back + into the lookback buffer. + If None, will return all infos (from ts=0 to the end). + neg_index_as_lookback: If True, negative values in `indices` are + interpreted as "before ts=0", meaning going back into the lookback + buffer. For example, an episode with infos + [{"l":4}, {"l":5}, {"l":6}, {"a":7}, {"b":8}, {"c":9}], where the + first 3 items are the lookback buffer (ts=0 item is {"a": 7}), will + respond to `get_infos(-1, neg_index_as_lookback=True)` with + `{"l":6}` and to + `get_infos(slice(-2, 1), neg_index_as_lookback=True)` with + `[{"l":5}, {"l":6}, {"a":7}]`. + fill: An optional value to use for filling up the returned results at + the boundaries. This filling only happens if the requested index range's + start/stop boundaries exceed the episode's boundaries (including the + lookback buffer on the left side). This comes in very handy, if users + don't want to worry about reaching such boundaries and want to + auto-fill. For example, an episode with infos + [{"l":10}, {"l":11}, {"a":12}, {"b":13}, {"c":14}] and lookback buffer + size of 2 (meaning infos {"l":10}, {"l":11} are part of the lookback + buffer) will respond to `get_infos(slice(-7, -2), fill={"o": 0.0})` + with `[{"o":0.0}, {"o":0.0}, {"l":10}, {"l":11}, {"a":12}]`. + + Examples: + + .. testcode:: + + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + + episode = SingleAgentEpisode( + infos=[{"a":0}, {"b":1}, {"c":2}, {"d":3}], + # The following is needed, but not relevant for this demo. + observations=[0, 1, 2, 3], actions=[1, 2, 3], rewards=[1, 2, 3], + len_lookback_buffer=0, # no lookback; all data is actually "in" episode + ) + # Plain usage (`indices` arg only). + episode.get_infos(-1) # {"d":3} + episode.get_infos(0) # {"a":0} + episode.get_infos([0, 2]) # [{"a":0},{"c":2}] + episode.get_infos([-1, 0]) # [{"d":3},{"a":0}] + episode.get_infos(slice(None, 2)) # [{"a":0},{"b":1}] + episode.get_infos(slice(-2, None)) # [{"c":2},{"d":3}] + # Using `fill=...` (requesting slices beyond the boundaries). + # TODO (sven): This would require a space being provided. Maybe we can + # skip this check for infos, which don't have a space anyways. + # episode.get_infos(slice(-5, -3), fill={"o":-1}) # [{"o":-1},{"a":0}] + # episode.get_infos(slice(3, 5), fill={"o":-2}) # [{"d":3},{"o":-2}] + + Returns: + The collected info dicts. + As a 0-axis batch, if there are several `indices` or a list of exactly one + index provided OR `indices` is a slice object. + As single item (B=0 -> no additional 0-axis) if `indices` is a single int. + """ + return self.infos.get( + indices=indices, + neg_index_as_lookback=neg_index_as_lookback, + fill=fill, + ) + + def get_actions( + self, + indices: Optional[Union[int, List[int], slice]] = None, + *, + neg_index_as_lookback: bool = False, + fill: Optional[Any] = None, + one_hot_discrete: bool = False, + ) -> Any: + """Returns individual actions or batched ranges thereof from this episode. + + Args: + indices: A single int is interpreted as an index, from which to return the + individual action stored at this index. + A list of ints is interpreted as a list of indices from which to gather + individual actions in a batch of size len(indices). + A slice object is interpreted as a range of actions to be returned. + Thereby, negative indices by default are interpreted as "before the end" + unless the `neg_index_as_lookback=True` option is used, in which case + negative indices are interpreted as "before ts=0", meaning going back + into the lookback buffer. + If None, will return all actions (from ts=0 to the end). + neg_index_as_lookback: If True, negative values in `indices` are + interpreted as "before ts=0", meaning going back into the lookback + buffer. For example, an episode with actions [4, 5, 6, 7, 8, 9], where + [4, 5, 6] is the lookback buffer range (ts=0 item is 7), will respond + to `get_actions(-1, neg_index_as_lookback=True)` with `6` and + to `get_actions(slice(-2, 1), neg_index_as_lookback=True)` with + `[5, 6, 7]`. + fill: An optional value to use for filling up the returned results at + the boundaries. This filling only happens if the requested index range's + start/stop boundaries exceed the episode's boundaries (including the + lookback buffer on the left side). This comes in very handy, if users + don't want to worry about reaching such boundaries and want to zero-pad. + For example, an episode with actions [10, 11, 12, 13, 14] and + lookback buffer size of 2 (meaning actions `10` and `11` are part + of the lookback buffer) will respond to + `get_actions(slice(-7, -2), fill=0.0)` with `[0.0, 0.0, 10, 11, 12]`. + one_hot_discrete: If True, will return one-hot vectors (instead of + int-values) for those sub-components of a (possibly complex) action + space that are Discrete or MultiDiscrete. Note that if `fill=0` and the + requested `indices` are out of the range of our data, the returned + one-hot vectors will actually be zero-hot (all slots zero). + + Examples: + + .. testcode:: + + import gymnasium as gym + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + + episode = SingleAgentEpisode( + # Discrete(4) actions (ints between 0 and 4 (excl.)) + action_space=gym.spaces.Discrete(4), + actions=[1, 2, 3], + observations=[0, 1, 2, 3], rewards=[1, 2, 3], # <- not relevant here + len_lookback_buffer=0, # no lookback; all data is actually "in" episode + ) + # Plain usage (`indices` arg only). + episode.get_actions(-1) # 3 + episode.get_actions(0) # 1 + episode.get_actions([0, 2]) # [1, 3] + episode.get_actions([-1, 0]) # [3, 1] + episode.get_actions(slice(None, 2)) # [1, 2] + episode.get_actions(slice(-2, None)) # [2, 3] + # Using `fill=...` (requesting slices beyond the boundaries). + episode.get_actions(slice(-5, -2), fill=-9) # [-9, -9, 1, 2] + episode.get_actions(slice(1, 5), fill=-7) # [2, 3, -7, -7] + # Using `one_hot_discrete=True`. + episode.get_actions(1, one_hot_discrete=True) # [0 0 1 0] (action=2) + episode.get_actions(2, one_hot_discrete=True) # [0 0 0 1] (action=3) + episode.get_actions( + slice(0, 2), + one_hot_discrete=True, + ) # [[0 1 0 0], [0 0 0 1]] (actions=1 and 3) + # Special case: Using `fill=0.0` AND `one_hot_discrete=True`. + episode.get_actions( + -1, + neg_index_as_lookback=True, # -1 means one left of ts=0 + fill=0.0, + one_hot_discrete=True, + ) # [0 0 0 0] <- all 0s one-hot tensor (note difference to [1 0 0 0]!) + + Returns: + The collected actions. + As a 0-axis batch, if there are several `indices` or a list of exactly one + index provided OR `indices` is a slice object. + As single item (B=0 -> no additional 0-axis) if `indices` is a single int. + """ + return self.actions.get( + indices=indices, + neg_index_as_lookback=neg_index_as_lookback, + fill=fill, + one_hot_discrete=one_hot_discrete, + ) + + def get_rewards( + self, + indices: Optional[Union[int, List[int], slice]] = None, + *, + neg_index_as_lookback: bool = False, + fill: Optional[float] = None, + ) -> Any: + """Returns individual rewards or batched ranges thereof from this episode. + + Args: + indices: A single int is interpreted as an index, from which to return the + individual reward stored at this index. + A list of ints is interpreted as a list of indices from which to gather + individual rewards in a batch of size len(indices). + A slice object is interpreted as a range of rewards to be returned. + Thereby, negative indices by default are interpreted as "before the end" + unless the `neg_index_as_lookback=True` option is used, in which case + negative indices are interpreted as "before ts=0", meaning going back + into the lookback buffer. + If None, will return all rewards (from ts=0 to the end). + neg_index_as_lookback: Negative values in `indices` are interpreted as + as "before ts=0", meaning going back into the lookback buffer. + For example, an episode with rewards [4, 5, 6, 7, 8, 9], where + [4, 5, 6] is the lookback buffer range (ts=0 item is 7), will respond + to `get_rewards(-1, neg_index_as_lookback=True)` with `6` and + to `get_rewards(slice(-2, 1), neg_index_as_lookback=True)` with + `[5, 6, 7]`. + fill: An optional float value to use for filling up the returned results at + the boundaries. This filling only happens if the requested index range's + start/stop boundaries exceed the episode's boundaries (including the + lookback buffer on the left side). This comes in very handy, if users + don't want to worry about reaching such boundaries and want to zero-pad. + For example, an episode with rewards [10, 11, 12, 13, 14] and + lookback buffer size of 2 (meaning rewards `10` and `11` are part + of the lookback buffer) will respond to + `get_rewards(slice(-7, -2), fill=0.0)` with `[0.0, 0.0, 10, 11, 12]`. + + Examples: + + .. testcode:: + + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + + episode = SingleAgentEpisode( + rewards=[1.0, 2.0, 3.0], + observations=[0, 1, 2, 3], actions=[1, 2, 3], # <- not relevant here + len_lookback_buffer=0, # no lookback; all data is actually "in" episode + ) + # Plain usage (`indices` arg only). + episode.get_rewards(-1) # 3.0 + episode.get_rewards(0) # 1.0 + episode.get_rewards([0, 2]) # [1.0, 3.0] + episode.get_rewards([-1, 0]) # [3.0, 1.0] + episode.get_rewards(slice(None, 2)) # [1.0, 2.0] + episode.get_rewards(slice(-2, None)) # [2.0, 3.0] + # Using `fill=...` (requesting slices beyond the boundaries). + episode.get_rewards(slice(-5, -2), fill=0.0) # [0.0, 0.0, 1.0, 2.0] + episode.get_rewards(slice(1, 5), fill=0.0) # [2.0, 3.0, 0.0, 0.0] + + Returns: + The collected rewards. + As a 0-axis batch, if there are several `indices` or a list of exactly one + index provided OR `indices` is a slice object. + As single item (B=0 -> no additional 0-axis) if `indices` is a single int. + """ + return self.rewards.get( + indices=indices, + neg_index_as_lookback=neg_index_as_lookback, + fill=fill, + ) + + def get_extra_model_outputs( + self, + key: str, + indices: Optional[Union[int, List[int], slice]] = None, + *, + neg_index_as_lookback: bool = False, + fill: Optional[Any] = None, + ) -> Any: + """Returns extra model outputs (under given key) from this episode. + + Args: + key: The `key` within `self.extra_model_outputs` to extract data for. + indices: A single int is interpreted as an index, from which to return an + individual extra model output stored under `key` at index. + A list of ints is interpreted as a list of indices from which to gather + individual actions in a batch of size len(indices). + A slice object is interpreted as a range of extra model outputs to be + returned. Thereby, negative indices by default are interpreted as + "before the end" unless the `neg_index_as_lookback=True` option is + used, in which case negative indices are interpreted as "before ts=0", + meaning going back into the lookback buffer. + If None, will return all extra model outputs (from ts=0 to the end). + neg_index_as_lookback: If True, negative values in `indices` are + interpreted as "before ts=0", meaning going back into the lookback + buffer. For example, an episode with + extra_model_outputs['a'] = [4, 5, 6, 7, 8, 9], where [4, 5, 6] is the + lookback buffer range (ts=0 item is 7), will respond to + `get_extra_model_outputs("a", -1, neg_index_as_lookback=True)` with + `6` and to `get_extra_model_outputs("a", slice(-2, 1), + neg_index_as_lookback=True)` with `[5, 6, 7]`. + fill: An optional value to use for filling up the returned results at + the boundaries. This filling only happens if the requested index range's + start/stop boundaries exceed the episode's boundaries (including the + lookback buffer on the left side). This comes in very handy, if users + don't want to worry about reaching such boundaries and want to zero-pad. + For example, an episode with + extra_model_outputs["b"] = [10, 11, 12, 13, 14] and lookback buffer + size of 2 (meaning `10` and `11` are part of the lookback buffer) will + respond to + `get_extra_model_outputs("b", slice(-7, -2), fill=0.0)` with + `[0.0, 0.0, 10, 11, 12]`. + TODO (sven): This would require a space being provided. Maybe we can + automatically infer the space from existing data? + + Examples: + + .. testcode:: + + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + + episode = SingleAgentEpisode( + extra_model_outputs={"mo": [1, 2, 3]}, + len_lookback_buffer=0, # no lookback; all data is actually "in" episode + # The following is needed, but not relevant for this demo. + observations=[0, 1, 2, 3], actions=[1, 2, 3], rewards=[1, 2, 3], + ) + + # Plain usage (`indices` arg only). + episode.get_extra_model_outputs("mo", -1) # 3 + episode.get_extra_model_outputs("mo", 1) # 0 + episode.get_extra_model_outputs("mo", [0, 2]) # [1, 3] + episode.get_extra_model_outputs("mo", [-1, 0]) # [3, 1] + episode.get_extra_model_outputs("mo", slice(None, 2)) # [1, 2] + episode.get_extra_model_outputs("mo", slice(-2, None)) # [2, 3] + # Using `fill=...` (requesting slices beyond the boundaries). + # TODO (sven): This would require a space being provided. Maybe we can + # automatically infer the space from existing data? + # episode.get_extra_model_outputs("mo", slice(-5, -2), fill=0) # [0, 0, 1] + # episode.get_extra_model_outputs("mo", slice(2, 5), fill=-1) # [3, -1, -1] + + Returns: + The collected extra_model_outputs[`key`]. + As a 0-axis batch, if there are several `indices` or a list of exactly one + index provided OR `indices` is a slice object. + As single item (B=0 -> no additional 0-axis) if `indices` is a single int. + """ + value = self.extra_model_outputs[key] + # The expected case is: `value` is a `InfiniteLookbackBuffer`. + if isinstance(value, InfiniteLookbackBuffer): + return value.get( + indices=indices, + neg_index_as_lookback=neg_index_as_lookback, + fill=fill, + ) + # TODO (sven): This does not seem to be solid yet. Users should NOT be able + # to just write directly into our buffers. Instead, use: + # `self.set_extra_model_outputs(key, new_data, at_indices=...)` and if key + # is not known, add a new buffer to the `extra_model_outputs` dict. + assert False + # It might be that the user has added new key/value pairs in their custom + # postprocessing/connector logic. The values are then most likely numpy + # arrays. We convert them automatically to buffers and get the requested + # indices (with the given options) from there. + return InfiniteLookbackBuffer(value).get( + indices, fill=fill, neg_index_as_lookback=neg_index_as_lookback + ) + + def set_observations( + self, + *, + new_data, + at_indices: Optional[Union[int, List[int], slice]] = None, + neg_index_as_lookback: bool = False, + ) -> None: + """Overwrites all or some of this Episode's observations with the provided data. + + Note that an episode's observation data cannot be written to directly as it is + managed by a `InfiniteLookbackBuffer` object. Normally, individual, current + observations are added to the episode either by calling `self.add_env_step` or + more directly (and manually) via `self.observations.append|extend()`. + However, for certain postprocessing steps, the entirety (or a slice) of an + episode's observations might have to be rewritten, which is when + `self.set_observations()` should be used. + + Args: + new_data: The new observation data to overwrite existing data with. + This may be a list of individual observation(s) in case this episode + is still not numpy'ized yet. In case this episode has already been + numpy'ized, this should be (possibly complex) struct matching the + observation space and with a batch size of its leafs exactly the size + of the to-be-overwritten slice or segment (provided by `at_indices`). + at_indices: A single int is interpreted as one index, which to overwrite + with `new_data` (which is expected to be a single observation). + A list of ints is interpreted as a list of indices, all of which to + overwrite with `new_data` (which is expected to be of the same size + as `len(at_indices)`). + A slice object is interpreted as a range of indices to be overwritten + with `new_data` (which is expected to be of the same size as the + provided slice). + Thereby, negative indices by default are interpreted as "before the end" + unless the `neg_index_as_lookback=True` option is used, in which case + negative indices are interpreted as "before ts=0", meaning going back + into the lookback buffer. + neg_index_as_lookback: If True, negative values in `at_indices` are + interpreted as "before ts=0", meaning going back into the lookback + buffer. For example, an episode with + observations = [4, 5, 6, 7, 8, 9], where [4, 5, 6] is the + lookback buffer range (ts=0 item is 7), will handle a call to + `set_observations(individual_observation, -1, + neg_index_as_lookback=True)` by overwriting the value of 6 in our + observations buffer with the provided "individual_observation". + + Raises: + IndexError: If the provided `at_indices` do not match the size of + `new_data`. + """ + self.observations.set( + new_data=new_data, + at_indices=at_indices, + neg_index_as_lookback=neg_index_as_lookback, + ) + + def set_actions( + self, + *, + new_data, + at_indices: Optional[Union[int, List[int], slice]] = None, + neg_index_as_lookback: bool = False, + ) -> None: + """Overwrites all or some of this Episode's actions with the provided data. + + Note that an episode's action data cannot be written to directly as it is + managed by a `InfiniteLookbackBuffer` object. Normally, individual, current + actions are added to the episode either by calling `self.add_env_step` or + more directly (and manually) via `self.actions.append|extend()`. + However, for certain postprocessing steps, the entirety (or a slice) of an + episode's actions might have to be rewritten, which is when + `self.set_actions()` should be used. + + Args: + new_data: The new action data to overwrite existing data with. + This may be a list of individual action(s) in case this episode + is still not numpy'ized yet. In case this episode has already been + numpy'ized, this should be (possibly complex) struct matching the + action space and with a batch size of its leafs exactly the size + of the to-be-overwritten slice or segment (provided by `at_indices`). + at_indices: A single int is interpreted as one index, which to overwrite + with `new_data` (which is expected to be a single action). + A list of ints is interpreted as a list of indices, all of which to + overwrite with `new_data` (which is expected to be of the same size + as `len(at_indices)`). + A slice object is interpreted as a range of indices to be overwritten + with `new_data` (which is expected to be of the same size as the + provided slice). + Thereby, negative indices by default are interpreted as "before the end" + unless the `neg_index_as_lookback=True` option is used, in which case + negative indices are interpreted as "before ts=0", meaning going back + into the lookback buffer. + neg_index_as_lookback: If True, negative values in `at_indices` are + interpreted as "before ts=0", meaning going back into the lookback + buffer. For example, an episode with + actions = [4, 5, 6, 7, 8, 9], where [4, 5, 6] is the + lookback buffer range (ts=0 item is 7), will handle a call to + `set_actions(individual_action, -1, + neg_index_as_lookback=True)` by overwriting the value of 6 in our + actions buffer with the provided "individual_action". + + Raises: + IndexError: If the provided `at_indices` do not match the size of + `new_data`. + """ + self.actions.set( + new_data=new_data, + at_indices=at_indices, + neg_index_as_lookback=neg_index_as_lookback, + ) + + def set_rewards( + self, + *, + new_data, + at_indices: Optional[Union[int, List[int], slice]] = None, + neg_index_as_lookback: bool = False, + ) -> None: + """Overwrites all or some of this Episode's rewards with the provided data. + + Note that an episode's reward data cannot be written to directly as it is + managed by a `InfiniteLookbackBuffer` object. Normally, individual, current + rewards are added to the episode either by calling `self.add_env_step` or + more directly (and manually) via `self.rewards.append|extend()`. + However, for certain postprocessing steps, the entirety (or a slice) of an + episode's rewards might have to be rewritten, which is when + `self.set_rewards()` should be used. + + Args: + new_data: The new reward data to overwrite existing data with. + This may be a list of individual reward(s) in case this episode + is still not numpy'ized yet. In case this episode has already been + numpy'ized, this should be a np.ndarray with a length exactly + the size of the to-be-overwritten slice or segment (provided by + `at_indices`). + at_indices: A single int is interpreted as one index, which to overwrite + with `new_data` (which is expected to be a single reward). + A list of ints is interpreted as a list of indices, all of which to + overwrite with `new_data` (which is expected to be of the same size + as `len(at_indices)`). + A slice object is interpreted as a range of indices to be overwritten + with `new_data` (which is expected to be of the same size as the + provided slice). + Thereby, negative indices by default are interpreted as "before the end" + unless the `neg_index_as_lookback=True` option is used, in which case + negative indices are interpreted as "before ts=0", meaning going back + into the lookback buffer. + neg_index_as_lookback: If True, negative values in `at_indices` are + interpreted as "before ts=0", meaning going back into the lookback + buffer. For example, an episode with + rewards = [4, 5, 6, 7, 8, 9], where [4, 5, 6] is the + lookback buffer range (ts=0 item is 7), will handle a call to + `set_rewards(individual_reward, -1, + neg_index_as_lookback=True)` by overwriting the value of 6 in our + rewards buffer with the provided "individual_reward". + + Raises: + IndexError: If the provided `at_indices` do not match the size of + `new_data`. + """ + self.rewards.set( + new_data=new_data, + at_indices=at_indices, + neg_index_as_lookback=neg_index_as_lookback, + ) + + def set_extra_model_outputs( + self, + *, + key, + new_data, + at_indices: Optional[Union[int, List[int], slice]] = None, + neg_index_as_lookback: bool = False, + ) -> None: + """Overwrites all or some of this Episode's extra model outputs with `new_data`. + + Note that an episode's `extra_model_outputs` data cannot be written to directly + as it is managed by a `InfiniteLookbackBuffer` object. Normally, individual, + current `extra_model_output` values are added to the episode either by calling + `self.add_env_step` or more directly (and manually) via + `self.extra_model_outputs[key].append|extend()`. However, for certain + postprocessing steps, the entirety (or a slice) of an episode's + `extra_model_outputs` might have to be rewritten or a new key (a new type of + `extra_model_outputs`) must be inserted, which is when + `self.set_extra_model_outputs()` should be used. + + Args: + key: The `key` within `self.extra_model_outputs` to override data on or + to insert as a new key into `self.extra_model_outputs`. + new_data: The new data to overwrite existing data with. + This may be a list of individual reward(s) in case this episode + is still not numpy'ized yet. In case this episode has already been + numpy'ized, this should be a np.ndarray with a length exactly + the size of the to-be-overwritten slice or segment (provided by + `at_indices`). + at_indices: A single int is interpreted as one index, which to overwrite + with `new_data` (which is expected to be a single reward). + A list of ints is interpreted as a list of indices, all of which to + overwrite with `new_data` (which is expected to be of the same size + as `len(at_indices)`). + A slice object is interpreted as a range of indices to be overwritten + with `new_data` (which is expected to be of the same size as the + provided slice). + Thereby, negative indices by default are interpreted as "before the end" + unless the `neg_index_as_lookback=True` option is used, in which case + negative indices are interpreted as "before ts=0", meaning going back + into the lookback buffer. + neg_index_as_lookback: If True, negative values in `at_indices` are + interpreted as "before ts=0", meaning going back into the lookback + buffer. For example, an episode with + rewards = [4, 5, 6, 7, 8, 9], where [4, 5, 6] is the + lookback buffer range (ts=0 item is 7), will handle a call to + `set_rewards(individual_reward, -1, + neg_index_as_lookback=True)` by overwriting the value of 6 in our + rewards buffer with the provided "individual_reward". + + Raises: + IndexError: If the provided `at_indices` do not match the size of + `new_data`. + """ + # Record already exists -> Set existing record's data to new values. + assert key in self.extra_model_outputs + self.extra_model_outputs[key].set( + new_data=new_data, + at_indices=at_indices, + neg_index_as_lookback=neg_index_as_lookback, + ) + + def slice( + self, + slice_: slice, + *, + len_lookback_buffer: Optional[int] = None, + ) -> "SingleAgentEpisode": + """Returns a slice of this episode with the given slice object. + + For example, if `self` contains o0 (the reset observation), o1, o2, o3, and o4 + and the actions a1, a2, a3, and a4 (len of `self` is 4), then a call to + `self.slice(slice(1, 3))` would return a new SingleAgentEpisode with + observations o1, o2, and o3, and actions a2 and a3. Note here that there is + always one observation more in an episode than there are actions (and rewards + and extra model outputs) due to the initial observation received after an env + reset. + + .. testcode:: + + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + from ray.rllib.utils.test_utils import check + + # Generate a simple multi-agent episode. + observations = [0, 1, 2, 3, 4, 5] + actions = [1, 2, 3, 4, 5] + rewards = [0.1, 0.2, 0.3, 0.4, 0.5] + episode = SingleAgentEpisode( + observations=observations, + actions=actions, + rewards=rewards, + len_lookback_buffer=0, # all given data is part of the episode + ) + slice_1 = episode[:1] + check(slice_1.observations, [0, 1]) + check(slice_1.actions, [1]) + check(slice_1.rewards, [0.1]) + + slice_2 = episode[-2:] + check(slice_2.observations, [3, 4, 5]) + check(slice_2.actions, [4, 5]) + check(slice_2.rewards, [0.4, 0.5]) + + Args: + slice_: The slice object to use for slicing. This should exclude the + lookback buffer, which will be prepended automatically to the returned + slice. + len_lookback_buffer: If not None, forces the returned slice to try to have + this number of timesteps in its lookback buffer (if available). If None + (default), tries to make the returned slice's lookback as large as the + current lookback buffer of this episode (`self`). + + Returns: + The new SingleAgentEpisode representing the requested slice. + """ + # Translate `slice_` into one that only contains 0-or-positive ints and will + # NOT contain any None. + start = slice_.start + stop = slice_.stop + + # Start is None -> 0. + if start is None: + start = 0 + # Start is negative -> Interpret index as counting "from end". + elif start < 0: + start = len(self) + start + + # Stop is None -> Set stop to our len (one ts past last valid index). + if stop is None: + stop = len(self) + # Stop is negative -> Interpret index as counting "from end". + elif stop < 0: + stop = len(self) + stop + + step = slice_.step if slice_.step is not None else 1 + + # Figure out, whether slicing stops at the very end of this episode to know + # whether `self.is_terminated/is_truncated` should be kept as-is. + keep_done = stop == len(self) + # Provide correct timestep- and pre-buffer information. + t_started = self.t_started + start + + _lb = ( + len_lookback_buffer + if len_lookback_buffer is not None + else self.observations.lookback + ) + if ( + start >= 0 + and start - _lb < 0 + and self.observations.lookback < (_lb - start) + ): + _lb = self.observations.lookback + start + observations = InfiniteLookbackBuffer( + data=self.get_observations( + slice(start - _lb, stop + 1, step), + neg_index_as_lookback=True, + ), + lookback=_lb, + space=self.observation_space, + ) + + _lb = ( + len_lookback_buffer + if len_lookback_buffer is not None + else self.infos.lookback + ) + if start >= 0 and start - _lb < 0 and self.infos.lookback < (_lb - start): + _lb = self.infos.lookback + start + infos = InfiniteLookbackBuffer( + data=self.get_infos( + slice(start - _lb, stop + 1, step), + neg_index_as_lookback=True, + ), + lookback=_lb, + ) + + _lb = ( + len_lookback_buffer + if len_lookback_buffer is not None + else self.actions.lookback + ) + if start >= 0 and start - _lb < 0 and self.actions.lookback < (_lb - start): + _lb = self.actions.lookback + start + actions = InfiniteLookbackBuffer( + data=self.get_actions( + slice(start - _lb, stop, step), + neg_index_as_lookback=True, + ), + lookback=_lb, + space=self.action_space, + ) + + _lb = ( + len_lookback_buffer + if len_lookback_buffer is not None + else self.rewards.lookback + ) + if start >= 0 and start - _lb < 0 and self.rewards.lookback < (_lb - start): + _lb = self.rewards.lookback + start + rewards = InfiniteLookbackBuffer( + data=self.get_rewards( + slice(start - _lb, stop, step), + neg_index_as_lookback=True, + ), + lookback=_lb, + ) + + extra_model_outputs = {} + for k, v in self.extra_model_outputs.items(): + _lb = len_lookback_buffer if len_lookback_buffer is not None else v.lookback + if start >= 0 and start - _lb < 0 and v.lookback < (_lb - start): + _lb = v.lookback + start + extra_model_outputs[k] = InfiniteLookbackBuffer( + data=self.get_extra_model_outputs( + key=k, + indices=slice(start - _lb, stop, step), + neg_index_as_lookback=True, + ), + lookback=_lb, + ) + + return SingleAgentEpisode( + id_=self.id_, + # In the following, offset `start`s automatically by lookbacks. + observations=observations, + observation_space=self.observation_space, + infos=infos, + actions=actions, + action_space=self.action_space, + rewards=rewards, + extra_model_outputs=extra_model_outputs, + terminated=(self.is_terminated if keep_done else False), + truncated=(self.is_truncated if keep_done else False), + t_started=t_started, + ) + + def get_data_dict(self): + """Converts a SingleAgentEpisode into a data dict mapping str keys to data. + + The keys used are: + Columns.EPS_ID, T, OBS, INFOS, ACTIONS, REWARDS, TERMINATEDS, TRUNCATEDS, + and those in `self.extra_model_outputs`. + + Returns: + A data dict mapping str keys to data records. + """ + t = list(range(self.t_started, self.t)) + terminateds = [False] * (len(self) - 1) + [self.is_terminated] + truncateds = [False] * (len(self) - 1) + [self.is_truncated] + eps_id = [self.id_] * len(self) + + if self.is_numpy: + t = np.array(t) + terminateds = np.array(terminateds) + truncateds = np.array(truncateds) + eps_id = np.array(eps_id) + + return dict( + { + # Trivial 1D data (compiled above). + Columns.TERMINATEDS: terminateds, + Columns.TRUNCATEDS: truncateds, + Columns.T: t, + Columns.EPS_ID: eps_id, + # Retrieve obs, infos, actions, rewards using our get_... APIs, + # which return all relevant timesteps (excluding the lookback + # buffer!). Slice off last obs and infos to have the same number + # of them as we have actions and rewards. + Columns.OBS: self.get_observations(slice(None, -1)), + Columns.INFOS: self.get_infos(slice(None, -1)), + Columns.ACTIONS: self.get_actions(), + Columns.REWARDS: self.get_rewards(), + }, + # All `extra_model_outs`: Same as obs: Use get_... API. + **{ + k: self.get_extra_model_outputs(k) + for k in self.extra_model_outputs.keys() + }, + ) + + def get_sample_batch(self) -> SampleBatch: + """Converts this `SingleAgentEpisode` into a `SampleBatch`. + + Returns: + A SampleBatch containing all of this episode's data. + """ + return SampleBatch(self.get_data_dict()) + + def get_return(self) -> float: + """Calculates an episode's return, excluding the lookback buffer's rewards. + + The return is computed by a simple sum, neglecting the discount factor. + Note that if `self` is a continuation chunk (resulting from a call to + `self.cut()`), the previous chunk's rewards are NOT counted and thus NOT + part of the returned reward sum. + + Returns: + The sum of rewards collected during this episode, excluding possible data + inside the lookback buffer and excluding possible data in a predecessor + chunk. + """ + return sum(self.get_rewards()) + + def get_duration_s(self) -> float: + """Returns the duration of this Episode (chunk) in seconds.""" + if self._last_step_time is None: + return 0.0 + return self._last_step_time - self._start_time + + def env_steps(self) -> int: + """Returns the number of environment steps. + + Note, this episode instance could be a chunk of an actual episode. + + Returns: + An integer that counts the number of environment steps this episode instance + has seen. + """ + return len(self) + + def agent_steps(self) -> int: + """Returns the number of agent steps. + + Note, these are identical to the environment steps for a single-agent episode. + + Returns: + An integer counting the number of agent steps executed during the time this + episode instance records. + """ + return self.env_steps() + + def get_state(self) -> Dict[str, Any]: + """Returns the pickable state of an episode. + + The data in the episode is stored into a dictionary. Note that episodes + can also be generated from states (see `SingleAgentEpisode.from_state()`). + + Returns: + A dict containing all the data from the episode. + """ + infos = self.infos.get_state() + infos["data"] = np.array([info if info else None for info in infos["data"]]) + return { + "id_": self.id_, + "agent_id": self.agent_id, + "module_id": self.module_id, + "multi_agent_episode_id": self.multi_agent_episode_id, + # Note, all data is stored in `InfiniteLookbackBuffer`s. + "observations": self.observations.get_state(), + "actions": self.actions.get_state(), + "rewards": self.rewards.get_state(), + "infos": self.infos.get_state(), + "extra_model_outputs": { + k: v.get_state() if v else v + for k, v in self.extra_model_outputs.items() + } + if len(self.extra_model_outputs) > 0 + else None, + "is_terminated": self.is_terminated, + "is_truncated": self.is_truncated, + "t_started": self.t_started, + "t": self.t, + "_observation_space": gym_space_to_dict(self._observation_space) + if self._observation_space + else None, + "_action_space": gym_space_to_dict(self._action_space) + if self._action_space + else None, + "_start_time": self._start_time, + "_last_step_time": self._last_step_time, + "custom_data": self.custom_data, + } + + @staticmethod + def from_state(state: Dict[str, Any]) -> "SingleAgentEpisode": + """Creates a new `SingleAgentEpisode` instance from a state dict. + + Args: + state: The state dict, as returned by `self.get_state()`. + + Returns: + A new `SingleAgentEpisode` instance with the data from the state dict. + """ + # Create an empy episode instance. + episode = SingleAgentEpisode(id_=state["id_"]) + # Load all the data from the state dict into the episode. + episode.agent_id = state["agent_id"] + episode.module_id = state["module_id"] + episode.multi_agent_episode_id = state["multi_agent_episode_id"] + # Convert data back to `InfiniteLookbackBuffer`s. + episode.observations = InfiniteLookbackBuffer.from_state(state["observations"]) + episode.actions = InfiniteLookbackBuffer.from_state(state["actions"]) + episode.rewards = InfiniteLookbackBuffer.from_state(state["rewards"]) + episode.infos = InfiniteLookbackBuffer.from_state(state["infos"]) + episode.extra_model_outputs = ( + defaultdict( + functools.partial( + InfiniteLookbackBuffer, lookback=episode.observations.lookback + ), + { + k: InfiniteLookbackBuffer.from_state(v) + for k, v in state["extra_model_outputs"].items() + }, + ) + if state["extra_model_outputs"] + else defaultdict( + functools.partial( + InfiniteLookbackBuffer, lookback=episode.observations.lookback + ), + ) + ) + episode.is_terminated = state["is_terminated"] + episode.is_truncated = state["is_truncated"] + episode.t_started = state["t_started"] + episode.t = state["t"] + # We need to convert the spaces to dictionaries for serialization. + episode._observation_space = ( + gym_space_from_dict(state["_observation_space"]) + if state["_observation_space"] + else None + ) + episode._action_space = ( + gym_space_from_dict(state["_action_space"]) + if state["_action_space"] + else None + ) + episode._start_time = state["_start_time"] + episode._last_step_time = state["_last_step_time"] + episode._custom_data = state.get("custom_data", {}) + # Validate the episode. + episode.validate() + + return episode + + @property + def observation_space(self): + return self._observation_space + + @observation_space.setter + def observation_space(self, value): + self._observation_space = self.observations.space = value + + @property + def action_space(self): + return self._action_space + + @action_space.setter + def action_space(self, value): + self._action_space = self.actions.space = value + + def __len__(self) -> int: + """Returning the length of an episode. + + The length of an episode is defined by the length of its data, excluding + the lookback buffer data. The length is the number of timesteps an agent has + stepped through an environment thus far. + + The length is 0 in case of an episode whose env has NOT been reset yet, but + also 0 right after the `env.reset()` data has been added via + `self.add_env_reset()`. Only after the first call to `env.step()` (and + `self.add_env_step()`, the length will be 1. + + Returns: + An integer, defining the length of an episode. + """ + return self.t - self.t_started + + def __repr__(self): + return ( + f"SAEps(len={len(self)} done={self.is_done} " + f"R={self.get_return()} id_={self.id_})" + ) + + def __getitem__(self, item: slice) -> "SingleAgentEpisode": + """Enable squared bracket indexing- and slicing syntax, e.g. episode[-4:].""" + if isinstance(item, slice): + return self.slice(slice_=item) + else: + raise NotImplementedError( + f"SingleAgentEpisode does not support getting item '{item}'! " + "Only slice objects allowed with the syntax: `episode[a:b]`." + ) + + @Deprecated(new="SingleAgentEpisode.custom_data[some-key] = ...", error=True) + def add_temporary_timestep_data(self): + pass + + @Deprecated(new="SingleAgentEpisode.custom_data[some-key]", error=True) + def get_temporary_timestep_data(self): + pass diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/tcp_client_inference_env_runner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/tcp_client_inference_env_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..09f8f4a2e715ce46116d94b792106bf31797aa4a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/tcp_client_inference_env_runner.py @@ -0,0 +1,6 @@ +from ray.rllib.env.external.env_runner_server_for_external_inference import ( + EnvRunnerServerForExternalInference, +) + +# @Deprecated +TcpClientInferenceEnvRunner = EnvRunnerServerForExternalInference diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector_env.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector_env.py new file mode 100644 index 0000000000000000000000000000000000000000..b1da92dd0cad31a4fd2cdc7c2f3eeb5616aa129e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/env/vector_env.py @@ -0,0 +1,541 @@ +import logging +import gymnasium as gym +import numpy as np +from typing import Callable, List, Optional, Tuple, Union, Set + +from ray.rllib.env.base_env import BaseEnv, _DUMMY_AGENT_ID +from ray.rllib.utils.annotations import Deprecated, OldAPIStack, override +from ray.rllib.utils.typing import ( + EnvActionType, + EnvID, + EnvInfoDict, + EnvObsType, + EnvType, + MultiEnvDict, + AgentID, +) +from ray.util import log_once + +logger = logging.getLogger(__name__) + + +@OldAPIStack +class VectorEnv: + """An environment that supports batch evaluation using clones of sub-envs.""" + + def __init__( + self, observation_space: gym.Space, action_space: gym.Space, num_envs: int + ): + """Initializes a VectorEnv instance. + + Args: + observation_space: The observation Space of a single + sub-env. + action_space: The action Space of a single sub-env. + num_envs: The number of clones to make of the given sub-env. + """ + self.observation_space = observation_space + self.action_space = action_space + self.num_envs = num_envs + + @staticmethod + def vectorize_gym_envs( + make_env: Optional[Callable[[int], EnvType]] = None, + existing_envs: Optional[List[gym.Env]] = None, + num_envs: int = 1, + action_space: Optional[gym.Space] = None, + observation_space: Optional[gym.Space] = None, + restart_failed_sub_environments: bool = False, + # Deprecated. These seem to have never been used. + env_config=None, + policy_config=None, + ) -> "_VectorizedGymEnv": + """Translates any given gym.Env(s) into a VectorizedEnv object. + + Args: + make_env: Factory that produces a new gym.Env taking the sub-env's + vector index as only arg. Must be defined if the + number of `existing_envs` is less than `num_envs`. + existing_envs: Optional list of already instantiated sub + environments. + num_envs: Total number of sub environments in this VectorEnv. + action_space: The action space. If None, use existing_envs[0]'s + action space. + observation_space: The observation space. If None, use + existing_envs[0]'s observation space. + restart_failed_sub_environments: If True and any sub-environment (within + a vectorized env) throws any error during env stepping, the + Sampler will try to restart the faulty sub-environment. This is done + without disturbing the other (still intact) sub-environment and without + the RolloutWorker crashing. + + Returns: + The resulting _VectorizedGymEnv object (subclass of VectorEnv). + """ + return _VectorizedGymEnv( + make_env=make_env, + existing_envs=existing_envs or [], + num_envs=num_envs, + observation_space=observation_space, + action_space=action_space, + restart_failed_sub_environments=restart_failed_sub_environments, + ) + + def vector_reset( + self, *, seeds: Optional[List[int]] = None, options: Optional[List[dict]] = None + ) -> Tuple[List[EnvObsType], List[EnvInfoDict]]: + """Resets all sub-environments. + + Args: + seed: The list of seeds to be passed to the sub-environments' when resetting + them. If None, will not reset any existing PRNGs. If you pass + integers, the PRNGs will be reset even if they already exists. + options: The list of options dicts to be passed to the sub-environments' + when resetting them. + + Returns: + Tuple consitsing of a list of observations from each environment and + a list of info dicts from each environment. + """ + raise NotImplementedError + + def reset_at( + self, + index: Optional[int] = None, + *, + seed: Optional[int] = None, + options: Optional[dict] = None, + ) -> Union[Tuple[EnvObsType, EnvInfoDict], Exception]: + """Resets a single sub-environment. + + Args: + index: An optional sub-env index to reset. + seed: The seed to be passed to the sub-environment at index `index` when + resetting it. If None, will not reset any existing PRNG. If you pass an + integer, the PRNG will be reset even if it already exists. + options: An options dict to be passed to the sub-environment at index + `index` when resetting it. + + Returns: + Tuple consisting of observations from the reset sub environment and + an info dict of the reset sub environment. Alternatively an Exception + can be returned, indicating that the reset operation on the sub environment + has failed (and why it failed). + """ + raise NotImplementedError + + def restart_at(self, index: Optional[int] = None) -> None: + """Restarts a single sub-environment. + + Args: + index: An optional sub-env index to restart. + """ + raise NotImplementedError + + def vector_step( + self, actions: List[EnvActionType] + ) -> Tuple[ + List[EnvObsType], List[float], List[bool], List[bool], List[EnvInfoDict] + ]: + """Performs a vectorized step on all sub environments using `actions`. + + Args: + actions: List of actions (one for each sub-env). + + Returns: + A tuple consisting of + 1) New observations for each sub-env. + 2) Reward values for each sub-env. + 3) Terminated values for each sub-env. + 4) Truncated values for each sub-env. + 5) Info values for each sub-env. + """ + raise NotImplementedError + + def get_sub_environments(self) -> List[EnvType]: + """Returns the underlying sub environments. + + Returns: + List of all underlying sub environments. + """ + return [] + + # TODO: (sven) Experimental method. Make @PublicAPI at some point. + def try_render_at(self, index: Optional[int] = None) -> Optional[np.ndarray]: + """Renders a single environment. + + Args: + index: An optional sub-env index to render. + + Returns: + Either a numpy RGB image (shape=(w x h x 3) dtype=uint8) or + None in case rendering is handled directly by this method. + """ + pass + + def to_base_env( + self, + make_env: Optional[Callable[[int], EnvType]] = None, + num_envs: int = 1, + remote_envs: bool = False, + remote_env_batch_wait_ms: int = 0, + restart_failed_sub_environments: bool = False, + ) -> "BaseEnv": + """Converts an RLlib MultiAgentEnv into a BaseEnv object. + + The resulting BaseEnv is always vectorized (contains n + sub-environments) to support batched forward passes, where n may + also be 1. BaseEnv also supports async execution via the `poll` and + `send_actions` methods and thus supports external simulators. + + Args: + make_env: A callable taking an int as input (which indicates + the number of individual sub-environments within the final + vectorized BaseEnv) and returning one individual + sub-environment. + num_envs: The number of sub-environments to create in the + resulting (vectorized) BaseEnv. The already existing `env` + will be one of the `num_envs`. + remote_envs: Whether each sub-env should be a @ray.remote + actor. You can set this behavior in your config via the + `remote_worker_envs=True` option. + remote_env_batch_wait_ms: The wait time (in ms) to poll remote + sub-environments for, if applicable. Only used if + `remote_envs` is True. + + Returns: + The resulting BaseEnv object. + """ + env = VectorEnvWrapper(self) + return env + + @Deprecated(new="vectorize_gym_envs", error=True) + def wrap(self, *args, **kwargs) -> "_VectorizedGymEnv": + pass + + @Deprecated(new="get_sub_environments", error=True) + def get_unwrapped(self) -> List[EnvType]: + pass + + +@OldAPIStack +class _VectorizedGymEnv(VectorEnv): + """Internal wrapper to translate any gym.Envs into a VectorEnv object.""" + + def __init__( + self, + make_env: Optional[Callable[[int], EnvType]] = None, + existing_envs: Optional[List[gym.Env]] = None, + num_envs: int = 1, + *, + observation_space: Optional[gym.Space] = None, + action_space: Optional[gym.Space] = None, + restart_failed_sub_environments: bool = False, + # Deprecated. These seem to have never been used. + env_config=None, + policy_config=None, + ): + """Initializes a _VectorizedGymEnv object. + + Args: + make_env: Factory that produces a new gym.Env taking the sub-env's + vector index as only arg. Must be defined if the + number of `existing_envs` is less than `num_envs`. + existing_envs: Optional list of already instantiated sub + environments. + num_envs: Total number of sub environments in this VectorEnv. + action_space: The action space. If None, use existing_envs[0]'s + action space. + observation_space: The observation space. If None, use + existing_envs[0]'s observation space. + restart_failed_sub_environments: If True and any sub-environment (within + a vectorized env) throws any error during env stepping, we will try to + restart the faulty sub-environment. This is done + without disturbing the other (still intact) sub-environments. + """ + self.envs = existing_envs + self.make_env = make_env + self.restart_failed_sub_environments = restart_failed_sub_environments + + # Fill up missing envs (so we have exactly num_envs sub-envs in this + # VectorEnv. + while len(self.envs) < num_envs: + self.envs.append(make_env(len(self.envs))) + + super().__init__( + observation_space=observation_space or self.envs[0].observation_space, + action_space=action_space or self.envs[0].action_space, + num_envs=num_envs, + ) + + @override(VectorEnv) + def vector_reset( + self, *, seeds: Optional[List[int]] = None, options: Optional[List[dict]] = None + ) -> Tuple[List[EnvObsType], List[EnvInfoDict]]: + seeds = seeds or [None] * self.num_envs + options = options or [None] * self.num_envs + # Use reset_at(index) to restart and retry until + # we successfully create a new env. + resetted_obs = [] + resetted_infos = [] + for i in range(len(self.envs)): + while True: + obs, infos = self.reset_at(i, seed=seeds[i], options=options[i]) + if not isinstance(obs, Exception): + break + resetted_obs.append(obs) + resetted_infos.append(infos) + return resetted_obs, resetted_infos + + @override(VectorEnv) + def reset_at( + self, + index: Optional[int] = None, + *, + seed: Optional[int] = None, + options: Optional[dict] = None, + ) -> Tuple[Union[EnvObsType, Exception], Union[EnvInfoDict, Exception]]: + if index is None: + index = 0 + try: + obs_and_infos = self.envs[index].reset(seed=seed, options=options) + + except Exception as e: + if self.restart_failed_sub_environments: + logger.exception(e.args[0]) + self.restart_at(index) + obs_and_infos = e, {} + else: + raise e + + return obs_and_infos + + @override(VectorEnv) + def restart_at(self, index: Optional[int] = None) -> None: + if index is None: + index = 0 + + # Try closing down the old (possibly faulty) sub-env, but ignore errors. + try: + self.envs[index].close() + except Exception as e: + if log_once("close_sub_env"): + logger.warning( + "Trying to close old and replaced sub-environment (at vector " + f"index={index}), but closing resulted in error:\n{e}" + ) + env_to_del = self.envs[index] + self.envs[index] = None + del env_to_del + + # Re-create the sub-env at the new index. + logger.warning(f"Trying to restart sub-environment at index {index}.") + self.envs[index] = self.make_env(index) + logger.warning(f"Sub-environment at index {index} restarted successfully.") + + @override(VectorEnv) + def vector_step( + self, actions: List[EnvActionType] + ) -> Tuple[ + List[EnvObsType], List[float], List[bool], List[bool], List[EnvInfoDict] + ]: + obs_batch, reward_batch, terminated_batch, truncated_batch, info_batch = ( + [], + [], + [], + [], + [], + ) + for i in range(self.num_envs): + try: + results = self.envs[i].step(actions[i]) + except Exception as e: + if self.restart_failed_sub_environments: + logger.exception(e.args[0]) + self.restart_at(i) + results = e, 0.0, True, True, {} + else: + raise e + + obs, reward, terminated, truncated, info = results + + if not isinstance(info, dict): + raise ValueError( + "Info should be a dict, got {} ({})".format(info, type(info)) + ) + obs_batch.append(obs) + reward_batch.append(reward) + terminated_batch.append(terminated) + truncated_batch.append(truncated) + info_batch.append(info) + return obs_batch, reward_batch, terminated_batch, truncated_batch, info_batch + + @override(VectorEnv) + def get_sub_environments(self) -> List[EnvType]: + return self.envs + + @override(VectorEnv) + def try_render_at(self, index: Optional[int] = None): + if index is None: + index = 0 + return self.envs[index].render() + + +@OldAPIStack +class VectorEnvWrapper(BaseEnv): + """Internal adapter of VectorEnv to BaseEnv. + + We assume the caller will always send the full vector of actions in each + call to send_actions(), and that they call reset_at() on all completed + environments before calling send_actions(). + """ + + def __init__(self, vector_env: VectorEnv): + self.vector_env = vector_env + self.num_envs = vector_env.num_envs + self._observation_space = vector_env.observation_space + self._action_space = vector_env.action_space + + # Sub-environments' states. + self.new_obs = None + self.cur_rewards = None + self.cur_terminateds = None + self.cur_truncateds = None + self.cur_infos = None + # At first `poll()`, reset everything (all sub-environments). + self.first_reset_done = False + # Initialize sub-environments' state. + self._init_env_state(idx=None) + + @override(BaseEnv) + def poll( + self, + ) -> Tuple[ + MultiEnvDict, + MultiEnvDict, + MultiEnvDict, + MultiEnvDict, + MultiEnvDict, + MultiEnvDict, + ]: + from ray.rllib.env.base_env import with_dummy_agent_id + + if not self.first_reset_done: + self.first_reset_done = True + # TODO(sven): We probably would like to seed this call here as well. + self.new_obs, self.cur_infos = self.vector_env.vector_reset() + new_obs = dict(enumerate(self.new_obs)) + rewards = dict(enumerate(self.cur_rewards)) + terminateds = dict(enumerate(self.cur_terminateds)) + truncateds = dict(enumerate(self.cur_truncateds)) + infos = dict(enumerate(self.cur_infos)) + + # Empty all states (in case `poll()` gets called again). + self.new_obs = [] + self.cur_rewards = [] + self.cur_terminateds = [] + self.cur_truncateds = [] + self.cur_infos = [] + + return ( + with_dummy_agent_id(new_obs), + with_dummy_agent_id(rewards), + with_dummy_agent_id(terminateds, "__all__"), + with_dummy_agent_id(truncateds, "__all__"), + with_dummy_agent_id(infos), + {}, + ) + + @override(BaseEnv) + def send_actions(self, action_dict: MultiEnvDict) -> None: + from ray.rllib.env.base_env import _DUMMY_AGENT_ID + + action_vector = [None] * self.num_envs + for i in range(self.num_envs): + action_vector[i] = action_dict[i][_DUMMY_AGENT_ID] + ( + self.new_obs, + self.cur_rewards, + self.cur_terminateds, + self.cur_truncateds, + self.cur_infos, + ) = self.vector_env.vector_step(action_vector) + + @override(BaseEnv) + def try_reset( + self, + env_id: Optional[EnvID] = None, + *, + seed: Optional[int] = None, + options: Optional[dict] = None, + ) -> Tuple[MultiEnvDict, MultiEnvDict]: + from ray.rllib.env.base_env import _DUMMY_AGENT_ID + + if env_id is None: + env_id = 0 + assert isinstance(env_id, int) + obs, infos = self.vector_env.reset_at(env_id, seed=seed, options=options) + + # If exceptions were returned, return MultiEnvDict mapping env indices to + # these exceptions (for obs and infos). + if isinstance(obs, Exception): + return {env_id: obs}, {env_id: infos} + # Otherwise, return a MultiEnvDict (with single agent ID) and the actual + # obs and info dicts. + else: + return {env_id: {_DUMMY_AGENT_ID: obs}}, {env_id: {_DUMMY_AGENT_ID: infos}} + + @override(BaseEnv) + def try_restart(self, env_id: Optional[EnvID] = None) -> None: + assert env_id is None or isinstance(env_id, int) + # Restart the sub-env at the index. + self.vector_env.restart_at(env_id) + # Auto-reset (get ready for next `poll()`). + self._init_env_state(env_id) + + @override(BaseEnv) + def get_sub_environments(self, as_dict: bool = False) -> Union[List[EnvType], dict]: + if not as_dict: + return self.vector_env.get_sub_environments() + else: + return dict(enumerate(self.vector_env.get_sub_environments())) + + @override(BaseEnv) + def try_render(self, env_id: Optional[EnvID] = None) -> None: + assert env_id is None or isinstance(env_id, int) + return self.vector_env.try_render_at(env_id) + + @property + @override(BaseEnv) + def observation_space(self) -> gym.Space: + return self._observation_space + + @property + @override(BaseEnv) + def action_space(self) -> gym.Space: + return self._action_space + + @override(BaseEnv) + def get_agent_ids(self) -> Set[AgentID]: + return {_DUMMY_AGENT_ID} + + def _init_env_state(self, idx: Optional[int] = None) -> None: + """Resets all or one particular sub-environment's state (by index). + + Args: + idx: The index to reset at. If None, reset all the sub-environments' states. + """ + # If index is None, reset all sub-envs' states: + if idx is None: + self.new_obs = [None for _ in range(self.num_envs)] + self.cur_rewards = [0.0 for _ in range(self.num_envs)] + self.cur_terminateds = [False for _ in range(self.num_envs)] + self.cur_truncateds = [False for _ in range(self.num_envs)] + self.cur_infos = [{} for _ in range(self.num_envs)] + # Index provided, reset only the sub-env's state at the given index. + else: + self.new_obs[idx], self.cur_infos[idx] = self.vector_env.reset_at(idx) + # Reset all other states to null values. + self.cur_rewards[idx] = 0.0 + self.cur_terminateds[idx] = False + self.cur_truncateds[idx] = False diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..08f5bd48be3dbc03584483ed0066e5deac1efe2a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/__init__.py @@ -0,0 +1,20 @@ +from ray.rllib.evaluation.rollout_worker import RolloutWorker +from ray.rllib.evaluation.sample_batch_builder import ( + SampleBatchBuilder, + MultiAgentSampleBatchBuilder, +) +from ray.rllib.evaluation.sampler import SyncSampler +from ray.rllib.evaluation.postprocessing import compute_advantages +from ray.rllib.evaluation.metrics import collect_metrics +from ray.rllib.policy.sample_batch import SampleBatch, MultiAgentBatch + +__all__ = [ + "RolloutWorker", + "SampleBatch", + "MultiAgentBatch", + "SampleBatchBuilder", + "MultiAgentSampleBatchBuilder", + "SyncSampler", + "compute_advantages", + "collect_metrics", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/env_runner_v2.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/env_runner_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..f052ee7915573de385ef446d32a266d6b7ff475b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/env_runner_v2.py @@ -0,0 +1,1232 @@ +from collections import defaultdict +import logging +import time +import tree # pip install dm_tree +from typing import TYPE_CHECKING, Dict, Iterator, List, Optional, Set, Tuple, Union +import numpy as np + +from ray.rllib.env.base_env import ASYNC_RESET_RETURN, BaseEnv +from ray.rllib.env.external_env import ExternalEnvWrapper +from ray.rllib.env.wrappers.atari_wrappers import MonitorEnv, get_wrapper_by_cls +from ray.rllib.evaluation.collectors.simple_list_collector import _PolicyCollectorGroup +from ray.rllib.evaluation.episode_v2 import EpisodeV2 +from ray.rllib.evaluation.metrics import RolloutMetrics +from ray.rllib.models.preprocessors import Preprocessor +from ray.rllib.policy.policy import Policy +from ray.rllib.policy.sample_batch import MultiAgentBatch, SampleBatch, concat_samples +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.filter import Filter +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.spaces.space_utils import unbatch, get_original_space +from ray.rllib.utils.typing import ( + ActionConnectorDataType, + AgentConnectorDataType, + AgentID, + EnvActionType, + EnvID, + EnvInfoDict, + EnvObsType, + MultiAgentDict, + MultiEnvDict, + PolicyID, + PolicyOutputType, + SampleBatchType, + StateBatches, + TensorStructType, +) +from ray.util.debug import log_once + +if TYPE_CHECKING: + from gymnasium.envs.classic_control.rendering import SimpleImageViewer + + from ray.rllib.callbacks.callbacks import RLlibCallback + from ray.rllib.evaluation.rollout_worker import RolloutWorker + + +logger = logging.getLogger(__name__) + + +MIN_LARGE_BATCH_THRESHOLD = 1000 +DEFAULT_LARGE_BATCH_THRESHOLD = 5000 +MS_TO_SEC = 1000.0 + + +@OldAPIStack +class _PerfStats: + """Sampler perf stats that will be included in rollout metrics.""" + + def __init__(self, ema_coef: Optional[float] = None): + # If not None, enable Exponential Moving Average mode. + # The way we update stats is by: + # updated = (1 - ema_coef) * old + ema_coef * new + # In general provides more responsive stats about sampler performance. + # TODO(jungong) : make ema the default (only) mode if it works well. + self.ema_coef = ema_coef + + self.iters = 0 + self.raw_obs_processing_time = 0.0 + self.inference_time = 0.0 + self.action_processing_time = 0.0 + self.env_wait_time = 0.0 + self.env_render_time = 0.0 + + def incr(self, field: str, value: Union[int, float]): + if field == "iters": + self.iters += value + return + + # All the other fields support either global average or ema mode. + if self.ema_coef is None: + # Global average. + self.__dict__[field] += value + else: + self.__dict__[field] = (1.0 - self.ema_coef) * self.__dict__[ + field + ] + self.ema_coef * value + + def _get_avg(self): + # Mean multiplicator (1000 = sec -> ms). + factor = MS_TO_SEC / self.iters + return { + # Raw observation preprocessing. + "mean_raw_obs_processing_ms": self.raw_obs_processing_time * factor, + # Computing actions through policy. + "mean_inference_ms": self.inference_time * factor, + # Processing actions (to be sent to env, e.g. clipping). + "mean_action_processing_ms": self.action_processing_time * factor, + # Waiting for environment (during poll). + "mean_env_wait_ms": self.env_wait_time * factor, + # Environment rendering (False by default). + "mean_env_render_ms": self.env_render_time * factor, + } + + def _get_ema(self): + # In EMA mode, stats are already (exponentially) averaged, + # hence we only need to do the sec -> ms conversion here. + return { + # Raw observation preprocessing. + "mean_raw_obs_processing_ms": self.raw_obs_processing_time * MS_TO_SEC, + # Computing actions through policy. + "mean_inference_ms": self.inference_time * MS_TO_SEC, + # Processing actions (to be sent to env, e.g. clipping). + "mean_action_processing_ms": self.action_processing_time * MS_TO_SEC, + # Waiting for environment (during poll). + "mean_env_wait_ms": self.env_wait_time * MS_TO_SEC, + # Environment rendering (False by default). + "mean_env_render_ms": self.env_render_time * MS_TO_SEC, + } + + def get(self): + if self.ema_coef is None: + return self._get_avg() + else: + return self._get_ema() + + +@OldAPIStack +class _NewDefaultDict(defaultdict): + def __missing__(self, env_id): + ret = self[env_id] = self.default_factory(env_id) + return ret + + +@OldAPIStack +def _build_multi_agent_batch( + episode_id: int, + batch_builder: _PolicyCollectorGroup, + large_batch_threshold: int, + multiple_episodes_in_batch: bool, +) -> MultiAgentBatch: + """Build MultiAgentBatch from a dict of _PolicyCollectors. + + Args: + env_steps: total env steps. + policy_collectors: collected training SampleBatchs by policy. + + Returns: + Always returns a sample batch in MultiAgentBatch format. + """ + ma_batch = {} + for pid, collector in batch_builder.policy_collectors.items(): + if collector.agent_steps <= 0: + continue + + if batch_builder.agent_steps > large_batch_threshold and log_once( + "large_batch_warning" + ): + logger.warning( + "More than {} observations in {} env steps for " + "episode {} ".format( + batch_builder.agent_steps, batch_builder.env_steps, episode_id + ) + + "are buffered in the sampler. If this is more than you " + "expected, check that that you set a horizon on your " + "environment correctly and that it terminates at some " + "point. Note: In multi-agent environments, " + "`rollout_fragment_length` sets the batch size based on " + "(across-agents) environment steps, not the steps of " + "individual agents, which can result in unexpectedly " + "large batches." + + ( + "Also, you may be waiting for your Env to " + "terminate (batch_mode=`complete_episodes`). Make sure " + "it does at some point." + if not multiple_episodes_in_batch + else "" + ) + ) + + batch = collector.build() + + ma_batch[pid] = batch + + # Create the multi agent batch. + return MultiAgentBatch(policy_batches=ma_batch, env_steps=batch_builder.env_steps) + + +@OldAPIStack +def _batch_inference_sample_batches(eval_data: List[SampleBatch]) -> SampleBatch: + """Batch a list of input SampleBatches into a single SampleBatch. + + Args: + eval_data: list of SampleBatches. + + Returns: + single batched SampleBatch. + """ + inference_batch = concat_samples(eval_data) + if "state_in_0" in inference_batch: + batch_size = len(eval_data) + inference_batch[SampleBatch.SEQ_LENS] = np.ones(batch_size, dtype=np.int32) + return inference_batch + + +@OldAPIStack +class EnvRunnerV2: + """Collect experiences from user environment using Connectors.""" + + def __init__( + self, + worker: "RolloutWorker", + base_env: BaseEnv, + multiple_episodes_in_batch: bool, + callbacks: "RLlibCallback", + perf_stats: _PerfStats, + rollout_fragment_length: int = 200, + count_steps_by: str = "env_steps", + render: bool = None, + ): + """ + Args: + worker: Reference to the current rollout worker. + base_env: Env implementing BaseEnv. + multiple_episodes_in_batch: Whether to pack multiple + episodes into each batch. This guarantees batches will be exactly + `rollout_fragment_length` in size. + callbacks: User callbacks to run on episode events. + perf_stats: Record perf stats into this object. + rollout_fragment_length: The length of a fragment to collect + before building a SampleBatch from the data and resetting + the SampleBatchBuilder object. + count_steps_by: One of "env_steps" (default) or "agent_steps". + Use "agent_steps", if you want rollout lengths to be counted + by individual agent steps. In a multi-agent env, + a single env_step contains one or more agent_steps, depending + on how many agents are present at any given time in the + ongoing episode. + render: Whether to try to render the environment after each + step. + """ + self._worker = worker + if isinstance(base_env, ExternalEnvWrapper): + raise ValueError( + "Policies using the new Connector API do not support ExternalEnv." + ) + self._base_env = base_env + self._multiple_episodes_in_batch = multiple_episodes_in_batch + self._callbacks = callbacks + self._perf_stats = perf_stats + self._rollout_fragment_length = rollout_fragment_length + self._count_steps_by = count_steps_by + self._render = render + + # May be populated for image rendering. + self._simple_image_viewer: Optional[ + "SimpleImageViewer" + ] = self._get_simple_image_viewer() + + # Keeps track of active episodes. + self._active_episodes: Dict[EnvID, EpisodeV2] = {} + self._batch_builders: Dict[EnvID, _PolicyCollectorGroup] = _NewDefaultDict( + self._new_batch_builder + ) + + self._large_batch_threshold: int = ( + max(MIN_LARGE_BATCH_THRESHOLD, self._rollout_fragment_length * 10) + if self._rollout_fragment_length != float("inf") + else DEFAULT_LARGE_BATCH_THRESHOLD + ) + + def _get_simple_image_viewer(self): + """Maybe construct a SimpleImageViewer instance for episode rendering.""" + # Try to render the env, if required. + if not self._render: + return None + + try: + from gymnasium.envs.classic_control.rendering import SimpleImageViewer + + return SimpleImageViewer() + except (ImportError, ModuleNotFoundError): + self._render = False # disable rendering + logger.warning( + "Could not import gymnasium.envs.classic_control." + "rendering! Try `pip install gymnasium[all]`." + ) + + return None + + def _call_on_episode_start(self, episode, env_id): + # Call each policy's Exploration.on_episode_start method. + # Note: This may break the exploration (e.g. ParameterNoise) of + # policies in the `policy_map` that have not been recently used + # (and are therefore stashed to disk). However, we certainly do not + # want to loop through all (even stashed) policies here as that + # would counter the purpose of the LRU policy caching. + for p in self._worker.policy_map.cache.values(): + if getattr(p, "exploration", None) is not None: + p.exploration.on_episode_start( + policy=p, + environment=self._base_env, + episode=episode, + tf_sess=p.get_session(), + ) + # Call `on_episode_start()` callback. + self._callbacks.on_episode_start( + worker=self._worker, + base_env=self._base_env, + policies=self._worker.policy_map, + env_index=env_id, + episode=episode, + ) + + def _new_batch_builder(self, _) -> _PolicyCollectorGroup: + """Create a new batch builder. + + We create a _PolicyCollectorGroup based on the full policy_map + as the batch builder. + """ + return _PolicyCollectorGroup(self._worker.policy_map) + + def run(self) -> Iterator[SampleBatchType]: + """Samples and yields training episodes continuously. + + Yields: + Object containing state, action, reward, terminal condition, + and other fields as dictated by `policy`. + """ + while True: + outputs = self.step() + for o in outputs: + yield o + + def step(self) -> List[SampleBatchType]: + """Samples training episodes by stepping through environments.""" + + self._perf_stats.incr("iters", 1) + + t0 = time.time() + # Get observations from all ready agents. + # types: MultiEnvDict, MultiEnvDict, MultiEnvDict, MultiEnvDict, ... + ( + unfiltered_obs, + rewards, + terminateds, + truncateds, + infos, + off_policy_actions, + ) = self._base_env.poll() + env_poll_time = time.time() - t0 + + # Process observations and prepare for policy evaluation. + t1 = time.time() + # types: Set[EnvID], Dict[PolicyID, List[AgentConnectorDataType]], + # List[Union[RolloutMetrics, SampleBatchType]] + active_envs, to_eval, outputs = self._process_observations( + unfiltered_obs=unfiltered_obs, + rewards=rewards, + terminateds=terminateds, + truncateds=truncateds, + infos=infos, + ) + self._perf_stats.incr("raw_obs_processing_time", time.time() - t1) + + # Do batched policy eval (accross vectorized envs). + t2 = time.time() + # types: Dict[PolicyID, Tuple[TensorStructType, StateBatch, dict]] + eval_results = self._do_policy_eval(to_eval=to_eval) + self._perf_stats.incr("inference_time", time.time() - t2) + + # Process results and update episode state. + t3 = time.time() + actions_to_send: Dict[ + EnvID, Dict[AgentID, EnvActionType] + ] = self._process_policy_eval_results( + active_envs=active_envs, + to_eval=to_eval, + eval_results=eval_results, + off_policy_actions=off_policy_actions, + ) + self._perf_stats.incr("action_processing_time", time.time() - t3) + + # Return computed actions to ready envs. We also send to envs that have + # taken off-policy actions; those envs are free to ignore the action. + t4 = time.time() + self._base_env.send_actions(actions_to_send) + self._perf_stats.incr("env_wait_time", env_poll_time + time.time() - t4) + + self._maybe_render() + + return outputs + + def _get_rollout_metrics( + self, episode: EpisodeV2, policy_map: Dict[str, Policy] + ) -> List[RolloutMetrics]: + """Get rollout metrics from completed episode.""" + # TODO(jungong) : why do we need to handle atari metrics differently? + # Can we unify atari and normal env metrics? + atari_metrics: List[RolloutMetrics] = _fetch_atari_metrics(self._base_env) + if atari_metrics is not None: + for m in atari_metrics: + m._replace(custom_metrics=episode.custom_metrics) + return atari_metrics + # Create connector metrics + connector_metrics = {} + active_agents = episode.get_agents() + for agent in active_agents: + policy_id = episode.policy_for(agent) + policy = episode.policy_map[policy_id] + connector_metrics[policy_id] = policy.get_connector_metrics() + # Otherwise, return RolloutMetrics for the episode. + return [ + RolloutMetrics( + episode_length=episode.length, + episode_reward=episode.total_reward, + agent_rewards=dict(episode.agent_rewards), + custom_metrics=episode.custom_metrics, + perf_stats={}, + hist_data=episode.hist_data, + media=episode.media, + connector_metrics=connector_metrics, + ) + ] + + def _process_observations( + self, + unfiltered_obs: MultiEnvDict, + rewards: MultiEnvDict, + terminateds: MultiEnvDict, + truncateds: MultiEnvDict, + infos: MultiEnvDict, + ) -> Tuple[ + Set[EnvID], + Dict[PolicyID, List[AgentConnectorDataType]], + List[Union[RolloutMetrics, SampleBatchType]], + ]: + """Process raw obs from env. + + Group data for active agents by policy. Reset environments that are done. + + Args: + unfiltered_obs: The unfiltered, raw observations from the BaseEnv + (vectorized, possibly multi-agent). Dict of dict: By env index, + then agent ID, then mapped to actual obs. + rewards: The rewards MultiEnvDict of the BaseEnv. + terminateds: The `terminated` flags MultiEnvDict of the BaseEnv. + truncateds: The `truncated` flags MultiEnvDict of the BaseEnv. + infos: The MultiEnvDict of infos dicts of the BaseEnv. + + Returns: + A tuple of: + A list of envs that were active during this step. + AgentConnectorDataType for active agents for policy evaluation. + SampleBatches and RolloutMetrics for completed agents for output. + """ + # Output objects. + # Note that we need to track envs that are active during this round explicitly, + # just to be confident which envs require us to send at least an empty action + # dict to. + # We can not get this from the _active_episode or to_eval lists because + # 1. All envs are not required to step during every single step. And + # 2. to_eval only contains data for the agents that are still active. An env may + # be active but all agents are done during the step. + active_envs: Set[EnvID] = set() + to_eval: Dict[PolicyID, List[AgentConnectorDataType]] = defaultdict(list) + outputs: List[Union[RolloutMetrics, SampleBatchType]] = [] + + # For each (vectorized) sub-environment. + # types: EnvID, Dict[AgentID, EnvObsType] + for env_id, env_obs in unfiltered_obs.items(): + # Check for env_id having returned an error instead of a multi-agent + # obs dict. This is how our BaseEnv can tell the caller to `poll()` that + # one of its sub-environments is faulty and should be restarted (and the + # ongoing episode should not be used for training). + if isinstance(env_obs, Exception): + assert terminateds[env_id]["__all__"] is True, ( + f"ERROR: When a sub-environment (env-id {env_id}) returns an error " + "as observation, the terminateds[__all__] flag must also be set to " + "True!" + ) + # all_agents_obs is an Exception here. + # Drop this episode and skip to next. + self._handle_done_episode( + env_id=env_id, + env_obs_or_exception=env_obs, + is_done=True, + active_envs=active_envs, + to_eval=to_eval, + outputs=outputs, + ) + continue + + if env_id not in self._active_episodes: + episode: EpisodeV2 = self.create_episode(env_id) + self._active_episodes[env_id] = episode + else: + episode: EpisodeV2 = self._active_episodes[env_id] + # If this episode is brand-new, call the episode start callback(s). + # Note: EpisodeV2s are initialized with length=-1 (before the reset). + if not episode.has_init_obs(): + self._call_on_episode_start(episode, env_id) + + # Check episode termination conditions. + if terminateds[env_id]["__all__"] or truncateds[env_id]["__all__"]: + all_agents_done = True + else: + all_agents_done = False + active_envs.add(env_id) + + # Special handling of common info dict. + episode.set_last_info("__common__", infos[env_id].get("__common__", {})) + + # Agent sample batches grouped by policy. Each set of sample batches will + # go through agent connectors together. + sample_batches_by_policy = defaultdict(list) + # Whether an agent is terminated or truncated. + agent_terminateds = {} + agent_truncateds = {} + for agent_id, obs in env_obs.items(): + assert agent_id != "__all__" + + policy_id: PolicyID = episode.policy_for(agent_id) + + agent_terminated = bool( + terminateds[env_id]["__all__"] or terminateds[env_id].get(agent_id) + ) + agent_terminateds[agent_id] = agent_terminated + agent_truncated = bool( + truncateds[env_id]["__all__"] + or truncateds[env_id].get(agent_id, False) + ) + agent_truncateds[agent_id] = agent_truncated + + # A completely new agent is already done -> Skip entirely. + if not episode.has_init_obs(agent_id) and ( + agent_terminated or agent_truncated + ): + continue + + values_dict = { + SampleBatch.T: episode.length, # Episodes start at -1 before we + # add the initial obs. After that, we infer from initial obs at + # t=0 since that will be our new episode.length. + SampleBatch.ENV_ID: env_id, + SampleBatch.AGENT_INDEX: episode.agent_index(agent_id), + # Last action (SampleBatch.ACTIONS) column will be populated by + # StateBufferConnector. + # Reward received after taking action at timestep t. + SampleBatch.REWARDS: rewards[env_id].get(agent_id, 0.0), + # After taking action=a, did we reach terminal? + SampleBatch.TERMINATEDS: agent_terminated, + # Was the episode truncated artificially + # (e.g. b/c of some time limit)? + SampleBatch.TRUNCATEDS: agent_truncated, + SampleBatch.INFOS: infos[env_id].get(agent_id, {}), + SampleBatch.NEXT_OBS: obs, + } + + # Queue this obs sample for connector preprocessing. + sample_batches_by_policy[policy_id].append((agent_id, values_dict)) + + # The entire episode is done. + if all_agents_done: + # Let's check to see if there are any agents that haven't got the + # last obs yet. If there are, we have to create fake-last + # observations for them. (the environment is not required to do so if + # terminateds[__all__]==True or truncateds[__all__]==True). + for agent_id in episode.get_agents(): + # If the latest obs we got for this agent is done, or if its + # episode state is already done, nothing to do. + if ( + agent_terminateds.get(agent_id, False) + or agent_truncateds.get(agent_id, False) + or episode.is_done(agent_id) + ): + continue + + policy_id: PolicyID = episode.policy_for(agent_id) + policy = self._worker.policy_map[policy_id] + + # Create a fake observation by sampling the original env + # observation space. + obs_space = get_original_space(policy.observation_space) + # Although there is no obs for this agent, there may be + # good rewards and info dicts for it. + # This is the case for e.g. OpenSpiel games, where a reward + # is only earned with the last step, but the obs for that + # step is {}. + reward = rewards[env_id].get(agent_id, 0.0) + info = infos[env_id].get(agent_id, {}) + values_dict = { + SampleBatch.T: episode.length, + SampleBatch.ENV_ID: env_id, + SampleBatch.AGENT_INDEX: episode.agent_index(agent_id), + # TODO(sven): These should be the summed-up(!) rewards since the + # last observation received for this agent. + SampleBatch.REWARDS: reward, + SampleBatch.TERMINATEDS: True, + SampleBatch.TRUNCATEDS: truncateds[env_id].get(agent_id, False), + SampleBatch.INFOS: info, + SampleBatch.NEXT_OBS: obs_space.sample(), + } + + # Queue these fake obs for connector preprocessing too. + sample_batches_by_policy[policy_id].append((agent_id, values_dict)) + + # Run agent connectors. + for policy_id, batches in sample_batches_by_policy.items(): + policy: Policy = self._worker.policy_map[policy_id] + # Collected full MultiAgentDicts for this environment. + # Run agent connectors. + assert ( + policy.agent_connectors + ), "EnvRunnerV2 requires agent connectors to work." + + acd_list: List[AgentConnectorDataType] = [ + AgentConnectorDataType(env_id, agent_id, data) + for agent_id, data in batches + ] + + # For all agents mapped to policy_id, run their data + # through agent_connectors. + processed = policy.agent_connectors(acd_list) + + for d in processed: + # Record transition info if applicable. + if not episode.has_init_obs(d.agent_id): + episode.add_init_obs( + agent_id=d.agent_id, + init_obs=d.data.raw_dict[SampleBatch.NEXT_OBS], + init_infos=d.data.raw_dict[SampleBatch.INFOS], + t=d.data.raw_dict[SampleBatch.T], + ) + else: + episode.add_action_reward_done_next_obs( + d.agent_id, d.data.raw_dict + ) + + # Need to evaluate next actions. + if not ( + all_agents_done + or agent_terminateds.get(d.agent_id, False) + or agent_truncateds.get(d.agent_id, False) + or episode.is_done(d.agent_id) + ): + # Add to eval set if env is not done and this particular agent + # is also not done. + item = AgentConnectorDataType(d.env_id, d.agent_id, d.data) + to_eval[policy_id].append(item) + + # Finished advancing episode by 1 step, mark it so. + episode.step() + + # Exception: The very first env.poll() call causes the env to get reset + # (no step taken yet, just a single starting observation logged). + # We need to skip this callback in this case. + if episode.length > 0: + # Invoke the `on_episode_step` callback after the step is logged + # to the episode. + self._callbacks.on_episode_step( + worker=self._worker, + base_env=self._base_env, + policies=self._worker.policy_map, + episode=episode, + env_index=env_id, + ) + + # Episode is terminated/truncated for all agents + # (terminateds[__all__] == True or truncateds[__all__] == True). + if all_agents_done: + # _handle_done_episode will build a MultiAgentBatch for all + # the agents that are done during this step of rollout in + # the case of _multiple_episodes_in_batch=False. + self._handle_done_episode( + env_id, + env_obs, + terminateds[env_id]["__all__"] or truncateds[env_id]["__all__"], + active_envs, + to_eval, + outputs, + ) + + # Try to build something. + if self._multiple_episodes_in_batch: + sample_batch = self._try_build_truncated_episode_multi_agent_batch( + self._batch_builders[env_id], episode + ) + if sample_batch: + outputs.append(sample_batch) + + # SampleBatch built from data collected by batch_builder. + # Clean up and delete the batch_builder. + del self._batch_builders[env_id] + + return active_envs, to_eval, outputs + + def _build_done_episode( + self, + env_id: EnvID, + is_done: bool, + outputs: List[SampleBatchType], + ): + """Builds a MultiAgentSampleBatch from the episode and adds it to outputs. + + Args: + env_id: The env id. + is_done: Whether the env is done. + outputs: The list of outputs to add the + """ + episode: EpisodeV2 = self._active_episodes[env_id] + batch_builder = self._batch_builders[env_id] + + episode.postprocess_episode( + batch_builder=batch_builder, + is_done=is_done, + check_dones=is_done, + ) + + # If, we are not allowed to pack the next episode into the same + # SampleBatch (batch_mode=complete_episodes) -> Build the + # MultiAgentBatch from a single episode and add it to "outputs". + # Otherwise, just postprocess and continue collecting across + # episodes. + if not self._multiple_episodes_in_batch: + ma_sample_batch = _build_multi_agent_batch( + episode.episode_id, + batch_builder, + self._large_batch_threshold, + self._multiple_episodes_in_batch, + ) + if ma_sample_batch: + outputs.append(ma_sample_batch) + + # SampleBatch built from data collected by batch_builder. + # Clean up and delete the batch_builder. + del self._batch_builders[env_id] + + def __process_resetted_obs_for_eval( + self, + env_id: EnvID, + obs: Dict[EnvID, Dict[AgentID, EnvObsType]], + infos: Dict[EnvID, Dict[AgentID, EnvInfoDict]], + episode: EpisodeV2, + to_eval: Dict[PolicyID, List[AgentConnectorDataType]], + ): + """Process resetted obs through agent connectors for policy eval. + + Args: + env_id: The env id. + obs: The Resetted obs. + episode: New episode. + to_eval: List of agent connector data for policy eval. + """ + per_policy_resetted_obs: Dict[PolicyID, List] = defaultdict(list) + # types: AgentID, EnvObsType + for agent_id, raw_obs in obs[env_id].items(): + policy_id: PolicyID = episode.policy_for(agent_id) + per_policy_resetted_obs[policy_id].append((agent_id, raw_obs)) + + for policy_id, agents_obs in per_policy_resetted_obs.items(): + policy = self._worker.policy_map[policy_id] + acd_list: List[AgentConnectorDataType] = [ + AgentConnectorDataType( + env_id, + agent_id, + { + SampleBatch.NEXT_OBS: obs, + SampleBatch.INFOS: infos, + SampleBatch.T: episode.length, + SampleBatch.AGENT_INDEX: episode.agent_index(agent_id), + }, + ) + for agent_id, obs in agents_obs + ] + # Call agent connectors on these initial obs. + processed = policy.agent_connectors(acd_list) + + for d in processed: + episode.add_init_obs( + agent_id=d.agent_id, + init_obs=d.data.raw_dict[SampleBatch.NEXT_OBS], + init_infos=d.data.raw_dict[SampleBatch.INFOS], + t=d.data.raw_dict[SampleBatch.T], + ) + to_eval[policy_id].append(d) + + def _handle_done_episode( + self, + env_id: EnvID, + env_obs_or_exception: MultiAgentDict, + is_done: bool, + active_envs: Set[EnvID], + to_eval: Dict[PolicyID, List[AgentConnectorDataType]], + outputs: List[SampleBatchType], + ) -> None: + """Handle an all-finished episode. + + Add collected SampleBatch to batch builder. Reset corresponding env, etc. + + Args: + env_id: Environment ID. + env_obs_or_exception: Last per-environment observation or Exception. + env_infos: Last per-environment infos. + is_done: If all agents are done. + active_envs: Set of active env ids. + to_eval: Output container for policy eval data. + outputs: Output container for collected sample batches. + """ + if isinstance(env_obs_or_exception, Exception): + episode_or_exception: Exception = env_obs_or_exception + # Tell the sampler we have got a faulty episode. + outputs.append(RolloutMetrics(episode_faulty=True)) + else: + episode_or_exception: EpisodeV2 = self._active_episodes[env_id] + # Add rollout metrics. + outputs.extend( + self._get_rollout_metrics( + episode_or_exception, policy_map=self._worker.policy_map + ) + ) + # Output the collected episode after adding rollout metrics so that we + # always fetch metrics with RolloutWorker before we fetch samples. + # This is because we need to behave like env_runner() for now. + self._build_done_episode(env_id, is_done, outputs) + + # Clean up and deleted the post-processed episode now that we have collected + # its data. + self.end_episode(env_id, episode_or_exception) + # Create a new episode instance (before we reset the sub-environment). + new_episode: EpisodeV2 = self.create_episode(env_id) + + # The sub environment at index `env_id` might throw an exception + # during the following `try_reset()` attempt. If configured with + # `restart_failed_sub_environments=True`, the BaseEnv will restart + # the affected sub environment (create a new one using its c'tor) and + # must reset the recreated sub env right after that. + # Should the sub environment fail indefinitely during these + # repeated reset attempts, the entire worker will be blocked. + # This would be ok, b/c the alternative would be the worker crashing + # entirely. + while True: + resetted_obs, resetted_infos = self._base_env.try_reset(env_id) + + if ( + resetted_obs is None + or resetted_obs == ASYNC_RESET_RETURN + or not isinstance(resetted_obs[env_id], Exception) + ): + break + else: + # Report a faulty episode. + outputs.append(RolloutMetrics(episode_faulty=True)) + + # Reset connector state if this is a hard reset. + for p in self._worker.policy_map.cache.values(): + p.agent_connectors.reset(env_id) + + # Creates a new episode if this is not async return. + # If reset is async, we will get its result in some future poll. + if resetted_obs is not None and resetted_obs != ASYNC_RESET_RETURN: + self._active_episodes[env_id] = new_episode + self._call_on_episode_start(new_episode, env_id) + + self.__process_resetted_obs_for_eval( + env_id, + resetted_obs, + resetted_infos, + new_episode, + to_eval, + ) + + # Step after adding initial obs. This will give us 0 env and agent step. + new_episode.step() + active_envs.add(env_id) + + def create_episode(self, env_id: EnvID) -> EpisodeV2: + """Creates a new EpisodeV2 instance and returns it. + + Calls `on_episode_created` callbacks, but does NOT reset the respective + sub-environment yet. + + Args: + env_id: Env ID. + + Returns: + The newly created EpisodeV2 instance. + """ + # Make sure we currently don't have an active episode under this env ID. + assert env_id not in self._active_episodes + + # Create a new episode under the same `env_id` and call the + # `on_episode_created` callbacks. + new_episode = EpisodeV2( + env_id, + self._worker.policy_map, + self._worker.policy_mapping_fn, + worker=self._worker, + callbacks=self._callbacks, + ) + + # Call `on_episode_created()` callback. + self._callbacks.on_episode_created( + worker=self._worker, + base_env=self._base_env, + policies=self._worker.policy_map, + env_index=env_id, + episode=new_episode, + ) + return new_episode + + def end_episode( + self, env_id: EnvID, episode_or_exception: Union[EpisodeV2, Exception] + ): + """Cleans up an episode that has finished. + + Args: + env_id: Env ID. + episode_or_exception: Instance of an episode if it finished successfully. + Otherwise, the exception that was thrown, + """ + # Signal the end of an episode, either successfully with an Episode or + # unsuccessfully with an Exception. + self._callbacks.on_episode_end( + worker=self._worker, + base_env=self._base_env, + policies=self._worker.policy_map, + episode=episode_or_exception, + env_index=env_id, + ) + + # Call each (in-memory) policy's Exploration.on_episode_end + # method. + # Note: This may break the exploration (e.g. ParameterNoise) of + # policies in the `policy_map` that have not been recently used + # (and are therefore stashed to disk). However, we certainly do not + # want to loop through all (even stashed) policies here as that + # would counter the purpose of the LRU policy caching. + for p in self._worker.policy_map.cache.values(): + if getattr(p, "exploration", None) is not None: + p.exploration.on_episode_end( + policy=p, + environment=self._base_env, + episode=episode_or_exception, + tf_sess=p.get_session(), + ) + + if isinstance(episode_or_exception, EpisodeV2): + episode = episode_or_exception + if episode.total_agent_steps == 0: + # if the key does not exist it means that throughout the episode all + # observations were empty (i.e. there was no agent in the env) + msg = ( + f"Data from episode {episode.episode_id} does not show any agent " + f"interactions. Hint: Make sure for at least one timestep in the " + f"episode, env.step() returns non-empty values." + ) + raise ValueError(msg) + + # Clean up the episode and batch_builder for this env id. + if env_id in self._active_episodes: + del self._active_episodes[env_id] + + def _try_build_truncated_episode_multi_agent_batch( + self, batch_builder: _PolicyCollectorGroup, episode: EpisodeV2 + ) -> Union[None, SampleBatch, MultiAgentBatch]: + # Measure batch size in env-steps. + if self._count_steps_by == "env_steps": + built_steps = batch_builder.env_steps + ongoing_steps = episode.active_env_steps + # Measure batch-size in agent-steps. + else: + built_steps = batch_builder.agent_steps + ongoing_steps = episode.active_agent_steps + + # Reached the fragment-len -> We should build an MA-Batch. + if built_steps + ongoing_steps >= self._rollout_fragment_length: + if self._count_steps_by != "agent_steps": + assert built_steps + ongoing_steps == self._rollout_fragment_length, ( + f"built_steps ({built_steps}) + ongoing_steps ({ongoing_steps}) != " + f"rollout_fragment_length ({self._rollout_fragment_length})." + ) + + # If we reached the fragment-len only because of `episode_id` + # (still ongoing) -> postprocess `episode_id` first. + if built_steps < self._rollout_fragment_length: + episode.postprocess_episode(batch_builder=batch_builder, is_done=False) + + # If builder has collected some data, + # build the MA-batch and add to return values. + if batch_builder.agent_steps > 0: + return _build_multi_agent_batch( + episode.episode_id, + batch_builder, + self._large_batch_threshold, + self._multiple_episodes_in_batch, + ) + # No batch-builder: + # We have reached the rollout-fragment length w/o any agent + # steps! Warn that the environment may never request any + # actions from any agents. + elif log_once("no_agent_steps"): + logger.warning( + "Your environment seems to be stepping w/o ever " + "emitting agent observations (agents are never " + "requested to act)!" + ) + + return None + + def _do_policy_eval( + self, + to_eval: Dict[PolicyID, List[AgentConnectorDataType]], + ) -> Dict[PolicyID, PolicyOutputType]: + """Call compute_actions on collected episode data to get next action. + + Args: + to_eval: Mapping of policy IDs to lists of AgentConnectorDataType objects + (items in these lists will be the batch's items for the model + forward pass). + + Returns: + Dict mapping PolicyIDs to compute_actions_from_input_dict() outputs. + """ + policies = self._worker.policy_map + + # In case policy map has changed, try to find the new policy that + # should handle all these per-agent eval data. + # Throws exception if these agents are mapped to multiple different + # policies now. + def _try_find_policy_again(eval_data: AgentConnectorDataType): + policy_id = None + for d in eval_data: + episode = self._active_episodes[d.env_id] + # Force refresh policy mapping on the episode. + pid = episode.policy_for(d.agent_id, refresh=True) + if policy_id is not None and pid != policy_id: + raise ValueError( + "Policy map changed. The list of eval data that was handled " + f"by a same policy is now handled by policy {pid} " + "and {policy_id}. " + "Please don't do this in the middle of an episode." + ) + policy_id = pid + return _get_or_raise(self._worker.policy_map, policy_id) + + eval_results: Dict[PolicyID, TensorStructType] = {} + for policy_id, eval_data in to_eval.items(): + # In case the policyID has been removed from this worker, we need to + # re-assign policy_id and re-lookup the Policy object to use. + try: + policy: Policy = _get_or_raise(policies, policy_id) + except ValueError: + # policy_mapping_fn from the worker may have already been + # changed (mapping fn not staying constant within one episode). + policy: Policy = _try_find_policy_again(eval_data) + + input_dict = _batch_inference_sample_batches( + [d.data.sample_batch for d in eval_data] + ) + + eval_results[policy_id] = policy.compute_actions_from_input_dict( + input_dict, + timestep=policy.global_timestep, + episodes=[self._active_episodes[t.env_id] for t in eval_data], + ) + + return eval_results + + def _process_policy_eval_results( + self, + active_envs: Set[EnvID], + to_eval: Dict[PolicyID, List[AgentConnectorDataType]], + eval_results: Dict[PolicyID, PolicyOutputType], + off_policy_actions: MultiEnvDict, + ): + """Process the output of policy neural network evaluation. + + Records policy evaluation results into agent connectors and + returns replies to send back to agents in the env. + + Args: + active_envs: Set of env IDs that are still active. + to_eval: Mapping of policy IDs to lists of AgentConnectorDataType objects. + eval_results: Mapping of policy IDs to list of + actions, rnn-out states, extra-action-fetches dicts. + off_policy_actions: Doubly keyed dict of env-ids -> agent ids -> + off-policy-action, returned by a `BaseEnv.poll()` call. + + Returns: + Nested dict of env id -> agent id -> actions to be sent to + Env (np.ndarrays). + """ + actions_to_send: Dict[EnvID, Dict[AgentID, EnvActionType]] = defaultdict(dict) + + for env_id in active_envs: + actions_to_send[env_id] = {} # at minimum send empty dict + + # types: PolicyID, List[AgentConnectorDataType] + for policy_id, eval_data in to_eval.items(): + actions: TensorStructType = eval_results[policy_id][0] + actions = convert_to_numpy(actions) + + rnn_out: StateBatches = eval_results[policy_id][1] + extra_action_out: dict = eval_results[policy_id][2] + + # In case actions is a list (representing the 0th dim of a batch of + # primitive actions), try converting it first. + if isinstance(actions, list): + actions = np.array(actions) + # Split action-component batches into single action rows. + actions: List[EnvActionType] = unbatch(actions) + + policy: Policy = _get_or_raise(self._worker.policy_map, policy_id) + assert ( + policy.agent_connectors and policy.action_connectors + ), "EnvRunnerV2 requires action connectors to work." + + # types: int, EnvActionType + for i, action in enumerate(actions): + env_id: int = eval_data[i].env_id + agent_id: AgentID = eval_data[i].agent_id + input_dict: TensorStructType = eval_data[i].data.raw_dict + + rnn_states: List[StateBatches] = tree.map_structure( + lambda x, i=i: x[i], rnn_out + ) + + # extra_action_out could be a nested dict + fetches: Dict = tree.map_structure( + lambda x, i=i: x[i], extra_action_out + ) + + # Post-process policy output by running them through action connectors. + ac_data = ActionConnectorDataType( + env_id, agent_id, input_dict, (action, rnn_states, fetches) + ) + + action_to_send, rnn_states, fetches = policy.action_connectors( + ac_data + ).output + + # The action we want to buffer is the direct output of + # compute_actions_from_input_dict() here. This is because we want to + # send the unsqushed actions to the environment while learning and + # possibly basing subsequent actions on the squashed actions. + action_to_buffer = ( + action + if env_id not in off_policy_actions + or agent_id not in off_policy_actions[env_id] + else off_policy_actions[env_id][agent_id] + ) + + # Notify agent connectors with this new policy output. + # Necessary for state buffering agent connectors, for example. + ac_data: ActionConnectorDataType = ActionConnectorDataType( + env_id, + agent_id, + input_dict, + (action_to_buffer, rnn_states, fetches), + ) + policy.agent_connectors.on_policy_output(ac_data) + + assert agent_id not in actions_to_send[env_id] + actions_to_send[env_id][agent_id] = action_to_send + + return actions_to_send + + def _maybe_render(self): + """Visualize environment.""" + # Check if we should render. + if not self._render or not self._simple_image_viewer: + return + + t5 = time.time() + + # Render can either return an RGB image (uint8 [w x h x 3] numpy + # array) or take care of rendering itself (returning True). + rendered = self._base_env.try_render() + # Rendering returned an image -> Display it in a SimpleImageViewer. + if isinstance(rendered, np.ndarray) and len(rendered.shape) == 3: + self._simple_image_viewer.imshow(rendered) + elif rendered not in [True, False, None]: + raise ValueError( + f"The env's ({self._base_env}) `try_render()` method returned an" + " unsupported value! Make sure you either return a " + "uint8/w x h x 3 (RGB) image or handle rendering in a " + "window and then return `True`." + ) + + self._perf_stats.incr("env_render_time", time.time() - t5) + + +def _fetch_atari_metrics(base_env: BaseEnv) -> List[RolloutMetrics]: + """Atari games have multiple logical episodes, one per life. + + However, for metrics reporting we count full episodes, all lives included. + """ + sub_environments = base_env.get_sub_environments() + if not sub_environments: + return None + atari_out = [] + for sub_env in sub_environments: + monitor = get_wrapper_by_cls(sub_env, MonitorEnv) + if not monitor: + return None + for eps_rew, eps_len in monitor.next_episode_results(): + atari_out.append(RolloutMetrics(eps_len, eps_rew)) + return atari_out + + +def _get_or_raise( + mapping: Dict[PolicyID, Union[Policy, Preprocessor, Filter]], policy_id: PolicyID +) -> Union[Policy, Preprocessor, Filter]: + """Returns an object under key `policy_id` in `mapping`. + + Args: + mapping (Dict[PolicyID, Union[Policy, Preprocessor, Filter]]): The + mapping dict from policy id (str) to actual object (Policy, + Preprocessor, etc.). + policy_id: The policy ID to lookup. + + Returns: + Union[Policy, Preprocessor, Filter]: The found object. + + Raises: + ValueError: If `policy_id` cannot be found in `mapping`. + """ + if policy_id not in mapping: + raise ValueError( + "Could not find policy for agent: PolicyID `{}` not found " + "in policy map, whose keys are `{}`.".format(policy_id, mapping.keys()) + ) + return mapping[policy_id] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/episode_v2.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/episode_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..e894bee48a561b1279a81af06166dcf5d43a17a8 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/episode_v2.py @@ -0,0 +1,378 @@ +import random +from collections import defaultdict +import numpy as np +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple + +from ray.rllib.env.base_env import _DUMMY_AGENT_ID +from ray.rllib.evaluation.collectors.simple_list_collector import ( + _PolicyCollector, + _PolicyCollectorGroup, +) +from ray.rllib.evaluation.collectors.agent_collector import AgentCollector +from ray.rllib.policy.policy_map import PolicyMap +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.typing import AgentID, EnvID, EnvInfoDict, PolicyID, TensorType + +if TYPE_CHECKING: + from ray.rllib.callbacks.callbacks import RLlibCallback + from ray.rllib.evaluation.rollout_worker import RolloutWorker + + +@OldAPIStack +class EpisodeV2: + """Tracks the current state of a (possibly multi-agent) episode.""" + + def __init__( + self, + env_id: EnvID, + policies: PolicyMap, + policy_mapping_fn: Callable[[AgentID, "EpisodeV2", "RolloutWorker"], PolicyID], + *, + worker: Optional["RolloutWorker"] = None, + callbacks: Optional["RLlibCallback"] = None, + ): + """Initializes an Episode instance. + + Args: + env_id: The environment's ID in which this episode runs. + policies: The PolicyMap object (mapping PolicyIDs to Policy + objects) to use for determining, which policy is used for + which agent. + policy_mapping_fn: The mapping function mapping AgentIDs to + PolicyIDs. + worker: The RolloutWorker instance, in which this episode runs. + """ + # Unique id identifying this trajectory. + self.episode_id: int = random.randrange(int(1e18)) + # ID of the environment this episode is tracking. + self.env_id = env_id + # Summed reward across all agents in this episode. + self.total_reward: float = 0.0 + # Active (uncollected) # of env steps taken by this episode. + # Start from -1. After add_init_obs(), we will be at 0 step. + self.active_env_steps: int = -1 + # Total # of env steps taken by this episode. + # Start from -1, After add_init_obs(), we will be at 0 step. + self.total_env_steps: int = -1 + # Active (uncollected) agent steps. + self.active_agent_steps: int = 0 + # Total # of steps take by all agents in this env. + self.total_agent_steps: int = 0 + # Dict for user to add custom metrics. + # TODO (sven): We should probably unify custom_metrics, user_data, + # and hist_data into a single data container for user to track per-step. + # metrics and states. + self.custom_metrics: Dict[str, float] = {} + # Temporary storage. E.g. storing data in between two custom + # callbacks referring to the same episode. + self.user_data: Dict[str, Any] = {} + # Dict mapping str keys to List[float] for storage of + # per-timestep float data throughout the episode. + self.hist_data: Dict[str, List[float]] = {} + self.media: Dict[str, Any] = {} + + self.worker = worker + self.callbacks = callbacks + + self.policy_map: PolicyMap = policies + self.policy_mapping_fn: Callable[ + [AgentID, "EpisodeV2", "RolloutWorker"], PolicyID + ] = policy_mapping_fn + # Per-agent data collectors. + self._agent_to_policy: Dict[AgentID, PolicyID] = {} + self._agent_collectors: Dict[AgentID, AgentCollector] = {} + + self._next_agent_index: int = 0 + self._agent_to_index: Dict[AgentID, int] = {} + + # Summed rewards broken down by agent. + self.agent_rewards: Dict[Tuple[AgentID, PolicyID], float] = defaultdict(float) + self._agent_reward_history: Dict[AgentID, List[int]] = defaultdict(list) + + self._has_init_obs: Dict[AgentID, bool] = {} + self._last_terminateds: Dict[AgentID, bool] = {} + self._last_truncateds: Dict[AgentID, bool] = {} + # Keep last info dict around, in case an environment tries to signal + # us something. + self._last_infos: Dict[AgentID, Dict] = {} + + def policy_for( + self, agent_id: AgentID = _DUMMY_AGENT_ID, refresh: bool = False + ) -> PolicyID: + """Returns and stores the policy ID for the specified agent. + + If the agent is new, the policy mapping fn will be called to bind the + agent to a policy for the duration of the entire episode (even if the + policy_mapping_fn is changed in the meantime!). + + Args: + agent_id: The agent ID to lookup the policy ID for. + + Returns: + The policy ID for the specified agent. + """ + + # Perform a new policy_mapping_fn lookup and bind AgentID for the + # duration of this episode to the returned PolicyID. + if agent_id not in self._agent_to_policy or refresh: + policy_id = self._agent_to_policy[agent_id] = self.policy_mapping_fn( + agent_id, # agent_id + self, # episode + worker=self.worker, + ) + # Use already determined PolicyID. + else: + policy_id = self._agent_to_policy[agent_id] + + # PolicyID not found in policy map -> Error. + if policy_id not in self.policy_map: + raise KeyError( + "policy_mapping_fn returned invalid policy id " f"'{policy_id}'!" + ) + return policy_id + + def get_agents(self) -> List[AgentID]: + """Returns list of agent IDs that have appeared in this episode. + + Returns: + The list of all agent IDs that have appeared so far in this + episode. + """ + return list(self._agent_to_index.keys()) + + def agent_index(self, agent_id: AgentID) -> int: + """Get the index of an agent among its environment. + + A new index will be created if an agent is seen for the first time. + + Args: + agent_id: ID of an agent. + + Returns: + The index of this agent. + """ + if agent_id not in self._agent_to_index: + self._agent_to_index[agent_id] = self._next_agent_index + self._next_agent_index += 1 + return self._agent_to_index[agent_id] + + def step(self) -> None: + """Advance the episode forward by one step.""" + self.active_env_steps += 1 + self.total_env_steps += 1 + + def add_init_obs( + self, + *, + agent_id: AgentID, + init_obs: TensorType, + init_infos: Dict[str, TensorType], + t: int = -1, + ) -> None: + """Add initial env obs at the start of a new episode + + Args: + agent_id: Agent ID. + init_obs: Initial observations. + init_infos: Initial infos dicts. + t: timestamp. + """ + policy = self.policy_map[self.policy_for(agent_id)] + + # Add initial obs to Trajectory. + assert agent_id not in self._agent_collectors + + self._agent_collectors[agent_id] = AgentCollector( + policy.view_requirements, + max_seq_len=policy.config["model"]["max_seq_len"], + disable_action_flattening=policy.config.get( + "_disable_action_flattening", False + ), + is_policy_recurrent=policy.is_recurrent(), + intial_states=policy.get_initial_state(), + _enable_new_api_stack=False, + ) + self._agent_collectors[agent_id].add_init_obs( + episode_id=self.episode_id, + agent_index=self.agent_index(agent_id), + env_id=self.env_id, + init_obs=init_obs, + init_infos=init_infos, + t=t, + ) + + self._has_init_obs[agent_id] = True + + def add_action_reward_done_next_obs( + self, + agent_id: AgentID, + values: Dict[str, TensorType], + ) -> None: + """Add action, reward, info, and next_obs as a new step. + + Args: + agent_id: Agent ID. + values: Dict of action, reward, info, and next_obs. + """ + # Make sure, agent already has some (at least init) data. + assert agent_id in self._agent_collectors + + self.active_agent_steps += 1 + self.total_agent_steps += 1 + + # Include the current agent id for multi-agent algorithms. + if agent_id != _DUMMY_AGENT_ID: + values["agent_id"] = agent_id + + # Add action/reward/next-obs (and other data) to Trajectory. + self._agent_collectors[agent_id].add_action_reward_next_obs(values) + + # Keep track of agent reward history. + reward = values[SampleBatch.REWARDS] + self.total_reward += reward + self.agent_rewards[(agent_id, self.policy_for(agent_id))] += reward + self._agent_reward_history[agent_id].append(reward) + + # Keep track of last terminated info for agent. + if SampleBatch.TERMINATEDS in values: + self._last_terminateds[agent_id] = values[SampleBatch.TERMINATEDS] + # Keep track of last truncated info for agent. + if SampleBatch.TRUNCATEDS in values: + self._last_truncateds[agent_id] = values[SampleBatch.TRUNCATEDS] + + # Keep track of last info dict if available. + if SampleBatch.INFOS in values: + self.set_last_info(agent_id, values[SampleBatch.INFOS]) + + def postprocess_episode( + self, + batch_builder: _PolicyCollectorGroup, + is_done: bool = False, + check_dones: bool = False, + ) -> None: + """Build and return currently collected training samples by policies. + + Clear agent collector states if this episode is done. + + Args: + batch_builder: _PolicyCollectorGroup for saving the collected per-agent + sample batches. + is_done: If this episode is done (terminated or truncated). + check_dones: Whether to make sure per-agent trajectories are actually done. + """ + # TODO: (sven) Once we implement multi-agent communication channels, + # we have to resolve the restriction of only sending other agent + # batches from the same policy to the postprocess methods. + # Build SampleBatches for the given episode. + pre_batches = {} + for agent_id, collector in self._agent_collectors.items(): + # Build only if there is data and agent is part of given episode. + if collector.agent_steps == 0: + continue + pid = self.policy_for(agent_id) + policy = self.policy_map[pid] + pre_batch = collector.build_for_training(policy.view_requirements) + pre_batches[agent_id] = (pid, policy, pre_batch) + + for agent_id, (pid, policy, pre_batch) in pre_batches.items(): + # Entire episode is said to be done. + # Error if no DONE at end of this agent's trajectory. + if is_done and check_dones and not pre_batch.is_terminated_or_truncated(): + raise ValueError( + "Episode {} terminated for all agents, but we still " + "don't have a last observation for agent {} (policy " + "{}). ".format(self.episode_id, agent_id, self.policy_for(agent_id)) + + "Please ensure that you include the last observations " + "of all live agents when setting done[__all__] to " + "True." + ) + + # Skip a trajectory's postprocessing (and thus using it for training), + # if its agent's info exists and contains the training_enabled=False + # setting (used by our PolicyClients). + if not self._last_infos.get(agent_id, {}).get("training_enabled", True): + continue + + if ( + not pre_batch.is_single_trajectory() + or len(np.unique(pre_batch[SampleBatch.EPS_ID])) > 1 + ): + raise ValueError( + "Batches sent to postprocessing must only contain steps " + "from a single trajectory.", + pre_batch, + ) + + if len(pre_batches) > 1: + other_batches = pre_batches.copy() + del other_batches[agent_id] + else: + other_batches = {} + + # Call the Policy's Exploration's postprocess method. + post_batch = pre_batch + if getattr(policy, "exploration", None) is not None: + policy.exploration.postprocess_trajectory( + policy, post_batch, policy.get_session() + ) + post_batch.set_get_interceptor(None) + post_batch = policy.postprocess_trajectory(post_batch, other_batches, self) + + from ray.rllib.evaluation.rollout_worker import get_global_worker + + self.callbacks.on_postprocess_trajectory( + worker=get_global_worker(), + episode=self, + agent_id=agent_id, + policy_id=pid, + policies=self.policy_map, + postprocessed_batch=post_batch, + original_batches=pre_batches, + ) + + # Append post_batch for return. + if pid not in batch_builder.policy_collectors: + batch_builder.policy_collectors[pid] = _PolicyCollector(policy) + batch_builder.policy_collectors[pid].add_postprocessed_batch_for_training( + post_batch, policy.view_requirements + ) + + batch_builder.agent_steps += self.active_agent_steps + batch_builder.env_steps += self.active_env_steps + + # AgentCollector cleared. + self.active_agent_steps = 0 + self.active_env_steps = 0 + + def has_init_obs(self, agent_id: AgentID = None) -> bool: + """Returns whether this episode has initial obs for an agent. + + If agent_id is None, return whether we have received any initial obs, + in other words, whether this episode is completely fresh. + """ + if agent_id is not None: + return agent_id in self._has_init_obs and self._has_init_obs[agent_id] + else: + return any(list(self._has_init_obs.values())) + + def is_done(self, agent_id: AgentID) -> bool: + return self.is_terminated(agent_id) or self.is_truncated(agent_id) + + def is_terminated(self, agent_id: AgentID) -> bool: + return self._last_terminateds.get(agent_id, False) + + def is_truncated(self, agent_id: AgentID) -> bool: + return self._last_truncateds.get(agent_id, False) + + def set_last_info(self, agent_id: AgentID, info: Dict): + self._last_infos[agent_id] = info + + def last_info_for( + self, agent_id: AgentID = _DUMMY_AGENT_ID + ) -> Optional[EnvInfoDict]: + return self._last_infos.get(agent_id) + + @property + def length(self): + return self.total_env_steps diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/metrics.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..016ad2a86264389a131097f9d11a5132ab9c1a20 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/metrics.py @@ -0,0 +1,266 @@ +import collections +import logging +import numpy as np +from typing import List, Optional, TYPE_CHECKING + +from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.metrics.learner_info import LEARNER_STATS_KEY +from ray.rllib.utils.typing import GradInfoDict, LearnerStatsDict, ResultDict + +if TYPE_CHECKING: + from ray.rllib.env.env_runner_group import EnvRunnerGroup + +logger = logging.getLogger(__name__) + +RolloutMetrics = OldAPIStack( + collections.namedtuple( + "RolloutMetrics", + [ + "episode_length", + "episode_reward", + "agent_rewards", + "custom_metrics", + "perf_stats", + "hist_data", + "media", + "episode_faulty", + "connector_metrics", + ], + ) +) +RolloutMetrics.__new__.__defaults__ = (0, 0, {}, {}, {}, {}, {}, False, {}) + + +@OldAPIStack +def get_learner_stats(grad_info: GradInfoDict) -> LearnerStatsDict: + """Return optimization stats reported from the policy. + + .. testcode:: + :skipif: True + + grad_info = worker.learn_on_batch(samples) + + # {"td_error": [...], "learner_stats": {"vf_loss": ..., ...}} + + print(get_stats(grad_info)) + + .. testoutput:: + + {"vf_loss": ..., "policy_loss": ...} + """ + if LEARNER_STATS_KEY in grad_info: + return grad_info[LEARNER_STATS_KEY] + + multiagent_stats = {} + for k, v in grad_info.items(): + if type(v) is dict: + if LEARNER_STATS_KEY in v: + multiagent_stats[k] = v[LEARNER_STATS_KEY] + + return multiagent_stats + + +@OldAPIStack +def collect_metrics( + workers: "EnvRunnerGroup", + remote_worker_ids: Optional[List[int]] = None, + timeout_seconds: int = 180, + keep_custom_metrics: bool = False, +) -> ResultDict: + """Gathers episode metrics from rollout worker set. + + Args: + workers: EnvRunnerGroup. + remote_worker_ids: Optional list of IDs of remote workers to collect + metrics from. + timeout_seconds: Timeout in seconds for collecting metrics from remote workers. + keep_custom_metrics: Whether to keep custom metrics in the result dict as + they are (True) or to aggregate them (False). + + Returns: + A result dict of metrics. + """ + episodes = collect_episodes( + workers, remote_worker_ids, timeout_seconds=timeout_seconds + ) + metrics = summarize_episodes( + episodes, episodes, keep_custom_metrics=keep_custom_metrics + ) + return metrics + + +@OldAPIStack +def collect_episodes( + workers: "EnvRunnerGroup", + remote_worker_ids: Optional[List[int]] = None, + timeout_seconds: int = 180, +) -> List[RolloutMetrics]: + """Gathers new episodes metrics tuples from the given RolloutWorkers. + + Args: + workers: EnvRunnerGroup. + remote_worker_ids: Optional list of IDs of remote workers to collect + metrics from. + timeout_seconds: Timeout in seconds for collecting metrics from remote workers. + + Returns: + List of RolloutMetrics. + """ + # This will drop get_metrics() calls that are too slow. + # We can potentially make this an asynchronous call if this turns + # out to be a problem. + metric_lists = workers.foreach_env_runner( + lambda w: w.get_metrics(), + local_env_runner=True, + remote_worker_ids=remote_worker_ids, + timeout_seconds=timeout_seconds, + ) + if len(metric_lists) == 0: + logger.warning("WARNING: collected no metrics.") + + episodes = [] + for metrics in metric_lists: + episodes.extend(metrics) + + return episodes + + +@OldAPIStack +def summarize_episodes( + episodes: List[RolloutMetrics], + new_episodes: List[RolloutMetrics] = None, + keep_custom_metrics: bool = False, +) -> ResultDict: + """Summarizes a set of episode metrics tuples. + + Args: + episodes: List of most recent n episodes. This may include historical ones + (not newly collected in this iteration) in order to achieve the size of + the smoothing window. + new_episodes: All the episodes that were completed in this iteration. + keep_custom_metrics: Whether to keep custom metrics in the result dict as + they are (True) or to aggregate them (False). + + Returns: + A result dict of metrics. + """ + + if new_episodes is None: + new_episodes = episodes + + episode_rewards = [] + episode_lengths = [] + policy_rewards = collections.defaultdict(list) + custom_metrics = collections.defaultdict(list) + perf_stats = collections.defaultdict(list) + hist_stats = collections.defaultdict(list) + episode_media = collections.defaultdict(list) + connector_metrics = collections.defaultdict(list) + num_faulty_episodes = 0 + + for episode in episodes: + # Faulty episodes may still carry perf_stats data. + for k, v in episode.perf_stats.items(): + perf_stats[k].append(v) + # Continue if this is a faulty episode. + # There should be other meaningful stats to be collected. + if episode.episode_faulty: + num_faulty_episodes += 1 + continue + + episode_lengths.append(episode.episode_length) + episode_rewards.append(episode.episode_reward) + for k, v in episode.custom_metrics.items(): + custom_metrics[k].append(v) + is_multi_agent = ( + len(episode.agent_rewards) > 1 + or DEFAULT_POLICY_ID not in episode.agent_rewards + ) + if is_multi_agent: + for (_, policy_id), reward in episode.agent_rewards.items(): + policy_rewards[policy_id].append(reward) + for k, v in episode.hist_data.items(): + hist_stats[k] += v + for k, v in episode.media.items(): + episode_media[k].append(v) + if hasattr(episode, "connector_metrics"): + # Group connector metrics by connector_metric name for all policies + for per_pipeline_metrics in episode.connector_metrics.values(): + for per_connector_metrics in per_pipeline_metrics.values(): + for connector_metric_name, val in per_connector_metrics.items(): + connector_metrics[connector_metric_name].append(val) + + if episode_rewards: + min_reward = min(episode_rewards) + max_reward = max(episode_rewards) + avg_reward = np.mean(episode_rewards) + else: + min_reward = float("nan") + max_reward = float("nan") + avg_reward = float("nan") + if episode_lengths: + avg_length = np.mean(episode_lengths) + else: + avg_length = float("nan") + + # Show as histogram distributions. + hist_stats["episode_reward"] = episode_rewards + hist_stats["episode_lengths"] = episode_lengths + + policy_reward_min = {} + policy_reward_mean = {} + policy_reward_max = {} + for policy_id, rewards in policy_rewards.copy().items(): + policy_reward_min[policy_id] = np.min(rewards) + policy_reward_mean[policy_id] = np.mean(rewards) + policy_reward_max[policy_id] = np.max(rewards) + + # Show as histogram distributions. + hist_stats["policy_{}_reward".format(policy_id)] = rewards + + for k, v_list in custom_metrics.copy().items(): + filt = [v for v in v_list if not np.any(np.isnan(v))] + if keep_custom_metrics: + custom_metrics[k] = filt + else: + custom_metrics[k + "_mean"] = np.mean(filt) + if filt: + custom_metrics[k + "_min"] = np.min(filt) + custom_metrics[k + "_max"] = np.max(filt) + else: + custom_metrics[k + "_min"] = float("nan") + custom_metrics[k + "_max"] = float("nan") + del custom_metrics[k] + + for k, v_list in perf_stats.copy().items(): + perf_stats[k] = np.mean(v_list) + + mean_connector_metrics = dict() + for k, v_list in connector_metrics.items(): + mean_connector_metrics[k] = np.mean(v_list) + + return dict( + episode_reward_max=max_reward, + episode_reward_min=min_reward, + episode_reward_mean=avg_reward, + episode_len_mean=avg_length, + episode_media=dict(episode_media), + episodes_timesteps_total=sum(episode_lengths), + policy_reward_min=policy_reward_min, + policy_reward_max=policy_reward_max, + policy_reward_mean=policy_reward_mean, + custom_metrics=dict(custom_metrics), + hist_stats=dict(hist_stats), + sampler_perf=dict(perf_stats), + num_faulty_episodes=num_faulty_episodes, + connector_metrics=mean_connector_metrics, + # Added these (duplicate) values here for forward compatibility with the new API + # stack's metrics structure. This allows us to unify our test cases and keeping + # the new API stack clean of backward-compatible keys. + num_episodes=len(new_episodes), + episode_return_max=max_reward, + episode_return_min=min_reward, + episode_return_mean=avg_reward, + episodes_this_iter=len(new_episodes), # deprecate in favor of `num_epsodes_...` + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/observation_function.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/observation_function.py new file mode 100644 index 0000000000000000000000000000000000000000..c670ed5192cfefe29b76bf6b5e557e2bcb46fea5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/observation_function.py @@ -0,0 +1,87 @@ +from typing import Dict + +from ray.rllib.env import BaseEnv +from ray.rllib.policy import Policy +from ray.rllib.evaluation import RolloutWorker +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.framework import TensorType +from ray.rllib.utils.typing import AgentID, PolicyID + + +@OldAPIStack +class ObservationFunction: + """Interceptor function for rewriting observations from the environment. + + These callbacks can be used for preprocessing of observations, especially + in multi-agent scenarios. + + Observation functions can be specified in the multi-agent config by + specifying ``{"observation_fn": your_obs_func}``. Note that + ``your_obs_func`` can be a plain Python function. + + This API is **experimental**. + """ + + def __call__( + self, + agent_obs: Dict[AgentID, TensorType], + worker: RolloutWorker, + base_env: BaseEnv, + policies: Dict[PolicyID, Policy], + episode, + **kw + ) -> Dict[AgentID, TensorType]: + """Callback run on each environment step to observe the environment. + + This method takes in the original agent observation dict returned by + a MultiAgentEnv, and returns a possibly modified one. It can be + thought of as a "wrapper" around the environment. + + TODO(ekl): allow end-to-end differentiation through the observation + function and policy losses. + + TODO(ekl): enable batch processing. + + Args: + agent_obs: Dictionary of default observations from the + environment. The default implementation of observe() simply + returns this dict. + worker: Reference to the current rollout worker. + base_env: BaseEnv running the episode. The underlying + sub environment objects (BaseEnvs are vectorized) can be + retrieved by calling `base_env.get_sub_environments()`. + policies: Mapping of policy id to policy objects. In single + agent mode there will only be a single "default" policy. + episode: Episode state object. + kwargs: Forward compatibility placeholder. + + Returns: + new_agent_obs: copy of agent obs with updates. You can + rewrite or drop data from the dict if needed (e.g., the env + can have a dummy "global" observation, and the observer can + merge the global state into individual observations. + + .. testcode:: + :skipif: True + + # Observer that merges global state into individual obs. It is + # rewriting the discrete obs into a tuple with global state. + example_obs_fn1({"a": 1, "b": 2, "global_state": 101}, ...) + + .. testoutput:: + + {"a": [1, 101], "b": [2, 101]} + + .. testcode:: + :skipif: True + + # Observer for e.g., custom centralized critic model. It is + # rewriting the discrete obs into a dict with more data. + example_obs_fn2({"a": 1, "b": 2}, ...) + + .. testoutput:: + + {"a": {"self": 1, "other": 2}, "b": {"self": 2, "other": 1}} + """ + + return agent_obs diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/postprocessing.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/postprocessing.py new file mode 100644 index 0000000000000000000000000000000000000000..4b0a6c79bd60216408c9a772ab5630be01132321 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/postprocessing.py @@ -0,0 +1,328 @@ +import numpy as np +import scipy.signal +from typing import Dict, Optional + +from ray.rllib.policy.policy import Policy +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.annotations import DeveloperAPI, OldAPIStack +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.typing import AgentID +from ray.rllib.utils.typing import TensorType + + +@DeveloperAPI +class Postprocessing: + """Constant definitions for postprocessing.""" + + ADVANTAGES = "advantages" + VALUE_TARGETS = "value_targets" + + +@OldAPIStack +def adjust_nstep(n_step: int, gamma: float, batch: SampleBatch) -> None: + """Rewrites `batch` to encode n-step rewards, terminateds, truncateds, and next-obs. + + Observations and actions remain unaffected. At the end of the trajectory, + n is truncated to fit in the traj length. + + Args: + n_step: The number of steps to look ahead and adjust. + gamma: The discount factor. + batch: The SampleBatch to adjust (in place). + + Examples: + n-step=3 + Trajectory=o0 r0 d0, o1 r1 d1, o2 r2 d2, o3 r3 d3, o4 r4 d4=True o5 + gamma=0.9 + Returned trajectory: + 0: o0 [r0 + 0.9*r1 + 0.9^2*r2 + 0.9^3*r3] d3 o0'=o3 + 1: o1 [r1 + 0.9*r2 + 0.9^2*r3 + 0.9^3*r4] d4 o1'=o4 + 2: o2 [r2 + 0.9*r3 + 0.9^2*r4] d4 o1'=o5 + 3: o3 [r3 + 0.9*r4] d4 o3'=o5 + 4: o4 r4 d4 o4'=o5 + """ + + assert ( + batch.is_single_trajectory() + ), "Unexpected terminated|truncated in middle of trajectory!" + + len_ = len(batch) + + # Shift NEXT_OBS, TERMINATEDS, and TRUNCATEDS. + batch[SampleBatch.NEXT_OBS] = np.concatenate( + [ + batch[SampleBatch.OBS][n_step:], + np.stack([batch[SampleBatch.NEXT_OBS][-1]] * min(n_step, len_)), + ], + axis=0, + ) + batch[SampleBatch.TERMINATEDS] = np.concatenate( + [ + batch[SampleBatch.TERMINATEDS][n_step - 1 :], + np.tile(batch[SampleBatch.TERMINATEDS][-1], min(n_step - 1, len_)), + ], + axis=0, + ) + # Only fix `truncateds`, if present in the batch. + if SampleBatch.TRUNCATEDS in batch: + batch[SampleBatch.TRUNCATEDS] = np.concatenate( + [ + batch[SampleBatch.TRUNCATEDS][n_step - 1 :], + np.tile(batch[SampleBatch.TRUNCATEDS][-1], min(n_step - 1, len_)), + ], + axis=0, + ) + + # Change rewards in place. + for i in range(len_): + for j in range(1, n_step): + if i + j < len_: + batch[SampleBatch.REWARDS][i] += ( + gamma**j * batch[SampleBatch.REWARDS][i + j] + ) + + +@OldAPIStack +def compute_advantages( + rollout: SampleBatch, + last_r: float, + gamma: float = 0.9, + lambda_: float = 1.0, + use_gae: bool = True, + use_critic: bool = True, + rewards: TensorType = None, + vf_preds: TensorType = None, +): + """Given a rollout, compute its value targets and the advantages. + + Args: + rollout: SampleBatch of a single trajectory. + last_r: Value estimation for last observation. + gamma: Discount factor. + lambda_: Parameter for GAE. + use_gae: Using Generalized Advantage Estimation. + use_critic: Whether to use critic (value estimates). Setting + this to False will use 0 as baseline. + rewards: Override the reward values in rollout. + vf_preds: Override the value function predictions in rollout. + + Returns: + SampleBatch with experience from rollout and processed rewards. + """ + assert ( + SampleBatch.VF_PREDS in rollout or not use_critic + ), "use_critic=True but values not found" + assert use_critic or not use_gae, "Can't use gae without using a value function" + last_r = convert_to_numpy(last_r) + + if rewards is None: + rewards = rollout[SampleBatch.REWARDS] + if vf_preds is None and use_critic: + vf_preds = rollout[SampleBatch.VF_PREDS] + + if use_gae: + vpred_t = np.concatenate([vf_preds, np.array([last_r])]) + delta_t = rewards + gamma * vpred_t[1:] - vpred_t[:-1] + # This formula for the advantage comes from: + # "Generalized Advantage Estimation": https://arxiv.org/abs/1506.02438 + rollout[Postprocessing.ADVANTAGES] = discount_cumsum(delta_t, gamma * lambda_) + rollout[Postprocessing.VALUE_TARGETS] = ( + rollout[Postprocessing.ADVANTAGES] + vf_preds + ).astype(np.float32) + else: + rewards_plus_v = np.concatenate([rewards, np.array([last_r])]) + discounted_returns = discount_cumsum(rewards_plus_v, gamma)[:-1].astype( + np.float32 + ) + + if use_critic: + rollout[Postprocessing.ADVANTAGES] = discounted_returns - vf_preds + rollout[Postprocessing.VALUE_TARGETS] = discounted_returns + else: + rollout[Postprocessing.ADVANTAGES] = discounted_returns + rollout[Postprocessing.VALUE_TARGETS] = np.zeros_like( + rollout[Postprocessing.ADVANTAGES] + ) + + rollout[Postprocessing.ADVANTAGES] = rollout[Postprocessing.ADVANTAGES].astype( + np.float32 + ) + + return rollout + + +@OldAPIStack +def compute_gae_for_sample_batch( + policy: Policy, + sample_batch: SampleBatch, + other_agent_batches: Optional[Dict[AgentID, SampleBatch]] = None, + episode=None, +) -> SampleBatch: + """Adds GAE (generalized advantage estimations) to a trajectory. + + The trajectory contains only data from one episode and from one agent. + - If `config.batch_mode=truncate_episodes` (default), sample_batch may + contain a truncated (at-the-end) episode, in case the + `config.rollout_fragment_length` was reached by the sampler. + - If `config.batch_mode=complete_episodes`, sample_batch will contain + exactly one episode (no matter how long). + New columns can be added to sample_batch and existing ones may be altered. + + Args: + policy: The Policy used to generate the trajectory (`sample_batch`) + sample_batch: The SampleBatch to postprocess. + other_agent_batches: Optional dict of AgentIDs mapping to other + agents' trajectory data (from the same episode). + NOTE: The other agents use the same policy. + episode: Optional multi-agent episode object in which the agents + operated. + + Returns: + The postprocessed, modified SampleBatch (or a new one). + """ + # Compute the SampleBatch.VALUES_BOOTSTRAPPED column, which we'll need for the + # following `last_r` arg in `compute_advantages()`. + sample_batch = compute_bootstrap_value(sample_batch, policy) + + vf_preds = np.array(sample_batch[SampleBatch.VF_PREDS]) + rewards = np.array(sample_batch[SampleBatch.REWARDS]) + # We need to squeeze out the time dimension if there is one + # Sanity check that both have the same shape + if len(vf_preds.shape) == 2: + assert vf_preds.shape == rewards.shape + vf_preds = np.squeeze(vf_preds, axis=1) + rewards = np.squeeze(rewards, axis=1) + squeezed = True + else: + squeezed = False + + # Adds the policy logits, VF preds, and advantages to the batch, + # using GAE ("generalized advantage estimation") or not. + batch = compute_advantages( + rollout=sample_batch, + last_r=sample_batch[SampleBatch.VALUES_BOOTSTRAPPED][-1], + gamma=policy.config["gamma"], + lambda_=policy.config["lambda"], + use_gae=policy.config["use_gae"], + use_critic=policy.config.get("use_critic", True), + vf_preds=vf_preds, + rewards=rewards, + ) + + if squeezed: + # If we needed to squeeze rewards and vf_preds, we need to unsqueeze + # advantages again for it to have the same shape + batch[Postprocessing.ADVANTAGES] = np.expand_dims( + batch[Postprocessing.ADVANTAGES], axis=1 + ) + + return batch + + +@OldAPIStack +def compute_bootstrap_value(sample_batch: SampleBatch, policy: Policy) -> SampleBatch: + """Performs a value function computation at the end of a trajectory. + + If the trajectory is terminated (not truncated), will not use the value function, + but assume that the value of the last timestep is 0.0. + In all other cases, will use the given policy's value function to compute the + "bootstrapped" value estimate at the end of the given trajectory. To do so, the + very last observation (sample_batch[NEXT_OBS][-1]) and - if applicable - + the very last state output (sample_batch[STATE_OUT][-1]) wil be used as inputs to + the value function. + + The thus computed value estimate will be stored in a new column of the + `sample_batch`: SampleBatch.VALUES_BOOTSTRAPPED. Thereby, values at all timesteps + in this column are set to 0.0, except or the last timestep, which receives the + computed bootstrapped value. + This is done, such that in any loss function (which processes raw, intact + trajectories, such as those of IMPALA and APPO) can use this new column as follows: + + Example: numbers=ts in episode, '|'=episode boundary (terminal), + X=bootstrapped value (!= 0.0 b/c ts=12 is not a terminal). + ts=5 is NOT a terminal. + T: 8 9 10 11 12 <- no terminal + VF_PREDS: . . . . . + VALUES_BOOTSTRAPPED: 0 0 0 0 X + + Args: + sample_batch: The SampleBatch (single trajectory) for which to compute the + bootstrap value at the end. This SampleBatch will be altered in place + (by adding a new column: SampleBatch.VALUES_BOOTSTRAPPED). + policy: The Policy object, whose value function to use. + + Returns: + The altered SampleBatch (with the extra SampleBatch.VALUES_BOOTSTRAPPED + column). + """ + # Trajectory is actually complete -> last r=0.0. + if sample_batch[SampleBatch.TERMINATEDS][-1]: + last_r = 0.0 + # Trajectory has been truncated -> last r=VF estimate of last obs. + else: + # Input dict is provided to us automatically via the Model's + # requirements. It's a single-timestep (last one in trajectory) + # input_dict. + # Create an input dict according to the Policy's requirements. + input_dict = sample_batch.get_single_step_input_dict( + policy.view_requirements, index="last" + ) + last_r = policy._value(**input_dict) + + vf_preds = np.array(sample_batch[SampleBatch.VF_PREDS]) + # We need to squeeze out the time dimension if there is one + if len(vf_preds.shape) == 2: + vf_preds = np.squeeze(vf_preds, axis=1) + squeezed = True + else: + squeezed = False + + # Set the SampleBatch.VALUES_BOOTSTRAPPED field to VF_PREDS[1:] + the + # very last timestep (where this bootstrapping value is actually needed), which + # we set to the computed `last_r`. + sample_batch[SampleBatch.VALUES_BOOTSTRAPPED] = np.concatenate( + [ + convert_to_numpy(vf_preds[1:]), + np.array([convert_to_numpy(last_r)], dtype=np.float32), + ], + axis=0, + ) + + if squeezed: + sample_batch[SampleBatch.VF_PREDS] = np.expand_dims(vf_preds, axis=1) + sample_batch[SampleBatch.VALUES_BOOTSTRAPPED] = np.expand_dims( + sample_batch[SampleBatch.VALUES_BOOTSTRAPPED], axis=1 + ) + + return sample_batch + + +@OldAPIStack +def discount_cumsum(x: np.ndarray, gamma: float) -> np.ndarray: + """Calculates the discounted cumulative sum over a reward sequence `x`. + + y[t] - discount*y[t+1] = x[t] + reversed(y)[t] - discount*reversed(y)[t-1] = reversed(x)[t] + + Args: + gamma: The discount factor gamma. + + Returns: + The sequence containing the discounted cumulative sums + for each individual reward in `x` till the end of the trajectory. + + .. testcode:: + :skipif: True + + x = np.array([0.0, 1.0, 2.0, 3.0]) + gamma = 0.9 + discount_cumsum(x, gamma) + + .. testoutput:: + + array([0.0 + 0.9*1.0 + 0.9^2*2.0 + 0.9^3*3.0, + 1.0 + 0.9*2.0 + 0.9^2*3.0, + 2.0 + 0.9*3.0, + 3.0]) + """ + return scipy.signal.lfilter([1], [1, float(-gamma)], x[::-1], axis=0)[::-1] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/rollout_worker.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/rollout_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..7beec9447edcdf55bb2432878a04aa88ea08436e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/rollout_worker.py @@ -0,0 +1,2004 @@ +import copy +import importlib.util +import logging +import os +import platform +import threading +from collections import defaultdict +from types import FunctionType +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Collection, + Dict, + List, + Optional, + Set, + Tuple, + Type, + Union, +) + +from gymnasium.spaces import Space + +import ray +from ray import ObjectRef +from ray import cloudpickle as pickle +from ray.rllib.connectors.util import ( + create_connectors_for_policy, + maybe_get_filters_for_syncing, +) +from ray.rllib.core.rl_module import validate_module_id +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.env.base_env import BaseEnv, convert_to_base_env +from ray.rllib.env.env_context import EnvContext +from ray.rllib.env.env_runner import EnvRunner +from ray.rllib.env.external_multi_agent_env import ExternalMultiAgentEnv +from ray.rllib.env.multi_agent_env import MultiAgentEnv +from ray.rllib.env.wrappers.atari_wrappers import is_atari, wrap_deepmind +from ray.rllib.evaluation.metrics import RolloutMetrics +from ray.rllib.evaluation.sampler import SyncSampler +from ray.rllib.models import ModelCatalog +from ray.rllib.models.preprocessors import Preprocessor +from ray.rllib.offline import ( + D4RLReader, + DatasetReader, + DatasetWriter, + InputReader, + IOContext, + JsonReader, + JsonWriter, + MixedInput, + NoopOutput, + OutputWriter, + ShuffledInput, +) +from ray.rllib.policy.policy import Policy, PolicySpec +from ray.rllib.policy.policy_map import PolicyMap +from ray.rllib.policy.sample_batch import ( + DEFAULT_POLICY_ID, + MultiAgentBatch, + concat_samples, + convert_ma_batch_to_sample_batch, +) +from ray.rllib.policy.torch_policy import TorchPolicy +from ray.rllib.policy.torch_policy_v2 import TorchPolicyV2 +from ray.rllib.utils import force_list +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.debug import summarize, update_global_seed_if_necessary +from ray.rllib.utils.error import ERR_MSG_NO_GPUS, HOWTO_CHANGE_CONFIG +from ray.rllib.utils.filter import Filter, NoFilter +from ray.rllib.utils.framework import try_import_tf, try_import_torch +from ray.rllib.utils.from_config import from_config +from ray.rllib.utils.policy import create_policy_for_framework +from ray.rllib.utils.sgd import do_minibatch_sgd +from ray.rllib.utils.tf_run_builder import _TFRunBuilder +from ray.rllib.utils.tf_utils import get_gpu_devices as get_tf_gpu_devices +from ray.rllib.utils.tf_utils import get_tf_eager_cls_if_necessary +from ray.rllib.utils.typing import ( + AgentID, + EnvCreator, + EnvType, + ModelGradients, + ModelWeights, + MultiAgentPolicyConfigDict, + PartialAlgorithmConfigDict, + PolicyID, + PolicyState, + SampleBatchType, + T, +) +from ray.tune.registry import registry_contains_input, registry_get_input +from ray.util.annotations import PublicAPI +from ray.util.debug import disable_log_once_globally, enable_periodic_logging, log_once +from ray.util.iter import ParallelIteratorWorker + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + from ray.rllib.callbacks.callbacks import RLlibCallback + +tf1, tf, tfv = try_import_tf() +torch, _ = try_import_torch() + +logger = logging.getLogger(__name__) + +# Handle to the current rollout worker, which will be set to the most recently +# created RolloutWorker in this process. This can be helpful to access in +# custom env or policy classes for debugging or advanced use cases. +_global_worker: Optional["RolloutWorker"] = None + + +@OldAPIStack +def get_global_worker() -> "RolloutWorker": + """Returns a handle to the active rollout worker in this process.""" + + global _global_worker + return _global_worker + + +def _update_env_seed_if_necessary( + env: EnvType, seed: int, worker_idx: int, vector_idx: int +): + """Set a deterministic random seed on environment. + + NOTE: this may not work with remote environments (issue #18154). + """ + if seed is None: + return + + # A single RL job is unlikely to have more than 10K + # rollout workers. + max_num_envs_per_env_runner: int = 1000 + assert ( + worker_idx < max_num_envs_per_env_runner + ), "Too many envs per worker. Random seeds may collide." + computed_seed: int = worker_idx * max_num_envs_per_env_runner + vector_idx + seed + + # Gymnasium.env. + # This will silently fail for most Farama-foundation gymnasium environments. + # (they do nothing and return None per default) + if not hasattr(env, "reset"): + if log_once("env_has_no_reset_method"): + logger.info(f"Env {env} doesn't have a `reset()` method. Cannot seed.") + else: + try: + env.reset(seed=computed_seed) + except Exception: + logger.info( + f"Env {env} doesn't support setting a seed via its `reset()` " + "method! Implement this method as `reset(self, *, seed=None, " + "options=None)` for it to abide to the correct API. Cannot seed." + ) + + +@OldAPIStack +class RolloutWorker(ParallelIteratorWorker, EnvRunner): + """Common experience collection class. + + This class wraps a policy instance and an environment class to + collect experiences from the environment. You can create many replicas of + this class as Ray actors to scale RL training. + + This class supports vectorized and multi-agent policy evaluation (e.g., + VectorEnv, MultiAgentEnv, etc.) + + .. testcode:: + :skipif: True + + # Create a rollout worker and using it to collect experiences. + import gymnasium as gym + from ray.rllib.evaluation.rollout_worker import RolloutWorker + from ray.rllib.algorithms.ppo.ppo_tf_policy import PPOTF1Policy + worker = RolloutWorker( + env_creator=lambda _: gym.make("CartPole-v1"), + default_policy_class=PPOTF1Policy) + print(worker.sample()) + + # Creating a multi-agent rollout worker + from gymnasium.spaces import Discrete, Box + import random + MultiAgentTrafficGrid = ... + worker = RolloutWorker( + env_creator=lambda _: MultiAgentTrafficGrid(num_cars=25), + config=AlgorithmConfig().multi_agent( + policies={ + # Use an ensemble of two policies for car agents + "car_policy1": + (PGTFPolicy, Box(...), Discrete(...), + AlgorithmConfig.overrides(gamma=0.99)), + "car_policy2": + (PGTFPolicy, Box(...), Discrete(...), + AlgorithmConfig.overrides(gamma=0.95)), + # Use a single shared policy for all traffic lights + "traffic_light_policy": + (PGTFPolicy, Box(...), Discrete(...), {}), + }, + policy_mapping_fn=( + lambda agent_id, episode, **kwargs: + random.choice(["car_policy1", "car_policy2"]) + if agent_id.startswith("car_") else "traffic_light_policy"), + ), + ) + print(worker.sample()) + + .. testoutput:: + + SampleBatch({ + "obs": [[...]], "actions": [[...]], "rewards": [[...]], + "terminateds": [[...]], "truncateds": [[...]], "new_obs": [[...]]} + ) + + MultiAgentBatch({ + "car_policy1": SampleBatch(...), + "car_policy2": SampleBatch(...), + "traffic_light_policy": SampleBatch(...)} + ) + + """ + + def __init__( + self, + *, + env_creator: EnvCreator, + validate_env: Optional[Callable[[EnvType, EnvContext], None]] = None, + config: Optional["AlgorithmConfig"] = None, + worker_index: int = 0, + num_workers: Optional[int] = None, + recreated_worker: bool = False, + log_dir: Optional[str] = None, + spaces: Optional[Dict[PolicyID, Tuple[Space, Space]]] = None, + default_policy_class: Optional[Type[Policy]] = None, + dataset_shards: Optional[List[ray.data.Dataset]] = None, + **kwargs, + ): + """Initializes a RolloutWorker instance. + + Args: + env_creator: Function that returns a gym.Env given an EnvContext + wrapped configuration. + validate_env: Optional callable to validate the generated + environment (only on worker=0). + worker_index: For remote workers, this should be set to a + non-zero and unique value. This index is passed to created envs + through EnvContext so that envs can be configured per worker. + recreated_worker: Whether this worker is a recreated one. Workers are + recreated by an Algorithm (via EnvRunnerGroup) in case + `restart_failed_env_runners=True` and one of the original workers (or + an already recreated one) has failed. They don't differ from original + workers other than the value of this flag (`self.recreated_worker`). + log_dir: Directory where logs can be placed. + spaces: An optional space dict mapping policy IDs + to (obs_space, action_space)-tuples. This is used in case no + Env is created on this RolloutWorker. + """ + self._original_kwargs: dict = locals().copy() + del self._original_kwargs["self"] + + global _global_worker + _global_worker = self + + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + + # Default config needed? + if config is None or isinstance(config, dict): + config = AlgorithmConfig().update_from_dict(config or {}) + # Freeze config, so no one else can alter it from here on. + config.freeze() + + # Set extra python env variables before calling super constructor. + if config.extra_python_environs_for_driver and worker_index == 0: + for key, value in config.extra_python_environs_for_driver.items(): + os.environ[key] = str(value) + elif config.extra_python_environs_for_worker and worker_index > 0: + for key, value in config.extra_python_environs_for_worker.items(): + os.environ[key] = str(value) + + def gen_rollouts(): + while True: + yield self.sample() + + ParallelIteratorWorker.__init__(self, gen_rollouts, False) + EnvRunner.__init__(self, config=config) + + self.num_workers = ( + num_workers if num_workers is not None else self.config.num_env_runners + ) + # In case we are reading from distributed datasets, store the shards here + # and pick our shard by our worker-index. + self._ds_shards = dataset_shards + self.worker_index: int = worker_index + + # Lock to be able to lock this entire worker + # (via `self.lock()` and `self.unlock()`). + # This might be crucial to prevent a race condition in case + # `config.policy_states_are_swappable=True` and you are using an Algorithm + # with a learner thread. In this case, the thread might update a policy + # that is being swapped (during the update) by the Algorithm's + # training_step's `RolloutWorker.get_weights()` call (to sync back the + # new weights to all remote workers). + self._lock = threading.Lock() + + if ( + tf1 + and (config.framework_str == "tf2" or config.enable_tf1_exec_eagerly) + # This eager check is necessary for certain all-framework tests + # that use tf's eager_mode() context generator. + and not tf1.executing_eagerly() + ): + tf1.enable_eager_execution() + + if self.config.log_level: + logging.getLogger("ray.rllib").setLevel(self.config.log_level) + + if self.worker_index > 1: + disable_log_once_globally() # only need 1 worker to log + elif self.config.log_level == "DEBUG": + enable_periodic_logging() + + env_context = EnvContext( + self.config.env_config, + worker_index=self.worker_index, + vector_index=0, + num_workers=self.num_workers, + remote=self.config.remote_worker_envs, + recreated_worker=recreated_worker, + ) + self.env_context = env_context + self.config: AlgorithmConfig = config + self.callbacks: RLlibCallback = self.config.callbacks_class() + self.recreated_worker: bool = recreated_worker + + # Setup current policy_mapping_fn. Start with the one from the config, which + # might be None in older checkpoints (nowadays AlgorithmConfig has a proper + # default for this); Need to cover this situation via the backup lambda here. + self.policy_mapping_fn = ( + lambda agent_id, episode, worker, **kw: DEFAULT_POLICY_ID + ) + self.set_policy_mapping_fn(self.config.policy_mapping_fn) + + self.env_creator: EnvCreator = env_creator + # Resolve possible auto-fragment length. + configured_rollout_fragment_length = self.config.get_rollout_fragment_length( + worker_index=self.worker_index + ) + self.total_rollout_fragment_length: int = ( + configured_rollout_fragment_length * self.config.num_envs_per_env_runner + ) + self.preprocessing_enabled: bool = not config._disable_preprocessor_api + self.last_batch: Optional[SampleBatchType] = None + self.global_vars: dict = { + # TODO(sven): Make this per-policy! + "timestep": 0, + # Counter for performed gradient updates per policy in `self.policy_map`. + # Allows for compiling metrics on the off-policy'ness of an update given + # that the number of gradient updates of the sampling policies are known + # to the learner (and can be compared to the learner version of the same + # policy). + "num_grad_updates_per_policy": defaultdict(int), + } + + # If seed is provided, add worker index to it and 10k iff evaluation worker. + self.seed = ( + None + if self.config.seed is None + else self.config.seed + + self.worker_index + + self.config.in_evaluation * 10000 + ) + + # Update the global seed for numpy/random/tf-eager/torch if we are not + # the local worker, otherwise, this was already done in the Algorithm + # object itself. + if self.worker_index > 0: + update_global_seed_if_necessary(self.config.framework_str, self.seed) + + # A single environment provided by the user (via config.env). This may + # also remain None. + # 1) Create the env using the user provided env_creator. This may + # return a gym.Env (incl. MultiAgentEnv), an already vectorized + # VectorEnv, BaseEnv, ExternalEnv, or an ActorHandle (remote env). + # 2) Wrap - if applicable - with Atari/rendering wrappers. + # 3) Seed the env, if necessary. + # 4) Vectorize the existing single env by creating more clones of + # this env and wrapping it with the RLlib BaseEnv class. + self.env = self.make_sub_env_fn = None + + # Create a (single) env for this worker. + if not ( + self.worker_index == 0 + and self.num_workers > 0 + and not self.config.create_local_env_runner + ): + # Run the `env_creator` function passing the EnvContext. + self.env = env_creator(copy.deepcopy(self.env_context)) + + clip_rewards = self.config.clip_rewards + + if self.env is not None: + # Custom validation function given, typically a function attribute of the + # Algorithm. + if validate_env is not None: + validate_env(self.env, self.env_context) + + # We can't auto-wrap a BaseEnv. + if isinstance(self.env, (BaseEnv, ray.actor.ActorHandle)): + + def wrap(env): + return env + + # Atari type env and "deepmind" preprocessor pref. + elif is_atari(self.env) and self.config.preprocessor_pref == "deepmind": + # Deepmind wrappers already handle all preprocessing. + self.preprocessing_enabled = False + + # If clip_rewards not explicitly set to False, switch it + # on here (clip between -1.0 and 1.0). + if self.config.clip_rewards is None: + clip_rewards = True + + # Framestacking is used. + use_framestack = self.config.model.get("framestack") is True + + def wrap(env): + env = wrap_deepmind( + env, + dim=self.config.model.get("dim"), + framestack=use_framestack, + noframeskip=self.config.env_config.get("frameskip", 0) == 1, + ) + return env + + elif self.config.preprocessor_pref is None: + # Only turn off preprocessing + self.preprocessing_enabled = False + + def wrap(env): + return env + + else: + + def wrap(env): + return env + + # Wrap env through the correct wrapper. + self.env: EnvType = wrap(self.env) + # Ideally, we would use the same make_sub_env() function below + # to create self.env, but wrap(env) and self.env has a cyclic + # dependency on each other right now, so we would settle on + # duplicating the random seed setting logic for now. + _update_env_seed_if_necessary(self.env, self.seed, self.worker_index, 0) + # Call custom callback function `on_sub_environment_created`. + self.callbacks.on_sub_environment_created( + worker=self, + sub_environment=self.env, + env_context=self.env_context, + ) + + self.make_sub_env_fn = self._get_make_sub_env_fn( + env_creator, env_context, validate_env, wrap, self.seed + ) + + self.spaces = spaces + self.default_policy_class = default_policy_class + self.policy_dict, self.is_policy_to_train = self.config.get_multi_agent_setup( + env=self.env, + spaces=self.spaces, + default_policy_class=self.default_policy_class, + ) + + self.policy_map: Optional[PolicyMap] = None + # TODO(jungong) : clean up after non-connector env_runner is fully deprecated. + self.preprocessors: Dict[PolicyID, Preprocessor] = None + + # Check available number of GPUs. + num_gpus = ( + self.config.num_gpus + if self.worker_index == 0 + else self.config.num_gpus_per_env_runner + ) + + # Error if we don't find enough GPUs. + if ( + ray.is_initialized() + and ray._private.worker._mode() != ray._private.worker.LOCAL_MODE + and not config._fake_gpus + ): + devices = [] + if self.config.framework_str in ["tf2", "tf"]: + devices = get_tf_gpu_devices() + elif self.config.framework_str == "torch": + devices = list(range(torch.cuda.device_count())) + + if len(devices) < num_gpus: + raise RuntimeError( + ERR_MSG_NO_GPUS.format(len(devices), devices) + HOWTO_CHANGE_CONFIG + ) + # Warn, if running in local-mode and actual GPUs (not faked) are + # requested. + elif ( + ray.is_initialized() + and ray._private.worker._mode() == ray._private.worker.LOCAL_MODE + and num_gpus > 0 + and not self.config._fake_gpus + ): + logger.warning( + "You are running ray with `local_mode=True`, but have " + f"configured {num_gpus} GPUs to be used! In local mode, " + f"Policies are placed on the CPU and the `num_gpus` setting " + f"is ignored." + ) + + self.filters: Dict[PolicyID, Filter] = defaultdict(NoFilter) + + # If RLModule API is enabled, multi_rl_module_spec holds the specs of the + # RLModules. + self.multi_rl_module_spec = None + self._update_policy_map(policy_dict=self.policy_dict) + + # Update Policy's view requirements from Model, only if Policy directly + # inherited from base `Policy` class. At this point here, the Policy + # must have it's Model (if any) defined and ready to output an initial + # state. + for pol in self.policy_map.values(): + if not pol._model_init_state_automatically_added: + pol._update_model_view_requirements_from_init_state() + + if ( + self.config.is_multi_agent + and self.env is not None + and not isinstance( + self.env, + (BaseEnv, ExternalMultiAgentEnv, MultiAgentEnv, ray.actor.ActorHandle), + ) + ): + raise ValueError( + f"You are running a multi-agent setup, but the env {self.env} is not a " + f"subclass of BaseEnv, MultiAgentEnv, ActorHandle, or " + f"ExternalMultiAgentEnv!" + ) + + if self.worker_index == 0: + logger.info("Built filter map: {}".format(self.filters)) + + # This RolloutWorker has no env. + if self.env is None: + self.async_env = None + # Use a custom env-vectorizer and call it providing self.env. + elif "custom_vector_env" in self.config: + self.async_env = self.config.custom_vector_env(self.env) + # Default: Vectorize self.env via the make_sub_env function. This adds + # further clones of self.env and creates a RLlib BaseEnv (which is + # vectorized under the hood). + else: + # Always use vector env for consistency even if num_envs_per_env_runner=1. + self.async_env: BaseEnv = convert_to_base_env( + self.env, + make_env=self.make_sub_env_fn, + num_envs=self.config.num_envs_per_env_runner, + remote_envs=self.config.remote_worker_envs, + remote_env_batch_wait_ms=self.config.remote_env_batch_wait_ms, + worker=self, + restart_failed_sub_environments=( + self.config.restart_failed_sub_environments + ), + ) + + # `truncate_episodes`: Allow a batch to contain more than one episode + # (fragments) and always make the batch `rollout_fragment_length` + # long. + rollout_fragment_length_for_sampler = configured_rollout_fragment_length + if self.config.batch_mode == "truncate_episodes": + pack = True + # `complete_episodes`: Never cut episodes and sampler will return + # exactly one (complete) episode per poll. + else: + assert self.config.batch_mode == "complete_episodes" + rollout_fragment_length_for_sampler = float("inf") + pack = False + + # Create the IOContext for this worker. + self.io_context: IOContext = IOContext( + log_dir, self.config, self.worker_index, self + ) + + render = False + if self.config.render_env is True and ( + self.num_workers == 0 or self.worker_index == 1 + ): + render = True + + if self.env is None: + self.sampler = None + else: + self.sampler = SyncSampler( + worker=self, + env=self.async_env, + clip_rewards=clip_rewards, + rollout_fragment_length=rollout_fragment_length_for_sampler, + count_steps_by=self.config.count_steps_by, + callbacks=self.callbacks, + multiple_episodes_in_batch=pack, + normalize_actions=self.config.normalize_actions, + clip_actions=self.config.clip_actions, + observation_fn=self.config.observation_fn, + sample_collector_class=self.config.sample_collector, + render=render, + ) + + self.input_reader: InputReader = self._get_input_creator_from_config()( + self.io_context + ) + self.output_writer: OutputWriter = self._get_output_creator_from_config()( + self.io_context + ) + + # The current weights sequence number (version). May remain None for when + # not tracking weights versions. + self.weights_seq_no: Optional[int] = None + + @override(EnvRunner) + def make_env(self): + # Override this method, b/c it's abstract and must be overridden. + # However, we see no point in implementing it for the old API stack any longer + # (the RolloutWorker class will be deprecated soon). + raise NotImplementedError + + @override(EnvRunner) + def assert_healthy(self): + is_healthy = self.policy_map and self.input_reader and self.output_writer + assert is_healthy, ( + f"RolloutWorker {self} (idx={self.worker_index}; " + f"num_workers={self.num_workers}) not healthy!" + ) + + @override(EnvRunner) + def sample(self, **kwargs) -> SampleBatchType: + """Returns a batch of experience sampled from this worker. + + This method must be implemented by subclasses. + + Returns: + A columnar batch of experiences (e.g., tensors) or a MultiAgentBatch. + + .. testcode:: + :skipif: True + + import gymnasium as gym + from ray.rllib.evaluation.rollout_worker import RolloutWorker + from ray.rllib.algorithms.ppo.ppo_tf_policy import PPOTF1Policy + worker = RolloutWorker( + env_creator=lambda _: gym.make("CartPole-v1"), + default_policy_class=PPOTF1Policy, + config=AlgorithmConfig(), + ) + print(worker.sample()) + + .. testoutput:: + + SampleBatch({"obs": [...], "action": [...], ...}) + """ + if self.config.fake_sampler and self.last_batch is not None: + return self.last_batch + elif self.input_reader is None: + raise ValueError( + "RolloutWorker has no `input_reader` object! " + "Cannot call `sample()`. You can try setting " + "`create_local_env_runner` to True." + ) + + if log_once("sample_start"): + logger.info( + "Generating sample batch of size {}".format( + self.total_rollout_fragment_length + ) + ) + + batches = [self.input_reader.next()] + steps_so_far = ( + batches[0].count + if self.config.count_steps_by == "env_steps" + else batches[0].agent_steps() + ) + + # In truncate_episodes mode, never pull more than 1 batch per env. + # This avoids over-running the target batch size. + if ( + self.config.batch_mode == "truncate_episodes" + and not self.config.offline_sampling + ): + max_batches = self.config.num_envs_per_env_runner + else: + max_batches = float("inf") + while steps_so_far < self.total_rollout_fragment_length and ( + len(batches) < max_batches + ): + batch = self.input_reader.next() + steps_so_far += ( + batch.count + if self.config.count_steps_by == "env_steps" + else batch.agent_steps() + ) + batches.append(batch) + + batch = concat_samples(batches) + + self.callbacks.on_sample_end(worker=self, samples=batch) + + # Always do writes prior to compression for consistency and to allow + # for better compression inside the writer. + self.output_writer.write(batch) + + if log_once("sample_end"): + logger.info("Completed sample batch:\n\n{}\n".format(summarize(batch))) + + if self.config.compress_observations: + batch.compress(bulk=self.config.compress_observations == "bulk") + + if self.config.fake_sampler: + self.last_batch = batch + + return batch + + @override(EnvRunner) + def get_spaces(self) -> Dict[str, Tuple[Space, Space]]: + spaces = self.foreach_policy( + lambda p, pid: (pid, p.observation_space, p.action_space) + ) + spaces = {e[0]: (getattr(e[1], "original_space", e[1]), e[2]) for e in spaces} + # Try to add the actual env's obs/action spaces. + env_spaces = self.foreach_env( + lambda env: (env.observation_space, env.action_space) + ) + if env_spaces: + from ray.rllib.env import INPUT_ENV_SPACES + + spaces[INPUT_ENV_SPACES] = env_spaces[0] + return spaces + + @ray.method(num_returns=2) + def sample_with_count(self) -> Tuple[SampleBatchType, int]: + """Same as sample() but returns the count as a separate value. + + Returns: + A columnar batch of experiences (e.g., tensors) and the + size of the collected batch. + + .. testcode:: + :skipif: True + + import gymnasium as gym + from ray.rllib.evaluation.rollout_worker import RolloutWorker + from ray.rllib.algorithms.ppo.ppo_tf_policy import PPOTF1Policy + worker = RolloutWorker( + env_creator=lambda _: gym.make("CartPole-v1"), + default_policy_class=PPOTFPolicy) + print(worker.sample_with_count()) + + .. testoutput:: + + (SampleBatch({"obs": [...], "action": [...], ...}), 3) + """ + batch = self.sample() + return batch, batch.count + + def learn_on_batch(self, samples: SampleBatchType) -> Dict: + """Update policies based on the given batch. + + This is the equivalent to apply_gradients(compute_gradients(samples)), + but can be optimized to avoid pulling gradients into CPU memory. + + Args: + samples: The SampleBatch or MultiAgentBatch to learn on. + + Returns: + Dictionary of extra metadata from compute_gradients(). + + .. testcode:: + :skipif: True + + import gymnasium as gym + from ray.rllib.evaluation.rollout_worker import RolloutWorker + from ray.rllib.algorithms.ppo.ppo_tf_policy import PPOTF1Policy + worker = RolloutWorker( + env_creator=lambda _: gym.make("CartPole-v1"), + default_policy_class=PPOTF1Policy) + batch = worker.sample() + info = worker.learn_on_batch(samples) + """ + if log_once("learn_on_batch"): + logger.info( + "Training on concatenated sample batches:\n\n{}\n".format( + summarize(samples) + ) + ) + + info_out = {} + if isinstance(samples, MultiAgentBatch): + builders = {} + to_fetch = {} + for pid, batch in samples.policy_batches.items(): + if self.is_policy_to_train is not None and not self.is_policy_to_train( + pid, samples + ): + continue + # Decompress SampleBatch, in case some columns are compressed. + batch.decompress_if_needed() + + policy = self.policy_map[pid] + tf_session = policy.get_session() + if tf_session and hasattr(policy, "_build_learn_on_batch"): + builders[pid] = _TFRunBuilder(tf_session, "learn_on_batch") + to_fetch[pid] = policy._build_learn_on_batch(builders[pid], batch) + else: + info_out[pid] = policy.learn_on_batch(batch) + + info_out.update({pid: builders[pid].get(v) for pid, v in to_fetch.items()}) + else: + if self.is_policy_to_train is None or self.is_policy_to_train( + DEFAULT_POLICY_ID, samples + ): + info_out.update( + { + DEFAULT_POLICY_ID: self.policy_map[ + DEFAULT_POLICY_ID + ].learn_on_batch(samples) + } + ) + if log_once("learn_out"): + logger.debug("Training out:\n\n{}\n".format(summarize(info_out))) + return info_out + + def sample_and_learn( + self, + expected_batch_size: int, + num_sgd_iter: int, + sgd_minibatch_size: str, + standardize_fields: List[str], + ) -> Tuple[dict, int]: + """Sample and batch and learn on it. + + This is typically used in combination with distributed allreduce. + + Args: + expected_batch_size: Expected number of samples to learn on. + num_sgd_iter: Number of SGD iterations. + sgd_minibatch_size: SGD minibatch size. + standardize_fields: List of sample fields to normalize. + + Returns: + A tuple consisting of a dictionary of extra metadata returned from + the policies' `learn_on_batch()` and the number of samples + learned on. + """ + batch = self.sample() + assert batch.count == expected_batch_size, ( + "Batch size possibly out of sync between workers, expected:", + expected_batch_size, + "got:", + batch.count, + ) + logger.info( + "Executing distributed minibatch SGD " + "with epoch size {}, minibatch size {}".format( + batch.count, sgd_minibatch_size + ) + ) + info = do_minibatch_sgd( + batch, + self.policy_map, + self, + num_sgd_iter, + sgd_minibatch_size, + standardize_fields, + ) + return info, batch.count + + def compute_gradients( + self, + samples: SampleBatchType, + single_agent: bool = None, + ) -> Tuple[ModelGradients, dict]: + """Returns a gradient computed w.r.t the specified samples. + + Uses the Policy's/ies' compute_gradients method(s) to perform the + calculations. Skips policies that are not trainable as per + `self.is_policy_to_train()`. + + Args: + samples: The SampleBatch or MultiAgentBatch to compute gradients + for using this worker's trainable policies. + + Returns: + In the single-agent case, a tuple consisting of ModelGradients and + info dict of the worker's policy. + In the multi-agent case, a tuple consisting of a dict mapping + PolicyID to ModelGradients and a dict mapping PolicyID to extra + metadata info. + Note that the first return value (grads) can be applied as is to a + compatible worker using the worker's `apply_gradients()` method. + + .. testcode:: + :skipif: True + + import gymnasium as gym + from ray.rllib.evaluation.rollout_worker import RolloutWorker + from ray.rllib.algorithms.ppo.ppo_tf_policy import PPOTF1Policy + worker = RolloutWorker( + env_creator=lambda _: gym.make("CartPole-v1"), + default_policy_class=PPOTF1Policy) + batch = worker.sample() + grads, info = worker.compute_gradients(samples) + """ + if log_once("compute_gradients"): + logger.info("Compute gradients on:\n\n{}\n".format(summarize(samples))) + + if single_agent is True: + samples = convert_ma_batch_to_sample_batch(samples) + grad_out, info_out = self.policy_map[DEFAULT_POLICY_ID].compute_gradients( + samples + ) + info_out["batch_count"] = samples.count + return grad_out, info_out + + # Treat everything as is multi-agent. + samples = samples.as_multi_agent() + + # Calculate gradients for all policies. + grad_out, info_out = {}, {} + if self.config.framework_str == "tf": + for pid, batch in samples.policy_batches.items(): + if self.is_policy_to_train is not None and not self.is_policy_to_train( + pid, samples + ): + continue + policy = self.policy_map[pid] + builder = _TFRunBuilder(policy.get_session(), "compute_gradients") + grad_out[pid], info_out[pid] = policy._build_compute_gradients( + builder, batch + ) + grad_out = {k: builder.get(v) for k, v in grad_out.items()} + info_out = {k: builder.get(v) for k, v in info_out.items()} + else: + for pid, batch in samples.policy_batches.items(): + if self.is_policy_to_train is not None and not self.is_policy_to_train( + pid, samples + ): + continue + grad_out[pid], info_out[pid] = self.policy_map[pid].compute_gradients( + batch + ) + + info_out["batch_count"] = samples.count + if log_once("grad_out"): + logger.info("Compute grad info:\n\n{}\n".format(summarize(info_out))) + + return grad_out, info_out + + def apply_gradients( + self, + grads: Union[ModelGradients, Dict[PolicyID, ModelGradients]], + ) -> None: + """Applies the given gradients to this worker's models. + + Uses the Policy's/ies' apply_gradients method(s) to perform the + operations. + + Args: + grads: Single ModelGradients (single-agent case) or a dict + mapping PolicyIDs to the respective model gradients + structs. + + .. testcode:: + :skipif: True + + import gymnasium as gym + from ray.rllib.evaluation.rollout_worker import RolloutWorker + from ray.rllib.algorithms.ppo.ppo_tf_policy import PPOTF1Policy + worker = RolloutWorker( + env_creator=lambda _: gym.make("CartPole-v1"), + default_policy_class=PPOTF1Policy) + samples = worker.sample() + grads, info = worker.compute_gradients(samples) + worker.apply_gradients(grads) + """ + if log_once("apply_gradients"): + logger.info("Apply gradients:\n\n{}\n".format(summarize(grads))) + # Grads is a dict (mapping PolicyIDs to ModelGradients). + # Multi-agent case. + if isinstance(grads, dict): + for pid, g in grads.items(): + if self.is_policy_to_train is None or self.is_policy_to_train( + pid, None + ): + self.policy_map[pid].apply_gradients(g) + # Grads is a ModelGradients type. Single-agent case. + elif self.is_policy_to_train is None or self.is_policy_to_train( + DEFAULT_POLICY_ID, None + ): + self.policy_map[DEFAULT_POLICY_ID].apply_gradients(grads) + + @override(EnvRunner) + def get_metrics(self) -> List[RolloutMetrics]: + """Returns the thus-far collected metrics from this worker's rollouts. + + Returns: + List of RolloutMetrics collected thus-far. + """ + # Get metrics from sampler (if any). + if self.sampler is not None: + out = self.sampler.get_metrics() + else: + out = [] + + return out + + def foreach_env(self, func: Callable[[EnvType], T]) -> List[T]: + """Calls the given function with each sub-environment as arg. + + Args: + func: The function to call for each underlying + sub-environment (as only arg). + + Returns: + The list of return values of all calls to `func([env])`. + """ + + if self.async_env is None: + return [] + + envs = self.async_env.get_sub_environments() + # Empty list (not implemented): Call function directly on the + # BaseEnv. + if not envs: + return [func(self.async_env)] + # Call function on all underlying (vectorized) sub environments. + else: + return [func(e) for e in envs] + + def foreach_env_with_context( + self, func: Callable[[EnvType, EnvContext], T] + ) -> List[T]: + """Calls given function with each sub-env plus env_ctx as args. + + Args: + func: The function to call for each underlying + sub-environment and its EnvContext (as the args). + + Returns: + The list of return values of all calls to `func([env, ctx])`. + """ + + if self.async_env is None: + return [] + + envs = self.async_env.get_sub_environments() + # Empty list (not implemented): Call function directly on the + # BaseEnv. + if not envs: + return [func(self.async_env, self.env_context)] + # Call function on all underlying (vectorized) sub environments. + else: + ret = [] + for i, e in enumerate(envs): + ctx = self.env_context.copy_with_overrides(vector_index=i) + ret.append(func(e, ctx)) + return ret + + def get_policy(self, policy_id: PolicyID = DEFAULT_POLICY_ID) -> Optional[Policy]: + """Return policy for the specified id, or None. + + Args: + policy_id: ID of the policy to return. None for DEFAULT_POLICY_ID + (in the single agent case). + + Returns: + The policy under the given ID (or None if not found). + """ + return self.policy_map.get(policy_id) + + def add_policy( + self, + policy_id: PolicyID, + policy_cls: Optional[Type[Policy]] = None, + policy: Optional[Policy] = None, + *, + observation_space: Optional[Space] = None, + action_space: Optional[Space] = None, + config: Optional[PartialAlgorithmConfigDict] = None, + policy_state: Optional[PolicyState] = None, + policy_mapping_fn=None, + policies_to_train: Optional[ + Union[Collection[PolicyID], Callable[[PolicyID, SampleBatchType], bool]] + ] = None, + module_spec: Optional[RLModuleSpec] = None, + ) -> Policy: + """Adds a new policy to this RolloutWorker. + + Args: + policy_id: ID of the policy to add. + policy_cls: The Policy class to use for constructing the new Policy. + Note: Only one of `policy_cls` or `policy` must be provided. + policy: The Policy instance to add to this algorithm. + Note: Only one of `policy_cls` or `policy` must be provided. + observation_space: The observation space of the policy to add. + action_space: The action space of the policy to add. + config: The config overrides for the policy to add. + policy_state: Optional state dict to apply to the new + policy instance, right after its construction. + policy_mapping_fn: An optional (updated) policy mapping function + to use from here on. Note that already ongoing episodes will + not change their mapping but will use the old mapping till + the end of the episode. + policies_to_train: An optional collection of policy IDs to be + trained or a callable taking PolicyID and - optionally - + SampleBatchType and returning a bool (trainable or not?). + If None, will keep the existing setup in place. + Policies, whose IDs are not in the list (or for which the + callable returns False) will not be updated. + module_spec: In the new RLModule API we need to pass in the module_spec for + the new module that is supposed to be added. Knowing the policy spec is + not sufficient. + + Returns: + The newly added policy. + + Raises: + ValueError: If both `policy_cls` AND `policy` are provided. + KeyError: If the given `policy_id` already exists in this worker's + PolicyMap. + """ + validate_module_id(policy_id, error=False) + + if module_spec is not None: + raise ValueError( + "If you pass in module_spec to the policy, the RLModule API needs " + "to be enabled." + ) + + if policy_id in self.policy_map: + raise KeyError( + f"Policy ID '{policy_id}' already exists in policy map! " + "Make sure you use a Policy ID that has not been taken yet." + " Policy IDs that are already in your policy map: " + f"{list(self.policy_map.keys())}" + ) + if (policy_cls is None) == (policy is None): + raise ValueError( + "Only one of `policy_cls` or `policy` must be provided to " + "RolloutWorker.add_policy()!" + ) + + if policy is None: + policy_dict_to_add, _ = self.config.get_multi_agent_setup( + policies={ + policy_id: PolicySpec( + policy_cls, observation_space, action_space, config + ) + }, + env=self.env, + spaces=self.spaces, + default_policy_class=self.default_policy_class, + ) + else: + policy_dict_to_add = { + policy_id: PolicySpec( + type(policy), + policy.observation_space, + policy.action_space, + policy.config, + ) + } + + self.policy_dict.update(policy_dict_to_add) + self._update_policy_map( + policy_dict=policy_dict_to_add, + policy=policy, + policy_states={policy_id: policy_state}, + single_agent_rl_module_spec=module_spec, + ) + + self.set_policy_mapping_fn(policy_mapping_fn) + if policies_to_train is not None: + self.set_is_policy_to_train(policies_to_train) + + return self.policy_map[policy_id] + + def remove_policy( + self, + *, + policy_id: PolicyID = DEFAULT_POLICY_ID, + policy_mapping_fn: Optional[Callable[[AgentID], PolicyID]] = None, + policies_to_train: Optional[ + Union[Collection[PolicyID], Callable[[PolicyID, SampleBatchType], bool]] + ] = None, + ) -> None: + """Removes a policy from this RolloutWorker. + + Args: + policy_id: ID of the policy to be removed. None for + DEFAULT_POLICY_ID. + policy_mapping_fn: An optional (updated) policy mapping function + to use from here on. Note that already ongoing episodes will + not change their mapping but will use the old mapping till + the end of the episode. + policies_to_train: An optional collection of policy IDs to be + trained or a callable taking PolicyID and - optionally - + SampleBatchType and returning a bool (trainable or not?). + If None, will keep the existing setup in place. + Policies, whose IDs are not in the list (or for which the + callable returns False) will not be updated. + """ + if policy_id not in self.policy_map: + raise ValueError(f"Policy ID '{policy_id}' not in policy map!") + del self.policy_map[policy_id] + del self.preprocessors[policy_id] + self.set_policy_mapping_fn(policy_mapping_fn) + if policies_to_train is not None: + self.set_is_policy_to_train(policies_to_train) + + def set_policy_mapping_fn( + self, + policy_mapping_fn: Optional[Callable[[AgentID, Any], PolicyID]] = None, + ) -> None: + """Sets `self.policy_mapping_fn` to a new callable (if provided). + + Args: + policy_mapping_fn: The new mapping function to use. If None, + will keep the existing mapping function in place. + """ + if policy_mapping_fn is not None: + self.policy_mapping_fn = policy_mapping_fn + if not callable(self.policy_mapping_fn): + raise ValueError("`policy_mapping_fn` must be a callable!") + + def set_is_policy_to_train( + self, + is_policy_to_train: Union[ + Collection[PolicyID], Callable[[PolicyID, Optional[SampleBatchType]], bool] + ], + ) -> None: + """Sets `self.is_policy_to_train()` to a new callable. + + Args: + is_policy_to_train: A collection of policy IDs to be + trained or a callable taking PolicyID and - optionally - + SampleBatchType and returning a bool (trainable or not?). + If None, will keep the existing setup in place. + Policies, whose IDs are not in the list (or for which the + callable returns False) will not be updated. + """ + # If collection given, construct a simple default callable returning True + # if the PolicyID is found in the list/set of IDs. + if not callable(is_policy_to_train): + assert isinstance(is_policy_to_train, (list, set, tuple)), ( + "ERROR: `is_policy_to_train`must be a [list|set|tuple] or a " + "callable taking PolicyID and SampleBatch and returning " + "True|False (trainable or not?)." + ) + pols = set(is_policy_to_train) + + def is_policy_to_train(pid, batch=None): + return pid in pols + + self.is_policy_to_train = is_policy_to_train + + @PublicAPI(stability="alpha") + def get_policies_to_train( + self, batch: Optional[SampleBatchType] = None + ) -> Set[PolicyID]: + """Returns all policies-to-train, given an optional batch. + + Loops through all policies currently in `self.policy_map` and checks + the return value of `self.is_policy_to_train(pid, batch)`. + + Args: + batch: An optional SampleBatchType for the + `self.is_policy_to_train(pid, [batch]?)` check. + + Returns: + The set of currently trainable policy IDs, given the optional + `batch`. + """ + return { + pid + for pid in self.policy_map.keys() + if self.is_policy_to_train is None or self.is_policy_to_train(pid, batch) + } + + def for_policy( + self, + func: Callable[[Policy, Optional[Any]], T], + policy_id: Optional[PolicyID] = DEFAULT_POLICY_ID, + **kwargs, + ) -> T: + """Calls the given function with the specified policy as first arg. + + Args: + func: The function to call with the policy as first arg. + policy_id: The PolicyID of the policy to call the function with. + + Keyword Args: + kwargs: Additional kwargs to be passed to the call. + + Returns: + The return value of the function call. + """ + + return func(self.policy_map[policy_id], **kwargs) + + def foreach_policy( + self, func: Callable[[Policy, PolicyID, Optional[Any]], T], **kwargs + ) -> List[T]: + """Calls the given function with each (policy, policy_id) tuple. + + Args: + func: The function to call with each (policy, policy ID) tuple. + + Keyword Args: + kwargs: Additional kwargs to be passed to the call. + + Returns: + The list of return values of all calls to + `func([policy, pid, **kwargs])`. + """ + return [func(policy, pid, **kwargs) for pid, policy in self.policy_map.items()] + + def foreach_policy_to_train( + self, func: Callable[[Policy, PolicyID, Optional[Any]], T], **kwargs + ) -> List[T]: + """ + Calls the given function with each (policy, policy_id) tuple. + + Only those policies/IDs will be called on, for which + `self.is_policy_to_train()` returns True. + + Args: + func: The function to call with each (policy, policy ID) tuple, + for only those policies that `self.is_policy_to_train` + returns True. + + Keyword Args: + kwargs: Additional kwargs to be passed to the call. + + Returns: + The list of return values of all calls to + `func([policy, pid, **kwargs])`. + """ + return [ + # Make sure to only iterate over keys() and not items(). Iterating over + # items will access policy_map elements even for pids that we do not need, + # i.e. those that are not in policy_to_train. Access to policy_map elements + # can cause disk access for policies that were offloaded to disk. Since + # these policies will be skipped in the for-loop accessing them is + # unnecessary, making subsequent disk access unnecessary. + func(self.policy_map[pid], pid, **kwargs) + for pid in self.policy_map.keys() + if self.is_policy_to_train is None or self.is_policy_to_train(pid, None) + ] + + def sync_filters(self, new_filters: dict) -> None: + """Changes self's filter to given and rebases any accumulated delta. + + Args: + new_filters: Filters with new state to update local copy. + """ + assert all(k in new_filters for k in self.filters) + for k in self.filters: + self.filters[k].sync(new_filters[k]) + + def get_filters(self, flush_after: bool = False) -> Dict: + """Returns a snapshot of filters. + + Args: + flush_after: Clears the filter buffer state. + + Returns: + Dict for serializable filters + """ + return_filters = {} + for k, f in self.filters.items(): + return_filters[k] = f.as_serializable() + if flush_after: + f.reset_buffer() + return return_filters + + def get_state(self) -> dict: + filters = self.get_filters(flush_after=True) + policy_states = {} + for pid in self.policy_map.keys(): + # If required by the user, only capture policies that are actually + # trainable. Otherwise, capture all policies (for saving to disk). + if ( + not self.config.checkpoint_trainable_policies_only + or self.is_policy_to_train is None + or self.is_policy_to_train(pid) + ): + policy_states[pid] = self.policy_map[pid].get_state() + + return { + # List all known policy IDs here for convenience. When an Algorithm gets + # restored from a checkpoint, it will not have access to the list of + # possible IDs as each policy is stored in its own sub-dir + # (see "policy_states"). + "policy_ids": list(self.policy_map.keys()), + # Note that this field will not be stored in the algorithm checkpoint's + # state file, but each policy will get its own state file generated in + # a sub-dir within the algo's checkpoint dir. + "policy_states": policy_states, + # Also store current mapping fn and which policies to train. + "policy_mapping_fn": self.policy_mapping_fn, + "is_policy_to_train": self.is_policy_to_train, + # TODO: Filters will be replaced by connectors. + "filters": filters, + } + + def set_state(self, state: dict) -> None: + # Backward compatibility (old checkpoints' states would have the local + # worker state as a bytes object, not a dict). + if isinstance(state, bytes): + state = pickle.loads(state) + + # TODO: Once filters are handled by connectors, get rid of the "filters" + # key in `state` entirely (will be part of the policies then). + self.sync_filters(state["filters"]) + + # Support older checkpoint versions (< 1.0), in which the policy_map + # was stored under the "state" key, not "policy_states". + policy_states = ( + state["policy_states"] if "policy_states" in state else state["state"] + ) + for pid, policy_state in policy_states.items(): + # If - for some reason - we have an invalid PolicyID in the state, + # this might be from an older checkpoint (pre v1.0). Just warn here. + validate_module_id(pid, error=False) + + if pid not in self.policy_map: + spec = policy_state.get("policy_spec", None) + if spec is None: + logger.warning( + f"PolicyID '{pid}' was probably added on-the-fly (not" + " part of the static `multagent.policies` config) and" + " no PolicySpec objects found in the pickled policy " + f"state. Will not add `{pid}`, but ignore it for now." + ) + else: + policy_spec = ( + PolicySpec.deserialize(spec) if isinstance(spec, dict) else spec + ) + self.add_policy( + policy_id=pid, + policy_cls=policy_spec.policy_class, + observation_space=policy_spec.observation_space, + action_space=policy_spec.action_space, + config=policy_spec.config, + ) + if pid in self.policy_map: + self.policy_map[pid].set_state(policy_state) + + # Also restore mapping fn and which policies to train. + if "policy_mapping_fn" in state: + self.set_policy_mapping_fn(state["policy_mapping_fn"]) + if state.get("is_policy_to_train") is not None: + self.set_is_policy_to_train(state["is_policy_to_train"]) + + def get_weights( + self, + policies: Optional[Collection[PolicyID]] = None, + inference_only: bool = False, + ) -> Dict[PolicyID, ModelWeights]: + """Returns each policies' model weights of this worker. + + Args: + policies: List of PolicyIDs to get the weights from. + Use None for all policies. + inference_only: This argument is only added for interface + consistency with the new api stack. + + Returns: + Dict mapping PolicyIDs to ModelWeights. + + .. testcode:: + :skipif: True + + from ray.rllib.evaluation.rollout_worker import RolloutWorker + # Create a RolloutWorker. + worker = ... + weights = worker.get_weights() + print(weights) + + .. testoutput:: + + {"default_policy": {"layer1": array(...), "layer2": ...}} + """ + if policies is None: + policies = list(self.policy_map.keys()) + policies = force_list(policies) + + return { + # Make sure to only iterate over keys() and not items(). Iterating over + # items will access policy_map elements even for pids that we do not need, + # i.e. those that are not in policies. Access to policy_map elements can + # cause disk access for policies that were offloaded to disk. Since these + # policies will be skipped in the for-loop accessing them is unnecessary, + # making subsequent disk access unnecessary. + pid: self.policy_map[pid].get_weights() + for pid in self.policy_map.keys() + if pid in policies + } + + def set_weights( + self, + weights: Dict[PolicyID, ModelWeights], + global_vars: Optional[Dict] = None, + weights_seq_no: Optional[int] = None, + ) -> None: + """Sets each policies' model weights of this worker. + + Args: + weights: Dict mapping PolicyIDs to the new weights to be used. + global_vars: An optional global vars dict to set this + worker to. If None, do not update the global_vars. + weights_seq_no: If needed, a sequence number for the weights version + can be passed into this method. If not None, will store this seq no + (in self.weights_seq_no) and in future calls - if the seq no did not + change wrt. the last call - will ignore the call to save on performance. + + .. testcode:: + :skipif: True + + from ray.rllib.evaluation.rollout_worker import RolloutWorker + # Create a RolloutWorker. + worker = ... + weights = worker.get_weights() + # Set `global_vars` (timestep) as well. + worker.set_weights(weights, {"timestep": 42}) + """ + # Only update our weights, if no seq no given OR given seq no is different + # from ours. + if weights_seq_no is None or weights_seq_no != self.weights_seq_no: + # If per-policy weights are object refs, `ray.get()` them first. + if weights and isinstance(next(iter(weights.values())), ObjectRef): + actual_weights = ray.get(list(weights.values())) + weights = { + pid: actual_weights[i] for i, pid in enumerate(weights.keys()) + } + + for pid, w in weights.items(): + if pid in self.policy_map: + self.policy_map[pid].set_weights(w) + elif log_once("set_weights_on_non_existent_policy"): + logger.warning( + "`RolloutWorker.set_weights()` used with weights from " + f"policyID={pid}, but this policy cannot be found on this " + f"worker! Skipping ..." + ) + + self.weights_seq_no = weights_seq_no + + if global_vars: + self.set_global_vars(global_vars) + + def get_global_vars(self) -> dict: + """Returns the current `self.global_vars` dict of this RolloutWorker. + + Returns: + The current `self.global_vars` dict of this RolloutWorker. + + .. testcode:: + :skipif: True + + from ray.rllib.evaluation.rollout_worker import RolloutWorker + # Create a RolloutWorker. + worker = ... + global_vars = worker.get_global_vars() + print(global_vars) + + .. testoutput:: + + {"timestep": 424242} + """ + return self.global_vars + + def set_global_vars( + self, + global_vars: dict, + policy_ids: Optional[List[PolicyID]] = None, + ) -> None: + """Updates this worker's and all its policies' global vars. + + Updates are done using the dict's update method. + + Args: + global_vars: The global_vars dict to update the `self.global_vars` dict + from. + policy_ids: Optional list of Policy IDs to update. If None, will update all + policies on the to-be-updated workers. + + .. testcode:: + :skipif: True + + worker = ... + global_vars = worker.set_global_vars( + ... {"timestep": 4242}) + """ + # Handle per-policy values. + global_vars_copy = global_vars.copy() + gradient_updates_per_policy = global_vars_copy.pop( + "num_grad_updates_per_policy", {} + ) + self.global_vars["num_grad_updates_per_policy"].update( + gradient_updates_per_policy + ) + # Only update explicitly provided policies or those that that are being + # trained, in order to avoid superfluous access of policies, which might have + # been offloaded to the object store. + # Important b/c global vars are constantly being updated. + for pid in policy_ids if policy_ids is not None else self.policy_map.keys(): + if self.is_policy_to_train is None or self.is_policy_to_train(pid, None): + self.policy_map[pid].on_global_var_update( + dict( + global_vars_copy, + # If count is None, Policy won't update the counter. + **{"num_grad_updates": gradient_updates_per_policy.get(pid)}, + ) + ) + + # Update all other global vars. + self.global_vars.update(global_vars_copy) + + @override(EnvRunner) + def stop(self) -> None: + """Releases all resources used by this RolloutWorker.""" + + # If we have an env -> Release its resources. + if self.env is not None: + self.async_env.stop() + + # Close all policies' sessions (if tf static graph). + for policy in self.policy_map.cache.values(): + sess = policy.get_session() + # Closes the tf session, if any. + if sess is not None: + sess.close() + + def lock(self) -> None: + """Locks this RolloutWorker via its own threading.Lock.""" + self._lock.acquire() + + def unlock(self) -> None: + """Unlocks this RolloutWorker via its own threading.Lock.""" + self._lock.release() + + def setup_torch_data_parallel( + self, url: str, world_rank: int, world_size: int, backend: str + ) -> None: + """Join a torch process group for distributed SGD.""" + + logger.info( + "Joining process group, url={}, world_rank={}, " + "world_size={}, backend={}".format(url, world_rank, world_size, backend) + ) + torch.distributed.init_process_group( + backend=backend, init_method=url, rank=world_rank, world_size=world_size + ) + + for pid, policy in self.policy_map.items(): + if not isinstance(policy, (TorchPolicy, TorchPolicyV2)): + raise ValueError( + "This policy does not support torch distributed", policy + ) + policy.distributed_world_size = world_size + + def creation_args(self) -> dict: + """Returns the kwargs dict used to create this worker.""" + return self._original_kwargs + + def get_host(self) -> str: + """Returns the hostname of the process running this evaluator.""" + return platform.node() + + def get_node_ip(self) -> str: + """Returns the IP address of the node that this worker runs on.""" + return ray.util.get_node_ip_address() + + def find_free_port(self) -> int: + """Finds a free port on the node that this worker runs on.""" + from ray.air._internal.util import find_free_port + + return find_free_port() + + def _update_policy_map( + self, + *, + policy_dict: MultiAgentPolicyConfigDict, + policy: Optional[Policy] = None, + policy_states: Optional[Dict[PolicyID, PolicyState]] = None, + single_agent_rl_module_spec: Optional[RLModuleSpec] = None, + ) -> None: + """Updates the policy map (and other stuff) on this worker. + + It performs the following: + 1. It updates the observation preprocessors and updates the policy_specs + with the postprocessed observation_spaces. + 2. It updates the policy_specs with the complete algorithm_config (merged + with the policy_spec's config). + 3. If needed it will update the self.multi_rl_module_spec on this worker + 3. It updates the policy map with the new policies + 4. It updates the filter dict + 5. It calls the on_create_policy() hook of the callbacks on the newly added + policies. + + Args: + policy_dict: The policy dict to update the policy map with. + policy: The policy to update the policy map with. + policy_states: The policy states to update the policy map with. + single_agent_rl_module_spec: The RLModuleSpec to add to the + MultiRLModuleSpec. If None, the config's + `get_default_rl_module_spec` method's output will be used to create + the policy with. + """ + + # Update the input policy dict with the postprocessed observation spaces and + # merge configs. Also updates the preprocessor dict. + updated_policy_dict = self._get_complete_policy_specs_dict(policy_dict) + + # Builds the self.policy_map dict + self._build_policy_map( + policy_dict=updated_policy_dict, + policy=policy, + policy_states=policy_states, + ) + + # Initialize the filter dict + self._update_filter_dict(updated_policy_dict) + + # Call callback policy init hooks (only if the added policy did not exist + # before). + if policy is None: + self._call_callbacks_on_create_policy() + + if self.worker_index == 0: + logger.info(f"Built policy map: {self.policy_map}") + logger.info(f"Built preprocessor map: {self.preprocessors}") + + def _get_complete_policy_specs_dict( + self, policy_dict: MultiAgentPolicyConfigDict + ) -> MultiAgentPolicyConfigDict: + """Processes the policy dict and creates a new copy with the processed attrs. + + This processes the observation_space and prepares them for passing to rl module + construction. It also merges the policy configs with the algorithm config. + During this processing, we will also construct the preprocessors dict. + """ + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + + updated_policy_dict = copy.deepcopy(policy_dict) + # If our preprocessors dict does not exist yet, create it here. + self.preprocessors = self.preprocessors or {} + # Loop through given policy-dict and add each entry to our map. + for name, policy_spec in sorted(updated_policy_dict.items()): + logger.debug("Creating policy for {}".format(name)) + + # Policy brings its own complete AlgorithmConfig -> Use it for this policy. + if isinstance(policy_spec.config, AlgorithmConfig): + merged_conf = policy_spec.config + else: + # Update the general config with the specific config + # for this particular policy. + merged_conf: "AlgorithmConfig" = self.config.copy(copy_frozen=False) + merged_conf.update_from_dict(policy_spec.config or {}) + + # Update num_workers and worker_index. + merged_conf.worker_index = self.worker_index + + # Preprocessors. + obs_space = policy_spec.observation_space + # Initialize preprocessor for this policy to None. + self.preprocessors[name] = None + if self.preprocessing_enabled: + # Policies should deal with preprocessed (automatically flattened) + # observations if preprocessing is enabled. + preprocessor = ModelCatalog.get_preprocessor_for_space( + obs_space, + merged_conf.model, + include_multi_binary=False, + ) + # Original observation space should be accessible at + # obs_space.original_space after this step. + if preprocessor is not None: + obs_space = preprocessor.observation_space + + policy_spec.config = merged_conf + policy_spec.observation_space = obs_space + + return updated_policy_dict + + def _update_policy_dict_with_multi_rl_module( + self, policy_dict: MultiAgentPolicyConfigDict + ) -> MultiAgentPolicyConfigDict: + for name, policy_spec in policy_dict.items(): + policy_spec.config["__multi_rl_module_spec"] = self.multi_rl_module_spec + return policy_dict + + def _build_policy_map( + self, + *, + policy_dict: MultiAgentPolicyConfigDict, + policy: Optional[Policy] = None, + policy_states: Optional[Dict[PolicyID, PolicyState]] = None, + ) -> None: + """Adds the given policy_dict to `self.policy_map`. + + Args: + policy_dict: The MultiAgentPolicyConfigDict to be added to this + worker's PolicyMap. + policy: If the policy to add already exists, user can provide it here. + policy_states: Optional dict from PolicyIDs to PolicyStates to + restore the states of the policies being built. + """ + + # If our policy_map does not exist yet, create it here. + self.policy_map = self.policy_map or PolicyMap( + capacity=self.config.policy_map_capacity, + policy_states_are_swappable=self.config.policy_states_are_swappable, + ) + + # Loop through given policy-dict and add each entry to our map. + for name, policy_spec in sorted(policy_dict.items()): + # Create the actual policy object. + if policy is None: + new_policy = create_policy_for_framework( + policy_id=name, + policy_class=get_tf_eager_cls_if_necessary( + policy_spec.policy_class, policy_spec.config + ), + merged_config=policy_spec.config, + observation_space=policy_spec.observation_space, + action_space=policy_spec.action_space, + worker_index=self.worker_index, + seed=self.seed, + ) + else: + new_policy = policy + + self.policy_map[name] = new_policy + + restore_states = (policy_states or {}).get(name, None) + # Set the state of the newly created policy before syncing filters, etc. + if restore_states: + new_policy.set_state(restore_states) + + def _update_filter_dict(self, policy_dict: MultiAgentPolicyConfigDict) -> None: + """Updates the filter dict for the given policy_dict.""" + + for name, policy_spec in sorted(policy_dict.items()): + new_policy = self.policy_map[name] + # Note(jungong) : We should only create new connectors for the + # policy iff we are creating a new policy from scratch. i.e, + # we should NOT create new connectors when we already have the + # policy object created before this function call or have the + # restoring states from the caller. + # Also note that we cannot just check the existence of connectors + # to decide whether we should create connectors because we may be + # restoring a policy that has 0 connectors configured. + if ( + new_policy.agent_connectors is None + or new_policy.action_connectors is None + ): + # TODO(jungong) : revisit this. It will be nicer to create + # connectors as the last step of Policy.__init__(). + create_connectors_for_policy(new_policy, policy_spec.config) + maybe_get_filters_for_syncing(self, name) + + def _call_callbacks_on_create_policy(self): + """Calls the on_create_policy callback for each policy in the policy map.""" + for name, policy in self.policy_map.items(): + self.callbacks.on_create_policy(policy_id=name, policy=policy) + + def _get_input_creator_from_config(self): + def valid_module(class_path): + if ( + isinstance(class_path, str) + and not os.path.isfile(class_path) + and "." in class_path + ): + module_path, class_name = class_path.rsplit(".", 1) + try: + spec = importlib.util.find_spec(module_path) + if spec is not None: + return True + except (ModuleNotFoundError, ValueError): + print( + f"module {module_path} not found while trying to get " + f"input {class_path}" + ) + return False + + # A callable returning an InputReader object to use. + if isinstance(self.config.input_, FunctionType): + return self.config.input_ + # Use RLlib's Sampler classes (SyncSampler). + elif self.config.input_ == "sampler": + return lambda ioctx: ioctx.default_sampler_input() + # Ray Dataset input -> Use `config.input_config` to construct DatasetReader. + elif self.config.input_ == "dataset": + assert self._ds_shards is not None + # Input dataset shards should have already been prepared. + # We just need to take the proper shard here. + return lambda ioctx: DatasetReader( + self._ds_shards[self.worker_index], ioctx + ) + # Dict: Mix of different input methods with different ratios. + elif isinstance(self.config.input_, dict): + return lambda ioctx: ShuffledInput( + MixedInput(self.config.input_, ioctx), self.config.shuffle_buffer_size + ) + # A pre-registered input descriptor (str). + elif isinstance(self.config.input_, str) and registry_contains_input( + self.config.input_ + ): + return registry_get_input(self.config.input_) + # D4RL input. + elif "d4rl" in self.config.input_: + env_name = self.config.input_.split(".")[-1] + return lambda ioctx: D4RLReader(env_name, ioctx) + # Valid python module (class path) -> Create using `from_config`. + elif valid_module(self.config.input_): + return lambda ioctx: ShuffledInput( + from_config(self.config.input_, ioctx=ioctx) + ) + # JSON file or list of JSON files -> Use JsonReader (shuffled). + else: + return lambda ioctx: ShuffledInput( + JsonReader(self.config.input_, ioctx), self.config.shuffle_buffer_size + ) + + def _get_output_creator_from_config(self): + if isinstance(self.config.output, FunctionType): + return self.config.output + elif self.config.output is None: + return lambda ioctx: NoopOutput() + elif self.config.output == "dataset": + return lambda ioctx: DatasetWriter( + ioctx, compress_columns=self.config.output_compress_columns + ) + elif self.config.output == "logdir": + return lambda ioctx: JsonWriter( + ioctx.log_dir, + ioctx, + max_file_size=self.config.output_max_file_size, + compress_columns=self.config.output_compress_columns, + ) + else: + return lambda ioctx: JsonWriter( + self.config.output, + ioctx, + max_file_size=self.config.output_max_file_size, + compress_columns=self.config.output_compress_columns, + ) + + def _get_make_sub_env_fn( + self, env_creator, env_context, validate_env, env_wrapper, seed + ): + def _make_sub_env_local(vector_index): + # Used to created additional environments during environment + # vectorization. + + # Create the env context (config dict + meta-data) for + # this particular sub-env within the vectorized one. + env_ctx = env_context.copy_with_overrides(vector_index=vector_index) + # Create the sub-env. + env = env_creator(env_ctx) + # Custom validation function given by user. + if validate_env is not None: + validate_env(env, env_ctx) + # Use our wrapper, defined above. + env = env_wrapper(env) + + # Make sure a deterministic random seed is set on + # all the sub-environments if specified. + _update_env_seed_if_necessary( + env, seed, env_context.worker_index, vector_index + ) + return env + + if not env_context.remote: + + def _make_sub_env_remote(vector_index): + sub_env = _make_sub_env_local(vector_index) + self.callbacks.on_sub_environment_created( + worker=self, + sub_environment=sub_env, + env_context=env_context.copy_with_overrides( + worker_index=env_context.worker_index, + vector_index=vector_index, + remote=False, + ), + ) + return sub_env + + return _make_sub_env_remote + + else: + return _make_sub_env_local diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/sample_batch_builder.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/sample_batch_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..c4c748fe3bce75308b9f99e3af4fd1644c4cf525 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/sample_batch_builder.py @@ -0,0 +1,264 @@ +import collections +import logging +import numpy as np +from typing import List, Any, Dict, TYPE_CHECKING + +from ray.rllib.env.base_env import _DUMMY_AGENT_ID +from ray.rllib.policy.policy import Policy +from ray.rllib.policy.sample_batch import SampleBatch, MultiAgentBatch +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.debug import summarize +from ray.rllib.utils.deprecation import deprecation_warning +from ray.rllib.utils.typing import PolicyID, AgentID +from ray.util.debug import log_once + +if TYPE_CHECKING: + from ray.rllib.callbacks.callbacks import RLlibCallback + +logger = logging.getLogger(__name__) + + +def _to_float_array(v: List[Any]) -> np.ndarray: + arr = np.array(v) + if arr.dtype == np.float64: + return arr.astype(np.float32) # save some memory + return arr + + +@OldAPIStack +class SampleBatchBuilder: + """Util to build a SampleBatch incrementally. + + For efficiency, SampleBatches hold values in column form (as arrays). + However, it is useful to add data one row (dict) at a time. + """ + + _next_unroll_id = 0 # disambiguates unrolls within a single episode + + def __init__(self): + self.buffers: Dict[str, List] = collections.defaultdict(list) + self.count = 0 + + def add_values(self, **values: Any) -> None: + """Add the given dictionary (row) of values to this batch.""" + + for k, v in values.items(): + self.buffers[k].append(v) + self.count += 1 + + def add_batch(self, batch: SampleBatch) -> None: + """Add the given batch of values to this batch.""" + + for k, column in batch.items(): + self.buffers[k].extend(column) + self.count += batch.count + + def build_and_reset(self) -> SampleBatch: + """Returns a sample batch including all previously added values.""" + + batch = SampleBatch({k: _to_float_array(v) for k, v in self.buffers.items()}) + if SampleBatch.UNROLL_ID not in batch: + batch[SampleBatch.UNROLL_ID] = np.repeat( + SampleBatchBuilder._next_unroll_id, batch.count + ) + SampleBatchBuilder._next_unroll_id += 1 + self.buffers.clear() + self.count = 0 + return batch + + +@OldAPIStack +class MultiAgentSampleBatchBuilder: + """Util to build SampleBatches for each policy in a multi-agent env. + + Input data is per-agent, while output data is per-policy. There is an M:N + mapping between agents and policies. We retain one local batch builder + per agent. When an agent is done, then its local batch is appended into the + corresponding policy batch for the agent's policy. + """ + + def __init__( + self, + policy_map: Dict[PolicyID, Policy], + clip_rewards: bool, + callbacks: "RLlibCallback", + ): + """Initialize a MultiAgentSampleBatchBuilder. + + Args: + policy_map (Dict[str,Policy]): Maps policy ids to policy instances. + clip_rewards (Union[bool,float]): Whether to clip rewards before + postprocessing (at +/-1.0) or the actual value to +/- clip. + callbacks: RLlib callbacks. + """ + if log_once("MultiAgentSampleBatchBuilder"): + deprecation_warning(old="MultiAgentSampleBatchBuilder", error=False) + self.policy_map = policy_map + self.clip_rewards = clip_rewards + # Build the Policies' SampleBatchBuilders. + self.policy_builders = {k: SampleBatchBuilder() for k in policy_map.keys()} + # Whenever we observe a new agent, add a new SampleBatchBuilder for + # this agent. + self.agent_builders = {} + # Internal agent-to-policy map. + self.agent_to_policy = {} + self.callbacks = callbacks + # Number of "inference" steps taken in the environment. + # Regardless of the number of agents involved in each of these steps. + self.count = 0 + + def total(self) -> int: + """Returns the total number of steps taken in the env (all agents). + + Returns: + int: The number of steps taken in total in the environment over all + agents. + """ + + return sum(a.count for a in self.agent_builders.values()) + + def has_pending_agent_data(self) -> bool: + """Returns whether there is pending unprocessed data. + + Returns: + bool: True if there is at least one per-agent builder (with data + in it). + """ + + return len(self.agent_builders) > 0 + + def add_values(self, agent_id: AgentID, policy_id: AgentID, **values: Any) -> None: + """Add the given dictionary (row) of values to this batch. + + Args: + agent_id: Unique id for the agent we are adding values for. + policy_id: Unique id for policy controlling the agent. + values: Row of values to add for this agent. + """ + + if agent_id not in self.agent_builders: + self.agent_builders[agent_id] = SampleBatchBuilder() + self.agent_to_policy[agent_id] = policy_id + + # Include the current agent id for multi-agent algorithms. + if agent_id != _DUMMY_AGENT_ID: + values["agent_id"] = agent_id + + self.agent_builders[agent_id].add_values(**values) + + def postprocess_batch_so_far(self, episode=None) -> None: + """Apply policy postprocessors to any unprocessed rows. + + This pushes the postprocessed per-agent batches onto the per-policy + builders, clearing per-agent state. + + Args: + episode (Optional[Episode]): The Episode object that + holds this MultiAgentBatchBuilder object. + """ + + # Materialize the batches so far. + pre_batches = {} + for agent_id, builder in self.agent_builders.items(): + pre_batches[agent_id] = ( + self.policy_map[self.agent_to_policy[agent_id]], + builder.build_and_reset(), + ) + + # Apply postprocessor. + post_batches = {} + if self.clip_rewards is True: + for _, (_, pre_batch) in pre_batches.items(): + pre_batch["rewards"] = np.sign(pre_batch["rewards"]) + elif self.clip_rewards: + for _, (_, pre_batch) in pre_batches.items(): + pre_batch["rewards"] = np.clip( + pre_batch["rewards"], + a_min=-self.clip_rewards, + a_max=self.clip_rewards, + ) + for agent_id, (_, pre_batch) in pre_batches.items(): + other_batches = pre_batches.copy() + del other_batches[agent_id] + policy = self.policy_map[self.agent_to_policy[agent_id]] + if ( + not pre_batch.is_single_trajectory() + or len(set(pre_batch[SampleBatch.EPS_ID])) > 1 + ): + raise ValueError( + "Batches sent to postprocessing must only contain steps " + "from a single trajectory.", + pre_batch, + ) + # Call the Policy's Exploration's postprocess method. + post_batches[agent_id] = pre_batch + if getattr(policy, "exploration", None) is not None: + policy.exploration.postprocess_trajectory( + policy, post_batches[agent_id], policy.get_session() + ) + post_batches[agent_id] = policy.postprocess_trajectory( + post_batches[agent_id], other_batches, episode + ) + + if log_once("after_post"): + logger.info( + "Trajectory fragment after postprocess_trajectory():\n\n{}\n".format( + summarize(post_batches) + ) + ) + + # Append into policy batches and reset + from ray.rllib.evaluation.rollout_worker import get_global_worker + + for agent_id, post_batch in sorted(post_batches.items()): + self.callbacks.on_postprocess_trajectory( + worker=get_global_worker(), + episode=episode, + agent_id=agent_id, + policy_id=self.agent_to_policy[agent_id], + policies=self.policy_map, + postprocessed_batch=post_batch, + original_batches=pre_batches, + ) + self.policy_builders[self.agent_to_policy[agent_id]].add_batch(post_batch) + + self.agent_builders.clear() + self.agent_to_policy.clear() + + def check_missing_dones(self) -> None: + for agent_id, builder in self.agent_builders.items(): + if not builder.buffers.is_terminated_or_truncated(): + raise ValueError( + "The environment terminated for all agents, but we still " + "don't have a last observation for " + "agent {} (policy {}). ".format( + agent_id, self.agent_to_policy[agent_id] + ) + + "Please ensure that you include the last observations " + "of all live agents when setting '__all__' terminated|truncated " + "to True. " + ) + + def build_and_reset(self, episode=None) -> MultiAgentBatch: + """Returns the accumulated sample batches for each policy. + + Any unprocessed rows will be first postprocessed with a policy + postprocessor. The internal state of this builder will be reset. + + Args: + episode (Optional[Episode]): The Episode object that + holds this MultiAgentBatchBuilder object or None. + + Returns: + MultiAgentBatch: Returns the accumulated sample batches for each + policy. + """ + + self.postprocess_batch_so_far(episode) + policy_batches = {} + for policy_id, builder in self.policy_builders.items(): + if builder.count > 0: + policy_batches[policy_id] = builder.build_and_reset() + old_count = self.count + self.count = 0 + return MultiAgentBatch.wrap_as_needed(policy_batches, old_count) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/sampler.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..c6b4ce937e6babc33d2de1282ed631e373fc68f7 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/sampler.py @@ -0,0 +1,253 @@ +import logging +import queue +from abc import ABCMeta, abstractmethod +from collections import defaultdict, namedtuple +from typing import ( + TYPE_CHECKING, + Any, + List, + Optional, + Type, + Union, +) + +from ray.rllib.env.base_env import BaseEnv, convert_to_base_env +from ray.rllib.evaluation.collectors.sample_collector import SampleCollector +from ray.rllib.evaluation.collectors.simple_list_collector import SimpleListCollector +from ray.rllib.evaluation.env_runner_v2 import EnvRunnerV2, _PerfStats +from ray.rllib.evaluation.metrics import RolloutMetrics +from ray.rllib.offline import InputReader +from ray.rllib.policy.sample_batch import concat_samples +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.deprecation import deprecation_warning, DEPRECATED_VALUE +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.typing import SampleBatchType +from ray.util.debug import log_once + +if TYPE_CHECKING: + from ray.rllib.callbacks.callbacks import RLlibCallback + from ray.rllib.evaluation.observation_function import ObservationFunction + from ray.rllib.evaluation.rollout_worker import RolloutWorker + +tf1, tf, _ = try_import_tf() +logger = logging.getLogger(__name__) + +_PolicyEvalData = namedtuple( + "_PolicyEvalData", + ["env_id", "agent_id", "obs", "info", "rnn_state", "prev_action", "prev_reward"], +) + +# A batch of RNN states with dimensions [state_index, batch, state_object]. +StateBatch = List[List[Any]] + + +class _NewEpisodeDefaultDict(defaultdict): + def __missing__(self, env_id): + if self.default_factory is None: + raise KeyError(env_id) + else: + ret = self[env_id] = self.default_factory(env_id) + return ret + + +@OldAPIStack +class SamplerInput(InputReader, metaclass=ABCMeta): + """Reads input experiences from an existing sampler.""" + + @override(InputReader) + def next(self) -> SampleBatchType: + batches = [self.get_data()] + batches.extend(self.get_extra_batches()) + if len(batches) == 0: + raise RuntimeError("No data available from sampler.") + return concat_samples(batches) + + @abstractmethod + def get_data(self) -> SampleBatchType: + """Called by `self.next()` to return the next batch of data. + + Override this in child classes. + + Returns: + The next batch of data. + """ + raise NotImplementedError + + @abstractmethod + def get_metrics(self) -> List[RolloutMetrics]: + """Returns list of episode metrics since the last call to this method. + + The list will contain one RolloutMetrics object per completed episode. + + Returns: + List of RolloutMetrics objects, one per completed episode since + the last call to this method. + """ + raise NotImplementedError + + @abstractmethod + def get_extra_batches(self) -> List[SampleBatchType]: + """Returns list of extra batches since the last call to this method. + + The list will contain all SampleBatches or + MultiAgentBatches that the user has provided thus-far. Users can + add these "extra batches" to an episode by calling the episode's + `add_extra_batch([SampleBatchType])` method. This can be done from + inside an overridden `Policy.compute_actions_from_input_dict(..., + episodes)` or from a custom callback's `on_episode_[start|step|end]()` + methods. + + Returns: + List of SamplesBatches or MultiAgentBatches provided thus-far by + the user since the last call to this method. + """ + raise NotImplementedError + + +@OldAPIStack +class SyncSampler(SamplerInput): + """Sync SamplerInput that collects experiences when `get_data()` is called.""" + + def __init__( + self, + *, + worker: "RolloutWorker", + env: BaseEnv, + clip_rewards: Union[bool, float], + rollout_fragment_length: int, + count_steps_by: str = "env_steps", + callbacks: "RLlibCallback", + multiple_episodes_in_batch: bool = False, + normalize_actions: bool = True, + clip_actions: bool = False, + observation_fn: Optional["ObservationFunction"] = None, + sample_collector_class: Optional[Type[SampleCollector]] = None, + render: bool = False, + # Obsolete. + policies=None, + policy_mapping_fn=None, + preprocessors=None, + obs_filters=None, + tf_sess=None, + horizon=DEPRECATED_VALUE, + soft_horizon=DEPRECATED_VALUE, + no_done_at_end=DEPRECATED_VALUE, + ): + """Initializes a SyncSampler instance. + + Args: + worker: The RolloutWorker that will use this Sampler for sampling. + env: Any Env object. Will be converted into an RLlib BaseEnv. + clip_rewards: True for +/-1.0 clipping, + actual float value for +/- value clipping. False for no + clipping. + rollout_fragment_length: The length of a fragment to collect + before building a SampleBatch from the data and resetting + the SampleBatchBuilder object. + count_steps_by: One of "env_steps" (default) or "agent_steps". + Use "agent_steps", if you want rollout lengths to be counted + by individual agent steps. In a multi-agent env, + a single env_step contains one or more agent_steps, depending + on how many agents are present at any given time in the + ongoing episode. + callbacks: The RLlibCallback object to use when episode + events happen during rollout. + multiple_episodes_in_batch: Whether to pack multiple + episodes into each batch. This guarantees batches will be + exactly `rollout_fragment_length` in size. + normalize_actions: Whether to normalize actions to the + action space's bounds. + clip_actions: Whether to clip actions according to the + given action_space's bounds. + observation_fn: Optional multi-agent observation func to use for + preprocessing observations. + sample_collector_class: An optional SampleCollector sub-class to + use to collect, store, and retrieve environment-, model-, + and sampler data. + render: Whether to try to render the environment after each step. + """ + # All of the following arguments are deprecated. They will instead be + # provided via the passed in `worker` arg, e.g. `worker.policy_map`. + if log_once("deprecated_sync_sampler_args"): + if policies is not None: + deprecation_warning(old="policies") + if policy_mapping_fn is not None: + deprecation_warning(old="policy_mapping_fn") + if preprocessors is not None: + deprecation_warning(old="preprocessors") + if obs_filters is not None: + deprecation_warning(old="obs_filters") + if tf_sess is not None: + deprecation_warning(old="tf_sess") + if horizon != DEPRECATED_VALUE: + deprecation_warning(old="horizon", error=True) + if soft_horizon != DEPRECATED_VALUE: + deprecation_warning(old="soft_horizon", error=True) + if no_done_at_end != DEPRECATED_VALUE: + deprecation_warning(old="no_done_at_end", error=True) + + self.base_env = convert_to_base_env(env) + self.rollout_fragment_length = rollout_fragment_length + self.extra_batches = queue.Queue() + self.perf_stats = _PerfStats( + ema_coef=worker.config.sampler_perf_stats_ema_coef, + ) + if not sample_collector_class: + sample_collector_class = SimpleListCollector + self.sample_collector = sample_collector_class( + worker.policy_map, + clip_rewards, + callbacks, + multiple_episodes_in_batch, + rollout_fragment_length, + count_steps_by=count_steps_by, + ) + self.render = render + + # Keep a reference to the underlying EnvRunnerV2 instance for + # unit testing purpose. + self._env_runner_obj = EnvRunnerV2( + worker=worker, + base_env=self.base_env, + multiple_episodes_in_batch=multiple_episodes_in_batch, + callbacks=callbacks, + perf_stats=self.perf_stats, + rollout_fragment_length=rollout_fragment_length, + count_steps_by=count_steps_by, + render=self.render, + ) + self._env_runner = self._env_runner_obj.run() + self.metrics_queue = queue.Queue() + + @override(SamplerInput) + def get_data(self) -> SampleBatchType: + while True: + item = next(self._env_runner) + if isinstance(item, RolloutMetrics): + self.metrics_queue.put(item) + else: + return item + + @override(SamplerInput) + def get_metrics(self) -> List[RolloutMetrics]: + completed = [] + while True: + try: + completed.append( + self.metrics_queue.get_nowait()._replace( + perf_stats=self.perf_stats.get() + ) + ) + except queue.Empty: + break + return completed + + @override(SamplerInput) + def get_extra_batches(self) -> List[SampleBatchType]: + extra = [] + while True: + try: + extra.append(self.extra_batches.get_nowait()) + except queue.Empty: + break + return extra diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/worker_set.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/worker_set.py new file mode 100644 index 0000000000000000000000000000000000000000..0eeea1ea2c8f00cd0cc3075af18cb0f1b7228126 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/evaluation/worker_set.py @@ -0,0 +1,10 @@ +from ray.rllib.utils.deprecation import Deprecated + + +@Deprecated( + new="ray.rllib.env.env_runner_group.EnvRunnerGroup", + help="The class has only be renamed w/o any changes in functionality.", + error=True, +) +class WorkerSet: + pass diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/centralized_critic.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/centralized_critic.py new file mode 100644 index 0000000000000000000000000000000000000000..39d70d19d208834c925ae7be72d2c2995b0b63d7 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/centralized_critic.py @@ -0,0 +1,319 @@ +# @OldAPIStack + +# *********************************************************************************** +# IMPORTANT NOTE: This script uses the old API stack and will soon be replaced by +# `ray.rllib.examples.multi_agent.pettingzoo_shared_value_function.py`! +# *********************************************************************************** + +"""An example of customizing PPO to leverage a centralized critic. + +Here the model and policy are hard-coded to implement a centralized critic +for TwoStepGame, but you can adapt this for your own use cases. + +Compared to simply running `rllib/examples/two_step_game.py --run=PPO`, +this centralized critic version reaches vf_explained_variance=1.0 more stably +since it takes into account the opponent actions as well as the policy's. +Note that this is also using two independent policies instead of weight-sharing +with one. + +See also: centralized_critic_2.py for a simpler approach that instead +modifies the environment. +""" + +import argparse +from gymnasium.spaces import Discrete +import numpy as np +import os + +import ray +from ray import tune +from ray.tune.result import TRAINING_ITERATION +from ray.rllib.algorithms.ppo.ppo import PPO, PPOConfig +from ray.rllib.algorithms.ppo.ppo_tf_policy import ( + PPOTF1Policy, + PPOTF2Policy, +) +from ray.rllib.algorithms.ppo.ppo_torch_policy import PPOTorchPolicy +from ray.rllib.evaluation.postprocessing import compute_advantages, Postprocessing +from ray.rllib.examples.envs.classes.multi_agent.two_step_game import TwoStepGame +from ray.rllib.examples._old_api_stack.models.centralized_critic_models import ( + CentralizedCriticModel, + TorchCentralizedCriticModel, +) +from ray.rllib.models import ModelCatalog +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_tf, try_import_torch +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + NUM_ENV_STEPS_SAMPLED_LIFETIME, +) +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.test_utils import check_learning_achieved +from ray.rllib.utils.tf_utils import explained_variance, make_tf_callable +from ray.rllib.utils.torch_utils import convert_to_torch_tensor + +tf1, tf, tfv = try_import_tf() +torch, nn = try_import_torch() + +OPPONENT_OBS = "opponent_obs" +OPPONENT_ACTION = "opponent_action" + +parser = argparse.ArgumentParser() +parser.add_argument( + "--framework", + choices=["tf", "tf2", "torch"], + default="torch", + help="The DL framework specifier.", +) +parser.add_argument( + "--as-test", + action="store_true", + help="Whether this script should be run as a test: --stop-reward must " + "be achieved within --stop-timesteps AND --stop-iters.", +) +parser.add_argument( + "--stop-iters", type=int, default=100, help="Number of iterations to train." +) +parser.add_argument( + "--stop-timesteps", type=int, default=100000, help="Number of timesteps to train." +) +parser.add_argument( + "--stop-reward", type=float, default=7.99, help="Reward at which we stop training." +) + + +class CentralizedValueMixin: + """Add method to evaluate the central value function from the model.""" + + def __init__(self): + if self.config["framework"] != "torch": + self.compute_central_vf = make_tf_callable(self.get_session())( + self.model.central_value_function + ) + else: + self.compute_central_vf = self.model.central_value_function + + +# Grabs the opponent obs/act and includes it in the experience train_batch, +# and computes GAE using the central vf predictions. +def centralized_critic_postprocessing( + policy, sample_batch, other_agent_batches=None, episode=None +): + pytorch = policy.config["framework"] == "torch" + if (pytorch and hasattr(policy, "compute_central_vf")) or ( + not pytorch and policy.loss_initialized() + ): + assert other_agent_batches is not None + [(_, _, opponent_batch)] = list(other_agent_batches.values()) + + # also record the opponent obs and actions in the trajectory + sample_batch[OPPONENT_OBS] = opponent_batch[SampleBatch.CUR_OBS] + sample_batch[OPPONENT_ACTION] = opponent_batch[SampleBatch.ACTIONS] + + # overwrite default VF prediction with the central VF + if args.framework == "torch": + sample_batch[SampleBatch.VF_PREDS] = ( + policy.compute_central_vf( + convert_to_torch_tensor( + sample_batch[SampleBatch.CUR_OBS], policy.device + ), + convert_to_torch_tensor(sample_batch[OPPONENT_OBS], policy.device), + convert_to_torch_tensor( + sample_batch[OPPONENT_ACTION], policy.device + ), + ) + .cpu() + .detach() + .numpy() + ) + else: + sample_batch[SampleBatch.VF_PREDS] = convert_to_numpy( + policy.compute_central_vf( + sample_batch[SampleBatch.CUR_OBS], + sample_batch[OPPONENT_OBS], + sample_batch[OPPONENT_ACTION], + ) + ) + else: + # Policy hasn't been initialized yet, use zeros. + sample_batch[OPPONENT_OBS] = np.zeros_like(sample_batch[SampleBatch.CUR_OBS]) + sample_batch[OPPONENT_ACTION] = np.zeros_like(sample_batch[SampleBatch.ACTIONS]) + sample_batch[SampleBatch.VF_PREDS] = np.zeros_like( + sample_batch[SampleBatch.REWARDS], dtype=np.float32 + ) + + completed = sample_batch[SampleBatch.TERMINATEDS][-1] + if completed: + last_r = 0.0 + else: + last_r = sample_batch[SampleBatch.VF_PREDS][-1] + + train_batch = compute_advantages( + sample_batch, + last_r, + policy.config["gamma"], + policy.config["lambda"], + use_gae=policy.config["use_gae"], + ) + return train_batch + + +# Copied from PPO but optimizing the central value function. +def loss_with_central_critic(policy, base_policy, model, dist_class, train_batch): + # Save original value function. + vf_saved = model.value_function + + # Calculate loss with a custom value function. + model.value_function = lambda: policy.model.central_value_function( + train_batch[SampleBatch.CUR_OBS], + train_batch[OPPONENT_OBS], + train_batch[OPPONENT_ACTION], + ) + policy._central_value_out = model.value_function() + loss = base_policy.loss(model, dist_class, train_batch) + + # Restore original value function. + model.value_function = vf_saved + + return loss + + +def central_vf_stats(policy, train_batch): + # Report the explained variance of the central value function. + return { + "vf_explained_var": explained_variance( + train_batch[Postprocessing.VALUE_TARGETS], policy._central_value_out + ) + } + + +def get_ccppo_policy(base): + class CCPPOTFPolicy(CentralizedValueMixin, base): + def __init__(self, observation_space, action_space, config): + base.__init__(self, observation_space, action_space, config) + CentralizedValueMixin.__init__(self) + + @override(base) + def loss(self, model, dist_class, train_batch): + # Use super() to get to the base PPO policy. + # This special loss function utilizes a shared + # value function defined on self, and the loss function + # defined on PPO policies. + return loss_with_central_critic( + self, super(), model, dist_class, train_batch + ) + + @override(base) + def postprocess_trajectory( + self, sample_batch, other_agent_batches=None, episode=None + ): + return centralized_critic_postprocessing( + self, sample_batch, other_agent_batches, episode + ) + + @override(base) + def stats_fn(self, train_batch: SampleBatch): + stats = super().stats_fn(train_batch) + stats.update(central_vf_stats(self, train_batch)) + return stats + + return CCPPOTFPolicy + + +CCPPOStaticGraphTFPolicy = get_ccppo_policy(PPOTF1Policy) +CCPPOEagerTFPolicy = get_ccppo_policy(PPOTF2Policy) + + +class CCPPOTorchPolicy(CentralizedValueMixin, PPOTorchPolicy): + def __init__(self, observation_space, action_space, config): + PPOTorchPolicy.__init__(self, observation_space, action_space, config) + CentralizedValueMixin.__init__(self) + + @override(PPOTorchPolicy) + def loss(self, model, dist_class, train_batch): + return loss_with_central_critic(self, super(), model, dist_class, train_batch) + + @override(PPOTorchPolicy) + def postprocess_trajectory( + self, sample_batch, other_agent_batches=None, episode=None + ): + return centralized_critic_postprocessing( + self, sample_batch, other_agent_batches, episode + ) + + +class CentralizedCritic(PPO): + @classmethod + @override(PPO) + def get_default_policy_class(cls, config): + if config["framework"] == "torch": + return CCPPOTorchPolicy + elif config["framework"] == "tf": + return CCPPOStaticGraphTFPolicy + else: + return CCPPOEagerTFPolicy + + +if __name__ == "__main__": + ray.init(local_mode=True) + args = parser.parse_args() + + ModelCatalog.register_custom_model( + "cc_model", + TorchCentralizedCriticModel + if args.framework == "torch" + else CentralizedCriticModel, + ) + + config = ( + PPOConfig() + .api_stack( + enable_env_runner_and_connector_v2=False, + enable_rl_module_and_learner=False, + ) + .environment(TwoStepGame) + .framework(args.framework) + .env_runners(batch_mode="complete_episodes", num_env_runners=0) + .training(model={"custom_model": "cc_model"}) + .multi_agent( + policies={ + "pol1": ( + None, + Discrete(6), + TwoStepGame.action_space, + # `framework` would also be ok here. + PPOConfig.overrides(framework_str=args.framework), + ), + "pol2": ( + None, + Discrete(6), + TwoStepGame.action_space, + # `framework` would also be ok here. + PPOConfig.overrides(framework_str=args.framework), + ), + }, + policy_mapping_fn=lambda agent_id, episode, worker, **kwargs: "pol1" + if agent_id == 0 + else "pol2", + ) + # Use GPUs iff `RLLIB_NUM_GPUS` env var set to > 0. + .resources(num_gpus=int(os.environ.get("RLLIB_NUM_GPUS", "0"))) + ) + + stop = { + TRAINING_ITERATION: args.stop_iters, + NUM_ENV_STEPS_SAMPLED_LIFETIME: args.stop_timesteps, + f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": args.stop_reward, + } + + tuner = tune.Tuner( + CentralizedCritic, + param_space=config.to_dict(), + run_config=tune.RunConfig(stop=stop, verbose=1), + ) + results = tuner.fit() + + if args.as_test: + check_learning_achieved(results, args.stop_reward) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/compute_adapted_gae_on_postprocess_trajectory.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/compute_adapted_gae_on_postprocess_trajectory.py new file mode 100644 index 0000000000000000000000000000000000000000..44745c8722b84553f14e487c4aa7d3047632ff1b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/compute_adapted_gae_on_postprocess_trajectory.py @@ -0,0 +1,157 @@ +# @OldAPIStack + +""" +Adapted (time-dependent) GAE for PPO algorithm that you can activate by setting +use_adapted_gae=True in the policy config. Additionally, it's required that +"callbacks" include the custom callback class in the Algorithm's config. +Furthermore, the env must return in its info dictionary a key-value pair of +the form "d_ts": ... where the value is the length (time) of recent agent step. + +This adapted, time-dependent computation of advantages may be useful in cases +where agent's actions take various times and thus time steps are not +equidistant (https://docdro.id/400TvlR) +""" + +from ray.rllib.callbacks.callbacks import RLlibCallback +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.evaluation.postprocessing import Postprocessing +from ray.rllib.utils.annotations import override +import numpy as np + + +class MyCallbacks(RLlibCallback): + @override(RLlibCallback) + def on_postprocess_trajectory( + self, + *, + worker, + episode, + agent_id, + policy_id, + policies, + postprocessed_batch, + original_batches, + **kwargs + ): + super().on_postprocess_trajectory( + worker=worker, + episode=episode, + agent_id=agent_id, + policy_id=policy_id, + policies=policies, + postprocessed_batch=postprocessed_batch, + original_batches=original_batches, + **kwargs + ) + + if policies[policy_id].config.get("use_adapted_gae", False): + policy = policies[policy_id] + assert policy.config[ + "use_gae" + ], "Can't use adapted gae without use_gae=True!" + + info_dicts = postprocessed_batch[SampleBatch.INFOS] + assert np.all( + ["d_ts" in info_dict for info_dict in info_dicts] + ), "Info dicts in sample batch must contain data 'd_ts' \ + (=ts[i+1]-ts[i] length of time steps)!" + + d_ts = np.array( + [np.float(info_dict.get("d_ts")) for info_dict in info_dicts] + ) + assert np.all( + [e.is_integer() for e in d_ts] + ), "Elements of 'd_ts' (length of time steps) must be integer!" + + # Trajectory is actually complete -> last r=0.0. + if postprocessed_batch[SampleBatch.TERMINATEDS][-1]: + last_r = 0.0 + # Trajectory has been truncated -> last r=VF estimate of last obs. + else: + # Input dict is provided to us automatically via the Model's + # requirements. It's a single-timestep (last one in trajectory) + # input_dict. + # Create an input dict according to the Model's requirements. + input_dict = postprocessed_batch.get_single_step_input_dict( + policy.model.view_requirements, index="last" + ) + last_r = policy._value(**input_dict) + + gamma = policy.config["gamma"] + lambda_ = policy.config["lambda"] + + vpred_t = np.concatenate( + [postprocessed_batch[SampleBatch.VF_PREDS], np.array([last_r])] + ) + delta_t = ( + postprocessed_batch[SampleBatch.REWARDS] + + gamma**d_ts * vpred_t[1:] + - vpred_t[:-1] + ) + # This formula for the advantage is an adaption of + # "Generalized Advantage Estimation" + # (https://arxiv.org/abs/1506.02438) which accounts for time steps + # of irregular length (see proposal here ). + # NOTE: last time step delta is not required + postprocessed_batch[ + Postprocessing.ADVANTAGES + ] = generalized_discount_cumsum(delta_t, d_ts[:-1], gamma * lambda_) + postprocessed_batch[Postprocessing.VALUE_TARGETS] = ( + postprocessed_batch[Postprocessing.ADVANTAGES] + + postprocessed_batch[SampleBatch.VF_PREDS] + ).astype(np.float32) + + postprocessed_batch[Postprocessing.ADVANTAGES] = postprocessed_batch[ + Postprocessing.ADVANTAGES + ].astype(np.float32) + + +def generalized_discount_cumsum( + x: np.ndarray, deltas: np.ndarray, gamma: float +) -> np.ndarray: + """Calculates the 'time-dependent' discounted cumulative sum over a + (reward) sequence `x`. + + Recursive equations: + + y[t] - gamma**deltas[t+1]*y[t+1] = x[t] + + reversed(y)[t] - gamma**reversed(deltas)[t-1]*reversed(y)[t-1] = + reversed(x)[t] + + Args: + x (np.ndarray): A sequence of rewards or one-step TD residuals. + deltas (np.ndarray): A sequence of time step deltas (length of time + steps). + gamma: The discount factor gamma. + + Returns: + np.ndarray: The sequence containing the 'time-dependent' discounted + cumulative sums for each individual element in `x` till the end of + the trajectory. + + .. testcode:: + :skipif: True + + x = np.array([0.0, 1.0, 2.0, 3.0]) + deltas = np.array([1.0, 4.0, 15.0]) + gamma = 0.9 + generalized_discount_cumsum(x, deltas, gamma) + + .. testoutput:: + + array([0.0 + 0.9^1.0*1.0 + 0.9^4.0*2.0 + 0.9^15.0*3.0, + 1.0 + 0.9^4.0*2.0 + 0.9^15.0*3.0, + 2.0 + 0.9^15.0*3.0, + 3.0]) + """ + reversed_x = x[::-1] + reversed_deltas = deltas[::-1] + reversed_y = np.empty_like(x) + reversed_y[0] = reversed_x[0] + for i in range(1, x.size): + reversed_y[i] = ( + reversed_x[i] + gamma ** reversed_deltas[i - 1] * reversed_y[i - 1] + ) + + return reversed_y[::-1] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/quadx_waypoints.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/quadx_waypoints.py new file mode 100644 index 0000000000000000000000000000000000000000..9e846a84e4b7f39480903e0179d2806bae34ba12 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/quadx_waypoints.py @@ -0,0 +1,131 @@ +"""An example showing how to use PyFlyt gymnasium environment to train a UAV to +reach waypoints. + +For more infos about the PyFlyt gymnasium environment see the GitHub Repository: +https://github.com/jjshoots/PyFlyt/tree/master/PyFlyt + +This example + - Runs a single-agent `PyFlyt/QuadX-Waypoints-v1` experiment. + - Uses a gymnasium reward wrapper for reward scaling. + - Stops the experiment, if either `--stop-iters` (default is 200) or + `--stop-reward` (default is 90.0) is reached. + + +How to run this script +---------------------- +`python [script file name].py` + +Control the number of environments per `EnvRunner` via `--num-envs-per-env-runner`. +This will increase sampling speed. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` which should allow you to set breakpoints +anywhere in the RLlib code and have the execution stop there for inspection +and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` +""" +import gymnasium as gym +import sys + +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + TRAINING_ITERATION_TIMER, +) +from ray.tune.registry import get_trainable_cls, register_env + +sys.setrecursionlimit(3000) + +parser = add_rllib_example_script_args( + default_iters=200, + default_timesteps=100000, + default_reward=90.0, +) +parser.add_argument( + "--run", type=str, default="PPO", help="The RLlib-registered algorithm to use." +) +parser.add_argument("--env-name", type=str, default="quadx_waypoints") +parser.add_argument("--num-envs-per-env-runner", type=int, default=4) + + +class RewardWrapper(gym.RewardWrapper): + def __init__(self, env): + super().__init__(env) + + def reward(self, reward): + # Scale rewards: + if reward >= 99.0 or reward <= -99.0: + return reward / 10 + return reward + + +def create_quadx_waypoints_env(env_config): + import PyFlyt.gym_envs # noqa + from PyFlyt.gym_envs import FlattenWaypointEnv + + env = gym.make("PyFlyt/QuadX-Waypoints-v1") + # Wrap Environment to use max 10 and -10 for rewards + env = RewardWrapper(env) + + return FlattenWaypointEnv(env, context_length=1) + + +if __name__ == "__main__": + args = parser.parse_args() + + # Register the environment with tune. + register_env(args.env_name, env_creator=create_quadx_waypoints_env) + + # Get the algorithm class to use for training. + algo_cls = get_trainable_cls(args.run) + config = ( + algo_cls.get_default_config() + .environment(env=args.env_name) + .env_runners( + num_envs_per_env_runner=args.num_envs_per_env_runner, + ) + .reporting(min_time_s_per_iteration=0.1) + ) + + # If PPO set additional configurations. + if args.run == "PPO": + config.rl_module( + model_config={ + "fcnet_hiddens": [32], + "fcnet_activation": "linear", + "vf_share_layers": True, + } + ) + config.training( + minibatch_size=128, + train_batch_size_per_learner=10000, + ) + # If IMPALA set additional arguments. + elif args.run == "IMPALA": + config.env_runners(num_env_runners=2) + config.learners(num_gpus_per_learner=0) + config.training(vf_loss_coeff=0.01) + + # Set the stopping arguments. + EPISODE_RETURN_MEAN_KEY = f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}" + stop = { + TRAINING_ITERATION_TIMER: args.stop_iters, + EPISODE_RETURN_MEAN_KEY: args.stop_reward, + } + + # Run the experiment. + run_rllib_example_script_experiment( + config, + args, + stop=stop, + success_metric={ + f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": args.stop_reward, + }, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/replay_buffer_api.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/replay_buffer_api.py new file mode 100644 index 0000000000000000000000000000000000000000..0bdc6403d2290a98ff2ac8af9be876bfbaa76610 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/examples/replay_buffer_api.py @@ -0,0 +1,82 @@ +# @OldAPIStack + +# __sphinx_doc_replay_buffer_api_example_script_begin__ +"""Simple example of how to modify replay buffer behaviour. + +We modify DQN to utilize prioritized replay but supplying it with the +PrioritizedMultiAgentReplayBuffer instead of the standard MultiAgentReplayBuffer. +This is possible because DQN uses the DQN training iteration function, +which includes and a priority update, given that a fitting buffer is provided. +""" + +import argparse + +import ray +from ray import tune +from ray.tune.result import TRAINING_ITERATION +from ray.rllib.algorithms.dqn import DQNConfig +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.metrics import NUM_ENV_STEPS_SAMPLED_LIFETIME +from ray.rllib.utils.replay_buffers.replay_buffer import StorageUnit + +tf1, tf, tfv = try_import_tf() + +parser = argparse.ArgumentParser() + +parser.add_argument("--num-cpus", type=int, default=0) +parser.add_argument( + "--framework", + choices=["tf", "tf2", "torch"], + default="torch", + help="The DL framework specifier.", +) +parser.add_argument( + "--stop-iters", type=int, default=50, help="Number of iterations to train." +) +parser.add_argument( + "--stop-timesteps", type=int, default=100000, help="Number of timesteps to train." +) + +if __name__ == "__main__": + args = parser.parse_args() + + ray.init(num_cpus=args.num_cpus or None) + + # This is where we add prioritized experiences replay + # The training iteration function that is used by DQN already includes a priority + # update step. + replay_buffer_config = { + "type": "MultiAgentPrioritizedReplayBuffer", + # Although not necessary, we can modify the default constructor args of + # the replay buffer here + "prioritized_replay_alpha": 0.5, + "storage_unit": StorageUnit.SEQUENCES, + "replay_burn_in": 20, + "zero_init_states": True, + } + + config = ( + DQNConfig() + .environment("CartPole-v1") + .framework(framework=args.framework) + .env_runners(num_env_runners=4) + .training( + model=dict(use_lstm=True, lstm_cell_size=64, max_seq_len=20), + replay_buffer_config=replay_buffer_config, + ) + ) + + stop_config = { + NUM_ENV_STEPS_SAMPLED_LIFETIME: args.stop_timesteps, + TRAINING_ITERATION: args.stop_iters, + } + + results = tune.Tuner( + config.algo_class, + param_space=config, + run_config=tune.RunConfig(stop=stop_config), + ).fit() + + ray.shutdown() + +# __sphinx_doc_replay_buffer_api_example_script_end__ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d6a2b3345f868a12fb219485ce11e62a511abecc --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/__init__.py @@ -0,0 +1,23 @@ +from ray.rllib.execution.learner_thread import LearnerThread +from ray.rllib.execution.multi_gpu_learner_thread import MultiGPULearnerThread +from ray.rllib.execution.minibatch_buffer import MinibatchBuffer +from ray.rllib.execution.replay_ops import SimpleReplayBuffer +from ray.rllib.execution.rollout_ops import ( + standardize_fields, + synchronous_parallel_sample, +) +from ray.rllib.execution.train_ops import ( + train_one_step, + multi_gpu_train_one_step, +) + +__all__ = [ + "multi_gpu_train_one_step", + "standardize_fields", + "synchronous_parallel_sample", + "train_one_step", + "LearnerThread", + "MultiGPULearnerThread", + "SimpleReplayBuffer", + "MinibatchBuffer", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/learner_thread.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/learner_thread.py new file mode 100644 index 0000000000000000000000000000000000000000..49340a972c350acc6584d8274c87aab937198886 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/learner_thread.py @@ -0,0 +1,137 @@ +import copy +import queue +import threading +from typing import Dict, Optional + +from ray.util.timer import _Timer +from ray.rllib.evaluation.rollout_worker import RolloutWorker +from ray.rllib.execution.minibatch_buffer import MinibatchBuffer +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.metrics.learner_info import LearnerInfoBuilder, LEARNER_INFO +from ray.rllib.utils.metrics.window_stat import WindowStat +from ray.util.iter import _NextValueNotReady + +tf1, tf, tfv = try_import_tf() + + +@OldAPIStack +class LearnerThread(threading.Thread): + """Background thread that updates the local model from sample trajectories. + + The learner thread communicates with the main thread through Queues. This + is needed since Ray operations can only be run on the main thread. In + addition, moving heavyweight gradient ops session runs off the main thread + improves overall throughput. + """ + + def __init__( + self, + local_worker: RolloutWorker, + minibatch_buffer_size: int, + num_sgd_iter: int, + learner_queue_size: int, + learner_queue_timeout: int, + ): + """Initialize the learner thread. + + Args: + local_worker: process local rollout worker holding + policies this thread will call learn_on_batch() on + minibatch_buffer_size: max number of train batches to store + in the minibatching buffer + num_sgd_iter: number of passes to learn on per train batch + learner_queue_size: max size of queue of inbound + train batches to this thread + learner_queue_timeout: raise an exception if the queue has + been empty for this long in seconds + """ + threading.Thread.__init__(self) + self.learner_queue_size = WindowStat("size", 50) + self.local_worker = local_worker + self.inqueue = queue.Queue(maxsize=learner_queue_size) + self.outqueue = queue.Queue() + self.minibatch_buffer = MinibatchBuffer( + inqueue=self.inqueue, + size=minibatch_buffer_size, + timeout=learner_queue_timeout, + num_passes=num_sgd_iter, + init_num_passes=num_sgd_iter, + ) + self.queue_timer = _Timer() + self.grad_timer = _Timer() + self.load_timer = _Timer() + self.load_wait_timer = _Timer() + self.daemon = True + self.policy_ids_updated = [] + self.learner_info = {} + self.stopped = False + self.num_steps = 0 + + def run(self) -> None: + # Switch on eager mode if configured. + if self.local_worker.config.framework_str == "tf2": + tf1.enable_eager_execution() + while not self.stopped: + self.step() + + def step(self) -> Optional[_NextValueNotReady]: + with self.queue_timer: + try: + batch, _ = self.minibatch_buffer.get() + except queue.Empty: + return _NextValueNotReady() + with self.grad_timer: + # Use LearnerInfoBuilder as a unified way to build the final + # results dict from `learn_on_loaded_batch` call(s). + # This makes sure results dicts always have the same structure + # no matter the setup (multi-GPU, multi-agent, minibatch SGD, + # tf vs torch). + learner_info_builder = LearnerInfoBuilder(num_devices=1) + if self.local_worker.config.policy_states_are_swappable: + self.local_worker.lock() + multi_agent_results = self.local_worker.learn_on_batch(batch) + if self.local_worker.config.policy_states_are_swappable: + self.local_worker.unlock() + self.policy_ids_updated.extend(list(multi_agent_results.keys())) + for pid, results in multi_agent_results.items(): + learner_info_builder.add_learn_on_batch_results(results, pid) + self.learner_info = learner_info_builder.finalize() + + self.num_steps += 1 + # Put tuple: env-steps, agent-steps, and learner info into the queue. + self.outqueue.put((batch.count, batch.agent_steps(), self.learner_info)) + self.learner_queue_size.push(self.inqueue.qsize()) + + def add_learner_metrics(self, result: Dict, overwrite_learner_info=True) -> Dict: + """Add internal metrics to a result dict.""" + + def timer_to_ms(timer): + return round(1000 * timer.mean, 3) + + if overwrite_learner_info: + result["info"].update( + { + "learner_queue": self.learner_queue_size.stats(), + LEARNER_INFO: copy.deepcopy(self.learner_info), + "timing_breakdown": { + "learner_grad_time_ms": timer_to_ms(self.grad_timer), + "learner_load_time_ms": timer_to_ms(self.load_timer), + "learner_load_wait_time_ms": timer_to_ms(self.load_wait_timer), + "learner_dequeue_time_ms": timer_to_ms(self.queue_timer), + }, + } + ) + else: + result["info"].update( + { + "learner_queue": self.learner_queue_size.stats(), + "timing_breakdown": { + "learner_grad_time_ms": timer_to_ms(self.grad_timer), + "learner_load_time_ms": timer_to_ms(self.load_timer), + "learner_load_wait_time_ms": timer_to_ms(self.load_wait_timer), + "learner_dequeue_time_ms": timer_to_ms(self.queue_timer), + }, + } + ) + return result diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/minibatch_buffer.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/minibatch_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..4fdf09fd978a1ece439d1056f697733552857dad --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/minibatch_buffer.py @@ -0,0 +1,61 @@ +from typing import Any, Tuple +import queue + +from ray.rllib.utils.annotations import OldAPIStack + + +@OldAPIStack +class MinibatchBuffer: + """Ring buffer of recent data batches for minibatch SGD. + + This is for use with AsyncSamplesOptimizer. + """ + + def __init__( + self, + inqueue: queue.Queue, + size: int, + timeout: float, + num_passes: int, + init_num_passes: int = 1, + ): + """Initialize a minibatch buffer. + + Args: + inqueue (queue.Queue): Queue to populate the internal ring buffer + from. + size: Max number of data items to buffer. + timeout: Queue timeout + num_passes: Max num times each data item should be emitted. + init_num_passes: Initial passes for each data item. + Maxiumum number of passes per item are increased to num_passes over + time. + """ + self.inqueue = inqueue + self.size = size + self.timeout = timeout + self.max_initial_ttl = num_passes + self.cur_initial_ttl = init_num_passes + self.buffers = [None] * size + self.ttl = [0] * size + self.idx = 0 + + def get(self) -> Tuple[Any, bool]: + """Get a new batch from the internal ring buffer. + + Returns: + buf: Data item saved from inqueue. + released: True if the item is now removed from the ring buffer. + """ + if self.ttl[self.idx] <= 0: + self.buffers[self.idx] = self.inqueue.get(timeout=self.timeout) + self.ttl[self.idx] = self.cur_initial_ttl + if self.cur_initial_ttl < self.max_initial_ttl: + self.cur_initial_ttl += 1 + buf = self.buffers[self.idx] + self.ttl[self.idx] -= 1 + released = self.ttl[self.idx] <= 0 + if released: + self.buffers[self.idx] = None + self.idx = (self.idx + 1) % len(self.buffers) + return buf, released diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/multi_gpu_learner_thread.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/multi_gpu_learner_thread.py new file mode 100644 index 0000000000000000000000000000000000000000..aacf797b32b8b65da6e49f74492b5684e56bb1b7 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/multi_gpu_learner_thread.py @@ -0,0 +1,245 @@ +import logging +import queue +import threading + +from ray.util.timer import _Timer +from ray.rllib.execution.learner_thread import LearnerThread +from ray.rllib.execution.minibatch_buffer import MinibatchBuffer +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.deprecation import deprecation_warning +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.metrics.learner_info import LearnerInfoBuilder +from ray.rllib.evaluation.rollout_worker import RolloutWorker + +tf1, tf, tfv = try_import_tf() + +logger = logging.getLogger(__name__) + + +@OldAPIStack +class MultiGPULearnerThread(LearnerThread): + """Learner that can use multiple GPUs and parallel loading. + + This class is used for async sampling algorithms. + + Example workflow: 2 GPUs and 3 multi-GPU tower stacks. + -> On each GPU, there are 3 slots for batches, indexed 0, 1, and 2. + + Workers collect data from env and push it into inqueue: + Workers -> (data) -> self.inqueue + + We also have two queues, indicating, which stacks are loaded and which + are not. + - idle_tower_stacks = [0, 1, 2] <- all 3 stacks are free at first. + - ready_tower_stacks = [] <- None of the 3 stacks is loaded with data. + + `ready_tower_stacks` is managed by `ready_tower_stacks_buffer` for + possible minibatch-SGD iterations per loaded batch (this avoids a reload + from CPU to GPU for each SGD iter). + + n _MultiGPULoaderThreads: self.inqueue -get()-> + policy.load_batch_into_buffer() -> ready_stacks = [0 ...] + + This thread: self.ready_tower_stacks_buffer -get()-> + policy.learn_on_loaded_batch() -> if SGD-iters done, + put stack index back in idle_tower_stacks queue. + """ + + def __init__( + self, + local_worker: RolloutWorker, + num_gpus: int = 1, + lr=None, # deprecated. + train_batch_size: int = 500, + num_multi_gpu_tower_stacks: int = 1, + num_sgd_iter: int = 1, + learner_queue_size: int = 16, + learner_queue_timeout: int = 300, + num_data_load_threads: int = 16, + _fake_gpus: bool = False, + # Deprecated arg, use + minibatch_buffer_size=None, + ): + """Initializes a MultiGPULearnerThread instance. + + Args: + local_worker: Local RolloutWorker holding + policies this thread will call `load_batch_into_buffer` and + `learn_on_loaded_batch` on. + num_gpus: Number of GPUs to use for data-parallel SGD. + train_batch_size: Size of batches (minibatches if + `num_sgd_iter` > 1) to learn on. + num_multi_gpu_tower_stacks: Number of buffers to parallelly + load data into on one device. Each buffer is of size of + `train_batch_size` and hence increases GPU memory usage + accordingly. + num_sgd_iter: Number of passes to learn on per train batch + (minibatch if `num_sgd_iter` > 1). + learner_queue_size: Max size of queue of inbound + train batches to this thread. + num_data_load_threads: Number of threads to use to load + data into GPU memory in parallel. + """ + # Deprecated: No need to specify as we don't need the actual + # minibatch-buffer anyways. + if minibatch_buffer_size: + deprecation_warning( + old="MultiGPULearnerThread.minibatch_buffer_size", + error=True, + ) + super().__init__( + local_worker=local_worker, + minibatch_buffer_size=0, + num_sgd_iter=num_sgd_iter, + learner_queue_size=learner_queue_size, + learner_queue_timeout=learner_queue_timeout, + ) + # Delete reference to parent's minibatch_buffer, which is not needed. + # Instead, in multi-GPU mode, we pull tower stack indices from the + # `self.ready_tower_stacks_buffer` buffer, whose size is exactly + # `num_multi_gpu_tower_stacks`. + self.minibatch_buffer = None + + self.train_batch_size = train_batch_size + + self.policy_map = self.local_worker.policy_map + self.devices = next(iter(self.policy_map.values())).devices + + logger.info("MultiGPULearnerThread devices {}".format(self.devices)) + assert self.train_batch_size % len(self.devices) == 0 + assert self.train_batch_size >= len(self.devices), "batch too small" + + self.tower_stack_indices = list(range(num_multi_gpu_tower_stacks)) + + # Two queues for tower stacks: + # a) Those that are loaded with data ("ready") + # b) Those that are ready to be loaded with new data ("idle"). + self.idle_tower_stacks = queue.Queue() + self.ready_tower_stacks = queue.Queue() + # In the beginning, all stacks are idle (no loading has taken place + # yet). + for idx in self.tower_stack_indices: + self.idle_tower_stacks.put(idx) + # Start n threads that are responsible for loading data into the + # different (idle) stacks. + for i in range(num_data_load_threads): + self.loader_thread = _MultiGPULoaderThread(self, share_stats=(i == 0)) + self.loader_thread.start() + + # Create a buffer that holds stack indices that are "ready" + # (loaded with data). Those are stacks that we can call + # "learn_on_loaded_batch" on. + self.ready_tower_stacks_buffer = MinibatchBuffer( + self.ready_tower_stacks, + num_multi_gpu_tower_stacks, + learner_queue_timeout, + num_sgd_iter, + ) + + @override(LearnerThread) + def step(self) -> None: + if not self.loader_thread.is_alive(): + raise RuntimeError( + "The `_MultiGPULoaderThread` has died! Will therefore also terminate " + "the `MultiGPULearnerThread`." + ) + + with self.load_wait_timer: + buffer_idx, released = self.ready_tower_stacks_buffer.get() + + get_num_samples_loaded_into_buffer = 0 + with self.grad_timer: + # Use LearnerInfoBuilder as a unified way to build the final + # results dict from `learn_on_loaded_batch` call(s). + # This makes sure results dicts always have the same structure + # no matter the setup (multi-GPU, multi-agent, minibatch SGD, + # tf vs torch). + learner_info_builder = LearnerInfoBuilder(num_devices=len(self.devices)) + + for pid in self.policy_map.keys(): + # Not a policy-to-train. + if ( + self.local_worker.is_policy_to_train is not None + and not self.local_worker.is_policy_to_train(pid) + ): + continue + policy = self.policy_map[pid] + default_policy_results = policy.learn_on_loaded_batch( + offset=0, buffer_index=buffer_idx + ) + learner_info_builder.add_learn_on_batch_results( + default_policy_results, policy_id=pid + ) + self.policy_ids_updated.append(pid) + get_num_samples_loaded_into_buffer += ( + policy.get_num_samples_loaded_into_buffer(buffer_idx) + ) + + self.learner_info = learner_info_builder.finalize() + + if released: + self.idle_tower_stacks.put(buffer_idx) + + # Put tuple: env-steps, agent-steps, and learner info into the queue. + self.outqueue.put( + ( + get_num_samples_loaded_into_buffer, + get_num_samples_loaded_into_buffer, + self.learner_info, + ) + ) + self.learner_queue_size.push(self.inqueue.qsize()) + + +class _MultiGPULoaderThread(threading.Thread): + def __init__( + self, multi_gpu_learner_thread: MultiGPULearnerThread, share_stats: bool + ): + threading.Thread.__init__(self) + self.multi_gpu_learner_thread = multi_gpu_learner_thread + self.daemon = True + if share_stats: + self.queue_timer = multi_gpu_learner_thread.queue_timer + self.load_timer = multi_gpu_learner_thread.load_timer + else: + self.queue_timer = _Timer() + self.load_timer = _Timer() + + def run(self) -> None: + while True: + self._step() + + def _step(self) -> None: + s = self.multi_gpu_learner_thread + policy_map = s.policy_map + + # Get a new batch from the data (inqueue). + with self.queue_timer: + batch = s.inqueue.get() + + # Get next idle stack for loading. + buffer_idx = s.idle_tower_stacks.get() + + # Load the batch into the idle stack. + with self.load_timer: + for pid in policy_map.keys(): + if ( + s.local_worker.is_policy_to_train is not None + and not s.local_worker.is_policy_to_train(pid, batch) + ): + continue + policy = policy_map[pid] + if isinstance(batch, SampleBatch): + policy.load_batch_into_buffer( + batch=batch, + buffer_index=buffer_idx, + ) + elif pid in batch.policy_batches: + policy.load_batch_into_buffer( + batch=batch.policy_batches[pid], + buffer_index=buffer_idx, + ) + + # Tag just-loaded stack as "ready". + s.ready_tower_stacks.put(buffer_idx) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/replay_ops.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/replay_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..bcd1f026cf1e1b3696229f7c27b7f0d504142a64 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/replay_ops.py @@ -0,0 +1,37 @@ +from typing import Optional +import random + +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.replay_buffers.replay_buffer import warn_replay_capacity +from ray.rllib.utils.typing import SampleBatchType + + +@OldAPIStack +class SimpleReplayBuffer: + """Simple replay buffer that operates over batches.""" + + def __init__(self, num_slots: int, replay_proportion: Optional[float] = None): + """Initialize SimpleReplayBuffer. + + Args: + num_slots: Number of batches to store in total. + """ + self.num_slots = num_slots + self.replay_batches = [] + self.replay_index = 0 + + def add_batch(self, sample_batch: SampleBatchType) -> None: + warn_replay_capacity(item=sample_batch, num_items=self.num_slots) + if self.num_slots > 0: + if len(self.replay_batches) < self.num_slots: + self.replay_batches.append(sample_batch) + else: + self.replay_batches[self.replay_index] = sample_batch + self.replay_index += 1 + self.replay_index %= self.num_slots + + def replay(self) -> SampleBatchType: + return random.choice(self.replay_batches) + + def __len__(self): + return len(self.replay_batches) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/rollout_ops.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/rollout_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..d9a683fa7dbff4a5640f5b60f4845149ed9aed58 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/rollout_ops.py @@ -0,0 +1,207 @@ +import logging +from typing import List, Optional, Union +import tree + +from ray.rllib.env.env_runner_group import EnvRunnerGroup +from ray.rllib.policy.sample_batch import ( + SampleBatch, + DEFAULT_POLICY_ID, + concat_samples, +) +from ray.rllib.utils.annotations import ExperimentalAPI, OldAPIStack +from ray.rllib.utils.metrics import NUM_AGENT_STEPS_SAMPLED, NUM_ENV_STEPS_SAMPLED +from ray.rllib.utils.sgd import standardized +from ray.rllib.utils.typing import EpisodeType, SampleBatchType + +logger = logging.getLogger(__name__) + + +@ExperimentalAPI +def synchronous_parallel_sample( + *, + worker_set: EnvRunnerGroup, + max_agent_steps: Optional[int] = None, + max_env_steps: Optional[int] = None, + concat: bool = True, + sample_timeout_s: Optional[float] = None, + random_actions: bool = False, + _uses_new_env_runners: bool = False, + _return_metrics: bool = False, +) -> Union[List[SampleBatchType], SampleBatchType, List[EpisodeType], EpisodeType]: + """Runs parallel and synchronous rollouts on all remote workers. + + Waits for all workers to return from the remote calls. + + If no remote workers exist (num_workers == 0), use the local worker + for sampling. + + Alternatively to calling `worker.sample.remote()`, the user can provide a + `remote_fn()`, which will be applied to the worker(s) instead. + + Args: + worker_set: The EnvRunnerGroup to use for sampling. + remote_fn: If provided, use `worker.apply.remote(remote_fn)` instead + of `worker.sample.remote()` to generate the requests. + max_agent_steps: Optional number of agent steps to be included in the + final batch or list of episodes. + max_env_steps: Optional number of environment steps to be included in the + final batch or list of episodes. + concat: Whether to aggregate all resulting batches or episodes. in case of + batches the list of batches is concatinated at the end. in case of + episodes all episode lists from workers are flattened into a single list. + sample_timeout_s: The timeout in sec to use on the `foreach_env_runner` call. + After this time, the call will return with a result (or not if all + EnvRunners are stalling). If None, will block indefinitely and not timeout. + _uses_new_env_runners: Whether the new `EnvRunner API` is used. In this case + episodes instead of `SampleBatch` objects are returned. + + Returns: + The list of collected sample batch types or episode types (one for each parallel + rollout worker in the given `worker_set`). + + .. testcode:: + + # Define an RLlib Algorithm. + from ray.rllib.algorithms.ppo import PPO, PPOConfig + config = ( + PPOConfig() + .environment("CartPole-v1") + ) + algorithm = config.build() + # 2 remote EnvRunners (num_env_runners=2): + episodes = synchronous_parallel_sample( + worker_set=algorithm.env_runner_group, + _uses_new_env_runners=True, + concat=False, + ) + print(len(episodes)) + + .. testoutput:: + + 2 + """ + # Only allow one of `max_agent_steps` or `max_env_steps` to be defined. + assert not (max_agent_steps is not None and max_env_steps is not None) + + agent_or_env_steps = 0 + max_agent_or_env_steps = max_agent_steps or max_env_steps or None + sample_batches_or_episodes = [] + all_stats_dicts = [] + + random_action_kwargs = {} if not random_actions else {"random_actions": True} + + # Stop collecting batches as soon as one criterium is met. + while (max_agent_or_env_steps is None and agent_or_env_steps == 0) or ( + max_agent_or_env_steps is not None + and agent_or_env_steps < max_agent_or_env_steps + ): + # No remote workers in the set -> Use local worker for collecting + # samples. + if worker_set.num_remote_workers() <= 0: + sampled_data = [worker_set.local_env_runner.sample(**random_action_kwargs)] + if _return_metrics: + stats_dicts = [worker_set.local_env_runner.get_metrics()] + # Loop over remote workers' `sample()` method in parallel. + else: + sampled_data = worker_set.foreach_env_runner( + ( + (lambda w: w.sample(**random_action_kwargs)) + if not _return_metrics + else (lambda w: (w.sample(**random_action_kwargs), w.get_metrics())) + ), + local_env_runner=False, + timeout_seconds=sample_timeout_s, + ) + # Nothing was returned (maybe all workers are stalling) or no healthy + # remote workers left: Break. + # There is no point staying in this loop, since we will not be able to + # get any new samples if we don't have any healthy remote workers left. + if not sampled_data or worker_set.num_healthy_remote_workers() <= 0: + if not sampled_data: + logger.warning( + "No samples returned from remote workers. If you have a " + "slow environment or model, consider increasing the " + "`sample_timeout_s` or decreasing the " + "`rollout_fragment_length` in `AlgorithmConfig.env_runners()." + ) + elif worker_set.num_healthy_remote_workers() <= 0: + logger.warning( + "No healthy remote workers left. Trying to restore workers ..." + ) + break + + if _return_metrics: + stats_dicts = [s[1] for s in sampled_data] + sampled_data = [s[0] for s in sampled_data] + + # Update our counters for the stopping criterion of the while loop. + if _return_metrics: + if max_agent_steps: + agent_or_env_steps += sum( + int(agent_stat) + for stat_dict in stats_dicts + for agent_stat in stat_dict[NUM_AGENT_STEPS_SAMPLED].values() + ) + else: + agent_or_env_steps += sum( + int(stat_dict[NUM_ENV_STEPS_SAMPLED]) for stat_dict in stats_dicts + ) + sample_batches_or_episodes.extend(sampled_data) + all_stats_dicts.extend(stats_dicts) + else: + for batch_or_episode in sampled_data: + if max_agent_steps: + agent_or_env_steps += ( + sum(e.agent_steps() for e in batch_or_episode) + if _uses_new_env_runners + else batch_or_episode.agent_steps() + ) + else: + agent_or_env_steps += ( + sum(e.env_steps() for e in batch_or_episode) + if _uses_new_env_runners + else batch_or_episode.env_steps() + ) + sample_batches_or_episodes.append(batch_or_episode) + # Break out (and ignore the remaining samples) if max timesteps (batch + # size) reached. We want to avoid collecting batches that are too large + # only because of a failed/restarted worker causing a second iteration + # of the main loop. + if ( + max_agent_or_env_steps is not None + and agent_or_env_steps >= max_agent_or_env_steps + ): + break + + if concat is True: + # If we have episodes flatten the episode list. + if _uses_new_env_runners: + sample_batches_or_episodes = tree.flatten(sample_batches_or_episodes) + # Otherwise we concatenate the `SampleBatch` objects + else: + sample_batches_or_episodes = concat_samples(sample_batches_or_episodes) + + if _return_metrics: + return sample_batches_or_episodes, all_stats_dicts + return sample_batches_or_episodes + + +@OldAPIStack +def standardize_fields(samples: SampleBatchType, fields: List[str]) -> SampleBatchType: + """Standardize fields of the given SampleBatch""" + wrapped = False + + if isinstance(samples, SampleBatch): + samples = samples.as_multi_agent() + wrapped = True + + for policy_id in samples.policy_batches: + batch = samples.policy_batches[policy_id] + for field in fields: + if field in batch: + batch[field] = standardized(batch[field]) + + if wrapped: + samples = samples.policy_batches[DEFAULT_POLICY_ID] + + return samples diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/segment_tree.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/segment_tree.py new file mode 100644 index 0000000000000000000000000000000000000000..5e7a5fd102f60ec53ca2a1a39f1ea68205f10ed2 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/segment_tree.py @@ -0,0 +1,212 @@ +import operator +from typing import Any, Optional + + +class SegmentTree: + """A Segment Tree data structure. + + https://en.wikipedia.org/wiki/Segment_tree + + Can be used as regular array, but with two important differences: + + a) Setting an item's value is slightly slower. It is O(lg capacity), + instead of O(1). + b) Offers efficient `reduce` operation which reduces the tree's values + over some specified contiguous subsequence of items in the array. + Operation could be e.g. min/max/sum. + + The data is stored in a list, where the length is 2 * capacity. + The second half of the list stores the actual values for each index, so if + capacity=8, values are stored at indices 8 to 15. The first half of the + array contains the reduced-values of the different (binary divided) + segments, e.g. (capacity=4): + 0=not used + 1=reduced-value over all elements (array indices 4 to 7). + 2=reduced-value over array indices (4 and 5). + 3=reduced-value over array indices (6 and 7). + 4-7: values of the tree. + NOTE that the values of the tree are accessed by indices starting at 0, so + `tree[0]` accesses `internal_array[4]` in the above example. + """ + + def __init__( + self, capacity: int, operation: Any, neutral_element: Optional[Any] = None + ): + """Initializes a Segment Tree object. + + Args: + capacity: Total size of the array - must be a power of two. + operation: Lambda obj, obj -> obj + The operation for combining elements (eg. sum, max). + Must be a mathematical group together with the set of + possible values for array elements. + neutral_element (Optional[obj]): The neutral element for + `operation`. Use None for automatically finding a value: + max: float("-inf"), min: float("inf"), sum: 0.0. + """ + + assert ( + capacity > 0 and capacity & (capacity - 1) == 0 + ), "Capacity must be positive and a power of 2!" + self.capacity = capacity + if neutral_element is None: + neutral_element = ( + 0.0 + if operation is operator.add + else float("-inf") + if operation is max + else float("inf") + ) + self.neutral_element = neutral_element + self.value = [self.neutral_element for _ in range(2 * capacity)] + self.operation = operation + + def reduce(self, start: int = 0, end: Optional[int] = None) -> Any: + """Applies `self.operation` to subsequence of our values. + + Subsequence is contiguous, includes `start` and excludes `end`. + + self.operation( + arr[start], operation(arr[start+1], operation(... arr[end]))) + + Args: + start: Start index to apply reduction to. + end (Optional[int]): End index to apply reduction to (excluded). + + Returns: + any: The result of reducing self.operation over the specified + range of `self._value` elements. + """ + if end is None: + end = self.capacity + elif end < 0: + end += self.capacity + + # Init result with neutral element. + result = self.neutral_element + # Map start/end to our actual index space (second half of array). + start += self.capacity + end += self.capacity + + # Example: + # internal-array (first half=sums, second half=actual values): + # 0 1 2 3 | 4 5 6 7 + # - 6 1 5 | 1 0 2 3 + + # tree.sum(0, 3) = 3 + # internally: start=4, end=7 -> sum values 1 0 2 = 3. + + # Iterate over tree starting in the actual-values (second half) + # section. + # 1) start=4 is even -> do nothing. + # 2) end=7 is odd -> end-- -> end=6 -> add value to result: result=2 + # 3) int-divide start and end by 2: start=2, end=3 + # 4) start still smaller end -> iterate once more. + # 5) start=2 is even -> do nothing. + # 6) end=3 is odd -> end-- -> end=2 -> add value to result: result=1 + # NOTE: This adds the sum of indices 4 and 5 to the result. + + # Iterate as long as start != end. + while start < end: + + # If start is odd: Add its value to result and move start to + # next even value. + if start & 1: + result = self.operation(result, self.value[start]) + start += 1 + + # If end is odd: Move end to previous even value, then add its + # value to result. NOTE: This takes care of excluding `end` in any + # situation. + if end & 1: + end -= 1 + result = self.operation(result, self.value[end]) + + # Divide both start and end by 2 to make them "jump" into the + # next upper level reduce-index space. + start //= 2 + end //= 2 + + # Then repeat till start == end. + + return result + + def __setitem__(self, idx: int, val: float) -> None: + """ + Inserts/overwrites a value in/into the tree. + + Args: + idx: The index to insert to. Must be in [0, `self.capacity`[ + val: The value to insert. + """ + assert 0 <= idx < self.capacity, f"idx={idx} capacity={self.capacity}" + + # Index of the leaf to insert into (always insert in "second half" + # of the tree, the first half is reserved for already calculated + # reduction-values). + idx += self.capacity + self.value[idx] = val + + # Recalculate all affected reduction values (in "first half" of tree). + idx = idx >> 1 # Divide by 2 (faster than division). + while idx >= 1: + update_idx = 2 * idx # calculate only once + # Update the reduction value at the correct "first half" idx. + self.value[idx] = self.operation( + self.value[update_idx], self.value[update_idx + 1] + ) + idx = idx >> 1 # Divide by 2 (faster than division). + + def __getitem__(self, idx: int) -> Any: + assert 0 <= idx < self.capacity + return self.value[idx + self.capacity] + + def get_state(self): + return self.value + + def set_state(self, state): + assert len(state) == self.capacity * 2 + self.value = state + + +class SumSegmentTree(SegmentTree): + """A SegmentTree with the reduction `operation`=operator.add.""" + + def __init__(self, capacity: int): + super(SumSegmentTree, self).__init__(capacity=capacity, operation=operator.add) + + def sum(self, start: int = 0, end: Optional[Any] = None) -> Any: + """Returns the sum over a sub-segment of the tree.""" + return self.reduce(start, end) + + def find_prefixsum_idx(self, prefixsum: float) -> int: + """Finds highest i, for which: sum(arr[0]+..+arr[i - i]) <= prefixsum. + + Args: + prefixsum: `prefixsum` upper bound in above constraint. + + Returns: + int: Largest possible index (i) satisfying above constraint. + """ + assert 0 <= prefixsum <= self.sum() + 1e-5 + # Global sum node. + idx = 1 + + # While non-leaf (first half of tree). + while idx < self.capacity: + update_idx = 2 * idx + if self.value[update_idx] > prefixsum: + idx = update_idx + else: + prefixsum -= self.value[update_idx] + idx = update_idx + 1 + return idx - self.capacity + + +class MinSegmentTree(SegmentTree): + def __init__(self, capacity: int): + super(MinSegmentTree, self).__init__(capacity=capacity, operation=min) + + def min(self, start: int = 0, end: Optional[Any] = None) -> Any: + """Returns min(arr[start], ..., arr[end])""" + return self.reduce(start, end) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/train_ops.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/train_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..732beb92e7c4f8bd2fa107b5a9f783f8536d309b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/execution/train_ops.py @@ -0,0 +1,204 @@ +import logging +import numpy as np +import math +from typing import Dict + +from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.deprecation import deprecation_warning +from ray.rllib.utils.metrics import ( + NUM_ENV_STEPS_TRAINED, + NUM_AGENT_STEPS_TRAINED, + LEARN_ON_BATCH_TIMER, + LOAD_BATCH_TIMER, +) +from ray.rllib.utils.metrics.learner_info import LearnerInfoBuilder +from ray.rllib.utils.sgd import do_minibatch_sgd +from ray.util import log_once + +tf1, tf, tfv = try_import_tf() + +logger = logging.getLogger(__name__) + + +@OldAPIStack +def train_one_step(algorithm, train_batch, policies_to_train=None) -> Dict: + """Function that improves the all policies in `train_batch` on the local worker. + + .. testcode:: + :skipif: True + + from ray.rllib.execution.rollout_ops import synchronous_parallel_sample + algo = [...] + train_batch = synchronous_parallel_sample(algo.env_runner_group) + # This trains the policy on one batch. + print(train_one_step(algo, train_batch))) + + .. testoutput:: + + {"default_policy": ...} + + Updates the NUM_ENV_STEPS_TRAINED and NUM_AGENT_STEPS_TRAINED counters as well as + the LEARN_ON_BATCH_TIMER timer of the `algorithm` object. + """ + config = algorithm.config + workers = algorithm.env_runner_group + local_worker = workers.local_env_runner + num_sgd_iter = config.get("num_epochs", config.get("num_sgd_iter", 1)) + minibatch_size = config.get("minibatch_size") + if minibatch_size is None: + minibatch_size = config.get("sgd_minibatch_size", 0) + + learn_timer = algorithm._timers[LEARN_ON_BATCH_TIMER] + with learn_timer: + # Subsample minibatches (size=`minibatch_size`) from the + # train batch and loop through train batch `num_sgd_iter` times. + if num_sgd_iter > 1 or minibatch_size > 0: + info = do_minibatch_sgd( + train_batch, + { + pid: local_worker.get_policy(pid) + for pid in policies_to_train + or local_worker.get_policies_to_train(train_batch) + }, + local_worker, + num_sgd_iter, + minibatch_size, + [], + ) + # Single update step using train batch. + else: + info = local_worker.learn_on_batch(train_batch) + + learn_timer.push_units_processed(train_batch.count) + algorithm._counters[NUM_ENV_STEPS_TRAINED] += train_batch.count + algorithm._counters[NUM_AGENT_STEPS_TRAINED] += train_batch.agent_steps() + + if algorithm.reward_estimators: + info[DEFAULT_POLICY_ID]["off_policy_estimation"] = {} + for name, estimator in algorithm.reward_estimators.items(): + info[DEFAULT_POLICY_ID]["off_policy_estimation"][name] = estimator.train( + train_batch + ) + return info + + +@OldAPIStack +def multi_gpu_train_one_step(algorithm, train_batch) -> Dict: + """Multi-GPU version of train_one_step. + + Uses the policies' `load_batch_into_buffer` and `learn_on_loaded_batch` methods + to be more efficient wrt CPU/GPU data transfers. For example, when doing multiple + passes through a train batch (e.g. for PPO) using `config.num_sgd_iter`, the + actual train batch is only split once and loaded once into the GPU(s). + + .. testcode:: + :skipif: True + + from ray.rllib.execution.rollout_ops import synchronous_parallel_sample + algo = [...] + train_batch = synchronous_parallel_sample(algo.env_runner_group) + # This trains the policy on one batch. + print(multi_gpu_train_one_step(algo, train_batch))) + + .. testoutput:: + + {"default_policy": ...} + + Updates the NUM_ENV_STEPS_TRAINED and NUM_AGENT_STEPS_TRAINED counters as well as + the LOAD_BATCH_TIMER and LEARN_ON_BATCH_TIMER timers of the Algorithm instance. + """ + if log_once("mulit_gpu_train_one_step_deprecation_warning"): + deprecation_warning( + old=("ray.rllib.execution.train_ops.multi_gpu_train_one_step") + ) + config = algorithm.config + workers = algorithm.env_runner_group + local_worker = workers.local_env_runner + num_sgd_iter = config.get("num_epochs", config.get("num_sgd_iter", 1)) + minibatch_size = config.get("minibatch_size") + if minibatch_size is None: + minibatch_size = config["train_batch_size"] + + # Determine the number of devices (GPUs or 1 CPU) we use. + num_devices = int(math.ceil(config["num_gpus"] or 1)) + + # Make sure total batch size is dividable by the number of devices. + # Batch size per tower. + per_device_batch_size = minibatch_size // num_devices + # Total batch size. + batch_size = per_device_batch_size * num_devices + assert batch_size % num_devices == 0 + assert batch_size >= num_devices, "Batch size too small!" + + # Handle everything as if multi-agent. + train_batch = train_batch.as_multi_agent() + + # Load data into GPUs. + load_timer = algorithm._timers[LOAD_BATCH_TIMER] + with load_timer: + num_loaded_samples = {} + for policy_id, batch in train_batch.policy_batches.items(): + # Not a policy-to-train. + if ( + local_worker.is_policy_to_train is not None + and not local_worker.is_policy_to_train(policy_id, train_batch) + ): + continue + + # Decompress SampleBatch, in case some columns are compressed. + batch.decompress_if_needed() + + # Load the entire train batch into the Policy's only buffer + # (idx=0). Policies only have >1 buffers, if we are training + # asynchronously. + num_loaded_samples[policy_id] = local_worker.policy_map[ + policy_id + ].load_batch_into_buffer(batch, buffer_index=0) + + # Execute minibatch SGD on loaded data. + learn_timer = algorithm._timers[LEARN_ON_BATCH_TIMER] + with learn_timer: + # Use LearnerInfoBuilder as a unified way to build the final + # results dict from `learn_on_loaded_batch` call(s). + # This makes sure results dicts always have the same structure + # no matter the setup (multi-GPU, multi-agent, minibatch SGD, + # tf vs torch). + learner_info_builder = LearnerInfoBuilder(num_devices=num_devices) + + for policy_id, samples_per_device in num_loaded_samples.items(): + policy = local_worker.policy_map[policy_id] + num_batches = max(1, int(samples_per_device) // int(per_device_batch_size)) + logger.debug("== sgd epochs for {} ==".format(policy_id)) + for _ in range(num_sgd_iter): + permutation = np.random.permutation(num_batches) + for batch_index in range(num_batches): + # Learn on the pre-loaded data in the buffer. + # Note: For minibatch SGD, the data is an offset into + # the pre-loaded entire train batch. + results = policy.learn_on_loaded_batch( + permutation[batch_index] * per_device_batch_size, buffer_index=0 + ) + + learner_info_builder.add_learn_on_batch_results(results, policy_id) + + # Tower reduce and finalize results. + learner_info = learner_info_builder.finalize() + + load_timer.push_units_processed(train_batch.count) + learn_timer.push_units_processed(train_batch.count) + + # TODO: Move this into Algorithm's `training_step` method for + # better transparency. + algorithm._counters[NUM_ENV_STEPS_TRAINED] += train_batch.count + algorithm._counters[NUM_AGENT_STEPS_TRAINED] += train_batch.agent_steps() + + if algorithm.reward_estimators: + learner_info[DEFAULT_POLICY_ID]["off_policy_estimation"] = {} + for name, estimator in algorithm.reward_estimators.items(): + learner_info[DEFAULT_POLICY_ID]["off_policy_estimation"][ + name + ] = estimator.train(train_batch) + + return learner_info diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8d7091e208fd2108d5b0f42fbf0a7ec27b850f0f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/__init__.py @@ -0,0 +1,12 @@ +from ray.rllib.models.action_dist import ActionDistribution +from ray.rllib.models.catalog import ModelCatalog, MODEL_DEFAULTS +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.preprocessors import Preprocessor + +__all__ = [ + "ActionDistribution", + "ModelCatalog", + "ModelV2", + "Preprocessor", + "MODEL_DEFAULTS", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/action_dist.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/action_dist.py new file mode 100644 index 0000000000000000000000000000000000000000..1cacfdef60c5e76831a23cd53bc326141ebcc54e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/action_dist.py @@ -0,0 +1,94 @@ +import numpy as np +import gymnasium as gym + +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.typing import TensorType, List, Union, ModelConfigDict + + +@OldAPIStack +class ActionDistribution: + """The policy action distribution of an agent. + + Attributes: + inputs: input vector to compute samples from. + model (ModelV2): reference to model producing the inputs. + """ + + def __init__(self, inputs: List[TensorType], model: ModelV2): + """Initializes an ActionDist object. + + Args: + inputs: input vector to compute samples from. + model (ModelV2): reference to model producing the inputs. This + is mainly useful if you want to use model variables to compute + action outputs (i.e., for autoregressive action distributions, + see examples/autoregressive_action_dist.py). + """ + self.inputs = inputs + self.model = model + + def sample(self) -> TensorType: + """Draw a sample from the action distribution.""" + raise NotImplementedError + + def deterministic_sample(self) -> TensorType: + """ + Get the deterministic "sampling" output from the distribution. + This is usually the max likelihood output, i.e. mean for Normal, argmax + for Categorical, etc.. + """ + raise NotImplementedError + + def sampled_action_logp(self) -> TensorType: + """Returns the log probability of the last sampled action.""" + raise NotImplementedError + + def logp(self, x: TensorType) -> TensorType: + """The log-likelihood of the action distribution.""" + raise NotImplementedError + + def kl(self, other: "ActionDistribution") -> TensorType: + """The KL-divergence between two action distributions.""" + raise NotImplementedError + + def entropy(self) -> TensorType: + """The entropy of the action distribution.""" + raise NotImplementedError + + def multi_kl(self, other: "ActionDistribution") -> TensorType: + """The KL-divergence between two action distributions. + + This differs from kl() in that it can return an array for + MultiDiscrete. TODO(ekl) consider removing this. + """ + return self.kl(other) + + def multi_entropy(self) -> TensorType: + """The entropy of the action distribution. + + This differs from entropy() in that it can return an array for + MultiDiscrete. TODO(ekl) consider removing this. + """ + return self.entropy() + + @staticmethod + @OldAPIStack + def required_model_output_shape( + action_space: gym.Space, model_config: ModelConfigDict + ) -> Union[int, np.ndarray]: + """Returns the required shape of an input parameter tensor for a + particular action space and an optional dict of distribution-specific + options. + + Args: + action_space (gym.Space): The action space this distribution will + be used for, whose shape attributes will be used to determine + the required shape of the input parameter tensor. + model_config: Model's config dict (as defined in catalog.py) + + Returns: + model_output_shape (int or np.ndarray of ints): size of the + required input vector (minus leading batch dimension). + """ + raise NotImplementedError diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/catalog.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/catalog.py new file mode 100644 index 0000000000000000000000000000000000000000..0b2d393c0d11db5feb0e4a9efd97724b4f3cb876 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/catalog.py @@ -0,0 +1,905 @@ +from functools import partial +import gymnasium as gym +from gymnasium.spaces import Box, Dict, Discrete, MultiDiscrete, Tuple +import logging +import numpy as np +import tree # pip install dm_tree +from typing import List, Optional, Type, Union + +from ray.tune.registry import ( + RLLIB_MODEL, + RLLIB_ACTION_DIST, + _global_registry, +) +from ray.rllib.models.action_dist import ActionDistribution +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.preprocessors import get_preprocessor, Preprocessor +from ray.rllib.models.tf.tf_action_dist import ( + Categorical, + Deterministic, + DiagGaussian, + Dirichlet, + MultiActionDistribution, + MultiCategorical, +) +from ray.rllib.models.torch.torch_action_dist import ( + TorchCategorical, + TorchDeterministic, + TorchDirichlet, + TorchDiagGaussian, + TorchMultiActionDistribution, + TorchMultiCategorical, +) +from ray.rllib.utils.annotations import DeveloperAPI, PublicAPI +from ray.rllib.utils.deprecation import ( + DEPRECATED_VALUE, + deprecation_warning, +) +from ray.rllib.utils.error import UnsupportedSpaceException +from ray.rllib.utils.framework import try_import_tf, try_import_torch +from ray.rllib.utils.from_config import from_config +from ray.rllib.utils.spaces.simplex import Simplex +from ray.rllib.utils.spaces.space_utils import flatten_space +from ray.rllib.utils.typing import ModelConfigDict, TensorType + +tf1, tf, tfv = try_import_tf() +torch, _ = try_import_torch() + +logger = logging.getLogger(__name__) + +# fmt: off +# __sphinx_doc_begin__ +MODEL_DEFAULTS: ModelConfigDict = { + "fcnet_hiddens": [256, 256], + "fcnet_activation": "tanh", + "fcnet_weights_initializer": None, + "fcnet_weights_initializer_config": None, + "fcnet_bias_initializer": None, + "fcnet_bias_initializer_config": None, + "conv_filters": None, + "conv_activation": "relu", + "conv_kernel_initializer": None, + "conv_kernel_initializer_config": None, + "conv_bias_initializer": None, + "conv_bias_initializer_config": None, + "conv_transpose_kernel_initializer": None, + "conv_transpose_kernel_initializer_config": None, + "conv_transpose_bias_initializer": None, + "conv_transpose_bias_initializer_config": None, + "post_fcnet_hiddens": [], + "post_fcnet_activation": "relu", + "post_fcnet_weights_initializer": None, + "post_fcnet_weights_initializer_config": None, + "post_fcnet_bias_initializer": None, + "post_fcnet_bias_initializer_config": None, + "free_log_std": False, + "log_std_clip_param": 20.0, + "no_final_linear": False, + "vf_share_layers": True, + "use_lstm": False, + "max_seq_len": 20, + "lstm_cell_size": 256, + "lstm_use_prev_action": False, + "lstm_use_prev_reward": False, + "lstm_weights_initializer": None, + "lstm_weights_initializer_config": None, + "lstm_bias_initializer": None, + "lstm_bias_initializer_config": None, + "_time_major": False, + "use_attention": False, + "attention_num_transformer_units": 1, + "attention_dim": 64, + "attention_num_heads": 1, + "attention_head_dim": 32, + "attention_memory_inference": 50, + "attention_memory_training": 50, + "attention_position_wise_mlp_dim": 32, + "attention_init_gru_gate_bias": 2.0, + "attention_use_n_prev_actions": 0, + "attention_use_n_prev_rewards": 0, + "framestack": True, + "dim": 84, + "grayscale": False, + "zero_mean": True, + "custom_model": None, + "custom_model_config": {}, + "custom_action_dist": None, + "custom_preprocessor": None, + "encoder_latent_dim": None, + "always_check_shapes": False, + + # Deprecated keys: + "lstm_use_prev_action_reward": DEPRECATED_VALUE, + "_use_default_native_models": DEPRECATED_VALUE, + "_disable_preprocessor_api": False, + "_disable_action_flattening": False, +} +# __sphinx_doc_end__ +# fmt: on + + +@DeveloperAPI +class ModelCatalog: + """Registry of models, preprocessors, and action distributions for envs. + + .. testcode:: + :skipif: True + + prep = ModelCatalog.get_preprocessor(env) + observation = prep.transform(raw_observation) + + dist_class, dist_dim = ModelCatalog.get_action_dist( + env.action_space, {}) + model = ModelCatalog.get_model_v2( + obs_space, action_space, num_outputs, options) + dist = dist_class(model.outputs, model) + action = dist.sample() + """ + + @staticmethod + @DeveloperAPI + def get_action_dist( + action_space: gym.Space, + config: ModelConfigDict, + dist_type: Optional[Union[str, Type[ActionDistribution]]] = None, + framework: str = "tf", + **kwargs + ) -> (type, int): + """Returns a distribution class and size for the given action space. + + Args: + action_space: Action space of the target gym env. + config (Optional[dict]): Optional model config. + dist_type (Optional[Union[str, Type[ActionDistribution]]]): + Identifier of the action distribution (str) interpreted as a + hint or the actual ActionDistribution class to use. + framework: One of "tf2", "tf", "torch", or "jax". + kwargs: Optional kwargs to pass on to the Distribution's + constructor. + + Returns: + Tuple: + - dist_class (ActionDistribution): Python class of the + distribution. + - dist_dim (int): The size of the input vector to the + distribution. + """ + + dist_cls = None + config = config or MODEL_DEFAULTS + # Custom distribution given. + if config.get("custom_action_dist"): + custom_action_config = config.copy() + action_dist_name = custom_action_config.pop("custom_action_dist") + logger.debug("Using custom action distribution {}".format(action_dist_name)) + dist_cls = _global_registry.get(RLLIB_ACTION_DIST, action_dist_name) + return ModelCatalog._get_multi_action_distribution( + dist_cls, action_space, custom_action_config, framework + ) + + # Dist_type is given directly as a class. + elif ( + type(dist_type) is type + and issubclass(dist_type, ActionDistribution) + and dist_type not in (MultiActionDistribution, TorchMultiActionDistribution) + ): + dist_cls = dist_type + # Box space -> DiagGaussian OR Deterministic. + elif isinstance(action_space, Box): + if action_space.dtype.name.startswith("int"): + low_ = np.min(action_space.low) + high_ = np.max(action_space.high) + dist_cls = ( + TorchMultiCategorical if framework == "torch" else MultiCategorical + ) + num_cats = int(np.prod(action_space.shape)) + return ( + partial( + dist_cls, + input_lens=[high_ - low_ + 1 for _ in range(num_cats)], + action_space=action_space, + ), + num_cats * (high_ - low_ + 1), + ) + else: + if len(action_space.shape) > 1: + raise UnsupportedSpaceException( + "Action space has multiple dimensions " + "{}. ".format(action_space.shape) + + "Consider reshaping this into a single dimension, " + "using a custom action distribution, " + "using a Tuple action space, or the multi-agent API." + ) + # TODO(sven): Check for bounds and return SquashedNormal, etc.. + if dist_type is None: + return ( + partial( + TorchDiagGaussian if framework == "torch" else DiagGaussian, + action_space=action_space, + ), + DiagGaussian.required_model_output_shape(action_space, config), + ) + elif dist_type == "deterministic": + dist_cls = ( + TorchDeterministic if framework == "torch" else Deterministic + ) + # Discrete Space -> Categorical. + elif isinstance(action_space, Discrete): + if framework == "torch": + dist_cls = TorchCategorical + elif framework == "jax": + from ray.rllib.models.jax.jax_action_dist import JAXCategorical + + dist_cls = JAXCategorical + else: + dist_cls = Categorical + # Tuple/Dict Spaces -> MultiAction. + elif dist_type in ( + MultiActionDistribution, + TorchMultiActionDistribution, + ) or isinstance(action_space, (Tuple, Dict)): + return ModelCatalog._get_multi_action_distribution( + ( + MultiActionDistribution + if framework == "tf" + else TorchMultiActionDistribution + ), + action_space, + config, + framework, + ) + # Simplex -> Dirichlet. + elif isinstance(action_space, Simplex): + dist_cls = TorchDirichlet if framework == "torch" else Dirichlet + # MultiDiscrete -> MultiCategorical. + elif isinstance(action_space, MultiDiscrete): + dist_cls = ( + TorchMultiCategorical if framework == "torch" else MultiCategorical + ) + return partial(dist_cls, input_lens=action_space.nvec), int( + sum(action_space.nvec) + ) + # Unknown type -> Error. + else: + raise NotImplementedError( + "Unsupported args: {} {}".format(action_space, dist_type) + ) + + return dist_cls, int(dist_cls.required_model_output_shape(action_space, config)) + + @staticmethod + @DeveloperAPI + def get_action_shape( + action_space: gym.Space, framework: str = "tf" + ) -> (np.dtype, List[int]): + """Returns action tensor dtype and shape for the action space. + + Args: + action_space: Action space of the target gym env. + framework: The framework identifier. One of "tf" or "torch". + + Returns: + (dtype, shape): Dtype and shape of the actions tensor. + """ + dl_lib = torch if framework == "torch" else tf + if isinstance(action_space, Discrete): + return action_space.dtype, (None,) + elif isinstance(action_space, (Box, Simplex)): + if np.issubdtype(action_space.dtype, np.floating): + return dl_lib.float32, (None,) + action_space.shape + elif np.issubdtype(action_space.dtype, np.integer): + return dl_lib.int32, (None,) + action_space.shape + else: + raise ValueError("RLlib doesn't support non int or float box spaces") + elif isinstance(action_space, MultiDiscrete): + return action_space.dtype, (None,) + action_space.shape + elif isinstance(action_space, (Tuple, Dict)): + flat_action_space = flatten_space(action_space) + size = 0 + all_discrete = True + for i in range(len(flat_action_space)): + if isinstance(flat_action_space[i], Discrete): + size += 1 + else: + all_discrete = False + size += np.prod(flat_action_space[i].shape) + size = int(size) + return dl_lib.int32 if all_discrete else dl_lib.float32, (None, size) + else: + raise NotImplementedError( + "Action space {} not supported".format(action_space) + ) + + @staticmethod + @DeveloperAPI + def get_action_placeholder( + action_space: gym.Space, name: str = "action" + ) -> TensorType: + """Returns an action placeholder consistent with the action space + + Args: + action_space: Action space of the target gym env. + name: An optional string to name the placeholder by. + Default: "action". + + Returns: + action_placeholder: A placeholder for the actions + """ + dtype, shape = ModelCatalog.get_action_shape(action_space, framework="tf") + + return tf1.placeholder(dtype, shape=shape, name=name) + + @staticmethod + @DeveloperAPI + def get_model_v2( + obs_space: gym.Space, + action_space: gym.Space, + num_outputs: int, + model_config: ModelConfigDict, + framework: str = "tf", + name: str = "default_model", + model_interface: type = None, + default_model: type = None, + **model_kwargs + ) -> ModelV2: + """Returns a suitable model compatible with given spaces and output. + + Args: + obs_space: Observation space of the target gym env. This + may have an `original_space` attribute that specifies how to + unflatten the tensor into a ragged tensor. + action_space: Action space of the target gym env. + num_outputs: The size of the output vector of the model. + model_config: The "model" sub-config dict + within the Algorithm's config dict. + framework: One of "tf2", "tf", "torch", or "jax". + name: Name (scope) for the model. + model_interface: Interface required for the model + default_model: Override the default class for the model. This + only has an effect when not using a custom model + model_kwargs: Args to pass to the ModelV2 constructor + + Returns: + model (ModelV2): Model to use for the policy. + """ + + # Validate the given config dict. + ModelCatalog._validate_config( + config=model_config, action_space=action_space, framework=framework + ) + + if model_config.get("custom_model"): + # Allow model kwargs to be overridden / augmented by + # custom_model_config. + customized_model_kwargs = dict( + model_kwargs, **model_config.get("custom_model_config", {}) + ) + + if isinstance(model_config["custom_model"], type): + model_cls = model_config["custom_model"] + elif ( + isinstance(model_config["custom_model"], str) + and "." in model_config["custom_model"] + ): + return from_config( + cls=model_config["custom_model"], + obs_space=obs_space, + action_space=action_space, + num_outputs=num_outputs, + model_config=customized_model_kwargs, + name=name, + ) + else: + model_cls = _global_registry.get( + RLLIB_MODEL, model_config["custom_model"] + ) + + # Only allow ModelV2 or native keras Models. + if not issubclass(model_cls, ModelV2): + if framework not in ["tf", "tf2"] or not issubclass( + model_cls, tf.keras.Model + ): + raise ValueError( + "`model_cls` must be a ModelV2 sub-class, but is" + " {}!".format(model_cls) + ) + + logger.info("Wrapping {} as {}".format(model_cls, model_interface)) + model_cls = ModelCatalog._wrap_if_needed(model_cls, model_interface) + + if framework in ["tf2", "tf"]: + # Try wrapping custom model with LSTM/attention, if required. + if model_config.get("use_lstm") or model_config.get("use_attention"): + from ray.rllib.models.tf.attention_net import ( + AttentionWrapper, + ) + from ray.rllib.models.tf.recurrent_net import ( + LSTMWrapper, + ) + + wrapped_cls = model_cls + forward = wrapped_cls.forward + model_cls = ModelCatalog._wrap_if_needed( + wrapped_cls, + LSTMWrapper + if model_config.get("use_lstm") + else AttentionWrapper, + ) + model_cls._wrapped_forward = forward + + # Obsolete: Track and warn if vars were created but not + # registered. Only still do this, if users do register their + # variables. If not (which they shouldn't), don't check here. + created = set() + + def track_var_creation(next_creator, **kw): + v = next_creator(**kw) + created.add(v.ref()) + return v + + with tf.variable_creator_scope(track_var_creation): + if issubclass(model_cls, tf.keras.Model): + instance = model_cls( + input_space=obs_space, + action_space=action_space, + num_outputs=num_outputs, + name=name, + **customized_model_kwargs, + ) + else: + # Try calling with kwargs first (custom ModelV2 should + # accept these as kwargs, not get them from + # config["custom_model_config"] anymore). + try: + instance = model_cls( + obs_space, + action_space, + num_outputs, + model_config, + name, + **customized_model_kwargs, + ) + except TypeError as e: + # Keyword error: Try old way w/o kwargs. + if "__init__() got an unexpected " in e.args[0]: + instance = model_cls( + obs_space, + action_space, + num_outputs, + model_config, + name, + **model_kwargs, + ) + logger.warning( + "Custom ModelV2 should accept all custom " + "options as **kwargs, instead of expecting" + " them in config['custom_model_config']!" + ) + # Other error -> re-raise. + else: + raise e + + # User still registered TFModelV2's variables: Check, whether + # ok. + registered = [] + if not isinstance(instance, tf.keras.Model): + registered = set(instance.var_list) + if len(registered) > 0: + not_registered = set() + for var in created: + if var not in registered: + not_registered.add(var) + if not_registered: + raise ValueError( + "It looks like you are still using " + "`{}.register_variables()` to register your " + "model's weights. This is no longer required, but " + "if you are still calling this method at least " + "once, you must make sure to register all created " + "variables properly. The missing variables are {}," + " and you only registered {}. " + "Did you forget to call `register_variables()` on " + "some of the variables in question?".format( + instance, not_registered, registered + ) + ) + elif framework == "torch": + # Try wrapping custom model with LSTM/attention, if required. + if model_config.get("use_lstm") or model_config.get("use_attention"): + from ray.rllib.models.torch.attention_net import AttentionWrapper + from ray.rllib.models.torch.recurrent_net import LSTMWrapper + + wrapped_cls = model_cls + forward = wrapped_cls.forward + model_cls = ModelCatalog._wrap_if_needed( + wrapped_cls, + LSTMWrapper + if model_config.get("use_lstm") + else AttentionWrapper, + ) + model_cls._wrapped_forward = forward + + # PyTorch automatically tracks nn.Modules inside the parent + # nn.Module's constructor. + # Try calling with kwargs first (custom ModelV2 should + # accept these as kwargs, not get them from + # config["custom_model_config"] anymore). + try: + instance = model_cls( + obs_space, + action_space, + num_outputs, + model_config, + name, + **customized_model_kwargs, + ) + except TypeError as e: + # Keyword error: Try old way w/o kwargs. + if "__init__() got an unexpected " in e.args[0]: + instance = model_cls( + obs_space, + action_space, + num_outputs, + model_config, + name, + **model_kwargs, + ) + logger.warning( + "Custom ModelV2 should accept all custom " + "options as **kwargs, instead of expecting" + " them in config['custom_model_config']!" + ) + # Other error -> re-raise. + else: + raise e + else: + raise NotImplementedError( + "`framework` must be 'tf2|tf|torch', but is " + "{}!".format(framework) + ) + + return instance + + # Find a default TFModelV2 and wrap with model_interface. + if framework in ["tf", "tf2"]: + v2_class = None + # Try to get a default v2 model. + if not model_config.get("custom_model"): + v2_class = default_model or ModelCatalog._get_v2_model_class( + obs_space, model_config, framework=framework + ) + + if not v2_class: + raise ValueError("ModelV2 class could not be determined!") + + if model_config.get("use_lstm") or model_config.get("use_attention"): + from ray.rllib.models.tf.attention_net import ( + AttentionWrapper, + ) + from ray.rllib.models.tf.recurrent_net import ( + LSTMWrapper, + ) + + wrapped_cls = v2_class + if model_config.get("use_lstm"): + v2_class = ModelCatalog._wrap_if_needed(wrapped_cls, LSTMWrapper) + v2_class._wrapped_forward = wrapped_cls.forward + else: + v2_class = ModelCatalog._wrap_if_needed( + wrapped_cls, AttentionWrapper + ) + v2_class._wrapped_forward = wrapped_cls.forward + + # Wrap in the requested interface. + wrapper = ModelCatalog._wrap_if_needed(v2_class, model_interface) + + if issubclass(wrapper, tf.keras.Model): + model = wrapper( + input_space=obs_space, + action_space=action_space, + num_outputs=num_outputs, + name=name, + **dict(model_kwargs, **model_config), + ) + return model + + return wrapper( + obs_space, action_space, num_outputs, model_config, name, **model_kwargs + ) + + # Find a default TorchModelV2 and wrap with model_interface. + elif framework == "torch": + # Try to get a default v2 model. + if not model_config.get("custom_model"): + v2_class = default_model or ModelCatalog._get_v2_model_class( + obs_space, model_config, framework=framework + ) + + if not v2_class: + raise ValueError("ModelV2 class could not be determined!") + + if model_config.get("use_lstm") or model_config.get("use_attention"): + from ray.rllib.models.torch.attention_net import AttentionWrapper + from ray.rllib.models.torch.recurrent_net import LSTMWrapper + + wrapped_cls = v2_class + forward = wrapped_cls.forward + if model_config.get("use_lstm"): + v2_class = ModelCatalog._wrap_if_needed(wrapped_cls, LSTMWrapper) + else: + v2_class = ModelCatalog._wrap_if_needed( + wrapped_cls, AttentionWrapper + ) + + v2_class._wrapped_forward = forward + + # Wrap in the requested interface. + wrapper = ModelCatalog._wrap_if_needed(v2_class, model_interface) + return wrapper( + obs_space, action_space, num_outputs, model_config, name, **model_kwargs + ) + + # Find a default JAXModelV2 and wrap with model_interface. + elif framework == "jax": + v2_class = default_model or ModelCatalog._get_v2_model_class( + obs_space, model_config, framework=framework + ) + # Wrap in the requested interface. + wrapper = ModelCatalog._wrap_if_needed(v2_class, model_interface) + return wrapper( + obs_space, action_space, num_outputs, model_config, name, **model_kwargs + ) + else: + raise NotImplementedError( + "`framework` must be 'tf2|tf|torch', but is {}!".format(framework) + ) + + @staticmethod + @DeveloperAPI + def get_preprocessor( + env: gym.Env, options: Optional[dict] = None, include_multi_binary: bool = False + ) -> Preprocessor: + """Returns a suitable preprocessor for the given env. + + This is a wrapper for get_preprocessor_for_space(). + """ + + return ModelCatalog.get_preprocessor_for_space( + env.observation_space, options, include_multi_binary + ) + + @staticmethod + @DeveloperAPI + def get_preprocessor_for_space( + observation_space: gym.Space, + options: dict = None, + include_multi_binary: bool = False, + ) -> Preprocessor: + """Returns a suitable preprocessor for the given observation space. + + Args: + observation_space: The input observation space. + options: Options to pass to the preprocessor. + include_multi_binary: Whether to include the MultiBinaryPreprocessor in + the possible preprocessors returned by this method. + + Returns: + preprocessor: Preprocessor for the observations. + """ + + options = options or MODEL_DEFAULTS + for k in options.keys(): + if k not in MODEL_DEFAULTS: + raise Exception( + "Unknown config key `{}`, all keys: {}".format( + k, list(MODEL_DEFAULTS) + ) + ) + + cls = get_preprocessor( + observation_space, include_multi_binary=include_multi_binary + ) + prep = cls(observation_space, options) + + if prep is not None: + logger.debug( + "Created preprocessor {}: {} -> {}".format( + prep, observation_space, prep.shape + ) + ) + return prep + + @staticmethod + @PublicAPI + def register_custom_model(model_name: str, model_class: type) -> None: + """Register a custom model class by name. + + The model can be later used by specifying {"custom_model": model_name} + in the model config. + + Args: + model_name: Name to register the model under. + model_class: Python class of the model. + """ + if tf is not None: + if issubclass(model_class, tf.keras.Model): + deprecation_warning(old="register_custom_model", error=False) + _global_registry.register(RLLIB_MODEL, model_name, model_class) + + @staticmethod + @PublicAPI + def register_custom_action_dist( + action_dist_name: str, action_dist_class: type + ) -> None: + """Register a custom action distribution class by name. + + The model can be later used by specifying + {"custom_action_dist": action_dist_name} in the model config. + + Args: + model_name: Name to register the action distribution under. + model_class: Python class of the action distribution. + """ + _global_registry.register( + RLLIB_ACTION_DIST, action_dist_name, action_dist_class + ) + + @staticmethod + def _wrap_if_needed(model_cls: type, model_interface: type) -> type: + if not model_interface or issubclass(model_cls, model_interface): + return model_cls + + assert issubclass(model_cls, ModelV2), model_cls + + class wrapper(model_interface, model_cls): + pass + + name = "{}_as_{}".format(model_cls.__name__, model_interface.__name__) + wrapper.__name__ = name + wrapper.__qualname__ = name + + return wrapper + + @staticmethod + def _get_v2_model_class( + input_space: gym.Space, model_config: ModelConfigDict, framework: str = "tf" + ) -> Type[ModelV2]: + VisionNet = None + ComplexNet = None + + if framework in ["tf2", "tf"]: + from ray.rllib.models.tf.fcnet import ( + FullyConnectedNetwork as FCNet, + ) + from ray.rllib.models.tf.visionnet import ( + VisionNetwork as VisionNet, + ) + from ray.rllib.models.tf.complex_input_net import ( + ComplexInputNetwork as ComplexNet, + ) + elif framework == "torch": + from ray.rllib.models.torch.fcnet import FullyConnectedNetwork as FCNet + from ray.rllib.models.torch.visionnet import VisionNetwork as VisionNet + from ray.rllib.models.torch.complex_input_net import ( + ComplexInputNetwork as ComplexNet, + ) + elif framework == "jax": + from ray.rllib.models.jax.fcnet import FullyConnectedNetwork as FCNet + else: + raise ValueError( + "framework={} not supported in `ModelCatalog._get_v2_model_" + "class`!".format(framework) + ) + + orig_space = ( + input_space + if not hasattr(input_space, "original_space") + else input_space.original_space + ) + + # `input_space` is 3D Box -> VisionNet. + if isinstance(input_space, Box) and len(input_space.shape) == 3: + if framework == "jax": + raise NotImplementedError("No non-FC default net for JAX yet!") + return VisionNet + # `input_space` is 1D Box -> FCNet. + elif ( + isinstance(input_space, Box) + and len(input_space.shape) == 1 + and ( + not isinstance(orig_space, (Dict, Tuple)) + or not any( + isinstance(s, Box) and len(s.shape) >= 2 + for s in flatten_space(orig_space) + ) + ) + ): + return FCNet + # Complex (Dict, Tuple, 2D Box (flatten), Discrete, MultiDiscrete). + else: + if framework == "jax": + raise NotImplementedError("No non-FC default net for JAX yet!") + return ComplexNet + + @staticmethod + def _get_multi_action_distribution(dist_class, action_space, config, framework): + # In case the custom distribution is a child of MultiActionDistr. + # If users want to completely ignore the suggested child + # distributions, they should simply do so in their custom class' + # constructor. + if issubclass( + dist_class, (MultiActionDistribution, TorchMultiActionDistribution) + ): + flat_action_space = flatten_space(action_space) + child_dists_and_in_lens = tree.map_structure( + lambda s: ModelCatalog.get_action_dist(s, config, framework=framework), + flat_action_space, + ) + child_dists = [e[0] for e in child_dists_and_in_lens] + input_lens = [int(e[1]) for e in child_dists_and_in_lens] + return ( + partial( + dist_class, + action_space=action_space, + child_distributions=child_dists, + input_lens=input_lens, + ), + int(sum(input_lens)), + ) + return dist_class, dist_class.required_model_output_shape(action_space, config) + + @staticmethod + def _validate_config( + config: ModelConfigDict, action_space: gym.spaces.Space, framework: str + ) -> None: + """Validates a given model config dict. + + Args: + config: The "model" sub-config dict + within the Algorithm's config dict. + action_space: The action space of the model, whose config are + validated. + framework: One of "jax", "tf2", "tf", or "torch". + + Raises: + ValueError: If something is wrong with the given config. + """ + # Soft-deprecate custom preprocessors. + if config.get("custom_preprocessor") is not None: + deprecation_warning( + old="model.custom_preprocessor", + new="gym.ObservationWrapper around your env or handle complex " + "inputs inside your Model", + error=True, + ) + + if config.get("use_attention") and config.get("use_lstm"): + raise ValueError( + "Only one of `use_lstm` or `use_attention` may be set to True!" + ) + + # For complex action spaces, only allow prev action inputs to + # LSTMs and attention nets iff `_disable_action_flattening=True`. + # TODO: `_disable_action_flattening=True` will be the default in + # the future. + if ( + ( + config.get("lstm_use_prev_action") + or config.get("attention_use_n_prev_actions", 0) > 0 + ) + and not config.get("_disable_action_flattening") + and isinstance(action_space, (Tuple, Dict)) + ): + raise ValueError( + "For your complex action space (Tuple|Dict) and your model's " + "`prev-actions` setup of your model, you must set " + "`_disable_action_flattening=True` in your main config dict!" + ) + + if framework == "jax": + if config.get("use_attention"): + raise ValueError( + "`use_attention` not available for framework=jax so far!" + ) + elif config.get("use_lstm"): + raise ValueError("`use_lstm` not available for framework=jax so far!") diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/distributions.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/distributions.py new file mode 100644 index 0000000000000000000000000000000000000000..dac7b108d6103ed513b2462440b6d7e58634d41a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/distributions.py @@ -0,0 +1,8 @@ +from ray.rllib.utils.deprecation import deprecation_warning +from ray.rllib.core.distribution.distribution import Distribution # noqa + +deprecation_warning( + old="ray.rllib.models.distributions.Distribution", + new="ray.rllib.core.distribution.distribution.Distribution", + error=False, +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/modelv2.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/modelv2.py new file mode 100644 index 0000000000000000000000000000000000000000..df07150e57bac2ead3c235f0abfe23f696921b5f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/modelv2.py @@ -0,0 +1,471 @@ +from collections import OrderedDict +import contextlib +import gymnasium as gym +from gymnasium.spaces import Space +import numpy as np +from typing import Dict, List, Any, Union + +from ray.rllib.models.preprocessors import get_preprocessor, RepeatedValuesPreprocessor +from ray.rllib.models.repeated_values import RepeatedValues +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy.view_requirement import ViewRequirement +from ray.rllib.utils import NullContextManager +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.deprecation import Deprecated +from ray.rllib.utils.framework import try_import_tf, try_import_torch, TensorType +from ray.rllib.utils.spaces.repeated import Repeated +from ray.rllib.utils.typing import ModelConfigDict, ModelInputDict, TensorStructType + +tf1, tf, tfv = try_import_tf() +torch, _ = try_import_torch() + + +@OldAPIStack +class ModelV2: + r"""Defines an abstract neural network model for use with RLlib. + + Custom models should extend either TFModelV2 or TorchModelV2 instead of + this class directly. + + Data flow: + obs -> forward() -> model_out + \-> value_function() -> V(s) + """ + + def __init__( + self, + obs_space: Space, + action_space: Space, + num_outputs: int, + model_config: ModelConfigDict, + name: str, + framework: str, + ): + """Initializes a ModelV2 instance. + + This method should create any variables used by the model. + + Args: + obs_space: Observation space of the target gym + env. This may have an `original_space` attribute that + specifies how to unflatten the tensor into a ragged tensor. + action_space: Action space of the target gym + env. + num_outputs: Number of output units of the model. + model_config: Config for the model, documented + in ModelCatalog. + name: Name (scope) for the model. + framework: Either "tf" or "torch". + """ + + self.obs_space: Space = obs_space + self.action_space: Space = action_space + self.num_outputs: int = num_outputs + self.model_config: ModelConfigDict = model_config + self.name: str = name or "default_model" + self.framework: str = framework + self._last_output = None + self.time_major = self.model_config.get("_time_major") + # Basic view requirement for all models: Use the observation as input. + self.view_requirements = { + SampleBatch.OBS: ViewRequirement(shift=0, space=self.obs_space), + } + + def get_initial_state(self) -> List[TensorType]: + """Get the initial recurrent state values for the model. + + Returns: + List of np.array (for tf) or Tensor (for torch) objects containing the + initial hidden state of an RNN, if applicable. + + .. testcode:: + :skipif: True + + import numpy as np + from ray.rllib.models.modelv2 import ModelV2 + class MyModel(ModelV2): + # ... + def get_initial_state(self): + return [ + np.zeros(self.cell_size, np.float32), + np.zeros(self.cell_size, np.float32), + ] + """ + return [] + + def forward( + self, + input_dict: Dict[str, TensorType], + state: List[TensorType], + seq_lens: TensorType, + ) -> (TensorType, List[TensorType]): + """Call the model with the given input tensors and state. + + Any complex observations (dicts, tuples, etc.) will be unpacked by + __call__ before being passed to forward(). To access the flattened + observation tensor, refer to input_dict["obs_flat"]. + + This method can be called any number of times. In eager execution, + each call to forward() will eagerly evaluate the model. In symbolic + execution, each call to forward creates a computation graph that + operates over the variables of this model (i.e., shares weights). + + Custom models should override this instead of __call__. + + Args: + input_dict: dictionary of input tensors, including "obs", + "obs_flat", "prev_action", "prev_reward", "is_training", + "eps_id", "agent_id", "infos", and "t". + state: list of state tensors with sizes matching those + returned by get_initial_state + the batch dimension + seq_lens: 1d tensor holding input sequence lengths + + Returns: + A tuple consisting of the model output tensor of size + [BATCH, num_outputs] and the list of new RNN state(s) if any. + + .. testcode:: + :skipif: True + + import numpy as np + from ray.rllib.models.modelv2 import ModelV2 + class MyModel(ModelV2): + # ... + def forward(self, input_dict, state, seq_lens): + model_out, self._value_out = self.base_model( + input_dict["obs"]) + return model_out, state + """ + raise NotImplementedError + + def value_function(self) -> TensorType: + """Returns the value function output for the most recent forward pass. + + Note that a `forward` call has to be performed first, before this + methods can return anything and thus that calling this method does not + cause an extra forward pass through the network. + + Returns: + Value estimate tensor of shape [BATCH]. + """ + raise NotImplementedError + + def custom_loss( + self, policy_loss: TensorType, loss_inputs: Dict[str, TensorType] + ) -> Union[List[TensorType], TensorType]: + """Override to customize the loss function used to optimize this model. + + This can be used to incorporate self-supervised losses (by defining + a loss over existing input and output tensors of this model), and + supervised losses (by defining losses over a variable-sharing copy of + this model's layers). + + You can find an runnable example in examples/custom_loss.py. + + Args: + policy_loss: List of or single policy loss(es) from the policy. + loss_inputs: map of input placeholders for rollout data. + + Returns: + List of or scalar tensor for the customized loss(es) for this + model. + """ + return policy_loss + + def metrics(self) -> Dict[str, TensorType]: + """Override to return custom metrics from your model. + + The stats will be reported as part of the learner stats, i.e., + info.learner.[policy_id, e.g. "default_policy"].model.key1=metric1 + + Returns: + The custom metrics for this model. + """ + return {} + + def __call__( + self, + input_dict: Union[SampleBatch, ModelInputDict], + state: List[Any] = None, + seq_lens: TensorType = None, + ) -> (TensorType, List[TensorType]): + """Call the model with the given input tensors and state. + + This is the method used by RLlib to execute the forward pass. It calls + forward() internally after unpacking nested observation tensors. + + Custom models should override forward() instead of __call__. + + Args: + input_dict: Dictionary of input tensors. + state: list of state tensors with sizes matching those + returned by get_initial_state + the batch dimension + seq_lens: 1D tensor holding input sequence lengths. + + Returns: + A tuple consisting of the model output tensor of size + [BATCH, output_spec.size] or a list of tensors corresponding to + output_spec.shape_list, and a list of state tensors of + [BATCH, state_size_i] if any. + """ + + # Original observations will be stored in "obs". + # Flattened (preprocessed) obs will be stored in "obs_flat". + + # SampleBatch case: Models can now be called directly with a + # SampleBatch (which also includes tracking-dict case (deprecated now), + # where tensors get automatically converted). + if isinstance(input_dict, SampleBatch): + restored = input_dict.copy(shallow=True) + else: + restored = input_dict.copy() + + # Backward compatibility. + if not state: + state = [] + i = 0 + while "state_in_{}".format(i) in input_dict: + state.append(input_dict["state_in_{}".format(i)]) + i += 1 + if seq_lens is None: + seq_lens = input_dict.get(SampleBatch.SEQ_LENS) + + # No Preprocessor used: `config._disable_preprocessor_api`=True. + # TODO: This is unnecessary for when no preprocessor is used. + # Obs are not flat then anymore. However, we'll keep this + # here for backward-compatibility until Preprocessors have + # been fully deprecated. + if self.model_config.get("_disable_preprocessor_api"): + restored["obs_flat"] = input_dict["obs"] + # Input to this Model went through a Preprocessor. + # Generate extra keys: "obs_flat" (vs "obs", which will hold the + # original obs). + else: + restored["obs"] = restore_original_dimensions( + input_dict["obs"], self.obs_space, self.framework + ) + try: + if len(input_dict["obs"].shape) > 2: + restored["obs_flat"] = flatten(input_dict["obs"], self.framework) + else: + restored["obs_flat"] = input_dict["obs"] + except AttributeError: + restored["obs_flat"] = input_dict["obs"] + + with self.context(): + res = self.forward(restored, state or [], seq_lens) + + if isinstance(input_dict, SampleBatch): + input_dict.accessed_keys = restored.accessed_keys - {"obs_flat"} + input_dict.deleted_keys = restored.deleted_keys + input_dict.added_keys = restored.added_keys - {"obs_flat"} + + if (not isinstance(res, list) and not isinstance(res, tuple)) or len(res) != 2: + raise ValueError( + "forward() must return a tuple of (output, state) tensors, " + "got {}".format(res) + ) + outputs, state_out = res + + if not isinstance(state_out, list): + raise ValueError("State output is not a list: {}".format(state_out)) + + self._last_output = outputs + return outputs, state_out if len(state_out) > 0 else (state or []) + + def last_output(self) -> TensorType: + """Returns the last output returned from calling the model.""" + return self._last_output + + def context(self) -> contextlib.AbstractContextManager: + """Returns a contextmanager for the current forward pass.""" + return NullContextManager() + + def variables( + self, as_dict: bool = False + ) -> Union[List[TensorType], Dict[str, TensorType]]: + """Returns the list (or a dict) of variables for this model. + + Args: + as_dict: Whether variables should be returned as dict-values + (using descriptive str keys). + + Returns: + The list (or dict if `as_dict` is True) of all variables of this + ModelV2. + """ + raise NotImplementedError + + def trainable_variables( + self, as_dict: bool = False + ) -> Union[List[TensorType], Dict[str, TensorType]]: + """Returns the list of trainable variables for this model. + + Args: + as_dict: Whether variables should be returned as dict-values + (using descriptive keys). + + Returns: + The list (or dict if `as_dict` is True) of all trainable + (tf)/requires_grad (torch) variables of this ModelV2. + """ + raise NotImplementedError + + def is_time_major(self) -> bool: + """If True, data for calling this ModelV2 must be in time-major format. + + Returns + Whether this ModelV2 requires a time-major (TxBx...) data + format. + """ + return self.time_major is True + + @Deprecated(error=True) + def import_from_h5(self, *args, **kwargs): + pass + + +@OldAPIStack +def flatten(obs: TensorType, framework: str) -> TensorType: + """Flatten the given tensor.""" + if framework in ["tf2", "tf"]: + return tf1.keras.layers.Flatten()(obs) + elif framework == "torch": + assert torch is not None + return torch.flatten(obs, start_dim=1) + else: + raise NotImplementedError("flatten", framework) + + +@OldAPIStack +def restore_original_dimensions( + obs: TensorType, obs_space: Space, tensorlib: Any = tf +) -> TensorStructType: + """Unpacks Dict and Tuple space observations into their original form. + + This is needed since we flatten Dict and Tuple observations in transit + within a SampleBatch. Before sending them to the model though, we should + unflatten them into Dicts or Tuples of tensors. + + Args: + obs: The flattened observation tensor. + obs_space: The flattened obs space. If this has the + `original_space` attribute, we will unflatten the tensor to that + shape. + tensorlib: The library used to unflatten (reshape) the array/tensor. + + Returns: + single tensor or dict / tuple of tensors matching the original + observation space. + """ + + if tensorlib in ["tf", "tf2"]: + assert tf is not None + tensorlib = tf + elif tensorlib == "torch": + assert torch is not None + tensorlib = torch + elif tensorlib == "numpy": + assert np is not None + tensorlib = np + original_space = getattr(obs_space, "original_space", obs_space) + return _unpack_obs(obs, original_space, tensorlib=tensorlib) + + +# Cache of preprocessors, for if the user is calling unpack obs often. +_cache = {} + + +@OldAPIStack +def _unpack_obs(obs: TensorType, space: Space, tensorlib: Any = tf) -> TensorStructType: + """Unpack a flattened Dict or Tuple observation array/tensor. + + Args: + obs: The flattened observation tensor, with last dimension equal to + the flat size and any number of batch dimensions. For example, for + Box(4,), the obs may have shape [B, 4], or [B, N, M, 4] in case + the Box was nested under two Repeated spaces. + space: The original space prior to flattening + tensorlib: The library used to unflatten (reshape) the array/tensor + """ + + if isinstance(space, (gym.spaces.Dict, gym.spaces.Tuple, Repeated)): + # Already unpacked? + if (isinstance(space, gym.spaces.Tuple) and isinstance(obs, (list, tuple))) or ( + isinstance(space, gym.spaces.Dict) and isinstance(obs, dict) + ): + return obs + # Unpack using preprocessor + if id(space) in _cache: + prep = _cache[id(space)] + else: + prep = get_preprocessor(space)(space) + # Make an attempt to cache the result, if enough space left. + if len(_cache) < 999: + _cache[id(space)] = prep + if len(obs.shape) < 2 or obs.shape[-1] != prep.shape[0]: + raise ValueError( + "Expected flattened obs shape of [..., {}], got {}".format( + prep.shape[0], obs.shape + ) + ) + offset = 0 + if tensorlib == tf: + + def get_value(v): + if v is None: + return -1 + elif isinstance(v, int): + return v + elif v.value is None: + return -1 + else: + return v.value + + batch_dims = [get_value(v) for v in obs.shape[:-1]] + else: + batch_dims = list(obs.shape[:-1]) + if isinstance(space, gym.spaces.Tuple): + assert len(prep.preprocessors) == len(space.spaces), len( + prep.preprocessors + ) == len(space.spaces) + u = [] + for p, v in zip(prep.preprocessors, space.spaces): + obs_slice = obs[..., offset : offset + p.size] + offset += p.size + u.append( + _unpack_obs( + tensorlib.reshape(obs_slice, batch_dims + list(p.shape)), + v, + tensorlib=tensorlib, + ) + ) + elif isinstance(space, gym.spaces.Dict): + assert len(prep.preprocessors) == len(space.spaces), len( + prep.preprocessors + ) == len(space.spaces) + u = OrderedDict() + for p, (k, v) in zip(prep.preprocessors, space.spaces.items()): + obs_slice = obs[..., offset : offset + p.size] + offset += p.size + u[k] = _unpack_obs( + tensorlib.reshape(obs_slice, batch_dims + list(p.shape)), + v, + tensorlib=tensorlib, + ) + # Repeated space. + else: + assert isinstance(prep, RepeatedValuesPreprocessor), prep + child_size = prep.child_preprocessor.size + # The list lengths are stored in the first slot of the flat obs. + lengths = obs[..., 0] + # [B, ..., 1 + max_len * child_sz] -> [B, ..., max_len, child_sz] + with_repeat_dim = tensorlib.reshape( + obs[..., 1:], batch_dims + [space.max_len, child_size] + ) + # Retry the unpack, dropping the List container space. + u = _unpack_obs(with_repeat_dim, space.child_space, tensorlib=tensorlib) + return RepeatedValues(u, lengths=lengths, max_len=prep._obs_space.max_len) + return u + else: + return obs diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/preprocessors.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/preprocessors.py new file mode 100644 index 0000000000000000000000000000000000000000..ad15d0c155124e38ba7fb8c84b162b7a564d4c9a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/preprocessors.py @@ -0,0 +1,447 @@ +from collections import OrderedDict +import logging +import numpy as np +import gymnasium as gym +from typing import Any, List + +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.spaces.repeated import Repeated +from ray.rllib.utils.typing import TensorType +from ray.rllib.utils.images import resize +from ray.rllib.utils.spaces.space_utils import convert_element_to_space_type + +ATARI_OBS_SHAPE = (210, 160, 3) +ATARI_RAM_OBS_SHAPE = (128,) + +# Only validate env observations vs the observation space every n times in a +# Preprocessor. +OBS_VALIDATION_INTERVAL = 100 + +logger = logging.getLogger(__name__) + + +@OldAPIStack +class Preprocessor: + """Defines an abstract observation preprocessor function. + + Attributes: + shape (List[int]): Shape of the preprocessed output. + """ + + def __init__(self, obs_space: gym.Space, options: dict = None): + _legacy_patch_shapes(obs_space) + self._obs_space = obs_space + if not options: + from ray.rllib.models.catalog import MODEL_DEFAULTS + + self._options = MODEL_DEFAULTS.copy() + else: + self._options = options + self.shape = self._init_shape(obs_space, self._options) + self._size = int(np.prod(self.shape)) + self._i = 0 + self._obs_for_type_matching = self._obs_space.sample() + + def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]: + """Returns the shape after preprocessing.""" + raise NotImplementedError + + def transform(self, observation: TensorType) -> np.ndarray: + """Returns the preprocessed observation.""" + raise NotImplementedError + + def write(self, observation: TensorType, array: np.ndarray, offset: int) -> None: + """Alternative to transform for more efficient flattening.""" + array[offset : offset + self._size] = self.transform(observation) + + def check_shape(self, observation: Any) -> None: + """Checks the shape of the given observation.""" + if self._i % OBS_VALIDATION_INTERVAL == 0: + # Convert lists to np.ndarrays. + if type(observation) is list and isinstance( + self._obs_space, gym.spaces.Box + ): + observation = np.array(observation).astype(np.float32) + if not self._obs_space.contains(observation): + observation = convert_element_to_space_type( + observation, self._obs_for_type_matching + ) + try: + if not self._obs_space.contains(observation): + raise ValueError( + "Observation ({} dtype={}) outside given space ({})!".format( + observation, + observation.dtype + if isinstance(self._obs_space, gym.spaces.Box) + else None, + self._obs_space, + ) + ) + except AttributeError as e: + raise ValueError( + "Observation for a Box/MultiBinary/MultiDiscrete space " + "should be an np.array, not a Python list.", + observation, + ) from e + self._i += 1 + + @property + def size(self) -> int: + return self._size + + @property + def observation_space(self) -> gym.Space: + obs_space = gym.spaces.Box(-1.0, 1.0, self.shape, dtype=np.float32) + # Stash the unwrapped space so that we can unwrap dict and tuple spaces + # automatically in modelv2.py + classes = ( + DictFlatteningPreprocessor, + OneHotPreprocessor, + RepeatedValuesPreprocessor, + TupleFlatteningPreprocessor, + AtariRamPreprocessor, + GenericPixelPreprocessor, + ) + if isinstance(self, classes): + obs_space.original_space = self._obs_space + return obs_space + + +@OldAPIStack +class GenericPixelPreprocessor(Preprocessor): + """Generic image preprocessor. + + Note: for Atari games, use config {"preprocessor_pref": "deepmind"} + instead for deepmind-style Atari preprocessing. + """ + + @override(Preprocessor) + def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]: + self._grayscale = options.get("grayscale") + self._zero_mean = options.get("zero_mean") + self._dim = options.get("dim") + if self._grayscale: + shape = (self._dim, self._dim, 1) + else: + shape = (self._dim, self._dim, 3) + + return shape + + @override(Preprocessor) + def transform(self, observation: TensorType) -> np.ndarray: + """Downsamples images from (210, 160, 3) by the configured factor.""" + self.check_shape(observation) + scaled = observation[25:-25, :, :] + if self._dim < 84: + scaled = resize(scaled, height=84, width=84) + # OpenAI: Resize by half, then down to 42x42 (essentially mipmapping). + # If we resize directly we lose pixels that, when mapped to 42x42, + # aren't close enough to the pixel boundary. + scaled = resize(scaled, height=self._dim, width=self._dim) + if self._grayscale: + scaled = scaled.mean(2) + scaled = scaled.astype(np.float32) + # Rescale needed for maintaining 1 channel + scaled = np.reshape(scaled, [self._dim, self._dim, 1]) + if self._zero_mean: + scaled = (scaled - 128) / 128 + else: + scaled *= 1.0 / 255.0 + return scaled + + +@OldAPIStack +class AtariRamPreprocessor(Preprocessor): + @override(Preprocessor) + def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]: + return (128,) + + @override(Preprocessor) + def transform(self, observation: TensorType) -> np.ndarray: + self.check_shape(observation) + return (observation.astype("float32") - 128) / 128 + + +@OldAPIStack +class OneHotPreprocessor(Preprocessor): + """One-hot preprocessor for Discrete and MultiDiscrete spaces. + + .. testcode:: + :skipif: True + + self.transform(Discrete(3).sample()) + + .. testoutput:: + + np.array([0.0, 1.0, 0.0]) + + .. testcode:: + :skipif: True + + self.transform(MultiDiscrete([2, 3]).sample()) + + .. testoutput:: + + np.array([0.0, 1.0, 0.0, 0.0, 1.0]) + """ + + @override(Preprocessor) + def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]: + if isinstance(obs_space, gym.spaces.Discrete): + return (self._obs_space.n,) + else: + return (np.sum(self._obs_space.nvec),) + + @override(Preprocessor) + def transform(self, observation: TensorType) -> np.ndarray: + self.check_shape(observation) + return gym.spaces.utils.flatten(self._obs_space, observation).astype(np.float32) + + @override(Preprocessor) + def write(self, observation: TensorType, array: np.ndarray, offset: int) -> None: + array[offset : offset + self.size] = self.transform(observation) + + +@OldAPIStack +class NoPreprocessor(Preprocessor): + @override(Preprocessor) + def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]: + return self._obs_space.shape + + @override(Preprocessor) + def transform(self, observation: TensorType) -> np.ndarray: + self.check_shape(observation) + return observation + + @override(Preprocessor) + def write(self, observation: TensorType, array: np.ndarray, offset: int) -> None: + array[offset : offset + self._size] = np.array(observation, copy=False).ravel() + + @property + @override(Preprocessor) + def observation_space(self) -> gym.Space: + return self._obs_space + + +@OldAPIStack +class MultiBinaryPreprocessor(Preprocessor): + """Preprocessor that turns a MultiBinary space into a Box. + + Note: Before RLModules were introduced, RLlib's ModelCatalogV2 would produce + ComplexInputNetworks that treat MultiBinary spaces as Boxes. This preprocessor is + needed to get rid of the ComplexInputNetworks and use RLModules instead because + RLModules lack the logic to handle MultiBinary or other non-Box spaces. + """ + + @override(Preprocessor) + def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]: + return self._obs_space.shape + + @override(Preprocessor) + def transform(self, observation: TensorType) -> np.ndarray: + # The shape stays the same, but the dtype changes. + self.check_shape(observation) + return observation.astype(np.float32) + + @override(Preprocessor) + def write(self, observation: TensorType, array: np.ndarray, offset: int) -> None: + array[offset : offset + self._size] = np.array(observation, copy=False).ravel() + + @property + @override(Preprocessor) + def observation_space(self) -> gym.Space: + obs_space = gym.spaces.Box(0.0, 1.0, self.shape, dtype=np.float32) + obs_space.original_space = self._obs_space + return obs_space + + +@OldAPIStack +class TupleFlatteningPreprocessor(Preprocessor): + """Preprocesses each tuple element, then flattens it all into a vector. + + RLlib models will unpack the flattened output before _build_layers_v2(). + """ + + @override(Preprocessor) + def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]: + assert isinstance(self._obs_space, gym.spaces.Tuple) + size = 0 + self.preprocessors = [] + for i in range(len(self._obs_space.spaces)): + space = self._obs_space.spaces[i] + logger.debug("Creating sub-preprocessor for {}".format(space)) + preprocessor_class = get_preprocessor(space) + if preprocessor_class is not None: + preprocessor = preprocessor_class(space, self._options) + size += preprocessor.size + else: + preprocessor = None + size += int(np.prod(space.shape)) + self.preprocessors.append(preprocessor) + return (size,) + + @override(Preprocessor) + def transform(self, observation: TensorType) -> np.ndarray: + self.check_shape(observation) + array = np.zeros(self.shape, dtype=np.float32) + self.write(observation, array, 0) + return array + + @override(Preprocessor) + def write(self, observation: TensorType, array: np.ndarray, offset: int) -> None: + assert len(observation) == len(self.preprocessors), observation + for o, p in zip(observation, self.preprocessors): + p.write(o, array, offset) + offset += p.size + + +@OldAPIStack +class DictFlatteningPreprocessor(Preprocessor): + """Preprocesses each dict value, then flattens it all into a vector. + + RLlib models will unpack the flattened output before _build_layers_v2(). + """ + + @override(Preprocessor) + def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]: + assert isinstance(self._obs_space, gym.spaces.Dict) + size = 0 + self.preprocessors = [] + for space in self._obs_space.spaces.values(): + logger.debug("Creating sub-preprocessor for {}".format(space)) + preprocessor_class = get_preprocessor(space) + if preprocessor_class is not None: + preprocessor = preprocessor_class(space, self._options) + size += preprocessor.size + else: + preprocessor = None + size += int(np.prod(space.shape)) + self.preprocessors.append(preprocessor) + return (size,) + + @override(Preprocessor) + def transform(self, observation: TensorType) -> np.ndarray: + self.check_shape(observation) + array = np.zeros(self.shape, dtype=np.float32) + self.write(observation, array, 0) + return array + + @override(Preprocessor) + def write(self, observation: TensorType, array: np.ndarray, offset: int) -> None: + if not isinstance(observation, OrderedDict): + observation = OrderedDict(sorted(observation.items())) + assert len(observation) == len(self.preprocessors), ( + len(observation), + len(self.preprocessors), + ) + for o, p in zip(observation.values(), self.preprocessors): + p.write(o, array, offset) + offset += p.size + + +@OldAPIStack +class RepeatedValuesPreprocessor(Preprocessor): + """Pads and batches the variable-length list value.""" + + @override(Preprocessor) + def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]: + assert isinstance(self._obs_space, Repeated) + child_space = obs_space.child_space + self.child_preprocessor = get_preprocessor(child_space)( + child_space, self._options + ) + # The first slot encodes the list length. + size = 1 + self.child_preprocessor.size * obs_space.max_len + return (size,) + + @override(Preprocessor) + def transform(self, observation: TensorType) -> np.ndarray: + array = np.zeros(self.shape) + if isinstance(observation, list): + for elem in observation: + self.child_preprocessor.check_shape(elem) + else: + pass # ValueError will be raised in write() below. + self.write(observation, array, 0) + return array + + @override(Preprocessor) + def write(self, observation: TensorType, array: np.ndarray, offset: int) -> None: + if not isinstance(observation, (list, np.ndarray)): + raise ValueError( + "Input for {} must be list type, got {}".format(self, observation) + ) + elif len(observation) > self._obs_space.max_len: + raise ValueError( + "Input {} exceeds max len of space {}".format( + observation, self._obs_space.max_len + ) + ) + # The first slot encodes the list length. + array[offset] = len(observation) + for i, elem in enumerate(observation): + offset_i = offset + 1 + i * self.child_preprocessor.size + self.child_preprocessor.write(elem, array, offset_i) + + +@OldAPIStack +def get_preprocessor(space: gym.Space, include_multi_binary=False) -> type: + """Returns an appropriate preprocessor class for the given space.""" + + _legacy_patch_shapes(space) + obs_shape = space.shape + + if isinstance(space, (gym.spaces.Discrete, gym.spaces.MultiDiscrete)): + preprocessor = OneHotPreprocessor + elif obs_shape == ATARI_OBS_SHAPE: + logger.debug( + "Defaulting to RLlib's GenericPixelPreprocessor because input " + "space has the atari-typical shape {}. Turn this behaviour off by setting " + "`preprocessor_pref=None` or " + "`preprocessor_pref='deepmind'` or disabling the preprocessing API " + "altogether with `_disable_preprocessor_api=True`.".format(ATARI_OBS_SHAPE) + ) + preprocessor = GenericPixelPreprocessor + elif obs_shape == ATARI_RAM_OBS_SHAPE: + logger.debug( + "Defaulting to RLlib's AtariRamPreprocessor because input " + "space has the atari-typical shape {}. Turn this behaviour off by setting " + "`preprocessor_pref=None` or " + "`preprocessor_pref='deepmind' or disabling the preprocessing API " + "altogether with `_disable_preprocessor_api=True`." + "`.".format(ATARI_OBS_SHAPE) + ) + preprocessor = AtariRamPreprocessor + elif isinstance(space, gym.spaces.Tuple): + preprocessor = TupleFlatteningPreprocessor + elif isinstance(space, gym.spaces.Dict): + preprocessor = DictFlatteningPreprocessor + elif isinstance(space, Repeated): + preprocessor = RepeatedValuesPreprocessor + # We usually only want to include this when using RLModules + elif isinstance(space, gym.spaces.MultiBinary) and include_multi_binary: + preprocessor = MultiBinaryPreprocessor + else: + preprocessor = NoPreprocessor + + return preprocessor + + +def _legacy_patch_shapes(space: gym.Space) -> List[int]: + """Assigns shapes to spaces that don't have shapes. + + This is only needed for older gym versions that don't set shapes properly + for Tuple and Discrete spaces. + """ + + if not hasattr(space, "shape"): + if isinstance(space, gym.spaces.Discrete): + space.shape = () + elif isinstance(space, gym.spaces.Tuple): + shapes = [] + for s in space.spaces: + shape = _legacy_patch_shapes(s) + shapes.append(shape) + space.shape = tuple(shapes) + + return space.shape diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/repeated_values.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/repeated_values.py new file mode 100644 index 0000000000000000000000000000000000000000..7ecef777f667bffec0008bb0b1fdf1aa7c88d52e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/repeated_values.py @@ -0,0 +1,204 @@ +from typing import List + +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.typing import TensorType, TensorStructType + + +@OldAPIStack +class RepeatedValues: + """Represents a variable-length list of items from spaces.Repeated. + + RepeatedValues are created when you use spaces.Repeated, and are + accessible as part of input_dict["obs"] in ModelV2 forward functions. + + Example: + Suppose the gym space definition was: + Repeated(Repeated(Box(K), N), M) + + Then in the model forward function, input_dict["obs"] is of type: + RepeatedValues(RepeatedValues()) + + The tensor is accessible via: + input_dict["obs"].values.values + + And the actual data lengths via: + # outer repetition, shape [B], range [0, M] + input_dict["obs"].lengths + -and- + # inner repetition, shape [B, M], range [0, N] + input_dict["obs"].values.lengths + + Attributes: + values: The padded data tensor of shape [B, max_len, ..., sz], + where B is the batch dimension, max_len is the max length of this + list, followed by any number of sub list max lens, followed by the + actual data size. + lengths (List[int]): Tensor of shape [B, ...] that represents the + number of valid items in each list. When the list is nested within + other lists, there will be extra dimensions for the parent list + max lens. + max_len: The max number of items allowed in each list. + + TODO(ekl): support conversion to tf.RaggedTensor. + """ + + def __init__(self, values: TensorType, lengths: List[int], max_len: int): + self.values = values + self.lengths = lengths + self.max_len = max_len + self._unbatched_repr = None + + def unbatch_all(self) -> List[List[TensorType]]: + """Unbatch both the repeat and batch dimensions into Python lists. + + This is only supported in PyTorch / TF eager mode. + + This lets you view the data unbatched in its original form, but is + not efficient for processing. + + .. testcode:: + :skipif: True + + batch = RepeatedValues() + items = batch.unbatch_all() + print(len(items) == B) + + .. testoutput:: + + True + + .. testcode:: + :skipif: True + + print(max(len(x) for x in items) <= N) + + .. testoutput:: + + True + + .. testcode:: + :skipif: True + + print(items) + + .. testoutput:: + + [[, ..., ], + ... + [, ], + ... + [], + ... + [, ..., ]] + """ + + if self._unbatched_repr is None: + B = _get_batch_dim_helper(self.values) + if B is None: + raise ValueError( + "Cannot call unbatch_all() when batch_dim is unknown. " + "This is probably because you are using TF graph mode." + ) + else: + B = int(B) + slices = self.unbatch_repeat_dim() + result = [] + for i in range(B): + if hasattr(self.lengths[i], "item"): + dynamic_len = int(self.lengths[i].item()) + else: + dynamic_len = int(self.lengths[i].numpy()) + dynamic_slice = [] + for j in range(dynamic_len): + dynamic_slice.append(_batch_index_helper(slices, i, j)) + result.append(dynamic_slice) + self._unbatched_repr = result + + return self._unbatched_repr + + def unbatch_repeat_dim(self) -> List[TensorType]: + """Unbatches the repeat dimension (the one `max_len` in size). + + This removes the repeat dimension. The result will be a Python list of + with length `self.max_len`. Note that the data is still padded. + + .. testcode:: + :skipif: True + + batch = RepeatedValues() + items = batch.unbatch() + len(items) == batch.max_len + + .. testoutput:: + + True + + .. testcode:: + :skipif: True + + print(items) + + .. testoutput:: + + [, ..., ] + """ + return _unbatch_helper(self.values, self.max_len) + + def __repr__(self): + return "RepeatedValues(value={}, lengths={}, max_len={})".format( + repr(self.values), repr(self.lengths), self.max_len + ) + + def __str__(self): + return repr(self) + + +def _get_batch_dim_helper(v: TensorStructType) -> int: + """Tries to find the batch dimension size of v, or None.""" + if isinstance(v, dict): + for u in v.values(): + return _get_batch_dim_helper(u) + elif isinstance(v, tuple): + return _get_batch_dim_helper(v[0]) + elif isinstance(v, RepeatedValues): + return _get_batch_dim_helper(v.values) + else: + B = v.shape[0] + if hasattr(B, "value"): + B = B.value # TensorFlow + return B + + +def _unbatch_helper(v: TensorStructType, max_len: int) -> TensorStructType: + """Recursively unpacks the repeat dimension (max_len).""" + if isinstance(v, dict): + return {k: _unbatch_helper(u, max_len) for (k, u) in v.items()} + elif isinstance(v, tuple): + return tuple(_unbatch_helper(u, max_len) for u in v) + elif isinstance(v, RepeatedValues): + unbatched = _unbatch_helper(v.values, max_len) + return [ + RepeatedValues(u, v.lengths[:, i, ...], v.max_len) + for i, u in enumerate(unbatched) + ] + else: + return [v[:, i, ...] for i in range(max_len)] + + +def _batch_index_helper(v: TensorStructType, i: int, j: int) -> TensorStructType: + """Selects the item at the ith batch index and jth repetition.""" + if isinstance(v, dict): + return {k: _batch_index_helper(u, i, j) for (k, u) in v.items()} + elif isinstance(v, tuple): + return tuple(_batch_index_helper(u, i, j) for u in v) + elif isinstance(v, list): + # This is the output of unbatch_repeat_dim(). Unfortunately we have to + # process it here instead of in unbatch_all(), since it may be buried + # under a dict / tuple. + return _batch_index_helper(v[j], i, j) + elif isinstance(v, RepeatedValues): + unbatched = v.unbatch_all() + # Don't need to select j here; that's already done in unbatch_all. + return unbatched[i] + else: + return v[i, ...] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0849a098440e6ea70237bf3a57d1bb6cc6924bd5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/models/utils.py @@ -0,0 +1,291 @@ +from typing import Callable, Optional, Union + +from ray.rllib.utils.annotations import DeveloperAPI +from ray.rllib.utils.framework import try_import_jax, try_import_tf, try_import_torch + + +@DeveloperAPI +def get_activation_fn( + name: Optional[Union[Callable, str]] = None, + framework: str = "tf", +): + """Returns a framework specific activation function, given a name string. + + Args: + name: One of "relu" (default), "tanh", "elu", + "swish" (or "silu", which is the same), or "linear" (same as None). + framework: One of "jax", "tf|tf2" or "torch". + + Returns: + A framework-specific activtion function. e.g. tf.nn.tanh or + torch.nn.ReLU. None if name in ["linear", None]. + + Raises: + ValueError: If name is an unknown activation function. + """ + # Already a callable, return as-is. + if callable(name): + return name + + name_lower = name.lower() if isinstance(name, str) else name + + # Infer the correct activation function from the string specifier. + if framework == "torch": + if name_lower in ["linear", None]: + return None + + _, nn = try_import_torch() + # First try getting the correct activation function from nn directly. + # Note that torch activation functions are not all lower case. + fn = getattr(nn, name, None) + if fn is not None: + return fn + + if name_lower in ["swish", "silu"]: + return nn.SiLU + elif name_lower == "relu": + return nn.ReLU + elif name_lower == "tanh": + return nn.Tanh + elif name_lower == "elu": + return nn.ELU + elif name_lower == "softmax": + return nn.Softmax + elif framework == "jax": + if name_lower in ["linear", None]: + return None + jax, _ = try_import_jax() + if name_lower in ["swish", "silu"]: + return jax.nn.swish + if name_lower == "relu": + return jax.nn.relu + elif name_lower == "tanh": + return jax.nn.hard_tanh + elif name_lower == "elu": + return jax.nn.elu + else: + assert framework in ["tf", "tf2"], "Unsupported framework `{}`!".format( + framework + ) + if name_lower in ["linear", None]: + return None + + tf1, tf, tfv = try_import_tf() + # Try getting the correct activation function from tf.nn directly. + # Note that tf activation functions are all lower case, so this should always + # work. + fn = getattr(tf.nn, name_lower, None) + + if fn is not None: + return fn + + raise ValueError( + "Unknown activation ({}) for framework={}!".format(name, framework) + ) + + +@DeveloperAPI +def get_initializer_fn(name: Optional[Union[str, Callable]], framework: str = "torch"): + """Returns the framework-specific initializer class or function. + + This function relies fully on the specified initializer classes and + functions in the frameworks `torch` and `tf2` (see for `torch` + https://pytorch.org/docs/stable/nn.init.html and for `tf2` see + https://www.tensorflow.org/api_docs/python/tf/keras/initializers). + + Note, for framework `torch` the in-place initializers are needed, i.e. names + should end with an underscore `_`, e.g. `glorot_uniform_`. + + Args: + name: Name of the initializer class or function in one of the two + supported frameworks, i.e. `torch` or `tf2`. + framework: The framework string, either `torch or `tf2`. + + Returns: + A framework-specific function or class defining an initializer to be used + for network initialization, + + Raises: + `ValueError` if the `name` is neither class or function in the specified + `framework`. Raises also a `ValueError`, if `name` does not define an + in-place initializer for framework `torch`. + """ + # Already a callable or `None` return as is. If `None` we use the default + # initializer defined in the framework-specific layers themselves. + if callable(name) or name is None: + return name + + if framework == "torch": + name_lower = name.lower() if isinstance(name, str) else name + + _, nn = try_import_torch() + + # Check, if the name includes an underscore. We must use the + # in-place initialization from Torch. + if not name_lower.endswith("_"): + raise ValueError( + "Not an in-place initializer: Torch weight initializers " + "need to be provided as their in-place version, i.e. " + " + '_'. See " + "https://pytorch.org/docs/stable/nn.init.html. " + f"User provided {name}." + ) + + # First, try to get the initialization directly from `nn.init`. + # Note, that all initialization methods in `nn.init` are lower + # case and that `_` defines the "in-place" method. + fn = getattr(nn.init, name_lower, None) + if fn is not None: + # TODO (simon): Raise a warning if not "in-place" method. + return fn + # Unknown initializer. + else: + # Inform the user that this initializer does not exist. + raise ValueError( + f"Unknown initializer name: {name_lower} is not a method in " + "`torch.nn.init`!" + ) + elif framework == "tf2": + # Note, as initializer classes in TensorFlow can be either given by their + # name in camel toe typing or by their shortcut we use the `name` as it is. + # See https://www.tensorflow.org/api_docs/python/tf/keras/initializers. + + _, tf, _ = try_import_tf() + + # Try to get the initialization function directly from `tf.keras.initializers`. + fn = getattr(tf.keras.initializers, name, None) + if fn is not None: + return fn + # Unknown initializer. + else: + # Inform the user that this initializer does not exist. + raise ValueError( + f"Unknown initializer: {name} is not a initializer in " + "`tf.keras.initializers`!" + ) + + +@DeveloperAPI +def get_filter_config(shape): + """Returns a default Conv2D filter config (list) for a given image shape. + + Args: + shape (Tuple[int]): The input (image) shape, e.g. (84,84,3). + + Returns: + List[list]: The Conv2D filter configuration usable as `conv_filters` + inside a model config dict. + """ + # 96x96x3 (e.g. CarRacing-v0). + filters_96x96 = [ + [16, [8, 8], 4], + [32, [4, 4], 2], + [256, [11, 11], 2], + ] + # Atari. + filters_84x84 = [ + [16, [8, 8], 4], + [32, [4, 4], 2], + [256, [11, 11], 1], + ] + # Dreamer-style (XS-sized model) Atari or DM Control Suite. + filters_64x64 = [ + [16, [4, 4], 2], + [32, [4, 4], 2], + [64, [4, 4], 2], + [128, [4, 4], 2], + ] + # Small (1/2) Atari. + filters_42x42 = [ + [16, [4, 4], 2], + [32, [4, 4], 2], + [256, [11, 11], 1], + ] + # Test image (10x10). + filters_10x10 = [ + [16, [5, 5], 2], + [32, [5, 5], 2], + ] + + shape = list(shape) + if len(shape) in [2, 3] and (shape[:2] == [96, 96] or shape[1:] == [96, 96]): + return filters_96x96 + elif len(shape) in [2, 3] and (shape[:2] == [84, 84] or shape[1:] == [84, 84]): + return filters_84x84 + elif len(shape) in [2, 3] and (shape[:2] == [64, 64] or shape[1:] == [64, 64]): + return filters_64x64 + elif len(shape) in [2, 3] and (shape[:2] == [42, 42] or shape[1:] == [42, 42]): + return filters_42x42 + elif len(shape) in [2, 3] and (shape[:2] == [10, 10] or shape[1:] == [10, 10]): + return filters_10x10 + else: + if list(shape) == [210, 160, 3]: + atari_help = ( + "This is the default atari obs shape. You may want to look at one of " + "RLlib's Atari examples for an example of how to wrap an Atari env. " + ) + else: + atari_help = "" + raise ValueError( + "No default CNN configuration for obs shape {}. ".format(shape) + + atari_help + + "You can specify `conv_filters` manually through your " + "AlgorithmConfig's model_config. " + "Default configurations are only available for inputs of the following " + "shapes: [42, 42, K], [84, 84, K], [64, 64, K], [10, 10, K]. You may " + "want to use a custom RLModule or a ConnectorV2 for that." + ) + + +@DeveloperAPI +def get_initializer(name, framework="tf"): + """Returns a framework specific initializer, given a name string. + + Args: + name: One of "xavier_uniform" (default), "xavier_normal". + framework: One of "jax", "tf|tf2" or "torch". + + Returns: + A framework-specific initializer function, e.g. + tf.keras.initializers.GlorotUniform or + torch.nn.init.xavier_uniform_. + + Raises: + ValueError: If name is an unknown initializer. + """ + # Already a callable, return as-is. + if callable(name): + return name + + if framework == "jax": + _, flax = try_import_jax() + assert flax is not None, "`flax` not installed. Try `pip install jax flax`." + import flax.linen as nn + + if name in [None, "default", "xavier_uniform"]: + return nn.initializers.xavier_uniform() + elif name == "xavier_normal": + return nn.initializers.xavier_normal() + if framework == "torch": + _, nn = try_import_torch() + assert nn is not None, "`torch` not installed. Try `pip install torch`." + if name in [None, "default", "xavier_uniform"]: + return nn.init.xavier_uniform_ + elif name == "xavier_normal": + return nn.init.xavier_normal_ + else: + assert framework in ["tf", "tf2"], "Unsupported framework `{}`!".format( + framework + ) + tf1, tf, tfv = try_import_tf() + assert ( + tf is not None + ), "`tensorflow` not installed. Try `pip install tensorflow`." + if name in [None, "default", "xavier_uniform"]: + return tf.keras.initializers.GlorotUniform + elif name == "xavier_normal": + return tf.keras.initializers.GlorotNormal + + raise ValueError( + "Unknown activation ({}) for framework={}!".format(name, framework) + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cc4a0d9bb05dc8ec1e2a904ba361f6be13a99120 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/__init__.py @@ -0,0 +1,30 @@ +from ray.rllib.offline.d4rl_reader import D4RLReader +from ray.rllib.offline.dataset_reader import DatasetReader, get_dataset_and_shards +from ray.rllib.offline.dataset_writer import DatasetWriter +from ray.rllib.offline.io_context import IOContext +from ray.rllib.offline.input_reader import InputReader +from ray.rllib.offline.mixed_input import MixedInput +from ray.rllib.offline.json_reader import JsonReader +from ray.rllib.offline.json_writer import JsonWriter +from ray.rllib.offline.output_writer import OutputWriter, NoopOutput +from ray.rllib.offline.resource import get_offline_io_resource_bundles +from ray.rllib.offline.shuffled_input import ShuffledInput +from ray.rllib.offline.feature_importance import FeatureImportance + + +__all__ = [ + "IOContext", + "JsonReader", + "JsonWriter", + "NoopOutput", + "OutputWriter", + "InputReader", + "MixedInput", + "ShuffledInput", + "D4RLReader", + "DatasetReader", + "DatasetWriter", + "get_dataset_and_shards", + "get_offline_io_resource_bundles", + "FeatureImportance", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/d4rl_reader.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/d4rl_reader.py new file mode 100644 index 0000000000000000000000000000000000000000..b9f18634b3d1c3eae21b570e11d1905509db948e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/d4rl_reader.py @@ -0,0 +1,51 @@ +import logging +import gymnasium as gym + +from ray.rllib.offline.input_reader import InputReader +from ray.rllib.offline.io_context import IOContext +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.annotations import override, PublicAPI +from ray.rllib.utils.typing import SampleBatchType +from typing import Dict + +logger = logging.getLogger(__name__) + + +@PublicAPI +class D4RLReader(InputReader): + """Reader object that loads the dataset from the D4RL dataset.""" + + @PublicAPI + def __init__(self, inputs: str, ioctx: IOContext = None): + """Initializes a D4RLReader instance. + + Args: + inputs: String corresponding to the D4RL environment name. + ioctx: Current IO context object. + """ + import d4rl + + self.env = gym.make(inputs) + self.dataset = _convert_to_batch(d4rl.qlearning_dataset(self.env)) + assert self.dataset.count >= 1 + self.counter = 0 + + @override(InputReader) + def next(self) -> SampleBatchType: + if self.counter >= self.dataset.count: + self.counter = 0 + + self.counter += 1 + return self.dataset.slice(start=self.counter, end=self.counter + 1) + + +def _convert_to_batch(dataset: Dict) -> SampleBatchType: + # Converts D4RL dataset to SampleBatch + d = {} + d[SampleBatch.OBS] = dataset["observations"] + d[SampleBatch.ACTIONS] = dataset["actions"] + d[SampleBatch.NEXT_OBS] = dataset["next_observations"] + d[SampleBatch.REWARDS] = dataset["rewards"] + d[SampleBatch.TERMINATEDS] = dataset["terminals"] + + return SampleBatch(d) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/dataset_reader.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/dataset_reader.py new file mode 100644 index 0000000000000000000000000000000000000000..1172aa7f5d0d57644640250d3767fab700e6766a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/dataset_reader.py @@ -0,0 +1,289 @@ +import logging +import math +from pathlib import Path +import re +import numpy as np +from typing import List, Tuple, TYPE_CHECKING, Optional +import zipfile + +import ray.data +from ray.rllib.offline.input_reader import InputReader +from ray.rllib.offline.io_context import IOContext +from ray.rllib.offline.json_reader import from_json_data, postprocess_actions +from ray.rllib.policy.sample_batch import concat_samples, SampleBatch, DEFAULT_POLICY_ID +from ray.rllib.utils.annotations import override, PublicAPI +from ray.rllib.utils.typing import SampleBatchType + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + +DEFAULT_NUM_CPUS_PER_TASK = 0.5 + +logger = logging.getLogger(__name__) + + +def _unzip_this_path(fpath: Path, extract_path: str): + with zipfile.ZipFile(str(fpath), "r") as zip_ref: + zip_ref.extractall(extract_path) + + +def _unzip_if_needed(paths: List[str], format: str): + """If a path in paths is a zip file, unzip it and use path of the unzipped file""" + ret_paths = [] + for path in paths: + if re.search("\\.zip$", str(path)): + # TODO: We need to add unzip support for s3 + if str(path).startswith("s3://"): + raise ValueError( + "unzip_if_needed currently does not support remote paths from s3" + ) + extract_path = "./" + try: + _unzip_this_path(str(path), extract_path) + except FileNotFoundError: + # intrepreted as a relative path to rllib folder + try: + # TODO: remove this later when we replace all tests with s3 paths + _unzip_this_path(Path(__file__).parent.parent / path, extract_path) + except FileNotFoundError: + raise FileNotFoundError(f"File not found: {path}") + + unzipped_path = str( + Path(extract_path).absolute() / f"{Path(path).stem}.{format}" + ) + ret_paths.append(unzipped_path) + else: + # TODO: We can get rid of this logic when we replace all tests with s3 paths + if str(path).startswith("s3://"): + ret_paths.append(path) + else: + if not Path(path).exists(): + relative_path = str(Path(__file__).parent.parent / path) + if not Path(relative_path).exists(): + raise FileNotFoundError(f"File not found: {path}") + path = relative_path + ret_paths.append(path) + return ret_paths + + +@PublicAPI +def get_dataset_and_shards( + config: "AlgorithmConfig", num_workers: int = 0 +) -> Tuple[ray.data.Dataset, List[ray.data.Dataset]]: + """Returns a dataset and a list of shards. + + This function uses algorithm configs to create a dataset and a list of shards. + The following config keys are used to create the dataset: + input: The input type should be "dataset". + input_config: A dict containing the following key and values: + `format`: str, speciifies the format of the input data. This will be the + format that ray dataset supports. See ray.data.Dataset for + supported formats. Only "parquet" or "json" are supported for now. + `paths`: str, a single string or a list of strings. Each string is a path + to a file or a directory holding the dataset. It can be either a local path + or a remote path (e.g. to an s3 bucket). + `loader_fn`: Callable[None, ray.data.Dataset], Instead of + specifying paths and format, you can specify a function to load the dataset. + `parallelism`: int, The number of tasks to use for loading the dataset. + If not specified, it will be set to the number of workers. + `num_cpus_per_read_task`: float, The number of CPUs to use for each read + task. If not specified, it will be set to 0.5. + + Args: + config: The config dict for the algorithm. + num_workers: The number of shards to create for remote workers. + + Returns: + dataset: The dataset object. + shards: A list of dataset shards. For num_workers > 0 the first returned + shared would be a dummy None shard for local_worker. + """ + # check input and input config keys + assert config.input_ == "dataset", ( + f"Must specify config.input_ as 'dataset' if" + f" calling `get_dataset_and_shards`. Got {config.input_}" + ) + + # check input config format + input_config = config.input_config + format = input_config.get("format") + + supported_fmts = ["json", "parquet"] + if format is not None and format not in supported_fmts: + raise ValueError( + f"Unsupported format {format}. Supported formats are {supported_fmts}" + ) + + # check paths and loader_fn since only one of them is required. + paths = input_config.get("paths") + loader_fn = input_config.get("loader_fn") + if loader_fn and (format or paths): + raise ValueError( + "When using a `loader_fn`, you cannot specify a `format` or `path`." + ) + + # check if at least loader_fn or format + path is specified. + if not (format and paths) and not loader_fn: + raise ValueError( + "Must specify either a `loader_fn` or a `format` and `path` in " + "`input_config`." + ) + + # check paths to be a str or list[str] if not None + if paths is not None: + if isinstance(paths, str): + paths = [paths] + elif isinstance(paths, list): + assert isinstance(paths[0], str), "Paths must be a list of path strings." + else: + raise ValueError("Paths must be a path string or a list of path strings.") + paths = _unzip_if_needed(paths, format) + + # TODO (Kourosh): num_workers is not necessary since we can use parallelism for + # everything. Having two parameters is confusing here. Remove num_workers later. + parallelism = input_config.get("parallelism", num_workers or 1) + cpus_per_task = input_config.get( + "num_cpus_per_read_task", DEFAULT_NUM_CPUS_PER_TASK + ) + + if loader_fn: + dataset = loader_fn() + elif format == "json": + dataset = ray.data.read_json( + paths, parallelism=parallelism, ray_remote_args={"num_cpus": cpus_per_task} + ) + elif format == "parquet": + dataset = ray.data.read_parquet( + paths, parallelism=parallelism, ray_remote_args={"num_cpus": cpus_per_task} + ) + else: + raise ValueError("Un-supported Ray dataset format: ", format) + + # Local worker will be responsible for sampling. + if num_workers == 0: + # Dataset is the only shard we need. + return dataset, [dataset] + # Remote workers are responsible for sampling: + else: + # Each remote worker gets 1 shard. + remote_shards = dataset.repartition( + num_blocks=num_workers, shuffle=False + ).split(num_workers) + + # The first None shard is for the local worker, which + # shouldn't be doing rollout work anyways. + return dataset, [None] + remote_shards + + +@PublicAPI +class DatasetReader(InputReader): + """Reader object that loads data from Ray Dataset. + + Examples: + config = { + "input": "dataset", + "input_config": { + "format": "json", + # A single data file, a directory, or anything + # that ray.data.dataset recognizes. + "paths": "/tmp/sample_batches/", + # By default, parallelism=num_workers. + "parallelism": 3, + # Dataset allocates 0.5 CPU for each reader by default. + # Adjust this value based on the size of your offline dataset. + "num_cpus_per_read_task": 0.5, + } + } + """ + + @PublicAPI + def __init__(self, ds: ray.data.Dataset, ioctx: Optional[IOContext] = None): + """Initializes a DatasetReader instance. + + Args: + ds: Ray dataset to sample from. + """ + self._ioctx = ioctx or IOContext() + self._default_policy = self.policy_map = None + self.preprocessor = None + self._dataset = ds + self.count = None if not self._dataset else self._dataset.count() + # do this to disable the ray data stdout logging + ray.data.DataContext.get_current().enable_progress_bars = False + + # the number of steps to return per call to next() + self.batch_size = self._ioctx.config.get("train_batch_size", 1) + num_workers = self._ioctx.config.get("num_env_runners", 0) + seed = self._ioctx.config.get("seed", None) + if num_workers: + self.batch_size = max(math.ceil(self.batch_size / num_workers), 1) + # We allow the creation of a non-functioning None DatasetReader. + # It's useful for example for a non-rollout local worker. + if ds: + if self._ioctx.worker is not None: + self._policy_map = self._ioctx.worker.policy_map + self._default_policy = self._policy_map.get(DEFAULT_POLICY_ID) + self.preprocessor = ( + self._ioctx.worker.preprocessors.get(DEFAULT_POLICY_ID) + if not self._ioctx.config.get("_disable_preprocessors", False) + else None + ) + print( + f"DatasetReader {self._ioctx.worker_index} has {ds.count()}, samples." + ) + + def iterator(): + while True: + ds = self._dataset.random_shuffle(seed=seed) + yield from ds.iter_rows() + + self._iter = iterator() + else: + self._iter = None + + @override(InputReader) + def next(self) -> SampleBatchType: + # next() should not get called on None DatasetReader. + assert self._iter is not None + ret = [] + count = 0 + while count < self.batch_size: + d = next(self._iter) + # Columns like obs are compressed when written by DatasetWriter. + d = from_json_data(d, self._ioctx.worker) + count += d.count + d = self._preprocess_if_needed(d) + d = postprocess_actions(d, self._ioctx) + d = self._postprocess_if_needed(d) + ret.append(d) + ret = concat_samples(ret) + return ret + + def _preprocess_if_needed(self, batch: SampleBatchType) -> SampleBatchType: + # TODO: @kourosh, preprocessor is only supported for single agent case. + if self.preprocessor: + for key in (SampleBatch.CUR_OBS, SampleBatch.NEXT_OBS): + if key in batch: + batch[key] = np.stack( + [self.preprocessor.transform(s) for s in batch[key]] + ) + return batch + + def _postprocess_if_needed(self, batch: SampleBatchType) -> SampleBatchType: + if not self._ioctx.config.get("postprocess_inputs"): + return batch + + if isinstance(batch, SampleBatch): + out = [] + for sub_batch in batch.split_by_episode(): + if self._default_policy is not None: + out.append(self._default_policy.postprocess_trajectory(sub_batch)) + else: + out.append(sub_batch) + return concat_samples(out) + else: + # TODO(ekl) this is trickier since the alignments between agent + # trajectories in the episode are not available any more. + raise NotImplementedError( + "Postprocessing of multi-agent data not implemented yet." + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/dataset_writer.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/dataset_writer.py new file mode 100644 index 0000000000000000000000000000000000000000..b517933ce985091f2192dd9b03e41e9b2d304cfe --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/dataset_writer.py @@ -0,0 +1,82 @@ +import logging +import os +import time + +from ray import data +from ray.rllib.offline.io_context import IOContext +from ray.rllib.offline.json_writer import _to_json_dict +from ray.rllib.offline.output_writer import OutputWriter +from ray.rllib.utils.annotations import override, PublicAPI +from ray.rllib.utils.typing import SampleBatchType +from typing import Dict, List + +logger = logging.getLogger(__name__) + + +@PublicAPI +class DatasetWriter(OutputWriter): + """Writer object that saves experiences using Datasets.""" + + @PublicAPI + def __init__( + self, + ioctx: IOContext = None, + compress_columns: List[str] = frozenset(["obs", "new_obs"]), + ): + """Initializes a DatasetWriter instance. + + Examples: + config = { + "output": "dataset", + "output_config": { + "format": "json", + "path": "/tmp/test_samples/", + "max_num_samples_per_file": 100000, + } + } + + Args: + ioctx: current IO context object. + compress_columns: list of sample batch columns to compress. + """ + self.ioctx = ioctx or IOContext() + + output_config: Dict = ioctx.output_config + assert ( + "format" in output_config + ), "output_config.format must be specified when using Dataset output." + assert ( + "path" in output_config + ), "output_config.path must be specified when using Dataset output." + + self.format = output_config["format"] + self.path = os.path.abspath(os.path.expanduser(output_config["path"])) + self.max_num_samples_per_file = ( + output_config["max_num_samples_per_file"] + if "max_num_samples_per_file" in output_config + else 100000 + ) + self.compress_columns = compress_columns + + self.samples = [] + + @override(OutputWriter) + def write(self, sample_batch: SampleBatchType): + start = time.time() + + # Make sure columns like obs are compressed and writable. + d = _to_json_dict(sample_batch, self.compress_columns) + self.samples.append(d) + + # Todo: We should flush at the end of sampling even if this + # condition was not reached. + if len(self.samples) >= self.max_num_samples_per_file: + ds = data.from_items(self.samples).repartition(num_blocks=1, shuffle=False) + if self.format == "json": + ds.write_json(self.path, try_create_dir=True) + elif self.format == "parquet": + ds.write_parquet(self.path, try_create_dir=True) + else: + raise ValueError("Unknown output type: ", self.format) + self.samples = [] + logger.debug("Wrote dataset in {}s".format(time.time() - start)) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/feature_importance.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/feature_importance.py new file mode 100644 index 0000000000000000000000000000000000000000..2efe17790a79e5ba830b3444f31f8f6b096a5e6e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/feature_importance.py @@ -0,0 +1,283 @@ +import copy +import numpy as np +import pandas as pd +from typing import Callable, Dict, Any + +import ray +from ray.data import Dataset + +from ray.rllib.policy import Policy +from ray.rllib.policy.sample_batch import SampleBatch, convert_ma_batch_to_sample_batch +from ray.rllib.utils.annotations import override, DeveloperAPI, ExperimentalAPI +from ray.rllib.utils.typing import SampleBatchType +from ray.rllib.offline.offline_evaluator import OfflineEvaluator + + +@DeveloperAPI +def _perturb_fn(batch: np.ndarray, index: int): + # shuffle the indexth column features + random_inds = np.random.permutation(batch.shape[0]) + batch[:, index] = batch[random_inds, index] + + +@ExperimentalAPI +def _perturb_df(batch: pd.DataFrame, index: int): + obs_batch = np.vstack(batch["obs"].values) + _perturb_fn(obs_batch, index) + batch["perturbed_obs"] = list(obs_batch) + return batch + + +def _compute_actions( + batch: pd.DataFrame, + policy_state: Dict[str, Any], + input_key: str = "", + output_key: str = "", +): + """A custom local function to do batch prediction of a policy. + + Given the policy state the action predictions are computed as a function of + `input_key` and stored in the `output_key` column. + + Args: + batch: A sub-batch from the dataset. + policy_state: The state of the policy to use for the prediction. + input_key: The key to use for the input to the policy. If not given, the + default is SampleBatch.OBS. + output_key: The key to use for the output of the policy. If not given, the + default is "predicted_actions". + + Returns: + The modified batch with the predicted actions added as a column. + """ + if not input_key: + input_key = SampleBatch.OBS + + policy = Policy.from_state(policy_state) + sample_batch = SampleBatch( + { + SampleBatch.OBS: np.vstack(batch[input_key].values), + } + ) + actions, _, _ = policy.compute_actions_from_input_dict(sample_batch, explore=False) + + if not output_key: + output_key = "predicted_actions" + batch[output_key] = actions + + return batch + + +@ray.remote +def get_feature_importance_on_index( + dataset: ray.data.Dataset, + *, + index: int, + perturb_fn: Callable[[pd.DataFrame, int], None], + batch_size: int, + policy_state: Dict[str, Any], +): + """A remote function to compute the feature importance of a given index. + + Args: + dataset: The dataset to use for the computation. The dataset should have `obs` + and `actions` columns. Each record should be flat d-dimensional array. + index: The index of the feature to compute the importance for. + perturb_fn: The function to use for perturbing the dataset at the given index. + batch_size: The batch size to use for the computation. + policy_state: The state of the policy to use for the computation. + + Returns: + The modified dataset that contains a `delta` column which is the absolute + difference between the expected output and the output due to the perturbation. + """ + perturbed_ds = dataset.map_batches( + perturb_fn, + batch_size=batch_size, + batch_format="pandas", + fn_kwargs={"index": index}, + ) + perturbed_actions = perturbed_ds.map_batches( + _compute_actions, + batch_size=batch_size, + batch_format="pandas", + fn_kwargs={ + "output_key": "perturbed_actions", + "input_key": "perturbed_obs", + "policy_state": policy_state, + }, + ) + + def delta_fn(batch): + # take the abs difference between columns 'ref_actions` and `perturbed_actions` + # and store it in `diff` + batch["delta"] = np.abs(batch["ref_actions"] - batch["perturbed_actions"]) + return batch + + delta = perturbed_actions.map_batches( + delta_fn, batch_size=batch_size, batch_format="pandas" + ) + + return delta + + +@DeveloperAPI +class FeatureImportance(OfflineEvaluator): + @override(OfflineEvaluator) + def __init__( + self, + policy: Policy, + repeat: int = 1, + limit_fraction: float = 1.0, + perturb_fn: Callable[[pd.DataFrame, int], pd.DataFrame] = _perturb_df, + ): + """Feature importance in a model inspection technique that can be used for any + fitted predictor when the data is tablular. + + This implementation is also known as permutation importance that is defined to + be the variation of the model's prediction when a single feature value is + randomly shuffled. In RLlib it is implemented as a custom OffPolicyEstimator + which is used to evaluate RLlib policies without performing environment + interactions. + + Example usage: In the example below the feature importance module is used to + evaluate the policy and the each feature's importance is computed after each + training iteration. The permutation are repeated `self.repeat` times and the + results are averages across repeats. + + ```python + config = ( + AlgorithmConfig() + .offline_data( + off_policy_estimation_methods= + { + "feature_importance": { + "type": FeatureImportance, + "repeat": 10, + "limit_fraction": 0.1, + } + } + ) + ) + + algorithm = DQN(config=config) + results = algorithm.train() + ``` + + Args: + policy: the policy to use for feature importance. + repeat: number of times to repeat the perturbation. + perturb_fn: function to perturb the features. By default reshuffle the + features within the batch. + limit_fraction: fraction of the dataset to use for feature importance + This is only used in estimate_on_dataset when the dataset is too large + to compute feature importance on. + """ + super().__init__(policy) + self.repeat = repeat + self.perturb_fn = perturb_fn + self.limit_fraction = limit_fraction + + def estimate(self, batch: SampleBatchType) -> Dict[str, Any]: + """Estimate the feature importance of the policy. + + Given a batch of tabular observations, the importance of each feature is + computed by perturbing each feature and computing the difference between the + perturbed policy and the reference policy. The importance is computed for each + feature and each perturbation is repeated `self.repeat` times. + + Args: + batch: the batch of data to use for feature importance. + + Returns: + A dict mapping each feature index string to its importance. + """ + batch = convert_ma_batch_to_sample_batch(batch) + obs_batch = batch["obs"] + n_features = obs_batch.shape[-1] + importance = np.zeros((self.repeat, n_features)) + + ref_actions, _, _ = self.policy.compute_actions(obs_batch, explore=False) + for r in range(self.repeat): + for i in range(n_features): + copy_obs_batch = copy.deepcopy(obs_batch) + _perturb_fn(copy_obs_batch, index=i) + perturbed_actions, _, _ = self.policy.compute_actions( + copy_obs_batch, explore=False + ) + importance[r, i] = np.mean(np.abs(perturbed_actions - ref_actions)) + + # take an average across repeats + importance = importance.mean(0) + metrics = {f"feature_{i}": importance[i] for i in range(len(importance))} + + return metrics + + @override(OfflineEvaluator) + def estimate_on_dataset( + self, dataset: Dataset, *, n_parallelism: int = ... + ) -> Dict[str, Any]: + """Estimate the feature importance of the policy given a dataset. + + For each feature in the dataset, the importance is computed by applying + perturbations to each feature and computing the difference between the + perturbed prediction and the reference prediction. The importance + computation for each feature and each perturbation is repeated `self.repeat` + times. If dataset is large the user can initialize the estimator with a + `limit_fraction` to limit the dataset to a fraction of the original dataset. + + The dataset should include a column named `obs` where each row is a vector of D + dimensions. The importance is computed for each dimension of the vector. + + Note (Implementation detail): The computation across features are distributed + with ray workers since each feature is independent of each other. + + Args: + dataset: the dataset to use for feature importance. + n_parallelism: number of parallel workers to use for feature importance. + + Returns: + A dict mapping each feature index string to its importance. + """ + + policy_state = self.policy.get_state() + # step 1: limit the dataset to a few first rows + ds = dataset.limit(int(self.limit_fraction * dataset.count())) + + # step 2: compute the reference actions + bsize = max(1, ds.count() // n_parallelism) + actions_ds = ds.map_batches( + _compute_actions, + batch_size=bsize, + fn_kwargs={ + "output_key": "ref_actions", + "policy_state": policy_state, + }, + ) + + # step 3: compute the feature importance + n_features = ds.take(1)[0][SampleBatch.OBS].shape[-1] + importance = np.zeros((self.repeat, n_features)) + for r in range(self.repeat): + # shuffle the entire dataset + shuffled_ds = actions_ds.random_shuffle() + bsize_per_task = max(1, (shuffled_ds.count() * n_features) // n_parallelism) + + # for each index perturb the dataset and compute the feat importance score + remote_fns = [ + get_feature_importance_on_index.remote( + dataset=shuffled_ds, + index=i, + perturb_fn=self.perturb_fn, + bsize=bsize_per_task, + policy_state=policy_state, + ) + for i in range(n_features) + ] + ds_w_fi_scores = ray.get(remote_fns) + importance[r] = np.array([d.mean("delta") for d in ds_w_fi_scores]) + + importance = importance.mean(0) + metrics = {f"feature_{i}": importance[i] for i in range(len(importance))} + + return metrics diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/input_reader.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/input_reader.py new file mode 100644 index 0000000000000000000000000000000000000000..042e3783c39d25c54286d36c93131b608f5e3a0f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/input_reader.py @@ -0,0 +1,132 @@ +from abc import ABCMeta, abstractmethod +import logging +import numpy as np +import threading + +from ray.rllib.policy.sample_batch import MultiAgentBatch +from ray.rllib.utils.annotations import PublicAPI +from ray.rllib.utils.framework import try_import_tf +from typing import Dict, List +from ray.rllib.utils.typing import TensorType, SampleBatchType + +tf1, tf, tfv = try_import_tf() + +logger = logging.getLogger(__name__) + + +@PublicAPI +class InputReader(metaclass=ABCMeta): + """API for collecting and returning experiences during policy evaluation.""" + + @abstractmethod + @PublicAPI + def next(self) -> SampleBatchType: + """Returns the next batch of read experiences. + + Returns: + The experience read (SampleBatch or MultiAgentBatch). + """ + raise NotImplementedError + + @PublicAPI + def tf_input_ops(self, queue_size: int = 1) -> Dict[str, TensorType]: + """Returns TensorFlow queue ops for reading inputs from this reader. + + The main use of these ops is for integration into custom model losses. + For example, you can use tf_input_ops() to read from files of external + experiences to add an imitation learning loss to your model. + + This method creates a queue runner thread that will call next() on this + reader repeatedly to feed the TensorFlow queue. + + Args: + queue_size: Max elements to allow in the TF queue. + + .. testcode:: + :skipif: True + + from ray.rllib.models.modelv2 import ModelV2 + from ray.rllib.offline.json_reader import JsonReader + imitation_loss = ... + class MyModel(ModelV2): + def custom_loss(self, policy_loss, loss_inputs): + reader = JsonReader(...) + input_ops = reader.tf_input_ops() + logits, _ = self._build_layers_v2( + {"obs": input_ops["obs"]}, + self.num_outputs, self.options) + il_loss = imitation_loss(logits, input_ops["action"]) + return policy_loss + il_loss + + You can find a runnable version of this in examples/custom_loss.py. + + Returns: + Dict of Tensors, one for each column of the read SampleBatch. + """ + + if hasattr(self, "_queue_runner"): + raise ValueError( + "A queue runner already exists for this input reader. " + "You can only call tf_input_ops() once per reader." + ) + + logger.info("Reading initial batch of data from input reader.") + batch = self.next() + if isinstance(batch, MultiAgentBatch): + raise NotImplementedError( + "tf_input_ops() is not implemented for multi agent batches" + ) + + # Note on casting to `np.array(batch[k])`: In order to get all keys that + # are numbers, we need to convert to numpy everything that is not a numpy array. + # This is because SampleBatches used to only hold numpy arrays, but since our + # RNN efforts under RLModules, we also allow lists. + keys = [ + k + for k in sorted(batch.keys()) + if np.issubdtype(np.array(batch[k]).dtype, np.number) + ] + dtypes = [batch[k].dtype for k in keys] + shapes = {k: (-1,) + s[1:] for (k, s) in [(k, batch[k].shape) for k in keys]} + queue = tf1.FIFOQueue(capacity=queue_size, dtypes=dtypes, names=keys) + tensors = queue.dequeue() + + logger.info("Creating TF queue runner for {}".format(self)) + self._queue_runner = _QueueRunner(self, queue, keys, dtypes) + self._queue_runner.enqueue(batch) + self._queue_runner.start() + + out = {k: tf.reshape(t, shapes[k]) for k, t in tensors.items()} + return out + + +class _QueueRunner(threading.Thread): + """Thread that feeds a TF queue from a InputReader.""" + + def __init__( + self, + input_reader: InputReader, + queue: "tf1.FIFOQueue", + keys: List[str], + dtypes: "tf.dtypes.DType", + ): + threading.Thread.__init__(self) + self.sess = tf1.get_default_session() + self.daemon = True + self.input_reader = input_reader + self.keys = keys + self.queue = queue + self.placeholders = [tf1.placeholder(dtype) for dtype in dtypes] + self.enqueue_op = queue.enqueue(dict(zip(keys, self.placeholders))) + + def enqueue(self, batch: SampleBatchType): + data = {self.placeholders[i]: batch[key] for i, key in enumerate(self.keys)} + self.sess.run(self.enqueue_op, feed_dict=data) + + def run(self): + while True: + try: + batch = self.input_reader.next() + self.enqueue(batch) + except Exception: + logger.exception("Error reading from input") diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/io_context.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/io_context.py new file mode 100644 index 0000000000000000000000000000000000000000..1d0ec1683b935ff4712d0873ac567d935a2b7642 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/io_context.py @@ -0,0 +1,72 @@ +import os +from typing import Optional, TYPE_CHECKING + +from ray.rllib.utils.annotations import PublicAPI + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + from ray.rllib.evaluation.sampler import SamplerInput + from ray.rllib.evaluation.rollout_worker import RolloutWorker + + +@PublicAPI +class IOContext: + """Class containing attributes to pass to input/output class constructors. + + RLlib auto-sets these attributes when constructing input/output classes, + such as InputReaders and OutputWriters. + """ + + @PublicAPI + def __init__( + self, + log_dir: Optional[str] = None, + config: Optional["AlgorithmConfig"] = None, + worker_index: int = 0, + worker: Optional["RolloutWorker"] = None, + ): + """Initializes a IOContext object. + + Args: + log_dir: The logging directory to read from/write to. + config: The (main) AlgorithmConfig object. + worker_index: When there are multiple workers created, this + uniquely identifies the current worker. 0 for the local + worker, >0 for any of the remote workers. + worker: The RolloutWorker object reference. + """ + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + + self.log_dir = log_dir or os.getcwd() + # In case no config is provided, use the default one, but set + # `actions_in_input_normalized=True` if we don't have a worker. + # Not having a worker and/or a config should only be the case in some test + # cases, though. + self.config = config or AlgorithmConfig().offline_data( + actions_in_input_normalized=worker is None + ).training(train_batch_size=1) + self.worker_index = worker_index + self.worker = worker + + @PublicAPI + def default_sampler_input(self) -> Optional["SamplerInput"]: + """Returns the RolloutWorker's SamplerInput object, if any. + + Returns None if the RolloutWorker has no SamplerInput. Note that local + workers in case there are also one or more remote workers by default + do not create a SamplerInput object. + + Returns: + The RolloutWorkers' SamplerInput object or None if none exists. + """ + return self.worker.sampler + + @property + @PublicAPI + def input_config(self): + return self.config.get("input_config", {}) + + @property + @PublicAPI + def output_config(self): + return self.config.get("output_config", {}) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/is_estimator.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/is_estimator.py new file mode 100644 index 0000000000000000000000000000000000000000..58c8da3e0c72358046a9192fae8461780eaf3bbf --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/is_estimator.py @@ -0,0 +1,10 @@ +from ray.rllib.offline.estimators.importance_sampling import ImportanceSampling +from ray.rllib.utils.deprecation import Deprecated + + +@Deprecated( + new="ray.rllib.offline.estimators.importance_sampling::ImportanceSampling", + error=True, +) +class ImportanceSamplingEstimator(ImportanceSampling): + pass diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/json_reader.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/json_reader.py new file mode 100644 index 0000000000000000000000000000000000000000..30562b515aac2562b33fbcb847720ee1f17c0131 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/json_reader.py @@ -0,0 +1,438 @@ +import glob +import json +import logging +import math + +import numpy as np +import os +from pathlib import Path +import random +import re +import tree # pip install dm_tree +from typing import List, Optional, TYPE_CHECKING, Union +from urllib.parse import urlparse +import zipfile + +try: + from smart_open import smart_open +except ImportError: + smart_open = None + +from ray.rllib.offline.input_reader import InputReader +from ray.rllib.offline.io_context import IOContext +from ray.rllib.policy.policy import Policy +from ray.rllib.policy.sample_batch import ( + DEFAULT_POLICY_ID, + MultiAgentBatch, + SampleBatch, + concat_samples, + convert_ma_batch_to_sample_batch, +) +from ray.rllib.utils.annotations import override, PublicAPI, DeveloperAPI +from ray.rllib.utils.compression import unpack_if_needed +from ray.rllib.utils.spaces.space_utils import clip_action, normalize_action +from ray.rllib.utils.typing import Any, FileType, SampleBatchType + +if TYPE_CHECKING: + from ray.rllib.evaluation import RolloutWorker + +logger = logging.getLogger(__name__) + +WINDOWS_DRIVES = [chr(i) for i in range(ord("c"), ord("z") + 1)] + + +def _adjust_obs_actions_for_policy(json_data: dict, policy: Policy) -> dict: + """Handle nested action/observation spaces for policies. + + Translates nested lists/dicts from the json into proper + np.ndarrays, according to the (nested) observation- and action- + spaces of the given policy. + + Providing nested lists w/o this preprocessing step would + confuse a SampleBatch constructor. + """ + for k, v in json_data.items(): + data_col = ( + policy.view_requirements[k].data_col + if k in policy.view_requirements + else "" + ) + # No action flattening -> Process nested (leaf) action(s). + if policy.config.get("_disable_action_flattening") and ( + k == SampleBatch.ACTIONS + or data_col == SampleBatch.ACTIONS + or k == SampleBatch.PREV_ACTIONS + or data_col == SampleBatch.PREV_ACTIONS + ): + json_data[k] = tree.map_structure_up_to( + policy.action_space_struct, + lambda comp: np.array(comp), + json_data[k], + check_types=False, + ) + # No preprocessing -> Process nested (leaf) observation(s). + elif policy.config.get("_disable_preprocessor_api") and ( + k == SampleBatch.OBS + or data_col == SampleBatch.OBS + or k == SampleBatch.NEXT_OBS + or data_col == SampleBatch.NEXT_OBS + ): + json_data[k] = tree.map_structure_up_to( + policy.observation_space_struct, + lambda comp: np.array(comp), + json_data[k], + check_types=False, + ) + return json_data + + +@DeveloperAPI +def _adjust_dones(json_data: dict) -> dict: + """Make sure DONES in json data is properly translated into TERMINATEDS.""" + new_json_data = {} + for k, v in json_data.items(): + # Translate DONES into TERMINATEDS. + if k == SampleBatch.DONES: + new_json_data[SampleBatch.TERMINATEDS] = v + # Leave everything else as-is. + else: + new_json_data[k] = v + + return new_json_data + + +@DeveloperAPI +def postprocess_actions(batch: SampleBatchType, ioctx: IOContext) -> SampleBatchType: + # Clip actions (from any values into env's bounds), if necessary. + cfg = ioctx.config + # TODO(jungong): We should not clip_action in input reader. + # Use connector to handle this. + if cfg.get("clip_actions"): + if ioctx.worker is None: + raise ValueError( + "clip_actions is True but cannot clip actions since no workers exist" + ) + + if isinstance(batch, SampleBatch): + policy = ioctx.worker.policy_map.get(DEFAULT_POLICY_ID) + if policy is None: + assert len(ioctx.worker.policy_map) == 1 + policy = next(iter(ioctx.worker.policy_map.values())) + batch[SampleBatch.ACTIONS] = clip_action( + batch[SampleBatch.ACTIONS], policy.action_space_struct + ) + else: + for pid, b in batch.policy_batches.items(): + b[SampleBatch.ACTIONS] = clip_action( + b[SampleBatch.ACTIONS], + ioctx.worker.policy_map[pid].action_space_struct, + ) + # Re-normalize actions (from env's bounds to zero-centered), if + # necessary. + if ( + cfg.get("actions_in_input_normalized") is False + and cfg.get("normalize_actions") is True + ): + if ioctx.worker is None: + raise ValueError( + "actions_in_input_normalized is False but" + "cannot normalize actions since no workers exist" + ) + + # If we have a complex action space and actions were flattened + # and we have to normalize -> Error. + error_msg = ( + "Normalization of offline actions that are flattened is not " + "supported! Make sure that you record actions into offline " + "file with the `_disable_action_flattening=True` flag OR " + "as already normalized (between -1.0 and 1.0) values. " + "Also, when reading already normalized action values from " + "offline files, make sure to set " + "`actions_in_input_normalized=True` so that RLlib will not " + "perform normalization on top." + ) + + if isinstance(batch, SampleBatch): + policy = ioctx.worker.policy_map.get(DEFAULT_POLICY_ID) + if policy is None: + assert len(ioctx.worker.policy_map) == 1 + policy = next(iter(ioctx.worker.policy_map.values())) + if isinstance( + policy.action_space_struct, (tuple, dict) + ) and not policy.config.get("_disable_action_flattening"): + raise ValueError(error_msg) + batch[SampleBatch.ACTIONS] = normalize_action( + batch[SampleBatch.ACTIONS], policy.action_space_struct + ) + else: + for pid, b in batch.policy_batches.items(): + policy = ioctx.worker.policy_map[pid] + if isinstance( + policy.action_space_struct, (tuple, dict) + ) and not policy.config.get("_disable_action_flattening"): + raise ValueError(error_msg) + b[SampleBatch.ACTIONS] = normalize_action( + b[SampleBatch.ACTIONS], + ioctx.worker.policy_map[pid].action_space_struct, + ) + + return batch + + +@DeveloperAPI +def from_json_data(json_data: Any, worker: Optional["RolloutWorker"]): + # Try to infer the SampleBatchType (SampleBatch or MultiAgentBatch). + if "type" in json_data: + data_type = json_data.pop("type") + else: + raise ValueError("JSON record missing 'type' field") + + if data_type == "SampleBatch": + if worker is not None and len(worker.policy_map) != 1: + raise ValueError( + "Found single-agent SampleBatch in input file, but our " + "PolicyMap contains more than 1 policy!" + ) + for k, v in json_data.items(): + json_data[k] = unpack_if_needed(v) + if worker is not None: + policy = next(iter(worker.policy_map.values())) + json_data = _adjust_obs_actions_for_policy(json_data, policy) + json_data = _adjust_dones(json_data) + return SampleBatch(json_data) + elif data_type == "MultiAgentBatch": + policy_batches = {} + for policy_id, policy_batch in json_data["policy_batches"].items(): + inner = {} + for k, v in policy_batch.items(): + # Translate DONES into TERMINATEDS. + if k == SampleBatch.DONES: + k = SampleBatch.TERMINATEDS + inner[k] = unpack_if_needed(v) + if worker is not None: + policy = worker.policy_map[policy_id] + inner = _adjust_obs_actions_for_policy(inner, policy) + inner = _adjust_dones(inner) + policy_batches[policy_id] = SampleBatch(inner) + return MultiAgentBatch(policy_batches, json_data["count"]) + else: + raise ValueError( + "Type field must be one of ['SampleBatch', 'MultiAgentBatch']", data_type + ) + + +# TODO(jungong) : use DatasetReader to back JsonReader, so we reduce +# codebase complexity without losing existing functionality. +@PublicAPI +class JsonReader(InputReader): + """Reader object that loads experiences from JSON file chunks. + + The input files will be read from in random order. + """ + + @PublicAPI + def __init__( + self, inputs: Union[str, List[str]], ioctx: Optional[IOContext] = None + ): + """Initializes a JsonReader instance. + + Args: + inputs: Either a glob expression for files, e.g. `/tmp/**/*.json`, + or a list of single file paths or URIs, e.g., + ["s3://bucket/file.json", "s3://bucket/file2.json"]. + ioctx: Current IO context object or None. + """ + logger.info( + "You are using JSONReader. It is recommended to use " + + "DatasetReader instead for better sharding support." + ) + + self.ioctx = ioctx or IOContext() + self.default_policy = self.policy_map = None + self.batch_size = 1 + if self.ioctx: + self.batch_size = self.ioctx.config.get("train_batch_size", 1) + num_workers = self.ioctx.config.get("num_env_runners", 0) + if num_workers: + self.batch_size = max(math.ceil(self.batch_size / num_workers), 1) + + if self.ioctx.worker is not None: + self.policy_map = self.ioctx.worker.policy_map + self.default_policy = self.policy_map.get(DEFAULT_POLICY_ID) + if self.default_policy is None: + assert len(self.policy_map) == 1 + self.default_policy = next(iter(self.policy_map.values())) + + if isinstance(inputs, str): + inputs = os.path.abspath(os.path.expanduser(inputs)) + if os.path.isdir(inputs): + inputs = [os.path.join(inputs, "*.json"), os.path.join(inputs, "*.zip")] + logger.warning(f"Treating input directory as glob patterns: {inputs}") + else: + inputs = [inputs] + + if any(urlparse(i).scheme not in [""] + WINDOWS_DRIVES for i in inputs): + raise ValueError( + "Don't know how to glob over `{}`, ".format(inputs) + + "please specify a list of files to read instead." + ) + else: + self.files = [] + for i in inputs: + self.files.extend(glob.glob(i)) + elif isinstance(inputs, (list, tuple)): + self.files = list(inputs) + else: + raise ValueError( + "type of inputs must be list or str, not {}".format(inputs) + ) + if self.files: + logger.info("Found {} input files.".format(len(self.files))) + else: + raise ValueError("No files found matching {}".format(inputs)) + self.cur_file = None + + @override(InputReader) + def next(self) -> SampleBatchType: + ret = [] + count = 0 + while count < self.batch_size: + batch = self._try_parse(self._next_line()) + tries = 0 + while not batch and tries < 100: + tries += 1 + logger.debug("Skipping empty line in {}".format(self.cur_file)) + batch = self._try_parse(self._next_line()) + if not batch: + raise ValueError( + "Failed to read valid experience batch from file: {}".format( + self.cur_file + ) + ) + batch = self._postprocess_if_needed(batch) + count += batch.count + ret.append(batch) + ret = concat_samples(ret) + return ret + + def read_all_files(self) -> SampleBatchType: + """Reads through all files and yields one SampleBatchType per line. + + When reaching the end of the last file, will start from the beginning + again. + + Yields: + One SampleBatch or MultiAgentBatch per line in all input files. + """ + for path in self.files: + file = self._try_open_file(path) + while True: + line = file.readline() + if not line: + break + batch = self._try_parse(line) + if batch is None: + break + yield batch + + def _postprocess_if_needed(self, batch: SampleBatchType) -> SampleBatchType: + if not self.ioctx.config.get("postprocess_inputs"): + return batch + + batch = convert_ma_batch_to_sample_batch(batch) + + if isinstance(batch, SampleBatch): + out = [] + for sub_batch in batch.split_by_episode(): + out.append(self.default_policy.postprocess_trajectory(sub_batch)) + return concat_samples(out) + else: + # TODO(ekl) this is trickier since the alignments between agent + # trajectories in the episode are not available any more. + raise NotImplementedError( + "Postprocessing of multi-agent data not implemented yet." + ) + + def _try_open_file(self, path): + if urlparse(path).scheme not in [""] + WINDOWS_DRIVES: + if smart_open is None: + raise ValueError( + "You must install the `smart_open` module to read " + "from URIs like {}".format(path) + ) + ctx = smart_open + else: + # Allow shortcut for home directory ("~/" -> env[HOME]). + if path.startswith("~/"): + path = os.path.join(os.environ.get("HOME", ""), path[2:]) + + # If path doesn't exist, try to interpret is as relative to the + # rllib directory (located ../../ from this very module). + path_orig = path + if not os.path.exists(path): + path = os.path.join(Path(__file__).parent.parent, path) + if not os.path.exists(path): + raise FileNotFoundError(f"Offline file {path_orig} not found!") + + # Unzip files, if necessary and re-point to extracted json file. + if re.search("\\.zip$", path): + with zipfile.ZipFile(path, "r") as zip_ref: + zip_ref.extractall(Path(path).parent) + path = re.sub("\\.zip$", ".json", path) + assert os.path.exists(path) + ctx = open + file = ctx(path, "r") + return file + + def _try_parse(self, line: str) -> Optional[SampleBatchType]: + line = line.strip() + if not line: + return None + try: + batch = self._from_json(line) + except Exception: + logger.exception( + "Ignoring corrupt json record in {}: {}".format(self.cur_file, line) + ) + return None + + batch = postprocess_actions(batch, self.ioctx) + + return batch + + def _next_line(self) -> str: + if not self.cur_file: + self.cur_file = self._next_file() + line = self.cur_file.readline() + tries = 0 + while not line and tries < 100: + tries += 1 + if hasattr(self.cur_file, "close"): # legacy smart_open impls + self.cur_file.close() + self.cur_file = self._next_file() + line = self.cur_file.readline() + if not line: + logger.debug("Ignoring empty file {}".format(self.cur_file)) + if not line: + raise ValueError( + "Failed to read next line from files: {}".format(self.files) + ) + return line + + def _next_file(self) -> FileType: + # If this is the first time, we open a file, make sure all workers + # start with a different one if possible. + if self.cur_file is None and self.ioctx.worker is not None: + idx = self.ioctx.worker.worker_index + total = self.ioctx.worker.num_workers or 1 + path = self.files[round((len(self.files) - 1) * (idx / total))] + # After the first file, pick all others randomly. + else: + path = random.choice(self.files) + return self._try_open_file(path) + + def _from_json(self, data: str) -> SampleBatchType: + if isinstance(data, bytes): # smart_open S3 doesn't respect "r" + data = data.decode("utf-8") + json_data = json.loads(data) + return from_json_data(json_data, self.ioctx.worker) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/json_writer.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/json_writer.py new file mode 100644 index 0000000000000000000000000000000000000000..4e15bfb2e550fa0013571a488c9e5c47044ed67c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/json_writer.py @@ -0,0 +1,142 @@ +from datetime import datetime +import json +import logging +import numpy as np +import os +from urllib.parse import urlparse +import time + +try: + from smart_open import smart_open +except ImportError: + smart_open = None + +from ray.air._internal.json import SafeFallbackEncoder +from ray.rllib.policy.sample_batch import MultiAgentBatch +from ray.rllib.offline.io_context import IOContext +from ray.rllib.offline.output_writer import OutputWriter +from ray.rllib.utils.annotations import override, PublicAPI +from ray.rllib.utils.compression import pack, compression_supported +from ray.rllib.utils.typing import FileType, SampleBatchType +from typing import Any, Dict, List + +logger = logging.getLogger(__name__) + +WINDOWS_DRIVES = [chr(i) for i in range(ord("c"), ord("z") + 1)] + + +# TODO(jungong): use DatasetWriter to back JsonWriter, so we reduce codebase complexity +# without losing existing functionality. +@PublicAPI +class JsonWriter(OutputWriter): + """Writer object that saves experiences in JSON file chunks.""" + + @PublicAPI + def __init__( + self, + path: str, + ioctx: IOContext = None, + max_file_size: int = 64 * 1024 * 1024, + compress_columns: List[str] = frozenset(["obs", "new_obs"]), + ): + """Initializes a JsonWriter instance. + + Args: + path: a path/URI of the output directory to save files in. + ioctx: current IO context object. + max_file_size: max size of single files before rolling over. + compress_columns: list of sample batch columns to compress. + """ + logger.info( + "You are using JSONWriter. It is recommended to use " + + "DatasetWriter instead." + ) + + self.ioctx = ioctx or IOContext() + self.max_file_size = max_file_size + self.compress_columns = compress_columns + if urlparse(path).scheme not in [""] + WINDOWS_DRIVES: + self.path_is_uri = True + else: + path = os.path.abspath(os.path.expanduser(path)) + # Try to create local dirs if they don't exist + os.makedirs(path, exist_ok=True) + assert os.path.exists(path), "Failed to create {}".format(path) + self.path_is_uri = False + self.path = path + self.file_index = 0 + self.bytes_written = 0 + self.cur_file = None + + @override(OutputWriter) + def write(self, sample_batch: SampleBatchType): + start = time.time() + data = _to_json(sample_batch, self.compress_columns) + f = self._get_file() + f.write(data) + f.write("\n") + if hasattr(f, "flush"): # legacy smart_open impls + f.flush() + self.bytes_written += len(data) + logger.debug( + "Wrote {} bytes to {} in {}s".format(len(data), f, time.time() - start) + ) + + def _get_file(self) -> FileType: + if not self.cur_file or self.bytes_written >= self.max_file_size: + if self.cur_file: + self.cur_file.close() + timestr = datetime.today().strftime("%Y-%m-%d_%H-%M-%S") + path = os.path.join( + self.path, + "output-{}_worker-{}_{}.json".format( + timestr, self.ioctx.worker_index, self.file_index + ), + ) + if self.path_is_uri: + if smart_open is None: + raise ValueError( + "You must install the `smart_open` module to write " + "to URIs like {}".format(path) + ) + self.cur_file = smart_open(path, "w") + else: + self.cur_file = open(path, "w") + self.file_index += 1 + self.bytes_written = 0 + logger.info("Writing to new output file {}".format(self.cur_file)) + return self.cur_file + + +def _to_jsonable(v, compress: bool) -> Any: + if compress and compression_supported(): + return str(pack(v)) + elif isinstance(v, np.ndarray): + return v.tolist() + + return v + + +def _to_json_dict(batch: SampleBatchType, compress_columns: List[str]) -> Dict: + out = {} + if isinstance(batch, MultiAgentBatch): + out["type"] = "MultiAgentBatch" + out["count"] = batch.count + policy_batches = {} + for policy_id, sub_batch in batch.policy_batches.items(): + policy_batches[policy_id] = {} + for k, v in sub_batch.items(): + policy_batches[policy_id][k] = _to_jsonable( + v, compress=k in compress_columns + ) + out["policy_batches"] = policy_batches + else: + out["type"] = "SampleBatch" + for k, v in batch.items(): + out[k] = _to_jsonable(v, compress=k in compress_columns) + return out + + +def _to_json(batch: SampleBatchType, compress_columns: List[str]) -> str: + out = _to_json_dict(batch, compress_columns) + return json.dumps(out, cls=SafeFallbackEncoder) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/mixed_input.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/mixed_input.py new file mode 100644 index 0000000000000000000000000000000000000000..8c8ad60b06f9baa34bfe7432e5ea6f95d59a3fbd --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/mixed_input.py @@ -0,0 +1,58 @@ +from types import FunctionType +from typing import Dict + +import numpy as np +from ray.rllib.offline.input_reader import InputReader +from ray.rllib.offline.io_context import IOContext +from ray.rllib.offline.json_reader import JsonReader +from ray.rllib.utils.annotations import override, DeveloperAPI +from ray.rllib.utils.typing import SampleBatchType +from ray.tune.registry import registry_get_input, registry_contains_input + + +@DeveloperAPI +class MixedInput(InputReader): + """Mixes input from a number of other input sources. + + .. testcode:: + :skipif: True + + from ray.rllib.offline.io_context import IOContext + from ray.rllib.offline.mixed_input import MixedInput + ioctx = IOContext(...) + MixedInput({ + "sampler": 0.4, + "/tmp/experiences/*.json": 0.4, + "s3://bucket/expert.json": 0.2, + }, ioctx) + """ + + @DeveloperAPI + def __init__(self, dist: Dict[JsonReader, float], ioctx: IOContext): + """Initialize a MixedInput. + + Args: + dist: dict mapping JSONReader paths or "sampler" to + probabilities. The probabilities must sum to 1.0. + ioctx: current IO context object. + """ + if sum(dist.values()) != 1.0: + raise ValueError("Values must sum to 1.0: {}".format(dist)) + self.choices = [] + self.p = [] + for k, v in dist.items(): + if k == "sampler": + self.choices.append(ioctx.default_sampler_input()) + elif isinstance(k, FunctionType): + self.choices.append(k(ioctx)) + elif isinstance(k, str) and registry_contains_input(k): + input_creator = registry_get_input(k) + self.choices.append(input_creator(ioctx)) + else: + self.choices.append(JsonReader(k, ioctx)) + self.p.append(v) + + @override(InputReader) + def next(self) -> SampleBatchType: + source = np.random.choice(self.choices, p=self.p) + return source.next() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/off_policy_estimator.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/off_policy_estimator.py new file mode 100644 index 0000000000000000000000000000000000000000..c8a08fb4a1dfa5c31a5fac94ded7e874504507aa --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/off_policy_estimator.py @@ -0,0 +1,10 @@ +from ray.rllib.offline.estimators.off_policy_estimator import ( # noqa: F401 + OffPolicyEstimator, +) +from ray.rllib.utils.deprecation import deprecation_warning + +deprecation_warning( + old="ray.rllib.offline.off_policy_estimator", + new="ray.rllib.offline.estimators.off_policy_estimator", + error=True, +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/offline_data.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/offline_data.py new file mode 100644 index 0000000000000000000000000000000000000000..f48346ed0cc712047036decd9ec13135e2f13284 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/offline_data.py @@ -0,0 +1,290 @@ +import logging +from pathlib import Path +import pyarrow.fs +import numpy as np +import ray +import time +import types + +from typing import Any, Dict, TYPE_CHECKING + +from ray.rllib.core import COMPONENT_RL_MODULE +from ray.rllib.env import INPUT_ENV_SPACES +from ray.rllib.offline.offline_prelearner import OfflinePreLearner +from ray.rllib.utils import unflatten_dict +from ray.rllib.policy.sample_batch import MultiAgentBatch, SampleBatch +from ray.rllib.utils import force_list +from ray.rllib.utils.annotations import ( + OverrideToImplementCustomLogic, + OverrideToImplementCustomLogic_CallToSuperRecommended, +) +from ray.util.annotations import PublicAPI + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + +logger = logging.getLogger(__name__) + + +@PublicAPI(stability="alpha") +class OfflineData: + @OverrideToImplementCustomLogic_CallToSuperRecommended + def __init__(self, config: "AlgorithmConfig"): + + # TODO (simon): Define self.spaces here. + self.config = config + self.is_multi_agent = self.config.is_multi_agent + self.path = ( + self.config.input_ + if isinstance(config.input_, list) + else Path(config.input_) + ) + # Use `read_parquet` as default data read method. + self.data_read_method = self.config.input_read_method + # Override default arguments for the data read method. + self.data_read_method_kwargs = self.config.input_read_method_kwargs + # In case `EpisodeType` or `BatchType` batches are read the size + # could differ from the final `train_batch_size_per_learner`. + self.data_read_batch_size = self.config.input_read_batch_size + + # If data should be materialized. + self.materialize_data = config.materialize_data + # If mapped data should be materialized. + self.materialize_mapped_data = config.materialize_mapped_data + # Flag to identify, if data has already been mapped with the + # `OfflinePreLearner`. + self.data_is_mapped = False + + # Set the filesystem. + self.filesystem = self.config.input_filesystem + self.filesystem_kwargs = self.config.input_filesystem_kwargs + self.filesystem_object = None + + # If a specific filesystem is given, set it up. Note, this could + # be `gcsfs` for GCS, `pyarrow` for S3 or `adlfs` for Azure Blob Storage. + # this filesystem is specifically needed, if a session has to be created + # with the cloud provider. + if self.filesystem == "gcs": + import gcsfs + + self.filesystem_object = gcsfs.GCSFileSystem(**self.filesystem_kwargs) + elif self.filesystem == "s3": + self.filesystem_object = pyarrow.fs.S3FileSystem(**self.filesystem_kwargs) + elif self.filesystem == "abs": + import adlfs + + self.filesystem_object = adlfs.AzureBlobFileSystem(**self.filesystem_kwargs) + elif isinstance(self.filesystem, pyarrow.fs.FileSystem): + self.filesystem_object = self.filesystem + elif self.filesystem is not None: + raise ValueError( + f"Unknown `config.input_filesystem` {self.filesystem}! Filesystems " + "can be None for local, any instance of `pyarrow.fs.FileSystem`, " + "'gcs' for GCS, 's3' for S3, or 'abs' for adlfs.AzureBlobFileSystem." + ) + # Add the filesystem object to the write method kwargs. + if self.filesystem_object: + self.data_read_method_kwargs.update( + { + "filesystem": self.filesystem_object, + } + ) + + try: + # Load the dataset. + start_time = time.perf_counter() + self.data = getattr(ray.data, self.data_read_method)( + self.path, **self.data_read_method_kwargs + ) + if self.materialize_data: + self.data = self.data.materialize() + stop_time = time.perf_counter() + logger.debug( + "===> [OfflineData] - Time for loading dataset: " + f"{stop_time - start_time}s." + ) + logger.info("Reading data from {}".format(self.path)) + except Exception as e: + logger.error(e) + # Avoids reinstantiating the batch iterator each time we sample. + self.batch_iterators = None + self.map_batches_kwargs = ( + self.default_map_batches_kwargs | self.config.map_batches_kwargs + ) + self.iter_batches_kwargs = ( + self.default_iter_batches_kwargs | self.config.iter_batches_kwargs + ) + self.returned_streaming_split = False + # Defines the prelearner class. Note, this could be user-defined. + self.prelearner_class = self.config.prelearner_class or OfflinePreLearner + # For remote learner setups. + self.locality_hints = None + self.learner_handles = None + self.module_spec = None + + @OverrideToImplementCustomLogic + def sample( + self, + num_samples: int, + return_iterator: bool = False, + num_shards: int = 1, + module_state: Dict[str, Any] = None, + ): + # Materialize the mapped data, if necessary. This runs for all the + # data the `OfflinePreLearner` logic and maps them to `MultiAgentBatch`es. + # TODO (simon, sven): This would never update the module nor the + # the connectors. If this is needed we have to check, if we give + # (a) only an iterator and let the learner and OfflinePreLearner + # communicate through the object storage. This only works when + # not materializing. + # (b) Rematerialize the data every couple of iterations. This is + # is costly. + if not self.data_is_mapped: + + if not module_state: + # Get the RLModule state from learners. + if num_shards >= 1: + # Call here the learner to get an up-to-date module state. + # TODO (simon): This is a workaround as along as learners cannot + # receive any calls from another actor. + module_state = ray.get( + self.learner_handles[0].get_state.remote( + component=COMPONENT_RL_MODULE, + ) + )[COMPONENT_RL_MODULE] + # Provide the `Learner`(s) GPU devices, if needed. + # if not self.map_batches_uses_gpus(self.config) and self.config._validate_config: + # devices = ray.get(self.learner_handles[0].get_device.remote()) + # devices = [devices] if not isinstance(devices, list) else devices + # device_strings = [ + # f"{device.type}:{str(device.index)}" + # if device.type == "cuda" + # else device.type + # for device in devices + # ] + # # Otherwise, set the GPU strings to `None`. + # # TODO (simon): Check inside 'OfflinePreLearner'. + # else: + # device_strings = None + else: + # Get the module state from the `Learner`(S). + module_state = self.learner_handles[0].get_state( + component=COMPONENT_RL_MODULE, + )[COMPONENT_RL_MODULE] + # Provide the `Learner`(s) GPU devices, if needed. + # if not self.map_batches_uses_gpus(self.config) and self.config._validate_config: + # device = self.learner_handles[0].get_device() + # device_strings = [ + # f"{device.type}:{str(device.index)}" + # if device.type == "cuda" + # else device.type + # ] + # else: + # device_strings = None + # Constructor `kwargs` for the `OfflinePreLearner`. + fn_constructor_kwargs = { + "config": self.config, + "spaces": self.spaces[INPUT_ENV_SPACES], + "module_spec": self.module_spec, + "module_state": module_state, + # "device_strings": self.get_devices(), + } + + # Map the data to run the `OfflinePreLearner`s in the data pipeline + # for training. + self.data = self.data.map_batches( + self.prelearner_class, + fn_constructor_kwargs=fn_constructor_kwargs, + batch_size=self.data_read_batch_size or num_samples, + **self.map_batches_kwargs, + ) + # Set the flag to `True`. + self.data_is_mapped = True + # If the user wants to materialize the data in memory. + if self.materialize_mapped_data: + self.data = self.data.materialize() + # Build an iterator, if necessary. Note, in case that an iterator should be + # returned now and we have already generated from the iterator, i.e. + # `isinstance(self.batch_iterators, types.GeneratorType) == True`, we need + # to create here a new iterator. + # TODO (simon): Check, if this iterator could potentially exhaust. + if not self.batch_iterators or ( + return_iterator and isinstance(self.batch_iterators, types.GeneratorType) + ): + # If we have more than one learner create an iterator for each of them + # by splitting the data stream. + if num_shards > 1: + logger.debug("===> [OfflineData]: Return streaming_split ... ") + # In case of multiple shards, we return multiple + # `StreamingSplitIterator` instances. + self.batch_iterators = self.data.streaming_split( + n=num_shards, + # Note, `equal` must be `True`, i.e. the batch size must + # be the same for all batches b/c otherwise remote learners + # could block each others. + equal=True, + locality_hints=self.locality_hints, + ) + # Otherwise we create a simple iterator and - if necessary - initialize + # it here. + else: + # Should an iterator be returned? + if return_iterator: + self.batch_iterators = self.data.iterator() + # Otherwise, the user wants batches returned. + else: + # Define a collate (last-mile) transformation that maps batches + # to RLlib's `MultiAgentBatch`. + def _collate_fn(_batch: Dict[str, np.ndarray]) -> MultiAgentBatch: + _batch = unflatten_dict(_batch) + return MultiAgentBatch( + { + module_id: SampleBatch(module_data) + for module_id, module_data in _batch.items() + }, + env_steps=sum( + len(next(iter(module_data.values()))) + for module_data in _batch.values() + ), + ) + + # If no iterator should be returned, or if we want to return a single + # batch iterator, we instantiate the batch iterator once, here. + self.batch_iterators = self.data.iter_batches( + batch_size=num_samples, + _collate_fn=_collate_fn, + **self.iter_batches_kwargs, + ) + self.batch_iterators = iter(self.batch_iterators) + + # Do we want to return an iterator or a single batch? + if return_iterator: + return force_list(self.batch_iterators) + else: + # Return a single batch from the iterator. + try: + return next(self.batch_iterators) + except StopIteration: + # If the batch iterator is exhausted, reinitiate a new one. + logger.debug( + "===> [OfflineData]: Batch iterator exhausted. Reinitiating ..." + ) + self.batch_iterators = None + return self.sample( + num_samples=num_samples, + return_iterator=return_iterator, + num_shards=num_shards, + ) + + @property + def default_map_batches_kwargs(self): + return { + "concurrency": max(2, self.config.num_learners), + "zero_copy_batch": True, + } + + @property + def default_iter_batches_kwargs(self): + return { + "prefetch_batches": 2, + } diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/offline_env_runner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/offline_env_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..704ed175be532df8990cc0317faa4f8a3e0b29fd --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/offline_env_runner.py @@ -0,0 +1,313 @@ +import logging +import ray + +from pathlib import Path +from typing import List + +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig +from ray.rllib.core.columns import Columns +from ray.rllib.env.env_runner import EnvRunner +from ray.rllib.env.single_agent_env_runner import SingleAgentEnvRunner +from ray.rllib.env.single_agent_episode import SingleAgentEpisode +from ray.rllib.utils.annotations import ( + override, + OverrideToImplementCustomLogic_CallToSuperRecommended, + OverrideToImplementCustomLogic, +) +from ray.rllib.utils.compression import pack_if_needed +from ray.rllib.utils.spaces.space_utils import to_jsonable_if_needed +from ray.rllib.utils.typing import EpisodeType +from ray.util.debug import log_once +from ray.util.annotations import PublicAPI + +logger = logging.Logger(__file__) + +# TODO (simon): This class can be agnostic to the episode type as it +# calls only get_state. + + +@PublicAPI(stability="alpha") +class OfflineSingleAgentEnvRunner(SingleAgentEnvRunner): + """The environment runner to record the single agent case.""" + + @override(SingleAgentEnvRunner) + @OverrideToImplementCustomLogic_CallToSuperRecommended + def __init__(self, *, config: AlgorithmConfig, **kwargs): + # Initialize the parent. + super().__init__(config=config, **kwargs) + + # Get the data context for this `EnvRunner`. + data_context = ray.data.DataContext.get_current() + # Limit the resources for Ray Data to the CPUs given to this `EnvRunner`. + data_context.execution_options.resource_limits = ( + data_context.execution_options.resource_limits.copy( + cpu=config.num_cpus_per_env_runner + ) + ) + + # Set the output write method. + self.output_write_method = self.config.output_write_method + self.output_write_method_kwargs = self.config.output_write_method_kwargs + + # Set the filesystem. + self.filesystem = self.config.output_filesystem + self.filesystem_kwargs = self.config.output_filesystem_kwargs + self.filesystem_object = None + + # Set the output base path. + self.output_path = self.config.output + # Set the subdir (environment specific). + self.subdir_path = self.config.env.lower() + # Set the worker-specific path name. Note, this is + # specifically to enable multi-threaded writing into + # the same directory. + self.worker_path = "run-" + f"{self.worker_index}".zfill(6) + + # If a specific filesystem is given, set it up. Note, this could + # be `gcsfs` for GCS, `pyarrow` for S3 or `adlfs` for Azure Blob Storage. + # this filesystem is specifically needed, if a session has to be created + # with the cloud provider. + + if self.filesystem == "gcs": + import gcsfs + + self.filesystem_object = gcsfs.GCSFileSystem(**self.filesystem_kwargs) + elif self.filesystem == "s3": + from pyarrow import fs + + self.filesystem_object = fs.S3FileSystem(**self.filesystem_kwargs) + elif self.filesystem == "abs": + import adlfs + + self.filesystem_object = adlfs.AzureBlobFileSystem(**self.filesystem_kwargs) + elif self.filesystem is not None: + raise ValueError( + f"Unknown filesystem: {self.filesystem}. Filesystems can be " + "'gcs' for GCS, 's3' for S3, or 'abs'" + ) + # Add the filesystem object to the write method kwargs. + self.output_write_method_kwargs.update( + { + "filesystem": self.filesystem_object, + } + ) + + # If we should store `SingleAgentEpisodes` or column data. + self.output_write_episodes = self.config.output_write_episodes + # Which columns should be compressed in the output data. + self.output_compress_columns = self.config.output_compress_columns + + # Buffer these many rows before writing to file. + self.output_max_rows_per_file = self.config.output_max_rows_per_file + # If the user defines a maximum number of rows per file, set the + # event to `False` and check during sampling. + if self.output_max_rows_per_file: + self.write_data_this_iter = False + # Otherwise the event is always `True` and we write always sampled + # data immediately to disk. + else: + self.write_data_this_iter = True + + # If the remaining data should be stored. Note, this is only + # relevant in case `output_max_rows_per_file` is defined. + self.write_remaining_data = self.config.output_write_remaining_data + + # Counts how often `sample` is called to define the output path for + # each file. + self._sample_counter = 0 + + # Define the buffer for experiences stored until written to disk. + self._samples = [] + + @override(SingleAgentEnvRunner) + @OverrideToImplementCustomLogic + def sample( + self, + *, + num_timesteps: int = None, + num_episodes: int = None, + explore: bool = None, + random_actions: bool = False, + force_reset: bool = False, + ) -> List[SingleAgentEpisode]: + """Samples from environments and writes data to disk.""" + + # Call the super sample method. + samples = super().sample( + num_timesteps=num_timesteps, + num_episodes=num_episodes, + explore=explore, + random_actions=random_actions, + force_reset=force_reset, + ) + + self._sample_counter += 1 + + # Add data to the buffers. + if self.output_write_episodes: + + import msgpack + import msgpack_numpy as mnp + + if log_once("msgpack"): + logger.info( + "Packing episodes with `msgpack` and encode array with " + "`msgpack_numpy` for serialization. This is needed for " + "recording episodes." + ) + # Note, we serialize episodes with `msgpack` and `msgpack_numpy` to + # ensure version compatibility. + self._samples.extend( + [msgpack.packb(eps.get_state(), default=mnp.encode) for eps in samples] + ) + else: + self._map_episodes_to_data(samples) + + # If the user defined the maximum number of rows to write. + if self.output_max_rows_per_file: + # Check, if this number is reached. + if len(self._samples) >= self.output_max_rows_per_file: + # Start the recording of data. + self.write_data_this_iter = True + + if self.write_data_this_iter: + # If the user wants a maximum number of experiences per file, + # cut the samples to write to disk from the buffer. + if self.output_max_rows_per_file: + # Reset the event. + self.write_data_this_iter = False + # Ensure that all data ready to be written is released from + # the buffer. Note, this is important in case we have many + # episodes sampled and a relatively small `output_max_rows_per_file`. + while len(self._samples) >= self.output_max_rows_per_file: + # Extract the number of samples to be written to disk this + # iteration. + samples_to_write = self._samples[: self.output_max_rows_per_file] + # Reset the buffer to the remaining data. This only makes sense, if + # `rollout_fragment_length` is smaller `output_max_rows_per_file` or + # a 2 x `output_max_rows_per_file`. + self._samples = self._samples[self.output_max_rows_per_file :] + samples_ds = ray.data.from_items(samples_to_write) + # Otherwise, write the complete data. + else: + samples_ds = ray.data.from_items(self._samples) + try: + # Setup the path for writing data. Each run will be written to + # its own file. A run is a writing event. The path will look + # like. 'base_path/env-name/00000-00000'. + path = ( + Path(self.output_path) + .joinpath(self.subdir_path) + .joinpath(self.worker_path + f"-{self._sample_counter}".zfill(6)) + ) + getattr(samples_ds, self.output_write_method)( + path.as_posix(), **self.output_write_method_kwargs + ) + logger.info(f"Wrote samples to storage at {path}.") + except Exception as e: + logger.error(e) + + self.metrics.log_value( + key="recording_buffer_size", + value=len(self._samples), + ) + + # Finally return the samples as usual. + return samples + + @override(EnvRunner) + @OverrideToImplementCustomLogic + def stop(self) -> None: + """Writes the reamining samples to disk + + Note, if the user defined `max_rows_per_file` the + number of rows for the remaining samples could be + less than the defined maximum row number by the user. + """ + # If there are samples left over we have to write htem to disk. them + # to a dataset. + if self._samples and self.write_remaining_data: + # Convert them to a `ray.data.Dataset`. + samples_ds = ray.data.from_items(self._samples) + # Increase the sample counter for the folder/file name. + self._sample_counter += 1 + # Try to write the dataset to disk/cloud storage. + try: + # Setup the path for writing data. Each run will be written to + # its own file. A run is a writing event. The path will look + # like. 'base_path/env-name/00000-00000'. + path = ( + Path(self.output_path) + .joinpath(self.subdir_path) + .joinpath(self.worker_path + f"-{self._sample_counter}".zfill(6)) + ) + getattr(samples_ds, self.output_write_method)( + path.as_posix(), **self.output_write_method_kwargs + ) + logger.info( + f"Wrote final samples to storage at {path}. Note " + "Note, final samples could be smaller in size than " + f"`max_rows_per_file`, if defined." + ) + except Exception as e: + logger.error(e) + + logger.debug(f"Experience buffer length: {len(self._samples)}") + + @OverrideToImplementCustomLogic + def _map_episodes_to_data(self, samples: List[EpisodeType]) -> None: + """Converts list of episodes to list of single dict experiences. + + Note, this method also appends all sampled experiences to the + buffer. + + Args: + samples: List of episodes to be converted. + """ + # Loop through all sampled episodes. + obs_space = self.env.observation_space + action_space = self.env.action_space + for sample in samples: + # Loop through all items of the episode. + for i in range(len(sample)): + sample_data = { + Columns.EPS_ID: sample.id_, + Columns.AGENT_ID: sample.agent_id, + Columns.MODULE_ID: sample.module_id, + # Compress observations, if requested. + Columns.OBS: pack_if_needed( + to_jsonable_if_needed(sample.get_observations(i), obs_space) + ) + if Columns.OBS in self.output_compress_columns + else to_jsonable_if_needed(sample.get_observations(i), obs_space), + # Compress actions, if requested. + Columns.ACTIONS: pack_if_needed( + to_jsonable_if_needed(sample.get_actions(i), action_space) + ) + if Columns.ACTIONS in self.output_compress_columns + else to_jsonable_if_needed(sample.get_actions(i), action_space), + Columns.REWARDS: sample.get_rewards(i), + # Compress next observations, if requested. + Columns.NEXT_OBS: pack_if_needed( + to_jsonable_if_needed(sample.get_observations(i + 1), obs_space) + ) + if Columns.OBS in self.output_compress_columns + else to_jsonable_if_needed( + sample.get_observations(i + 1), obs_space + ), + Columns.TERMINATEDS: False + if i < len(sample) - 1 + else sample.is_terminated, + Columns.TRUNCATEDS: False + if i < len(sample) - 1 + else sample.is_truncated, + **{ + # Compress any extra model output, if requested. + k: pack_if_needed(sample.get_extra_model_outputs(k, i)) + if k in self.output_compress_columns + else sample.get_extra_model_outputs(k, i) + for k in sample.extra_model_outputs.keys() + }, + } + # Finally append to the data buffer. + self._samples.append(sample_data) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/offline_evaluation_runner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/offline_evaluation_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..8578256c560dd3a394fdfd071ed397f9534ae3f7 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/offline_evaluation_runner.py @@ -0,0 +1,465 @@ +import ray +import types + +from typing import Any, Collection, Dict, Iterable, Optional, TYPE_CHECKING, Union + +from ray.data.iterator import DataIterator +from ray.rllib.core import ( + ALL_MODULES, + COMPONENT_RL_MODULE, +) +from ray.rllib.core.rl_module.apis import SelfSupervisedLossAPI +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec +from ray.rllib.policy.sample_batch import MultiAgentBatch +from ray.rllib.utils.annotations import override +from ray.rllib.utils.checkpoints import Checkpointable +from ray.rllib.utils.framework import get_device, try_import_torch +from ray.rllib.utils.metrics import ( + DATASET_NUM_ITERS_EVALUATED, + DATASET_NUM_ITERS_EVALUATED_LIFETIME, + MODULE_SAMPLE_BATCH_SIZE_MEAN, + NUM_ENV_STEPS_SAMPLED, + NUM_ENV_STEPS_SAMPLED_LIFETIME, + NUM_MODULE_STEPS_SAMPLED, + NUM_MODULE_STEPS_SAMPLED_LIFETIME, + OFFLINE_SAMPLING_TIMER, + WEIGHTS_SEQ_NO, +) +from ray.rllib.utils.minibatch_utils import MiniBatchRayDataIterator +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.runners.runner import Runner +from ray.rllib.utils.torch_utils import convert_to_torch_tensor +from ray.rllib.utils.typing import DeviceType, ModuleID, StateDict, TensorType + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + +torch, _ = try_import_torch() + +TOTAL_EVAL_LOSS_KEY = "total_eval_loss" + + +class OfflineEvaluationRunner(Runner, Checkpointable): + def __init__( + self, + config: "AlgorithmConfig", + module_spec: Optional[MultiRLModuleSpec] = None, + **kwargs, + ): + + # This needs to be defined before we call the `Runner.__init__` + # b/c the latter calls the `make_module` and then needs the spec. + # TODO (simon): Check, if we make this a generic attribute. + self.__module_spec: MultiRLModuleSpec = module_spec + self.__dataset_iterator = None + self.__batch_iterator = None + + Runner.__init__(self, config=config, **kwargs) + Checkpointable.__init__(self) + + # This has to be defined after we have a `self.config`. + self._loss_for_module_fn = types.MethodType(self.get_loss_for_module_fn(), self) + + @override(Runner) + def run( + self, + explore: bool = False, + train: bool = True, + **kwargs, + ) -> None: + + if self.__dataset_iterator is None: + raise ValueError( + f"{self} doesn't have a data iterator. Can't call `run` on " + "`OfflineEvaluationRunner`." + ) + + if not self._batch_iterator: + self.__batch_iterator = self._create_batch_iterator( + **self.config.iter_batches_kwargs + ) + + # Log current weight seq no. + self.metrics.log_value( + key=WEIGHTS_SEQ_NO, + value=self._weights_seq_no, + window=1, + ) + + with self.metrics.log_time(OFFLINE_SAMPLING_TIMER): + if explore is None: + explore = self.config.explore + + # Evaluate on offline data. + return self._evaluate( + explore=explore, + train=train, + ) + + def _create_batch_iterator(self, **kwargs) -> Iterable: + + # Return a minibatch iterator. + return MiniBatchRayDataIterator( + iterator=self._dataset_iterator, + device=self._device, + minibatch_size=self.config.offline_eval_batch_size_per_runner, + num_iters=self.config.dataset_num_iters_per_eval_runner, + **kwargs, + ) + + def _evaluate( + self, + explore: bool, + train: bool, + ) -> None: + + self.metrics.activate_tensor_mode() + + for iteration, tensor_minibatch in enumerate(self._batch_iterator): + # Check the MultiAgentBatch, whether our RLModule contains all ModuleIDs + # found in this batch. If not, throw an error. + unknown_module_ids = set(tensor_minibatch.policy_batches.keys()) - set( + self.module.keys() + ) + if unknown_module_ids: + raise ValueError( + f"Batch contains one or more ModuleIDs ({unknown_module_ids}) that " + f"are not in this Learner!" + ) + + if explore: + fwd_out = self.module.forward_exploration( + tensor_minibatch.policy_batches + ) + elif train: + fwd_out = self.module.forward_train(tensor_minibatch.policy_batches) + else: + fwd_out = self.module.forward_inference(tensor_minibatch.policy_batches) + + eval_loss_per_module = self.compute_eval_losses( + fwd_out=fwd_out, batch=tensor_minibatch.policy_batches + ) + + self._log_steps_evaluated_metrics(tensor_minibatch) + + # Record the number of batches pulled from the dataset. + self.metrics.log_value( + # TODO (simon): Create extra eval metrics. + (ALL_MODULES, DATASET_NUM_ITERS_EVALUATED), + iteration + 1, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (ALL_MODULES, DATASET_NUM_ITERS_EVALUATED_LIFETIME), + iteration + 1, + reduce="sum", + ) + # Log all individual RLModules' loss terms + # Note: We do this only once for the last of the minibatch updates, b/c the + # window is only 1 anyways. + for mid, loss in convert_to_numpy(eval_loss_per_module).items(): + self.metrics.log_value( + key=(mid, TOTAL_EVAL_LOSS_KEY), + value=loss, + window=1, + ) + + self.metrics.deactivate_tensor_mode() + + return self.metrics.reduce() + + @override(Checkpointable) + def get_ctor_args_and_kwargs(self): + return ( + (), # *args + {"config": self.config}, # **kwargs + ) + + @override(Checkpointable) + def get_state( + self, + components: Optional[Union[str, Collection[str]]] = None, + *, + not_components: Optional[Union[str, Collection[str]]] = None, + **kwargs, + ) -> StateDict: + state = { + NUM_ENV_STEPS_SAMPLED_LIFETIME: ( + self.metrics.peek(NUM_ENV_STEPS_SAMPLED_LIFETIME, default=0) + ), + } + + if self._check_component(COMPONENT_RL_MODULE, components, not_components): + state[COMPONENT_RL_MODULE] = self.module.get_state( + components=self._get_subcomponents(COMPONENT_RL_MODULE, components), + not_components=self._get_subcomponents( + COMPONENT_RL_MODULE, not_components + ), + **kwargs, + ) + state[WEIGHTS_SEQ_NO] = self._weights_seq_no + + return state + + def _convert_to_tensor(self, struct) -> TensorType: + """Converts structs to a framework-specific tensor.""" + return convert_to_torch_tensor(struct) + + @override(Runner) + def stop(self) -> None: + """Releases all resources used by this EnvRunner. + + For example, when using a gym.Env in this EnvRunner, you should make sure + that its `close()` method is called. + """ + pass + + @override(Runner) + def __del__(self) -> None: + """If this Actor is deleted, clears all resources used by it.""" + pass + + @override(Runner) + def assert_healthy(self): + """Checks that self.__init__() has been completed properly. + + Ensures that the instances has a `MultiRLModule` and an + environment defined. + + Raises: + AssertionError: If the EnvRunner Actor has NOT been properly initialized. + """ + # Make sure, we have built our RLModule properly and assigned a dataset iterator. + assert self._dataset_iterator and hasattr(self, "module") + + @override(Runner) + def get_metrics(self): + return self.metrics.reduce() + + def _convert_batch_type( + self, + batch: MultiAgentBatch, + to_device: bool = True, + pin_memory: bool = False, + use_stream: bool = False, + ) -> MultiAgentBatch: + batch = convert_to_torch_tensor( + batch.policy_batches, + device=self._device if to_device else None, + pin_memory=pin_memory, + use_stream=use_stream, + ) + # TODO (sven): This computation of `env_steps` is not accurate! + length = max(len(b) for b in batch.values()) + batch = MultiAgentBatch(batch, env_steps=length) + return batch + + def compute_eval_losses( + self, *, fwd_out: Dict[str, Any], batch: Dict[str, Any] + ) -> Dict[str, Any]: + + loss_per_module = {} + for module_id in fwd_out: + module_batch = batch[module_id] + module_fwd_out = fwd_out[module_id] + + module = self.module[module_id].unwrapped() + if isinstance(module, SelfSupervisedLossAPI): + loss = module.compute_self_supervised_loss( + learner=self, + module_id=module_id, + config=self.config.get_config_for_module(module_id), + batch=module_batch, + fwd_out=module_fwd_out, + ) + else: + loss = self.compute_eval_loss_for_module( + module_id=module_id, + config=self.config.get_config_for_module(module_id), + batch=module_batch, + fwd_out=module_fwd_out, + ) + loss_per_module[module_id] = loss + + return loss_per_module + + def compute_eval_loss_for_module( + self, + *, + module_id: ModuleID, + config: "AlgorithmConfig", + batch: Dict[str, Any], + fwd_out: Dict[str, TensorType], + ) -> TensorType: + + return self._loss_for_module_fn( + module_id=module_id, + config=config, + batch=batch, + fwd_out=fwd_out, + ) + + @override(Checkpointable) + def set_state(self, state: StateDict) -> None: + + # Update the RLModule state. + if COMPONENT_RL_MODULE in state: + # A missing value for WEIGHTS_SEQ_NO or a value of 0 means: Force the + # update. + weights_seq_no = state.get(WEIGHTS_SEQ_NO, 0) + + # Only update the weigths, if this is the first synchronization or + # if the weights of this `EnvRunner` lacks behind the actual ones. + if weights_seq_no == 0 or self._weights_seq_no < weights_seq_no: + rl_module_state = state[COMPONENT_RL_MODULE] + if isinstance(rl_module_state, ray.ObjectRef): + rl_module_state = ray.get(rl_module_state) + self.module.set_state(rl_module_state) + + # Update our weights_seq_no, if the new one is > 0. + if weights_seq_no > 0: + self._weights_seq_no = weights_seq_no + + # Update our lifetime counters. + # TODO (simon): Create extra metrics. + if NUM_ENV_STEPS_SAMPLED_LIFETIME in state: + self.metrics.set_value( + key=NUM_ENV_STEPS_SAMPLED_LIFETIME, + value=state[NUM_ENV_STEPS_SAMPLED_LIFETIME], + reduce="sum", + with_throughput=True, + ) + + def _log_steps_evaluated_metrics(self, batch: MultiAgentBatch) -> None: + for mid, module_batch in batch.policy_batches.items(): + # Log weights seq no for this batch. + self.metrics.log_value( + (mid, WEIGHTS_SEQ_NO), + self._weights_seq_no, + window=1, + ) + + module_batch_size = len(module_batch) + # Log average batch size (for each module). + self.metrics.log_value( + key=(mid, MODULE_SAMPLE_BATCH_SIZE_MEAN), + value=module_batch_size, + ) + # Log module steps (for each module). + self.metrics.log_value( + key=(mid, NUM_MODULE_STEPS_SAMPLED), + value=module_batch_size, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + key=(mid, NUM_MODULE_STEPS_SAMPLED_LIFETIME), + value=module_batch_size, + reduce="sum", + ) + # Log module steps (sum of all modules). + self.metrics.log_value( + key=(ALL_MODULES, NUM_MODULE_STEPS_SAMPLED), + value=module_batch_size, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + key=(ALL_MODULES, NUM_MODULE_STEPS_SAMPLED_LIFETIME), + value=module_batch_size, + reduce="sum", + ) + # Log env steps (all modules). + self.metrics.log_value( + (ALL_MODULES, NUM_ENV_STEPS_SAMPLED), + batch.env_steps(), + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (ALL_MODULES, NUM_ENV_STEPS_SAMPLED_LIFETIME), + batch.env_steps(), + reduce="sum", + with_throughput=True, + ) + + @override(Runner) + def set_device(self): + try: + self.__device = get_device( + self.config, + 0 + if not self.worker_index + else self.config.num_gpus_per_offline_eval_runner, + ) + except NotImplementedError: + self.__device = None + + @override(Runner) + def make_module(self): + try: + from ray.rllib.env import INPUT_ENV_SPACES + + if not self._module_spec: + self.__module_spec = self.config.get_multi_rl_module_spec( + # Note, usually we have no environemnt in case of offline evaluation. + env=self.config.env, + spaces={ + INPUT_ENV_SPACES: ( + self.config.observation_space, + self.config.action_space, + ) + }, + inference_only=self.config.offline_eval_rl_module_inference_only, + ) + # Build the module from its spec. + self.module = self._module_spec.build() + # TODO (simon): Implement GPU inference. + # Move the RLModule to our device. + # TODO (sven): In order to make this framework-agnostic, we should maybe + # make the MultiRLModule.build() method accept a device OR create an + # additional `(Multi)RLModule.to()` override. + + self.module.foreach_module( + lambda mid, mod: ( + mod.to(self._device) if isinstance(mod, torch.nn.Module) else mod + ) + ) + + # If `AlgorithmConfig.get_multi_rl_module_spec()` is not implemented, this env runner + # will not have an RLModule, but might still be usable with random actions. + except NotImplementedError: + self.module = None + + def get_loss_for_module_fn(self): + # Either the user has provided a loss-for-module function, or we take + # the loss function from the default `Learner` class. + return ( + self.config.offline_loss_for_module_fn + or self.config.get_default_learner_class().__dict__[ + "compute_loss_for_module" + ] + ) + + @property + def _dataset_iterator(self) -> DataIterator: + """Returns the dataset iterator.""" + return self.__dataset_iterator + + def set_dataset_iterator(self, iterator): + """Sets the dataset iterator.""" + self.__dataset_iterator = iterator + + @property + def _batch_iterator(self) -> MiniBatchRayDataIterator: + return self.__batch_iterator + + @property + def _device(self) -> DeviceType: + return self.__device + + @property + def _module_spec(self) -> MultiRLModuleSpec: + """Returns the `MultiRLModuleSpec` of this `Runner`.""" + return self.__module_spec diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/offline_evaluation_runner_group.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/offline_evaluation_runner_group.py new file mode 100644 index 0000000000000000000000000000000000000000..2f92e2d1aabf564858974dec49c4dc2e9fb59e3c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/offline_evaluation_runner_group.py @@ -0,0 +1,191 @@ +import ray +from typing import Any, Callable, Dict, List, Optional, TYPE_CHECKING + +from ray.data.iterator import DataIterator +from ray.rllib.core import DEFAULT_MODULE_ID +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec +from ray.rllib.env import INPUT_ENV_SPACES +from ray.rllib.offline.offline_data import OfflineData +from ray.rllib.offline.offline_evaluation_runner import OfflineEvaluationRunner +from ray.rllib.offline.offline_policy_evaluation_runner import ( + OfflinePolicyEvaluationRunner, + OfflinePolicyPreEvaluator, +) +from ray.rllib.offline.offline_prelearner import OfflinePreLearner +from ray.rllib.utils.annotations import override +from ray.rllib.utils.runners.runner_group import RunnerGroup + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + + +class OfflineEvaluationRunnerGroup(RunnerGroup): + def __init__( + self, + config: "AlgorithmConfig", + local_runner: Optional[bool] = False, + logdir: Optional[str] = None, + tune_trial_id: Optional[str] = None, + pg_offset: int = 0, + _setup: bool = True, + spaces: Optional[Dict[str, Any]] = None, + module_state: Dict[str, Any] = None, + module_spec: Optional[MultiRLModuleSpec] = None, + **kwargs: Dict[str, Any], + ) -> None: + + # TODO (simon): Check, if this should happen later when the dataset + # is created. Maybe just overriding _setup. + # First initialize the super class. + super().__init__( + config=config, + local_runner=local_runner, + logdir=logdir, + tune_trial_id=tune_trial_id, + pg_offset=pg_offset, + _setup=_setup, + module_state=module_state, + module_spec=module_spec, + spaces=spaces, + ) + + @override(RunnerGroup) + def _setup( + self, + *, + config: Optional["AlgorithmConfig"] = None, + num_runners: int = 0, + local_runner: Optional[bool] = False, + module_state: Dict[str, Any] = None, + module_spec: Optional[MultiRLModuleSpec] = None, + spaces: Optional[Dict[str, Any]] = None, + **kwargs: Dict[str, Any], + ) -> None: + + # Define the offline evaluation runner class. + self._runner_cls = config.offline_eval_runner_class or ( + OfflineEvaluationRunner + if config.offline_evaluation_type == "eval_loss" + else OfflinePolicyEvaluationRunner + ) + # Define + self._pre_learner_or_evaluator_cls = self.config.prelearner_class or ( + OfflinePreLearner + if config.offline_evaluation_type == "eval_loss" + else OfflinePolicyPreEvaluator + ) + self.config._is_frozen = False + self.config.prelearner_class = self._pre_learner_or_evaluator_cls + self.config._is_frozen = True + + # We can either run on a local runner or on remote runners only b/c + # streaming split needs remote runners. + if num_runners > 0 and local_runner: + raise ValueError( + f"Cannot run `OfflineEvaluationRunnerGroup with {num_runners=} " + "and a local runner. Either use no remote runners or only " + "remote runners." + ) + # Create all workers. + super()._setup( + config=config, + num_runners=num_runners, + local_runner=local_runner, + # Do not validate until the `DataIterators` are distributed. + validate=False, + module_spec=module_spec, + module_state=module_state, + spaces=spaces, + ) + + # Setup the evaluation offline dataset and return an iterator. + self._offline_data: OfflineData = OfflineData(config=config) + # We need the spaces to be defined for the `OfflinePreLearner`. + spaces = spaces or { + INPUT_ENV_SPACES: (config.observation_space, config.action_space) + } + self._offline_data.spaces = spaces + # The `OfflinePreLearner` also needs the module spec. + module_spec: MultiRLModuleSpec = module_spec or self.config.get_multi_rl_module_spec( + # TODO (simon): this needs merely the spaces defined via the connectors. + spaces={DEFAULT_MODULE_ID: spaces[INPUT_ENV_SPACES]}, + inference_only=self.config.offline_eval_rl_module_inference_only, + ) + self._offline_data.module_spec = module_spec + # If we have remote runners set the locality hints for the streaming split + # dataset iterators. + if self.num_remote_runners > 0: + runner_node_ids = self.foreach_runner( + lambda _: ray.get_runtime_context().get_node_id() + ) + if self.local_runner is not None: + runner_node_ids.insert(0, ray.get_runtime_context().get_node_id()) + self._offline_data.locality_hints = runner_node_ids + # Return a data iterator for each `Runner`. + self._offline_data_iterators: List[DataIterator] = self.offline_data.sample( + num_samples=self.config.offline_eval_batch_size_per_runner, + return_iterator=True, + num_shards=num_runners, + module_state=module_state, + ) + # Provide each `Runner` with a `DataIterator`. + self.foreach_runner( + func="set_dataset_iterator", + local_runner=local_runner, + kwargs=[ + {"iterator": iterator} for iterator in self._offline_data_iterators + ], + ) + # Now validate healthiness. + self.validate() + + @property + def runner_health_probe_timeout_s(self): + """Number of seconds to wait for health probe calls to `Runner`s.""" + return self.config.offline_eval_runner_health_probe_timeout_s + + @property + def runner_cls(self) -> Callable: + """Class for each runner.""" + return self._runner_cls + + @property + def num_runners(self) -> int: + """Number of runners to schedule and manage.""" + return self.config.num_offline_eval_runners + + @property + def offline_data(self) -> OfflineData: + return self._offline_data + + @property + def _remote_args(self): + """Remote arguments for each runner.""" + return { + "num_cpus": self._remote_config.num_cpus_per_offline_eval_runner, + "num_gpus": self._remote_config.num_gpus_per_offline_eval_runner, + "resources": self._remote_config.custom_resources_per_offline_eval_runner, + "max_restarts": ( + self.config.max_num_offline_eval_runner_restarts + if self.config.restart_failed_offline_eval_runners + else 0 + ), + } + + @property + def _ignore_ray_errors_on_runners(self): + """If errors in runners should be ignored.""" + return ( + self.config.ignore_offline_eval_runner_failures + or self.config.restart_failed_offline_eval_runners + ) + + @property + def _max_requests_in_flight_per_runner(self): + """Maximum requests in flight per runner.""" + return self.config.max_requests_in_flight_per_offline_eval_runner + + @property + def _validate_runners_after_construction(self): + """If runners should validated after constructed.""" + return self.config.validate_offline_eval_runners_after_construction diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/offline_evaluation_utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/offline_evaluation_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..de39f149f6958db0261571d6a4a8b264d359090d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/offline_evaluation_utils.py @@ -0,0 +1,131 @@ +import numpy as np +import pandas as pd +from typing import Any, Dict, Type, TYPE_CHECKING + +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy import Policy +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.annotations import DeveloperAPI + +if TYPE_CHECKING: + from ray.rllib.offline.estimators.fqe_torch_model import FQETorchModel + from ray.rllib.offline.estimators.off_policy_estimator import OffPolicyEstimator + + +@DeveloperAPI +def compute_q_and_v_values( + batch: pd.DataFrame, + model_class: Type["FQETorchModel"], + model_state: Dict[str, Any], + compute_q_values: bool = True, +) -> pd.DataFrame: + """Computes the Q and V values for the given batch of samples. + + This function is to be used with map_batches() to perform a batch prediction on a + dataset of records with `obs` and `actions` columns. + + Args: + batch: A sub-batch from the dataset. + model_class: The model class to use for the prediction. This class should be a + sub-class of FQEModel that implements the estimate_q() and estimate_v() + methods. + model_state: The state of the model to use for the prediction. + compute_q_values: Whether to compute the Q values or not. If False, only the V + is computed and returned. + + Returns: + The modified batch with the Q and V values added as columns. + """ + model = model_class.from_state(model_state) + + sample_batch = SampleBatch( + { + SampleBatch.OBS: np.vstack(batch[SampleBatch.OBS]), + SampleBatch.ACTIONS: np.vstack(batch[SampleBatch.ACTIONS]).squeeze(-1), + } + ) + + v_values = model.estimate_v(sample_batch) + v_values = convert_to_numpy(v_values) + batch["v_values"] = v_values + + if compute_q_values: + q_values = model.estimate_q(sample_batch) + q_values = convert_to_numpy(q_values) + batch["q_values"] = q_values + + return batch + + +@DeveloperAPI +def compute_is_weights( + batch: pd.DataFrame, + policy_state: Dict[str, Any], + estimator_class: Type["OffPolicyEstimator"], +) -> pd.DataFrame: + """Computes the importance sampling weights for the given batch of samples. + + For a lot of off-policy estimators, the importance sampling weights are computed as + the propensity score ratio between the new and old policies + (i.e. new_pi(act|obs) / old_pi(act|obs)). This function is to be used with + map_batches() to perform a batch prediction on a dataset of records with `obs`, + `actions`, `action_prob` and `rewards` columns. + + Args: + batch: A sub-batch from the dataset. + policy_state: The state of the policy to use for the prediction. + estimator_class: The estimator class to use for the prediction. This class + + Returns: + The modified batch with the importance sampling weights, weighted rewards, new + and old propensities added as columns. + """ + policy = Policy.from_state(policy_state) + estimator = estimator_class(policy=policy, gamma=0, epsilon_greedy=0) + sample_batch = SampleBatch( + { + SampleBatch.OBS: np.vstack(batch["obs"].values), + SampleBatch.ACTIONS: np.vstack(batch["actions"].values).squeeze(-1), + SampleBatch.ACTION_PROB: np.vstack(batch["action_prob"].values).squeeze(-1), + SampleBatch.REWARDS: np.vstack(batch["rewards"].values).squeeze(-1), + } + ) + new_prob = estimator.compute_action_probs(sample_batch) + old_prob = sample_batch[SampleBatch.ACTION_PROB] + rewards = sample_batch[SampleBatch.REWARDS] + weights = new_prob / old_prob + weighted_rewards = weights * rewards + + batch["weights"] = weights + batch["weighted_rewards"] = weighted_rewards + batch["new_prob"] = new_prob + batch["old_prob"] = old_prob + + return batch + + +@DeveloperAPI +def remove_time_dim(batch: pd.DataFrame) -> pd.DataFrame: + """Removes the time dimension from the given sub-batch of the dataset. + + If each row in a dataset has a time dimension ([T, D]), and T=1, this function will + remove the T dimension to convert each row to of shape [D]. If T > 1, the row is + left unchanged. This function is to be used with map_batches(). + + Args: + batch: The batch to remove the time dimension from. + Returns: + The modified batch with the time dimension removed (when applicable) + """ + BATCHED_KEYS = { + SampleBatch.OBS, + SampleBatch.ACTIONS, + SampleBatch.ACTION_PROB, + SampleBatch.REWARDS, + SampleBatch.NEXT_OBS, + SampleBatch.DONES, + } + for k in batch.columns: + if k in BATCHED_KEYS: + batch[k] = batch[k].apply(lambda x: x[0] if len(x) == 1 else x) + return batch diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/offline_evaluator.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/offline_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..60b87ff1296dfbad51629f172e07131170d02894 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/offline_evaluator.py @@ -0,0 +1,77 @@ +import abc +import os +import logging +from typing import Dict, Any + +from ray.data import Dataset + +from ray.rllib.policy import Policy +from ray.rllib.utils.annotations import DeveloperAPI, ExperimentalAPI +from ray.rllib.utils.typing import SampleBatchType + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +class OfflineEvaluator(abc.ABC): + """Interface for an offline evaluator of a policy""" + + @DeveloperAPI + def __init__(self, policy: Policy, **kwargs): + """Initializes an OffPolicyEstimator instance. + + Args: + policy: Policy to evaluate. + kwargs: forward compatibility placeholder. + """ + self.policy = policy + + @abc.abstractmethod + @DeveloperAPI + def estimate(self, batch: SampleBatchType, **kwargs) -> Dict[str, Any]: + """Returns the evaluation results for the given batch of episodes. + + Args: + batch: The batch to evaluate. + kwargs: forward compatibility placeholder. + + Returns: + The evaluation done on the given batch. The returned + dict can be any arbitrary mapping of strings to metrics. + """ + raise NotImplementedError + + @DeveloperAPI + def train(self, batch: SampleBatchType, **kwargs) -> Dict[str, Any]: + """Sometimes you need to train a model inside an evaluator. This method + abstracts the training process. + + Args: + batch: SampleBatch to train on + kwargs: forward compatibility placeholder. + + Returns: + Any optional metrics to return from the evaluator + """ + return {} + + @ExperimentalAPI + def estimate_on_dataset( + self, + dataset: Dataset, + *, + n_parallelism: int = os.cpu_count(), + ) -> Dict[str, Any]: + + """Calculates the estimate of the metrics based on the given offline dataset. + + Typically, the dataset is passed through only once via n_parallel tasks in + mini-batches to improve the run-time of metric estimation. + + Args: + dataset: The ray dataset object to do offline evaluation on. + n_parallelism: The number of parallelism to use for the computation. + + Returns: + Dict[str, Any]: A dictionary of the estimated values. + """ diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/offline_policy_evaluation_runner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/offline_policy_evaluation_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..2e2f63e9d7ffec43f8e27e418a2caf49e3b9ea8b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/offline_policy_evaluation_runner.py @@ -0,0 +1,637 @@ +import gymnasium as gym +import math +import numpy +import ray + +from enum import Enum +from typing import ( + Collection, + Dict, + Iterable, + List, + Optional, + TYPE_CHECKING, + Union, +) + +from ray.data.iterator import DataIterator +from ray.rllib.connectors.env_to_module import EnvToModulePipeline +from ray.rllib.core import ( + ALL_MODULES, + DEFAULT_AGENT_ID, + DEFAULT_MODULE_ID, + COMPONENT_ENV_TO_MODULE_CONNECTOR, + COMPONENT_RL_MODULE, +) +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec +from ray.rllib.env.single_agent_episode import SingleAgentEpisode +from ray.rllib.offline.offline_prelearner import OfflinePreLearner, SCHEMA +from ray.rllib.policy.sample_batch import MultiAgentBatch +from ray.rllib.utils.annotations import override +from ray.rllib.utils.checkpoints import Checkpointable +from ray.rllib.utils.framework import get_device, try_import_torch +from ray.rllib.utils.metrics import ( + DATASET_NUM_ITERS_EVALUATED, + DATASET_NUM_ITERS_EVALUATED_LIFETIME, + EPISODE_LEN_MAX, + EPISODE_LEN_MEAN, + EPISODE_LEN_MIN, + EPISODE_RETURN_MAX, + EPISODE_RETURN_MEAN, + EPISODE_RETURN_MIN, + MODULE_SAMPLE_BATCH_SIZE_MEAN, + NUM_ENV_STEPS_SAMPLED, + NUM_ENV_STEPS_SAMPLED_LIFETIME, + NUM_MODULE_STEPS_SAMPLED, + NUM_MODULE_STEPS_SAMPLED_LIFETIME, + OFFLINE_SAMPLING_TIMER, + WEIGHTS_SEQ_NO, +) +from ray.rllib.utils.minibatch_utils import MiniBatchRayDataIterator +from ray.rllib.utils.runners.runner import Runner +from ray.rllib.utils.torch_utils import convert_to_torch_tensor +from ray.rllib.utils.typing import ( + DeviceType, + EpisodeID, + StateDict, + TensorType, +) + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + +torch, _ = try_import_torch() + +TOTAL_EVAL_LOSS_KEY = "total_eval_loss" + + +# TODO (simon): Implement more ... +class OfflinePolicyEvaluationTypes(str, Enum): + """Defines the offline policy evaluation types. + + IS: Importance Sampling. + PDIS: Per-Decision Importance Sampling. In contrast to IS this method + weighs each reward and not the return as a whole. As a result it + usually exhibits lower variance. + """ + + IS = "is" + PDIS = "pdis" + + +class OfflinePolicyPreEvaluator(OfflinePreLearner): + def __call__(self, batch: Dict[str, numpy.ndarray]) -> Dict[str, numpy.ndarray]: + # If we directly read in episodes we just convert to list. + if self.input_read_episodes: + # Import `msgpack` for decoding. + import msgpack + import msgpack_numpy as mnp + + # Read the episodes and decode them. + episodes: List[SingleAgentEpisode] = [ + SingleAgentEpisode.from_state( + msgpack.unpackb(state, object_hook=mnp.decode) + ) + for state in batch["item"] + ] + # Ensure that all episodes are done and no duplicates are in the batch. + episodes = self._validate_episodes(episodes) + # Add the episodes to the buffer. + self.episode_buffer.add(episodes) + # TODO (simon): Refactor into a single code block for both cases. + episodes = self.episode_buffer.sample( + num_items=self.config.train_batch_size_per_learner, + batch_length_T=self.config.model_config.get("max_seq_len", 0) + if self._module.is_stateful() + else None, + n_step=self.config.get("n_step", 1) or 1, + # TODO (simon): This can be removed as soon as DreamerV3 has been + # cleaned up, i.e. can use episode samples for training. + sample_episodes=True, + to_numpy=True, + ) + # Else, if we have old stack `SampleBatch`es. + elif self.input_read_sample_batches: + episodes: List[ + SingleAgentEpisode + ] = OfflinePreLearner._map_sample_batch_to_episode( + self._is_multi_agent, + batch, + to_numpy=True, + schema=SCHEMA | self.config.input_read_schema, + input_compress_columns=self.config.input_compress_columns, + )[ + "episodes" + ] + # Ensure that all episodes are done and no duplicates are in the batch. + episodes = self._validate_episodes(episodes) + # Add the episodes to the buffer. + self.episode_buffer.add(episodes) + # Sample steps from the buffer. + episodes = self.episode_buffer.sample( + num_items=self.config.train_batch_size_per_learner, + batch_length_T=self.config.model_config.get("max_seq_len", 0) + if self._module.is_stateful() + else None, + n_step=self.config.get("n_step", 1) or 1, + # TODO (simon): This can be removed as soon as DreamerV3 has been + # cleaned up, i.e. can use episode samples for training. + sample_episodes=True, + to_numpy=True, + ) + # Otherwise we map the batch to episodes. + else: + episodes: List[SingleAgentEpisode] = self._map_to_episodes( + self._is_multi_agent, + batch, + schema=SCHEMA | self.config.input_read_schema, + to_numpy=False, + input_compress_columns=self.config.input_compress_columns, + observation_space=self.observation_space, + action_space=self.action_space, + )["episodes"] + + episode_dicts = [] + for episode in episodes: + # Note, we expect users to provide terminated episodes in `SingleAgentEpisode` + # or `SampleBatch` format. Otherwise computation of episode returns will be + # biased. + episode_dict = {} + episode_dict[Columns.OBS] = episode.get_observations(slice(0, len(episode))) + episode_dict[Columns.ACTIONS] = episode.get_actions() + episode_dict[Columns.REWARDS] = episode.get_rewards() + episode_dict[Columns.ACTION_LOGP] = episode.get_extra_model_outputs( + key=Columns.ACTION_LOGP + ) + episode_dicts.append(episode_dict) + + return {"episodes": episode_dicts} + + +class OfflinePolicyEvaluationRunner(Runner, Checkpointable): + def __init__( + self, + config: "AlgorithmConfig", + module_spec: Optional[MultiRLModuleSpec] = None, + **kwargs, + ): + + # This needs to be defined before we call the `Runner.__init__` + # b/c the latter calls the `make_module` and then needs the spec. + # TODO (simon): Check, if we make this a generic attribute. + self.__module_spec: MultiRLModuleSpec = module_spec + self.__dataset_iterator = None + self.__batch_iterator = None + + Runner.__init__(self, config=config, **kwargs) + Checkpointable.__init__(self) + + # This has to be defined after we have a `self.config`. + self.__spaces = kwargs.get("spaces") + self.__env_to_module = self.config.build_env_to_module_connector( + spaces=self._spaces, device=self._device + ) + self.__offline_evaluation_type = OfflinePolicyEvaluationTypes( + self.config["offline_evaluation_type"] + ) + + def run( + self, + explore: bool = False, + train: bool = True, + **kwargs, + ) -> None: + + if self.__dataset_iterator is None: + raise ValueError( + f"{self} doesn't have a data iterator. Can't call `run` on " + "`OfflinePolicyEvaluationRunner`." + ) + + if not self._batch_iterator: + self.__batch_iterator = self._create_batch_iterator( + **self.config.iter_batches_kwargs + ) + + # Log current weight seq no. + self.metrics.log_value( + key=WEIGHTS_SEQ_NO, + value=self._weights_seq_no, + window=1, + ) + + with self.metrics.log_time(OFFLINE_SAMPLING_TIMER): + if explore is None: + explore = self.config.explore + + # Evaluate on offline data. + return self._evaluate( + explore=explore, + train=train, + ) + + def _create_batch_iterator(self, **kwargs) -> Iterable: + + # Import the torch utils here b/c Ray Air imports `torch`` directly. + from ray.air._internal.torch_utils import ( + convert_ndarray_batch_to_torch_tensor_batch, + ) + + # Define the collate function that converts the flattened dictionary + # to a `MultiAgentBatch` with Tensors. + def _collate_fn( + _batch: Dict[str, numpy.ndarray] + ) -> Dict[EpisodeID, Dict[str, numpy.ndarray]]: + + return _batch["episodes"] + + # Define the finalize function that makes the host-to-device transfer. + def _finalize_fn( + _batch: Dict[EpisodeID, Dict[str, numpy.ndarray]] + ) -> Dict[EpisodeID, Dict[str, TensorType]]: + + return [ + convert_ndarray_batch_to_torch_tensor_batch( + episode, device=self._device, dtypes=torch.float32 + ) + for episode in _batch + ] + + # Return a minibatch iterator. + return MiniBatchRayDataIterator( + iterator=self._dataset_iterator, + collate_fn=_collate_fn, + finalize_fn=_finalize_fn, + minibatch_size=self.config.offline_eval_batch_size_per_runner, + num_iters=self.config.dataset_num_iters_per_eval_runner, + **kwargs, + ) + + def _evaluate( + self, + explore: bool, + train: bool, + ) -> None: + + self.metrics.activate_tensor_mode() + + num_env_steps = 0 + for iteration, tensor_minibatch in enumerate(self._batch_iterator): + for episode in tensor_minibatch: + action_dist_cls = self.module[ + DEFAULT_MODULE_ID + ].get_inference_action_dist_cls() + # TODO (simon): It needs here the `EnvToModule` pipeline. + action_logits = self.module[DEFAULT_MODULE_ID].forward_inference( + episode + )[Columns.ACTION_DIST_INPUTS] + # TODO (simon): It might need here the ModuleToEnv pipeline until the + # `GetActions` piece. + action_dist = action_dist_cls.from_logits(action_logits) + actions = action_dist.sample() + action_logp = action_dist.logp(actions) + # If we have action log-probs use them. + if Columns.ACTION_LOGP in episode: + behavior_action_logp = episode[Columns.ACTION_LOGP] + # Otherwise approximate them via the current action distribution. + else: + behavior_action_logp = action_dist.logp(episode[Columns.ACTIONS]) + + # Compute the weights. + if self.__offline_evaluation_type == OfflinePolicyEvaluationTypes.IS: + weight = torch.prod( + torch.exp(action_logp) / torch.exp(behavior_action_logp) + ) + # Note, we use the (un)-discounted return to compare with the `EnvRunner` + # returns. + episode_return = episode[Columns.REWARDS].sum() + offline_return = (weight * episode_return).item() + elif ( + self.__offline_evaluation_type == OfflinePolicyEvaluationTypes.PDIS + ): + weights = torch.exp(action_logp) / torch.exp(behavior_action_logp) + offline_return = torch.dot(weights, episode[Columns.REWARDS]).item() + + episode_len = episode[Columns.REWARDS].shape[0] + 1 + num_env_steps += episode_len + + self._log_episode_metrics(episode_len, offline_return) + + self._log_batch_metrics(len(tensor_minibatch), num_env_steps) + + # Record the number of batches pulled from the dataset. + self.metrics.log_value( + (ALL_MODULES, DATASET_NUM_ITERS_EVALUATED), + iteration + 1, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + (ALL_MODULES, DATASET_NUM_ITERS_EVALUATED_LIFETIME), + iteration + 1, + reduce="sum", + ) + + self.metrics.deactivate_tensor_mode() + + return self.metrics.reduce() + + @override(Checkpointable) + def get_ctor_args_and_kwargs(self): + return ( + (), # *args + {"config": self.config}, # **kwargs + ) + + @override(Checkpointable) + def get_state( + self, + components: Optional[Union[str, Collection[str]]] = None, + *, + not_components: Optional[Union[str, Collection[str]]] = None, + **kwargs, + ) -> StateDict: + state = { + NUM_ENV_STEPS_SAMPLED_LIFETIME: ( + self.metrics.peek(NUM_ENV_STEPS_SAMPLED_LIFETIME, default=0) + ), + } + + if self._check_component(COMPONENT_RL_MODULE, components, not_components): + state[COMPONENT_RL_MODULE] = self.module.get_state( + components=self._get_subcomponents(COMPONENT_RL_MODULE, components), + not_components=self._get_subcomponents( + COMPONENT_RL_MODULE, not_components + ), + **kwargs, + ) + state[WEIGHTS_SEQ_NO] = self._weights_seq_no + if self._check_component( + COMPONENT_ENV_TO_MODULE_CONNECTOR, components, not_components + ): + state[COMPONENT_ENV_TO_MODULE_CONNECTOR] = self._env_to_module.get_state() + + return state + + def _convert_to_tensor(self, struct) -> TensorType: + """Converts structs to a framework-specific tensor.""" + return convert_to_torch_tensor(struct) + + def stop(self) -> None: + """Releases all resources used by this EnvRunner. + + For example, when using a gym.Env in this EnvRunner, you should make sure + that its `close()` method is called. + """ + pass + + def __del__(self) -> None: + """If this Actor is deleted, clears all resources used by it.""" + pass + + @override(Runner) + def assert_healthy(self): + """Checks that self.__init__() has been completed properly. + + Ensures that the instances has a `MultiRLModule` and an + environment defined. + + Raises: + AssertionError: If the EnvRunner Actor has NOT been properly initialized. + """ + # Make sure, we have built our RLModule properly and assigned a dataset iterator. + assert self._dataset_iterator and hasattr(self, "module") + + @override(Runner) + def get_metrics(self): + return self.metrics.reduce() + + def _convert_batch_type( + self, + batch: MultiAgentBatch, + to_device: bool = True, + pin_memory: bool = False, + use_stream: bool = False, + ) -> MultiAgentBatch: + batch = convert_to_torch_tensor( + batch.policy_batches, + device=self._device if to_device else None, + pin_memory=pin_memory, + use_stream=use_stream, + ) + # TODO (sven): This computation of `env_steps` is not accurate! + length = max(len(b) for b in batch.values()) + batch = MultiAgentBatch(batch, env_steps=length) + return batch + + @override(Checkpointable) + def set_state(self, state: StateDict) -> None: + if COMPONENT_ENV_TO_MODULE_CONNECTOR in state: + self._env_to_module.set_state(state[COMPONENT_ENV_TO_MODULE_CONNECTOR]) + + # Update the RLModule state. + if COMPONENT_RL_MODULE in state: + # A missing value for WEIGHTS_SEQ_NO or a value of 0 means: Force the + # update. + weights_seq_no = state.get(WEIGHTS_SEQ_NO, 0) + + # Only update the weigths, if this is the first synchronization or + # if the weights of this `EnvRunner` lacks behind the actual ones. + if weights_seq_no == 0 or self._weights_seq_no < weights_seq_no: + rl_module_state = state[COMPONENT_RL_MODULE] + if isinstance(rl_module_state, ray.ObjectRef): + rl_module_state = ray.get(rl_module_state) + self.module.set_state(rl_module_state) + + # Update our weights_seq_no, if the new one is > 0. + if weights_seq_no > 0: + self._weights_seq_no = weights_seq_no + + # Update our lifetime counters. + # TODO (simon): Create extra metrics. + if NUM_ENV_STEPS_SAMPLED_LIFETIME in state: + self.metrics.set_value( + key=NUM_ENV_STEPS_SAMPLED_LIFETIME, + value=state[NUM_ENV_STEPS_SAMPLED_LIFETIME], + reduce="sum", + with_throughput=True, + ) + + def _log_episode_metrics(self, episode_len: int, episode_return: float) -> None: + """Logs episode metrics for each episode.""" + + # Log general episode metrics. + # Use the configured window, but factor in the parallelism of the + # `OfflinePolicyEvaluationRunners`. As a result, we only log the last + # `window / num_env_runners` steps here, b/c everything gets + # parallel-merged in the Algorithm process. + win = max( + 1, + int( + math.ceil( + self.config.metrics_num_episodes_for_smoothing + / (self.config.num_offline_eval_runners or 1) + ) + ), + ) + self.metrics.log_value(EPISODE_LEN_MEAN, episode_len, window=win) + self.metrics.log_value(EPISODE_RETURN_MEAN, episode_return, window=win) + # Per-agent returns. + self.metrics.log_value( + ("agent_episode_return_mean", DEFAULT_AGENT_ID), episode_return, window=win + ) + # Per-RLModule returns. + self.metrics.log_value( + ("module_episode_return_mean", DEFAULT_MODULE_ID), + episode_return, + window=win, + ) + + # For some metrics, log min/max as well. + self.metrics.log_value(EPISODE_LEN_MIN, episode_len, reduce="min", window=win) + self.metrics.log_value( + EPISODE_RETURN_MIN, episode_return, reduce="min", window=win + ) + self.metrics.log_value(EPISODE_LEN_MAX, episode_len, reduce="max", window=win) + self.metrics.log_value( + EPISODE_RETURN_MAX, episode_return, reduce="max", window=win + ) + + def _log_batch_metrics(self, batch_size: int, num_env_steps: int): + """Logs batch metrics for each mini batch.""" + + # Log weights seq no for this batch. + self.metrics.log_value( + (DEFAULT_MODULE_ID, WEIGHTS_SEQ_NO), + self._weights_seq_no, + window=1, + ) + + # Log average batch size (for each module). + self.metrics.log_value( + key=(DEFAULT_MODULE_ID, MODULE_SAMPLE_BATCH_SIZE_MEAN), + value=batch_size, + ) + # Log module steps (for each module). + self.metrics.log_value( + key=(DEFAULT_MODULE_ID, NUM_MODULE_STEPS_SAMPLED), + value=num_env_steps, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + key=(DEFAULT_MODULE_ID, NUM_MODULE_STEPS_SAMPLED_LIFETIME), + value=num_env_steps, + reduce="sum", + ) + # Log module steps (sum of all modules). + self.metrics.log_value( + key=(ALL_MODULES, NUM_MODULE_STEPS_SAMPLED), + value=num_env_steps, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + key=(ALL_MODULES, NUM_MODULE_STEPS_SAMPLED_LIFETIME), + value=num_env_steps, + reduce="sum", + ) + # Log env steps (all modules). + self.metrics.log_value( + key=(ALL_MODULES, NUM_ENV_STEPS_SAMPLED), + value=num_env_steps, + reduce="sum", + clear_on_reduce=True, + ) + self.metrics.log_value( + key=(ALL_MODULES, NUM_ENV_STEPS_SAMPLED_LIFETIME), + value=num_env_steps, + reduce="sum", + with_throughput=True, + ) + + @override(Runner) + def set_device(self): + try: + self.__device = get_device( + self.config, + 0 + if not self.worker_index + else self.config.num_gpus_per_offline_eval_runner, + ) + except NotImplementedError: + self.__device = None + + @override(Runner) + def make_module(self): + try: + from ray.rllib.env import INPUT_ENV_SPACES + + if not self._module_spec: + self.__module_spec = self.config.get_multi_rl_module_spec( + # Note, usually we have no environemnt in case of offline evaluation. + env=self.config.env, + spaces={ + INPUT_ENV_SPACES: ( + self.config.observation_space, + self.config.action_space, + ) + }, + inference_only=self.config.offline_eval_rl_module_inference_only, + ) + # Build the module from its spec. + self.module = self._module_spec.build() + # TODO (simon): Implement GPU inference. + # Move the RLModule to our device. + # TODO (sven): In order to make this framework-agnostic, we should maybe + # make the MultiRLModule.build() method accept a device OR create an + # additional `(Multi)RLModule.to()` override. + + self.module.foreach_module( + lambda mid, mod: ( + mod.to(self._device) if isinstance(mod, torch.nn.Module) else mod + ) + ) + + # If `AlgorithmConfig.get_multi_rl_module_spec()` is not implemented, this env runner + # will not have an RLModule, but might still be usable with random actions. + except NotImplementedError: + self.module = None + + @property + def _dataset_iterator(self) -> DataIterator: + """Returns the dataset iterator.""" + return self.__dataset_iterator + + def set_dataset_iterator(self, iterator): + """Sets the dataset iterator.""" + self.__dataset_iterator = iterator + + @property + def _batch_iterator(self) -> MiniBatchRayDataIterator: + return self.__batch_iterator + + @property + def _device(self) -> DeviceType: + return self.__device + + @property + def _module_spec(self) -> MultiRLModuleSpec: + """Returns the `MultiRLModuleSpec` of this `Runner`.""" + return self.__module_spec + + @property + def _spaces(self) -> Dict[str, gym.spaces.Space]: + """Returns the spaces of thsi `Runner`.""" + return self.__spaces + + @property + def _env_to_module(self) -> EnvToModulePipeline: + """Returns the env-to-module pipeline of this `Runner`.""" + return self.__env_to_module + + @property + def _offline_evaluation_type(self) -> Enum: + """Returns the offline evaluation type of this `Runner`.""" + return self.__offline_evaluation_type diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/offline_prelearner.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/offline_prelearner.py new file mode 100644 index 0000000000000000000000000000000000000000..782f5c0f0fdc94ebd269fab3808090e1093da0cd --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/offline_prelearner.py @@ -0,0 +1,641 @@ +import copy +import gymnasium as gym +import logging +import numpy as np +import tree +import uuid + +from typing import Any, Dict, List, Optional, Union, Set, Tuple, TYPE_CHECKING + +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec, MultiRLModule +from ray.rllib.env.single_agent_episode import SingleAgentEpisode +from ray.rllib.utils import flatten_dict +from ray.rllib.utils.annotations import ( + OverrideToImplementCustomLogic, + OverrideToImplementCustomLogic_CallToSuperRecommended, +) +from ray.rllib.utils.compression import unpack_if_needed +from ray.rllib.utils.replay_buffers.replay_buffer import ReplayBuffer +from ray.rllib.utils.spaces.space_utils import from_jsonable_if_needed +from ray.rllib.utils.typing import EpisodeType, ModuleID +from ray.util.annotations import PublicAPI + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + +#: This is the default schema used if no `input_read_schema` is set in +#: the config. If a user passes in a schema into `input_read_schema` +#: this user-defined schema has to comply with the keys of `SCHEMA`, +#: while values correspond to the columns in the user's dataset. Note +#: that only the user-defined values will be overridden while all +#: other values from SCHEMA remain as defined here. +SCHEMA = { + Columns.EPS_ID: Columns.EPS_ID, + Columns.AGENT_ID: Columns.AGENT_ID, + Columns.MODULE_ID: Columns.MODULE_ID, + Columns.OBS: Columns.OBS, + Columns.ACTIONS: Columns.ACTIONS, + Columns.REWARDS: Columns.REWARDS, + Columns.INFOS: Columns.INFOS, + Columns.NEXT_OBS: Columns.NEXT_OBS, + Columns.TERMINATEDS: Columns.TERMINATEDS, + Columns.TRUNCATEDS: Columns.TRUNCATEDS, + Columns.T: Columns.T, + # TODO (simon): Add remove as soon as we are new stack only. + "agent_index": "agent_index", + "dones": "dones", + "unroll_id": "unroll_id", +} + +logger = logging.getLogger(__name__) + + +@PublicAPI(stability="alpha") +class OfflinePreLearner: + """Class that coordinates data transformation from dataset to learner. + + This class is an essential part of the new `Offline RL API` of `RLlib`. + It is a callable class that is run in `ray.data.Dataset.map_batches` + when iterating over batches for training. It's basic function is to + convert data in batch from rows to episodes (`SingleAGentEpisode`s + for now) and to then run the learner connector pipeline to convert + further to trainable batches. These batches are used directly in the + `Learner`'s `update` method. + + The main reason to run these transformations inside of `map_batches` + is for better performance. Batches can be pre-fetched in `ray.data` + and therefore batch trransformation can be run highly parallelized to + the `Learner''s `update`. + + This class can be overridden to implement custom logic for transforming + batches and make them 'Learner'-ready. When deriving from this class + the `__call__` method and `_map_to_episodes` can be overridden to induce + custom logic for the complete transformation pipeline (`__call__`) or + for converting to episodes only ('_map_to_episodes`). + + Custom `OfflinePreLearner` classes can be passed into + `AlgorithmConfig.offline`'s `prelearner_class`. The `OfflineData` class + will then use the custom class in its data pipeline. + """ + + @OverrideToImplementCustomLogic_CallToSuperRecommended + def __init__( + self, + *, + config: "AlgorithmConfig", + spaces: Optional[Tuple[gym.Space, gym.Space]] = None, + module_spec: Optional[MultiRLModuleSpec] = None, + module_state: Optional[Dict[ModuleID, Any]] = None, + **kwargs: Dict[str, Any], + ): + + self.config: AlgorithmConfig = config + self.input_read_episodes: bool = self.config.input_read_episodes + self.input_read_sample_batches: bool = self.config.input_read_sample_batches + # Build the module from spec. + self._module: MultiRLModule = module_spec.build() + self._module.set_state(module_state) + # Map the module to the device, if necessary. + # TODO (simon): Check here if we already have a list. + # self._set_device(device_strings) + + # Store the observation and action space if defined, otherwise we + # set them to `None`. Note, if `None` the `convert_from_jsonable` + # will not convert the input space samples. + self.observation_space, self.action_space = spaces or (None, None) + + # Build the learner connector pipeline. + self._learner_connector = self.config.build_learner_connector( + input_observation_space=self.observation_space, + input_action_space=self.action_space, + ) + # Cache the policies to be trained to update weights only for these. + self._policies_to_train = self.config.policies_to_train + self._is_multi_agent: bool = config.is_multi_agent + # Set the counter to zero. + self.iter_since_last_module_update: int = 0 + # self._future = None + + # Set up an episode buffer, if the module is stateful or we sample from + # `SampleBatch` types. + if ( + self.input_read_sample_batches + or self._module.is_stateful() + or self.input_read_episodes + ): + # Either the user defined a buffer class or we fall back to the default. + prelearner_buffer_class = ( + self.config.prelearner_buffer_class + or self.default_prelearner_buffer_class + ) + prelearner_buffer_kwargs = ( + self.default_prelearner_buffer_kwargs + | self.config.prelearner_buffer_kwargs + ) + # Initialize the buffer. + self.episode_buffer = prelearner_buffer_class( + **prelearner_buffer_kwargs, + ) + + @OverrideToImplementCustomLogic + def __call__(self, batch: Dict[str, np.ndarray]) -> Dict[str, np.ndarray]: + """Prepares plain data batches for training with `Learner`'s. + + Args: + batch: A dictionary of numpy arrays containing either column data + with `self.config.input_read_schema`, `EpisodeType` data, or + `BatchType` data. + + Returns: + A `MultiAgentBatch` that can be passed to `Learner.update` methods. + """ + # If we directly read in episodes we just convert to list. + if self.input_read_episodes: + # Import `msgpack` for decoding. + import msgpack + import msgpack_numpy as mnp + + # Read the episodes and decode them. + episodes: List[SingleAgentEpisode] = [ + SingleAgentEpisode.from_state( + msgpack.unpackb(state, object_hook=mnp.decode) + ) + for state in batch["item"] + ] + # Ensure that all episodes are done and no duplicates are in the batch. + episodes = self._validate_episodes(episodes) + # Add the episodes to the buffer. + self.episode_buffer.add(episodes) + # TODO (simon): Refactor into a single code block for both cases. + episodes = self.episode_buffer.sample( + num_items=self.config.train_batch_size_per_learner, + batch_length_T=self.config.model_config.get("max_seq_len", 0) + if self._module.is_stateful() + else None, + n_step=self.config.get("n_step", 1) or 1, + # TODO (simon): This can be removed as soon as DreamerV3 has been + # cleaned up, i.e. can use episode samples for training. + sample_episodes=True, + to_numpy=True, + ) + # Else, if we have old stack `SampleBatch`es. + elif self.input_read_sample_batches: + episodes: List[ + SingleAgentEpisode + ] = OfflinePreLearner._map_sample_batch_to_episode( + self._is_multi_agent, + batch, + to_numpy=True, + schema=SCHEMA | self.config.input_read_schema, + input_compress_columns=self.config.input_compress_columns, + )[ + "episodes" + ] + # Ensure that all episodes are done and no duplicates are in the batch. + episodes = self._validate_episodes(episodes) + # Add the episodes to the buffer. + self.episode_buffer.add(episodes) + # Sample steps from the buffer. + episodes = self.episode_buffer.sample( + num_items=self.config.train_batch_size_per_learner, + batch_length_T=self.config.model_config.get("max_seq_len", 0) + if self._module.is_stateful() + else None, + n_step=self.config.get("n_step", 1) or 1, + # TODO (simon): This can be removed as soon as DreamerV3 has been + # cleaned up, i.e. can use episode samples for training. + sample_episodes=True, + to_numpy=True, + ) + # Otherwise we map the batch to episodes. + else: + episodes: List[SingleAgentEpisode] = self._map_to_episodes( + self._is_multi_agent, + batch, + schema=SCHEMA | self.config.input_read_schema, + to_numpy=False, + input_compress_columns=self.config.input_compress_columns, + observation_space=self.observation_space, + action_space=self.action_space, + )["episodes"] + + # TODO (simon): Make synching work. Right now this becomes blocking or never + # receives weights. Learners appear to be non accessi ble via other actors. + # Increase the counter for updating the module. + # self.iter_since_last_module_update += 1 + + # if self._future: + # refs, _ = ray.wait([self._future], timeout=0) + # print(f"refs: {refs}") + # if refs: + # module_state = ray.get(self._future) + # + # self._module.set_state(module_state) + # self._future = None + + # # Synch the learner module, if necessary. Note, in case of a local learner + # # we have a reference to the module and therefore an up-to-date module. + # if self.learner_is_remote and self.iter_since_last_module_update + # > self.config.prelearner_module_synch_period: + # # Reset the iteration counter. + # self.iter_since_last_module_update = 0 + # # Request the module weights from the remote learner. + # self._future = + # self._learner.get_module_state.remote(inference_only=False) + # # module_state = + # ray.get(self._learner.get_module_state.remote(inference_only=False)) + # # self._module.set_state(module_state) + + # Run the `Learner`'s connector pipeline. + batch = self._learner_connector( + rl_module=self._module, + batch={}, + episodes=episodes, + shared_data={}, + # TODO (sven): Add MetricsLogger to non-Learner components that have a + # LearnerConnector pipeline. + metrics=None, + ) + # Remove all data from modules that should not be trained. We do + # not want to pass around more data than necessary. + for module_id in batch: + if not self._should_module_be_updated(module_id, batch): + del batch[module_id] + + # Flatten the dictionary to increase serialization performance. + return flatten_dict(batch) + + @property + def default_prelearner_buffer_class(self) -> ReplayBuffer: + """Sets the default replay buffer.""" + from ray.rllib.utils.replay_buffers.episode_replay_buffer import ( + EpisodeReplayBuffer, + ) + + # Return the buffer. + return EpisodeReplayBuffer + + @property + def default_prelearner_buffer_kwargs(self) -> Dict[str, Any]: + """Sets the default arguments for the replay buffer. + + Note, the `capacity` might vary with the size of the episodes or + sample batches in the offline dataset. + """ + return { + "capacity": self.config.train_batch_size_per_learner * 10, + "batch_size_B": self.config.train_batch_size_per_learner, + } + + def _validate_episodes( + self, episodes: List[SingleAgentEpisode] + ) -> Set[SingleAgentEpisode]: + """Validate episodes sampled from the dataset. + + Note, our episode buffers cannot handle either duplicates nor + non-ordered fragmentations, i.e. fragments from episodes that do + not arrive in timestep order. + + Args: + episodes: A list of `SingleAgentEpisode` instances sampled + from a dataset. + + Returns: + A set of `SingleAgentEpisode` instances. + + Raises: + ValueError: If not all episodes are `done`. + """ + # Ensure that episodes are all done. + if not all(eps.is_done for eps in episodes): + raise ValueError( + "When sampling from episodes (`input_read_episodes=True`) all " + "recorded episodes must be done (i.e. either `terminated=True`) " + "or `truncated=True`)." + ) + # Ensure that episodes do not contain duplicates. Note, this can happen + # if the dataset is small and pulled batches contain multiple episodes. + unique_episode_ids = set() + episodes = { + eps + for eps in episodes + if eps.id_ not in unique_episode_ids + and not unique_episode_ids.add(eps.id_) + and eps.id_ not in self.episode_buffer.episode_id_to_index.keys() + } + return episodes + + def _should_module_be_updated(self, module_id, multi_agent_batch=None) -> bool: + """Checks which modules in a MultiRLModule should be updated.""" + if not self._policies_to_train: + # In case of no update information, the module is updated. + return True + elif not callable(self._policies_to_train): + return module_id in set(self._policies_to_train) + else: + return self._policies_to_train(module_id, multi_agent_batch) + + @OverrideToImplementCustomLogic + @staticmethod + def _map_to_episodes( + is_multi_agent: bool, + batch: Dict[str, Union[list, np.ndarray]], + schema: Dict[str, str] = SCHEMA, + to_numpy: bool = False, + input_compress_columns: Optional[List[str]] = None, + ignore_final_observation: Optional[bool] = False, + observation_space: gym.Space = None, + action_space: gym.Space = None, + **kwargs: Dict[str, Any], + ) -> Dict[str, List[EpisodeType]]: + """Maps a batch of data to episodes.""" + + # Set to empty list, if `None`. + input_compress_columns = input_compress_columns or [] + + # If spaces are given, we can use the space-specific + # conversion method to convert space samples. + if observation_space and action_space: + convert = from_jsonable_if_needed + # Otherwise we use an identity function. + else: + + def convert(sample, space): + return sample + + episodes = [] + for i, obs in enumerate(batch[schema[Columns.OBS]]): + + # If multi-agent we need to extract the agent ID. + # TODO (simon): Check, what happens with the module ID. + if is_multi_agent: + agent_id = ( + batch[schema[Columns.AGENT_ID]][i] + if Columns.AGENT_ID in batch + # The old stack uses "agent_index" instead of "agent_id". + # TODO (simon): Remove this as soon as we are new stack only. + else ( + batch[schema["agent_index"]][i] + if schema["agent_index"] in batch + else None + ) + ) + else: + agent_id = None + + if is_multi_agent: + # TODO (simon): Add support for multi-agent episodes. + pass + else: + # Unpack observations, if needed. + unpacked_obs = ( + convert(unpack_if_needed(obs), observation_space) + if Columns.OBS in input_compress_columns + else convert(obs, observation_space) + ) + # Set the next observation. + if ignore_final_observation: + unpacked_next_obs = tree.map_structure( + lambda x: 0 * x, copy.deepcopy(unpacked_obs) + ) + else: + unpacked_next_obs = ( + convert( + unpack_if_needed(batch[schema[Columns.NEXT_OBS]][i]), + observation_space, + ) + if Columns.OBS in input_compress_columns + else convert( + batch[schema[Columns.NEXT_OBS]][i], observation_space + ) + ) + # Build a single-agent episode with a single row of the batch. + episode = SingleAgentEpisode( + id_=str(batch[schema[Columns.EPS_ID]][i]) + if schema[Columns.EPS_ID] in batch + else uuid.uuid4().hex, + agent_id=agent_id, + # Observations might be (a) serialized and/or (b) converted + # to a JSONable (when a composite space was used). We unserialize + # and then reconvert from JSONable to space sample. + observations=[unpacked_obs, unpacked_next_obs], + infos=[ + {}, + batch[schema[Columns.INFOS]][i] + if schema[Columns.INFOS] in batch + else {}, + ], + # Actions might be (a) serialized and/or (b) converted to a JSONable + # (when a composite space was used). We unserializer and then + # reconvert from JSONable to space sample. + actions=[ + convert( + unpack_if_needed(batch[schema[Columns.ACTIONS]][i]), + action_space, + ) + if Columns.ACTIONS in input_compress_columns + else convert(batch[schema[Columns.ACTIONS]][i], action_space) + ], + rewards=[batch[schema[Columns.REWARDS]][i]], + terminated=batch[ + schema[Columns.TERMINATEDS] + if schema[Columns.TERMINATEDS] in batch + else "dones" + ][i], + truncated=batch[schema[Columns.TRUNCATEDS]][i] + if schema[Columns.TRUNCATEDS] in batch + else False, + # TODO (simon): Results in zero-length episodes in connector. + # t_started=batch[Columns.T if Columns.T in batch else + # "unroll_id"][i][0], + # TODO (simon): Single-dimensional columns are not supported. + # Extra model outputs might be serialized. We unserialize them here + # if needed. + # TODO (simon): Check, if we need here also reconversion from + # JSONable in case of composite spaces. + extra_model_outputs={ + k: [ + unpack_if_needed(v[i]) + if k in input_compress_columns + else v[i] + ] + for k, v in batch.items() + if ( + k not in schema + and k not in schema.values() + and k not in ["dones", "agent_index", "type"] + ) + }, + len_lookback_buffer=0, + ) + + if to_numpy: + episode.to_numpy() + episodes.append(episode) + # Note, `map_batches` expects a `Dict` as return value. + return {"episodes": episodes} + + @OverrideToImplementCustomLogic + @staticmethod + def _map_sample_batch_to_episode( + is_multi_agent: bool, + batch: Dict[str, Union[list, np.ndarray]], + schema: Dict[str, str] = SCHEMA, + to_numpy: bool = False, + input_compress_columns: Optional[List[str]] = None, + ) -> Dict[str, List[EpisodeType]]: + """Maps an old stack `SampleBatch` to new stack episodes.""" + + # Set `input_compress_columns` to an empty `list` if `None`. + input_compress_columns = input_compress_columns or [] + + # TODO (simon): CHeck, if needed. It could possibly happen that a batch contains + # data from different episodes. Merging and resplitting the batch would then + # be the solution. + # Check, if batch comes actually from multiple episodes. + # episode_begin_indices = np.where(np.diff(np.hstack(batch["eps_id"])) != 0) + 1 + + # Define a container to collect episodes. + episodes = [] + # Loop over `SampleBatch`es in the `ray.data` batch (a dict). + for i, obs in enumerate(batch[schema[Columns.OBS]]): + + # If multi-agent we need to extract the agent ID. + # TODO (simon): Check, what happens with the module ID. + if is_multi_agent: + agent_id = ( + # The old stack uses "agent_index" instead of "agent_id". + batch[schema["agent_index"]][i][0] + if schema["agent_index"] in batch + else None + ) + else: + agent_id = None + + if is_multi_agent: + # TODO (simon): Add support for multi-agent episodes. + pass + else: + # Unpack observations, if needed. Note, observations could + # be either compressed by their entirety (the complete batch + # column) or individually (each column entry). + if isinstance(obs, str): + # Decompress the observations if we have a string, i.e. + # observations are compressed in their entirety. + obs = unpack_if_needed(obs) + # Convert to a list of arrays. This is needed as input by + # the `SingleAgentEpisode`. + obs = [obs[i, ...] for i in range(obs.shape[0])] + # Otherwise observations are only compressed inside of the + # batch column (if at all). + elif isinstance(obs, np.ndarray): + # Unpack observations, if they are compressed otherwise we + # simply convert to a list, which is needed by the + # `SingleAgentEpisode`. + obs = ( + unpack_if_needed(obs.tolist()) + if schema[Columns.OBS] in input_compress_columns + else obs.tolist() + ) + else: + raise TypeError( + f"Unknown observation type: {type(obs)}. When mapping " + "from old recorded `SampleBatches` batched " + "observations should be either of type `np.array` " + "or - if the column is compressed - of `str` type." + ) + + if schema[Columns.NEXT_OBS] in batch: + # Append the last `new_obs` to get the correct length of + # observations. + obs.append( + unpack_if_needed(batch[schema[Columns.NEXT_OBS]][i][-1]) + if schema[Columns.OBS] in input_compress_columns + else batch[schema[Columns.NEXT_OBS]][i][-1] + ) + else: + # Otherwise we duplicate the last observation. + obs.append(obs[-1]) + + # Check, if we have `done`, `truncated`, or `terminated`s in + # the batch. + if ( + schema[Columns.TRUNCATEDS] in batch + and schema[Columns.TERMINATEDS] in batch + ): + truncated = batch[schema[Columns.TRUNCATEDS]][i][-1] + terminated = batch[schema[Columns.TERMINATEDS]][i][-1] + elif ( + schema[Columns.TRUNCATEDS] in batch + and schema[Columns.TERMINATEDS] not in batch + ): + truncated = batch[schema[Columns.TRUNCATEDS]][i][-1] + terminated = False + elif ( + schema[Columns.TRUNCATEDS] not in batch + and schema[Columns.TERMINATEDS] in batch + ): + terminated = batch[schema[Columns.TERMINATEDS]][i][-1] + truncated = False + elif "done" in batch: + terminated = batch["done"][i][-1] + truncated = False + # Otherwise, if no `terminated`, nor `truncated` nor `done` + # is given, we consider the episode as terminated. + else: + terminated = True + truncated = False + + # Create a `SingleAgentEpisode`. + episode = SingleAgentEpisode( + # If the recorded episode has an ID we use this ID, + # otherwise we generate a new one. + id_=str(batch[schema[Columns.EPS_ID]][i][0]) + if schema[Columns.EPS_ID] in batch + else uuid.uuid4().hex, + agent_id=agent_id, + observations=obs, + infos=( + batch[schema[Columns.INFOS]][i] + if schema[Columns.INFOS] in batch + else [{}] * len(obs) + ), + # Actions might be (a) serialized. We unserialize them here. + actions=( + unpack_if_needed(batch[schema[Columns.ACTIONS]][i]) + if Columns.ACTIONS in input_compress_columns + else batch[schema[Columns.ACTIONS]][i] + ), + rewards=batch[schema[Columns.REWARDS]][i], + terminated=terminated, + truncated=truncated, + # TODO (simon): Results in zero-length episodes in connector. + # t_started=batch[Columns.T if Columns.T in batch else + # "unroll_id"][i][0], + # TODO (simon): Single-dimensional columns are not supported. + # Extra model outputs might be serialized. We unserialize them here + # if needed. + # TODO (simon): Check, if we need here also reconversion from + # JSONable in case of composite spaces. + extra_model_outputs={ + k: unpack_if_needed(v[i]) + if k in input_compress_columns + else v[i] + for k, v in batch.items() + if ( + k not in schema + and k not in schema.values() + and k not in ["dones", "agent_index", "type"] + ) + }, + len_lookback_buffer=0, + ) + # Numpy'ized, if necessary. + # TODO (simon, sven): Check, if we should convert all data to lists + # before. Right now only obs are lists. + if to_numpy: + episode.to_numpy() + episodes.append(episode) + # Note, `map_batches` expects a `Dict` as return value. + return {"episodes": episodes} diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/output_writer.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/output_writer.py new file mode 100644 index 0000000000000000000000000000000000000000..ca26c5a538face19f1b552fa843ae558675093f8 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/output_writer.py @@ -0,0 +1,26 @@ +from ray.rllib.utils.annotations import override, PublicAPI +from ray.rllib.utils.typing import SampleBatchType + + +@PublicAPI +class OutputWriter: + """Writer API for saving experiences from policy evaluation.""" + + @PublicAPI + def write(self, sample_batch: SampleBatchType): + """Saves a batch of experiences. + + Args: + sample_batch: SampleBatch or MultiAgentBatch to save. + """ + raise NotImplementedError + + +@PublicAPI +class NoopOutput(OutputWriter): + """Output writer that discards its outputs.""" + + @override(OutputWriter) + def write(self, sample_batch: SampleBatchType): + # Do nothing. + pass diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/resource.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/resource.py new file mode 100644 index 0000000000000000000000000000000000000000..e658b9b682bc77110f2c6a23061c1f0e1ef4ca05 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/resource.py @@ -0,0 +1,30 @@ +from typing import Dict, List, TYPE_CHECKING +from ray.rllib.utils.annotations import PublicAPI + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + +DEFAULT_NUM_CPUS_PER_TASK = 0.5 + + +@PublicAPI +def get_offline_io_resource_bundles( + config: "AlgorithmConfig", +) -> List[Dict[str, float]]: + # DatasetReader is the only offline I/O component today that + # requires compute resources. + if config.input_ == "dataset": + input_config = config.input_config + # TODO (Kourosh): parallelism is use for reading the dataset, which defaults to + # num_workers. This logic here relies on the information that dataset reader + # will have the same logic. So to remove the information leakage, inside + # Algorithm config, we should set parallelism to num_workers if not specified + # and only deal with parallelism here or in dataset_reader.py. same thing is + # true with cpus_per_task. + parallelism = input_config.get("parallelism", config.get("num_env_runners", 1)) + cpus_per_task = input_config.get( + "num_cpus_per_read_task", DEFAULT_NUM_CPUS_PER_TASK + ) + return [{"CPU": cpus_per_task} for _ in range(parallelism)] + else: + return [] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/shuffled_input.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/shuffled_input.py new file mode 100644 index 0000000000000000000000000000000000000000..a7c2610185940b7df8b1da07a1b421fb671b5514 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/shuffled_input.py @@ -0,0 +1,42 @@ +import logging +import random + +from ray.rllib.offline.input_reader import InputReader +from ray.rllib.utils.annotations import override, DeveloperAPI +from ray.rllib.utils.typing import SampleBatchType + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +class ShuffledInput(InputReader): + """Randomizes data over a sliding window buffer of N batches. + + This increases the randomization of the data, which is useful if the + batches were not in random order to start with. + """ + + @DeveloperAPI + def __init__(self, child: InputReader, n: int = 0): + """Initializes a ShuffledInput instance. + + Args: + child: child input reader to shuffle. + n: If positive, shuffle input over this many batches. + """ + self.n = n + self.child = child + self.buffer = [] + + @override(InputReader) + def next(self) -> SampleBatchType: + if self.n <= 1: + return self.child.next() + if len(self.buffer) < self.n: + logger.info("Filling shuffle buffer to {} batches".format(self.n)) + while len(self.buffer) < self.n: + self.buffer.append(self.child.next()) + logger.info("Shuffle buffer filled") + i = random.randint(0, len(self.buffer) - 1) + self.buffer[i] = self.child.next() + return random.choice(self.buffer) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/wis_estimator.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/wis_estimator.py new file mode 100644 index 0000000000000000000000000000000000000000..128b50e24b2ace880299458885a5139736f134bc --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/offline/wis_estimator.py @@ -0,0 +1,13 @@ +from ray.rllib.offline.estimators.weighted_importance_sampling import ( + WeightedImportanceSampling, +) +from ray.rllib.utils.deprecation import Deprecated + + +@Deprecated( + new="ray.rllib.offline.estimators.weighted_importance_sampling::" + "WeightedImportanceSampling", + error=True, +) +class WeightedImportanceSamplingEstimator(WeightedImportanceSampling): + pass diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..23ae3c0f6e1cd0f47a8f9fb050b4de3314163f00 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/__init__.py @@ -0,0 +1,13 @@ +from ray.rllib.policy.policy import Policy +from ray.rllib.policy.torch_policy import TorchPolicy +from ray.rllib.policy.tf_policy import TFPolicy +from ray.rllib.policy.policy_template import build_policy_class +from ray.rllib.policy.tf_policy_template import build_tf_policy + +__all__ = [ + "Policy", + "TFPolicy", + "TorchPolicy", + "build_policy_class", + "build_tf_policy", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/dynamic_tf_policy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/dynamic_tf_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..9645faf6e08f998d69d3c8bc64069c3a00a2548f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/dynamic_tf_policy.py @@ -0,0 +1,1358 @@ +from collections import namedtuple, OrderedDict +import gymnasium as gym +import logging +import re +import tree # pip install dm_tree +from typing import Callable, Dict, List, Optional, Tuple, Type, Union + +from ray.util.debug import log_once +from ray.rllib.models.tf.tf_action_dist import TFActionDistribution +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.policy.policy import Policy +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy.tf_policy import TFPolicy +from ray.rllib.policy.view_requirement import ViewRequirement +from ray.rllib.models.catalog import ModelCatalog +from ray.rllib.utils import force_list +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.debug import summarize +from ray.rllib.utils.deprecation import ( + deprecation_warning, + DEPRECATED_VALUE, +) +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.metrics import ( + DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY, + NUM_GRAD_UPDATES_LIFETIME, +) +from ray.rllib.utils.spaces.space_utils import get_dummy_batch_for_space +from ray.rllib.utils.tf_utils import get_placeholder +from ray.rllib.utils.typing import ( + LocalOptimizer, + ModelGradients, + TensorType, + AlgorithmConfigDict, +) + +tf1, tf, tfv = try_import_tf() + +logger = logging.getLogger(__name__) + +# Variable scope in which created variables will be placed under. +TOWER_SCOPE_NAME = "tower" + + +@OldAPIStack +class DynamicTFPolicy(TFPolicy): + """A TFPolicy that auto-defines placeholders dynamically at runtime. + + Do not sub-class this class directly (neither should you sub-class + TFPolicy), but rather use rllib.policy.tf_policy_template.build_tf_policy + to generate your custom tf (graph-mode or eager) Policy classes. + """ + + def __init__( + self, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + config: AlgorithmConfigDict, + loss_fn: Callable[ + [Policy, ModelV2, Type[TFActionDistribution], SampleBatch], TensorType + ], + *, + stats_fn: Optional[ + Callable[[Policy, SampleBatch], Dict[str, TensorType]] + ] = None, + grad_stats_fn: Optional[ + Callable[[Policy, SampleBatch, ModelGradients], Dict[str, TensorType]] + ] = None, + before_loss_init: Optional[ + Callable[ + [Policy, gym.spaces.Space, gym.spaces.Space, AlgorithmConfigDict], None + ] + ] = None, + make_model: Optional[ + Callable[ + [Policy, gym.spaces.Space, gym.spaces.Space, AlgorithmConfigDict], + ModelV2, + ] + ] = None, + action_sampler_fn: Optional[ + Callable[ + [TensorType, List[TensorType]], + Union[ + Tuple[TensorType, TensorType], + Tuple[TensorType, TensorType, TensorType, List[TensorType]], + ], + ] + ] = None, + action_distribution_fn: Optional[ + Callable[ + [Policy, ModelV2, TensorType, TensorType, TensorType], + Tuple[TensorType, type, List[TensorType]], + ] + ] = None, + existing_inputs: Optional[Dict[str, "tf1.placeholder"]] = None, + existing_model: Optional[ModelV2] = None, + get_batch_divisibility_req: Optional[Callable[[Policy], int]] = None, + obs_include_prev_action_reward=DEPRECATED_VALUE, + ): + """Initializes a DynamicTFPolicy instance. + + Initialization of this class occurs in two phases and defines the + static graph. + + Phase 1: The model is created and model variables are initialized. + + Phase 2: A fake batch of data is created, sent to the trajectory + postprocessor, and then used to create placeholders for the loss + function. The loss and stats functions are initialized with these + placeholders. + + Args: + observation_space: Observation space of the policy. + action_space: Action space of the policy. + config: Policy-specific configuration data. + loss_fn: Function that returns a loss tensor for the policy graph. + stats_fn: Optional callable that - given the policy and batch + input tensors - returns a dict mapping str to TF ops. + These ops are fetched from the graph after loss calculations + and the resulting values can be found in the results dict + returned by e.g. `Algorithm.train()` or in tensorboard (if TB + logging is enabled). + grad_stats_fn: Optional callable that - given the policy, batch + input tensors, and calculated loss gradient tensors - returns + a dict mapping str to TF ops. These ops are fetched from the + graph after loss and gradient calculations and the resulting + values can be found in the results dict returned by e.g. + `Algorithm.train()` or in tensorboard (if TB logging is + enabled). + before_loss_init: Optional function to run prior to + loss init that takes the same arguments as __init__. + make_model: Optional function that returns a ModelV2 object + given policy, obs_space, action_space, and policy config. + All policy variables should be created in this function. If not + specified, a default model will be created. + action_sampler_fn: A callable returning either a sampled action and + its log-likelihood or a sampled action, its log-likelihood, + action distribution inputs and updated state given Policy, + ModelV2, observation inputs, explore, and is_training. + Provide `action_sampler_fn` if you would like to have full + control over the action computation step, including the + model forward pass, possible sampling from a distribution, + and exploration logic. + Note: If `action_sampler_fn` is given, `action_distribution_fn` + must be None. If both `action_sampler_fn` and + `action_distribution_fn` are None, RLlib will simply pass + inputs through `self.model` to get distribution inputs, create + the distribution object, sample from it, and apply some + exploration logic to the results. + The callable takes as inputs: Policy, ModelV2, obs_batch, + state_batches (optional), seq_lens (optional), + prev_actions_batch (optional), prev_rewards_batch (optional), + explore, and is_training. + action_distribution_fn: A callable returning distribution inputs + (parameters), a dist-class to generate an action distribution + object from, and internal-state outputs (or an empty list if + not applicable). + Provide `action_distribution_fn` if you would like to only + customize the model forward pass call. The resulting + distribution parameters are then used by RLlib to create a + distribution object, sample from it, and execute any + exploration logic. + Note: If `action_distribution_fn` is given, `action_sampler_fn` + must be None. If both `action_sampler_fn` and + `action_distribution_fn` are None, RLlib will simply pass + inputs through `self.model` to get distribution inputs, create + the distribution object, sample from it, and apply some + exploration logic to the results. + The callable takes as inputs: Policy, ModelV2, input_dict, + explore, timestep, is_training. + existing_inputs: When copying a policy, this specifies an existing + dict of placeholders to use instead of defining new ones. + existing_model: When copying a policy, this specifies an existing + model to clone and share weights with. + get_batch_divisibility_req: Optional callable that returns the + divisibility requirement for sample batches. If None, will + assume a value of 1. + """ + if obs_include_prev_action_reward != DEPRECATED_VALUE: + deprecation_warning(old="obs_include_prev_action_reward", error=True) + self.observation_space = obs_space + self.action_space = action_space + self.config = config + self.framework = "tf" + self._loss_fn = loss_fn + self._stats_fn = stats_fn + self._grad_stats_fn = grad_stats_fn + self._seq_lens = None + self._is_tower = existing_inputs is not None + + dist_class = None + if action_sampler_fn or action_distribution_fn: + if not make_model: + raise ValueError( + "`make_model` is required if `action_sampler_fn` OR " + "`action_distribution_fn` is given" + ) + else: + dist_class, logit_dim = ModelCatalog.get_action_dist( + action_space, self.config["model"] + ) + + # Setup self.model. + if existing_model: + if isinstance(existing_model, list): + self.model = existing_model[0] + # TODO: (sven) hack, but works for `target_[q_]?model`. + for i in range(1, len(existing_model)): + setattr(self, existing_model[i][0], existing_model[i][1]) + elif make_model: + self.model = make_model(self, obs_space, action_space, config) + else: + self.model = ModelCatalog.get_model_v2( + obs_space=obs_space, + action_space=action_space, + num_outputs=logit_dim, + model_config=self.config["model"], + framework="tf", + ) + # Auto-update model's inference view requirements, if recurrent. + self._update_model_view_requirements_from_init_state() + + # Input placeholders already given -> Use these. + if existing_inputs: + self._state_inputs = [ + v for k, v in existing_inputs.items() if k.startswith("state_in_") + ] + # Placeholder for RNN time-chunk valid lengths. + if self._state_inputs: + self._seq_lens = existing_inputs[SampleBatch.SEQ_LENS] + # Create new input placeholders. + else: + self._state_inputs = [ + get_placeholder( + space=vr.space, + time_axis=not isinstance(vr.shift, int), + name=k, + ) + for k, vr in self.model.view_requirements.items() + if k.startswith("state_in_") + ] + # Placeholder for RNN time-chunk valid lengths. + if self._state_inputs: + self._seq_lens = tf1.placeholder( + dtype=tf.int32, shape=[None], name="seq_lens" + ) + + # Use default settings. + # Add NEXT_OBS, STATE_IN_0.., and others. + self.view_requirements = self._get_default_view_requirements() + # Combine view_requirements for Model and Policy. + self.view_requirements.update(self.model.view_requirements) + # Disable env-info placeholder. + if SampleBatch.INFOS in self.view_requirements: + self.view_requirements[SampleBatch.INFOS].used_for_training = False + + # Setup standard placeholders. + if self._is_tower: + timestep = existing_inputs["timestep"] + explore = False + self._input_dict, self._dummy_batch = self._get_input_dict_and_dummy_batch( + self.view_requirements, existing_inputs + ) + else: + if not self.config.get("_disable_action_flattening"): + action_ph = ModelCatalog.get_action_placeholder(action_space) + prev_action_ph = {} + if SampleBatch.PREV_ACTIONS not in self.view_requirements: + prev_action_ph = { + SampleBatch.PREV_ACTIONS: ModelCatalog.get_action_placeholder( + action_space, "prev_action" + ) + } + ( + self._input_dict, + self._dummy_batch, + ) = self._get_input_dict_and_dummy_batch( + self.view_requirements, + dict({SampleBatch.ACTIONS: action_ph}, **prev_action_ph), + ) + else: + ( + self._input_dict, + self._dummy_batch, + ) = self._get_input_dict_and_dummy_batch(self.view_requirements, {}) + # Placeholder for (sampling steps) timestep (int). + timestep = tf1.placeholder_with_default( + tf.zeros((), dtype=tf.int64), (), name="timestep" + ) + # Placeholder for `is_exploring` flag. + explore = tf1.placeholder_with_default(True, (), name="is_exploring") + + # Placeholder for `is_training` flag. + self._input_dict.set_training(self._get_is_training_placeholder()) + + # Multi-GPU towers do not need any action computing/exploration + # graphs. + sampled_action = None + sampled_action_logp = None + dist_inputs = None + extra_action_fetches = {} + self._state_out = None + if not self._is_tower: + # Create the Exploration object to use for this Policy. + self.exploration = self._create_exploration() + + # Fully customized action generation (e.g., custom policy). + if action_sampler_fn: + action_sampler_outputs = action_sampler_fn( + self, + self.model, + obs_batch=self._input_dict[SampleBatch.CUR_OBS], + state_batches=self._state_inputs, + seq_lens=self._seq_lens, + prev_action_batch=self._input_dict.get(SampleBatch.PREV_ACTIONS), + prev_reward_batch=self._input_dict.get(SampleBatch.PREV_REWARDS), + explore=explore, + is_training=self._input_dict.is_training, + ) + if len(action_sampler_outputs) == 4: + ( + sampled_action, + sampled_action_logp, + dist_inputs, + self._state_out, + ) = action_sampler_outputs + else: + dist_inputs = None + self._state_out = [] + sampled_action, sampled_action_logp = action_sampler_outputs + # Distribution generation is customized, e.g., DQN, DDPG. + else: + if action_distribution_fn: + # Try new action_distribution_fn signature, supporting + # state_batches and seq_lens. + in_dict = self._input_dict + try: + ( + dist_inputs, + dist_class, + self._state_out, + ) = action_distribution_fn( + self, + self.model, + input_dict=in_dict, + state_batches=self._state_inputs, + seq_lens=self._seq_lens, + explore=explore, + timestep=timestep, + is_training=in_dict.is_training, + ) + # Trying the old way (to stay backward compatible). + # TODO: Remove in future. + except TypeError as e: + if ( + "positional argument" in e.args[0] + or "unexpected keyword argument" in e.args[0] + ): + ( + dist_inputs, + dist_class, + self._state_out, + ) = action_distribution_fn( + self, + self.model, + obs_batch=in_dict[SampleBatch.CUR_OBS], + state_batches=self._state_inputs, + seq_lens=self._seq_lens, + prev_action_batch=in_dict.get(SampleBatch.PREV_ACTIONS), + prev_reward_batch=in_dict.get(SampleBatch.PREV_REWARDS), + explore=explore, + is_training=in_dict.is_training, + ) + else: + raise e + + # Default distribution generation behavior: + # Pass through model. E.g., PG, PPO. + else: + if isinstance(self.model, tf.keras.Model): + dist_inputs, self._state_out, extra_action_fetches = self.model( + self._input_dict + ) + else: + dist_inputs, self._state_out = self.model(self._input_dict) + + action_dist = dist_class(dist_inputs, self.model) + + # Using exploration to get final action (e.g. via sampling). + ( + sampled_action, + sampled_action_logp, + ) = self.exploration.get_exploration_action( + action_distribution=action_dist, timestep=timestep, explore=explore + ) + + if dist_inputs is not None: + extra_action_fetches[SampleBatch.ACTION_DIST_INPUTS] = dist_inputs + + if sampled_action_logp is not None: + extra_action_fetches[SampleBatch.ACTION_LOGP] = sampled_action_logp + extra_action_fetches[SampleBatch.ACTION_PROB] = tf.exp( + tf.cast(sampled_action_logp, tf.float32) + ) + + # Phase 1 init. + sess = tf1.get_default_session() or tf1.Session( + config=tf1.ConfigProto(**self.config["tf_session_args"]) + ) + + batch_divisibility_req = ( + get_batch_divisibility_req(self) + if callable(get_batch_divisibility_req) + else (get_batch_divisibility_req or 1) + ) + + prev_action_input = ( + self._input_dict[SampleBatch.PREV_ACTIONS] + if SampleBatch.PREV_ACTIONS in self._input_dict.accessed_keys + else None + ) + prev_reward_input = ( + self._input_dict[SampleBatch.PREV_REWARDS] + if SampleBatch.PREV_REWARDS in self._input_dict.accessed_keys + else None + ) + + super().__init__( + observation_space=obs_space, + action_space=action_space, + config=config, + sess=sess, + obs_input=self._input_dict[SampleBatch.OBS], + action_input=self._input_dict[SampleBatch.ACTIONS], + sampled_action=sampled_action, + sampled_action_logp=sampled_action_logp, + dist_inputs=dist_inputs, + dist_class=dist_class, + loss=None, # dynamically initialized on run + loss_inputs=[], + model=self.model, + state_inputs=self._state_inputs, + state_outputs=self._state_out, + prev_action_input=prev_action_input, + prev_reward_input=prev_reward_input, + seq_lens=self._seq_lens, + max_seq_len=config["model"]["max_seq_len"], + batch_divisibility_req=batch_divisibility_req, + explore=explore, + timestep=timestep, + ) + + # Phase 2 init. + if before_loss_init is not None: + before_loss_init(self, obs_space, action_space, config) + if hasattr(self, "_extra_action_fetches"): + self._extra_action_fetches.update(extra_action_fetches) + else: + self._extra_action_fetches = extra_action_fetches + + # Loss initialization and model/postprocessing test calls. + if not self._is_tower: + self._initialize_loss_from_dummy_batch(auto_remove_unneeded_view_reqs=True) + + # Create MultiGPUTowerStacks, if we have at least one actual + # GPU or >1 CPUs (fake GPUs). + if len(self.devices) > 1 or any("gpu" in d for d in self.devices): + # Per-GPU graph copies created here must share vars with the + # policy. Therefore, `reuse` is set to tf1.AUTO_REUSE because + # Adam nodes are created after all of the device copies are + # created. + with tf1.variable_scope("", reuse=tf1.AUTO_REUSE): + self.multi_gpu_tower_stacks = [ + TFMultiGPUTowerStack(policy=self) + for i in range(self.config.get("num_multi_gpu_tower_stacks", 1)) + ] + + # Initialize again after loss and tower init. + self.get_session().run(tf1.global_variables_initializer()) + + @override(TFPolicy) + def copy(self, existing_inputs: List[Tuple[str, "tf1.placeholder"]]) -> TFPolicy: + """Creates a copy of self using existing input placeholders.""" + + flat_loss_inputs = tree.flatten(self._loss_input_dict) + flat_loss_inputs_no_rnn = tree.flatten(self._loss_input_dict_no_rnn) + + # Note that there might be RNN state inputs at the end of the list + if len(flat_loss_inputs) != len(existing_inputs): + raise ValueError( + "Tensor list mismatch", + self._loss_input_dict, + self._state_inputs, + existing_inputs, + ) + for i, v in enumerate(flat_loss_inputs_no_rnn): + if v.shape.as_list() != existing_inputs[i].shape.as_list(): + raise ValueError( + "Tensor shape mismatch", i, v.shape, existing_inputs[i].shape + ) + # By convention, the loss inputs are followed by state inputs and then + # the seq len tensor. + rnn_inputs = [] + for i in range(len(self._state_inputs)): + rnn_inputs.append( + ( + "state_in_{}".format(i), + existing_inputs[len(flat_loss_inputs_no_rnn) + i], + ) + ) + if rnn_inputs: + rnn_inputs.append((SampleBatch.SEQ_LENS, existing_inputs[-1])) + existing_inputs_unflattened = tree.unflatten_as( + self._loss_input_dict_no_rnn, + existing_inputs[: len(flat_loss_inputs_no_rnn)], + ) + input_dict = OrderedDict( + [("is_exploring", self._is_exploring), ("timestep", self._timestep)] + + [ + (k, existing_inputs_unflattened[k]) + for i, k in enumerate(self._loss_input_dict_no_rnn.keys()) + ] + + rnn_inputs + ) + + instance = self.__class__( + self.observation_space, + self.action_space, + self.config, + existing_inputs=input_dict, + existing_model=[ + self.model, + # Deprecated: Target models should all reside under + # `policy.target_model` now. + ("target_q_model", getattr(self, "target_q_model", None)), + ("target_model", getattr(self, "target_model", None)), + ], + ) + + instance._loss_input_dict = input_dict + losses = instance._do_loss_init(SampleBatch(input_dict)) + loss_inputs = [ + (k, existing_inputs_unflattened[k]) + for i, k in enumerate(self._loss_input_dict_no_rnn.keys()) + ] + + TFPolicy._initialize_loss(instance, losses, loss_inputs) + if instance._grad_stats_fn: + instance._stats_fetches.update( + instance._grad_stats_fn(instance, input_dict, instance._grads) + ) + return instance + + @override(Policy) + def get_initial_state(self) -> List[TensorType]: + if self.model: + return self.model.get_initial_state() + else: + return [] + + @override(Policy) + def load_batch_into_buffer( + self, + batch: SampleBatch, + buffer_index: int = 0, + ) -> int: + # Set the is_training flag of the batch. + batch.set_training(True) + + # Shortcut for 1 CPU only: Store batch in + # `self._loaded_single_cpu_batch`. + if len(self.devices) == 1 and self.devices[0] == "/cpu:0": + assert buffer_index == 0 + self._loaded_single_cpu_batch = batch + return len(batch) + + input_dict = self._get_loss_inputs_dict(batch, shuffle=False) + data_keys = tree.flatten(self._loss_input_dict_no_rnn) + if self._state_inputs: + state_keys = self._state_inputs + [self._seq_lens] + else: + state_keys = [] + inputs = [input_dict[k] for k in data_keys] + state_inputs = [input_dict[k] for k in state_keys] + + return self.multi_gpu_tower_stacks[buffer_index].load_data( + sess=self.get_session(), + inputs=inputs, + state_inputs=state_inputs, + num_grad_updates=batch.num_grad_updates, + ) + + @override(Policy) + def get_num_samples_loaded_into_buffer(self, buffer_index: int = 0) -> int: + # Shortcut for 1 CPU only: Batch should already be stored in + # `self._loaded_single_cpu_batch`. + if len(self.devices) == 1 and self.devices[0] == "/cpu:0": + assert buffer_index == 0 + return ( + len(self._loaded_single_cpu_batch) + if self._loaded_single_cpu_batch is not None + else 0 + ) + + return self.multi_gpu_tower_stacks[buffer_index].num_tuples_loaded + + @override(Policy) + def learn_on_loaded_batch(self, offset: int = 0, buffer_index: int = 0): + # Shortcut for 1 CPU only: Batch should already be stored in + # `self._loaded_single_cpu_batch`. + if len(self.devices) == 1 and self.devices[0] == "/cpu:0": + assert buffer_index == 0 + if self._loaded_single_cpu_batch is None: + raise ValueError( + "Must call Policy.load_batch_into_buffer() before " + "Policy.learn_on_loaded_batch()!" + ) + # Get the correct slice of the already loaded batch to use, + # based on offset and batch size. + batch_size = self.config.get("minibatch_size") + if batch_size is None: + batch_size = self.config.get( + "sgd_minibatch_size", self.config["train_batch_size"] + ) + if batch_size >= len(self._loaded_single_cpu_batch): + sliced_batch = self._loaded_single_cpu_batch + else: + sliced_batch = self._loaded_single_cpu_batch.slice( + start=offset, end=offset + batch_size + ) + return self.learn_on_batch(sliced_batch) + + tower_stack = self.multi_gpu_tower_stacks[buffer_index] + results = tower_stack.optimize(self.get_session(), offset) + self.num_grad_updates += 1 + + results.update( + { + NUM_GRAD_UPDATES_LIFETIME: self.num_grad_updates, + # -1, b/c we have to measure this diff before we do the update above. + DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY: ( + self.num_grad_updates - 1 - (tower_stack.num_grad_updates or 0) + ), + } + ) + + return results + + def _get_input_dict_and_dummy_batch(self, view_requirements, existing_inputs): + """Creates input_dict and dummy_batch for loss initialization. + + Used for managing the Policy's input placeholders and for loss + initialization. + Input_dict: Str -> tf.placeholders, dummy_batch: str -> np.arrays. + + Args: + view_requirements: The view requirements dict. + existing_inputs (Dict[str, tf.placeholder]): A dict of already + existing placeholders. + + Returns: + Tuple[Dict[str, tf.placeholder], Dict[str, np.ndarray]]: The + input_dict/dummy_batch tuple. + """ + input_dict = {} + for view_col, view_req in view_requirements.items(): + # Point state_in to the already existing self._state_inputs. + mo = re.match(r"state_in_(\d+)", view_col) + if mo is not None: + input_dict[view_col] = self._state_inputs[int(mo.group(1))] + # State-outs (no placeholders needed). + elif view_col.startswith("state_out_"): + continue + # Skip action dist inputs placeholder (do later). + elif view_col == SampleBatch.ACTION_DIST_INPUTS: + continue + # This is a tower: Input placeholders already exist. + elif view_col in existing_inputs: + input_dict[view_col] = existing_inputs[view_col] + # All others. + else: + time_axis = not isinstance(view_req.shift, int) + if view_req.used_for_training: + # Create a +time-axis placeholder if the shift is not an + # int (range or list of ints). + # Do not flatten actions if action flattening disabled. + if self.config.get("_disable_action_flattening") and view_col in [ + SampleBatch.ACTIONS, + SampleBatch.PREV_ACTIONS, + ]: + flatten = False + # Do not flatten observations if no preprocessor API used. + elif ( + view_col in [SampleBatch.OBS, SampleBatch.NEXT_OBS] + and self.config["_disable_preprocessor_api"] + ): + flatten = False + # Flatten everything else. + else: + flatten = True + input_dict[view_col] = get_placeholder( + space=view_req.space, + name=view_col, + time_axis=time_axis, + flatten=flatten, + ) + dummy_batch = self._get_dummy_batch_from_view_requirements(batch_size=32) + + return SampleBatch(input_dict, seq_lens=self._seq_lens), dummy_batch + + @override(Policy) + def _initialize_loss_from_dummy_batch( + self, auto_remove_unneeded_view_reqs: bool = True, stats_fn=None + ) -> None: + # Create the optimizer/exploration optimizer here. Some initialization + # steps (e.g. exploration postprocessing) may need this. + if not self._optimizers: + self._optimizers = force_list(self.optimizer()) + # Backward compatibility. + self._optimizer = self._optimizers[0] + + # Test calls depend on variable init, so initialize model first. + self.get_session().run(tf1.global_variables_initializer()) + + # Fields that have not been accessed are not needed for action + # computations -> Tag them as `used_for_compute_actions=False`. + for key, view_req in self.view_requirements.items(): + if ( + not key.startswith("state_in_") + and key not in self._input_dict.accessed_keys + ): + view_req.used_for_compute_actions = False + for key, value in self._extra_action_fetches.items(): + self._dummy_batch[key] = get_dummy_batch_for_space( + gym.spaces.Box( + -1.0, 1.0, shape=value.shape.as_list()[1:], dtype=value.dtype.name + ), + batch_size=len(self._dummy_batch), + ) + self._input_dict[key] = get_placeholder(value=value, name=key) + if key not in self.view_requirements: + logger.info("Adding extra-action-fetch `{}` to view-reqs.".format(key)) + self.view_requirements[key] = ViewRequirement( + space=gym.spaces.Box( + -1.0, + 1.0, + shape=value.shape.as_list()[1:], + dtype=value.dtype.name, + ), + used_for_compute_actions=False, + ) + dummy_batch = self._dummy_batch + + logger.info("Testing `postprocess_trajectory` w/ dummy batch.") + self.exploration.postprocess_trajectory(self, dummy_batch, self.get_session()) + _ = self.postprocess_trajectory(dummy_batch) + # Add new columns automatically to (loss) input_dict. + for key in dummy_batch.added_keys: + if key not in self._input_dict: + self._input_dict[key] = get_placeholder( + value=dummy_batch[key], name=key + ) + if key not in self.view_requirements: + self.view_requirements[key] = ViewRequirement( + space=gym.spaces.Box( + -1.0, + 1.0, + shape=dummy_batch[key].shape[1:], + dtype=dummy_batch[key].dtype, + ), + used_for_compute_actions=False, + ) + + train_batch = SampleBatch( + dict(self._input_dict, **self._loss_input_dict), + _is_training=True, + ) + + if self._state_inputs: + train_batch[SampleBatch.SEQ_LENS] = self._seq_lens + self._loss_input_dict.update( + {SampleBatch.SEQ_LENS: train_batch[SampleBatch.SEQ_LENS]} + ) + + self._loss_input_dict.update(dict(train_batch)) + + if log_once("loss_init"): + logger.debug( + "Initializing loss function with dummy input:\n\n{}\n".format( + summarize(train_batch) + ) + ) + + losses = self._do_loss_init(train_batch) + + all_accessed_keys = ( + train_batch.accessed_keys + | dummy_batch.accessed_keys + | dummy_batch.added_keys + | set(self.model.view_requirements.keys()) + ) + + TFPolicy._initialize_loss( + self, + losses, + [(k, v) for k, v in train_batch.items() if k in all_accessed_keys] + + ( + [(SampleBatch.SEQ_LENS, train_batch[SampleBatch.SEQ_LENS])] + if SampleBatch.SEQ_LENS in train_batch + else [] + ), + ) + + if "is_training" in self._loss_input_dict: + del self._loss_input_dict["is_training"] + + # Call the grads stats fn. + # TODO: (sven) rename to simply stats_fn to match eager and torch. + if self._grad_stats_fn: + self._stats_fetches.update( + self._grad_stats_fn(self, train_batch, self._grads) + ) + + # Add new columns automatically to view-reqs. + if auto_remove_unneeded_view_reqs: + # Add those needed for postprocessing and training. + all_accessed_keys = train_batch.accessed_keys | dummy_batch.accessed_keys + # Tag those only needed for post-processing (with some exceptions). + for key in dummy_batch.accessed_keys: + if ( + key not in train_batch.accessed_keys + and key not in self.model.view_requirements + and key + not in [ + SampleBatch.EPS_ID, + SampleBatch.AGENT_INDEX, + SampleBatch.UNROLL_ID, + SampleBatch.TERMINATEDS, + SampleBatch.TRUNCATEDS, + SampleBatch.REWARDS, + SampleBatch.INFOS, + SampleBatch.T, + SampleBatch.OBS_EMBEDS, + ] + ): + if key in self.view_requirements: + self.view_requirements[key].used_for_training = False + if key in self._loss_input_dict: + del self._loss_input_dict[key] + # Remove those not needed at all (leave those that are needed + # by Sampler to properly execute sample collection). + # Also always leave TERMINATEDS, TRUNCATEDS, REWARDS, and INFOS, + # no matter what. + for key in list(self.view_requirements.keys()): + if ( + key not in all_accessed_keys + and key + not in [ + SampleBatch.EPS_ID, + SampleBatch.AGENT_INDEX, + SampleBatch.UNROLL_ID, + SampleBatch.TERMINATEDS, + SampleBatch.TRUNCATEDS, + SampleBatch.REWARDS, + SampleBatch.INFOS, + SampleBatch.T, + ] + and key not in self.model.view_requirements + ): + # If user deleted this key manually in postprocessing + # fn, warn about it and do not remove from + # view-requirements. + if key in dummy_batch.deleted_keys: + logger.warning( + "SampleBatch key '{}' was deleted manually in " + "postprocessing function! RLlib will " + "automatically remove non-used items from the " + "data stream. Remove the `del` from your " + "postprocessing function.".format(key) + ) + # If we are not writing output to disk, safe to erase + # this key to save space in the sample batch. + elif self.config["output"] is None: + del self.view_requirements[key] + + if key in self._loss_input_dict: + del self._loss_input_dict[key] + # Add those data_cols (again) that are missing and have + # dependencies by view_cols. + for key in list(self.view_requirements.keys()): + vr = self.view_requirements[key] + if ( + vr.data_col is not None + and vr.data_col not in self.view_requirements + ): + used_for_training = vr.data_col in train_batch.accessed_keys + self.view_requirements[vr.data_col] = ViewRequirement( + space=vr.space, used_for_training=used_for_training + ) + + self._loss_input_dict_no_rnn = { + k: v + for k, v in self._loss_input_dict.items() + if (v not in self._state_inputs and v != self._seq_lens) + } + + def _do_loss_init(self, train_batch: SampleBatch): + losses = self._loss_fn(self, self.model, self.dist_class, train_batch) + losses = force_list(losses) + if self._stats_fn: + self._stats_fetches.update(self._stats_fn(self, train_batch)) + # Override the update ops to be those of the model. + self._update_ops = [] + if not isinstance(self.model, tf.keras.Model): + self._update_ops = self.model.update_ops() + return losses + + +@OldAPIStack +class TFMultiGPUTowerStack: + """Optimizer that runs in parallel across multiple local devices. + + TFMultiGPUTowerStack automatically splits up and loads training data + onto specified local devices (e.g. GPUs) with `load_data()`. During a call + to `optimize()`, the devices compute gradients over slices of the data in + parallel. The gradients are then averaged and applied to the shared + weights. + + The data loaded is pinned in device memory until the next call to + `load_data`, so you can make multiple passes (possibly in randomized order) + over the same data once loaded. + + This is similar to tf1.train.SyncReplicasOptimizer, but works within a + single TensorFlow graph, i.e. implements in-graph replicated training: + + https://www.tensorflow.org/api_docs/python/tf/train/SyncReplicasOptimizer + """ + + def __init__( + self, + # Deprecated. + optimizer=None, + devices=None, + input_placeholders=None, + rnn_inputs=None, + max_per_device_batch_size=None, + build_graph=None, + grad_norm_clipping=None, + # Use only `policy` argument from here on. + policy: TFPolicy = None, + ): + """Initializes a TFMultiGPUTowerStack instance. + + Args: + policy: The TFPolicy object that this tower stack + belongs to. + """ + # Obsoleted usage, use only `policy` arg from here on. + if policy is None: + deprecation_warning( + old="TFMultiGPUTowerStack(...)", + new="TFMultiGPUTowerStack(policy=[Policy])", + error=True, + ) + self.policy = None + self.optimizers = optimizer + self.devices = devices + self.max_per_device_batch_size = max_per_device_batch_size + self.policy_copy = build_graph + else: + self.policy: TFPolicy = policy + self.optimizers: List[LocalOptimizer] = self.policy._optimizers + self.devices = self.policy.devices + self.max_per_device_batch_size = ( + max_per_device_batch_size + or policy.config.get( + "minibatch_size", policy.config.get("train_batch_size", 999999) + ) + ) // len(self.devices) + input_placeholders = tree.flatten(self.policy._loss_input_dict_no_rnn) + rnn_inputs = [] + if self.policy._state_inputs: + rnn_inputs = self.policy._state_inputs + [self.policy._seq_lens] + grad_norm_clipping = self.policy.config.get("grad_clip") + self.policy_copy = self.policy.copy + + assert len(self.devices) > 1 or "gpu" in self.devices[0] + self.loss_inputs = input_placeholders + rnn_inputs + + shared_ops = tf1.get_collection( + tf1.GraphKeys.UPDATE_OPS, scope=tf1.get_variable_scope().name + ) + + # Then setup the per-device loss graphs that use the shared weights + self._batch_index = tf1.placeholder(tf.int32, name="batch_index") + + # Dynamic batch size, which may be shrunk if there isn't enough data + self._per_device_batch_size = tf1.placeholder( + tf.int32, name="per_device_batch_size" + ) + self._loaded_per_device_batch_size = max_per_device_batch_size + + # When loading RNN input, we dynamically determine the max seq len + self._max_seq_len = tf1.placeholder(tf.int32, name="max_seq_len") + self._loaded_max_seq_len = 1 + + device_placeholders = [[] for _ in range(len(self.devices))] + + for t in tree.flatten(self.loss_inputs): + # Split on the CPU in case the data doesn't fit in GPU memory. + with tf.device("/cpu:0"): + splits = tf.split(t, len(self.devices)) + for i, d in enumerate(self.devices): + device_placeholders[i].append(splits[i]) + + self._towers = [] + for tower_i, (device, placeholders) in enumerate( + zip(self.devices, device_placeholders) + ): + self._towers.append( + self._setup_device( + tower_i, device, placeholders, len(tree.flatten(input_placeholders)) + ) + ) + + if self.policy.config["_tf_policy_handles_more_than_one_loss"]: + avgs = [] + for i, optim in enumerate(self.optimizers): + avg = _average_gradients([t.grads[i] for t in self._towers]) + if grad_norm_clipping: + clipped = [] + for grad, _ in avg: + clipped.append(grad) + clipped, _ = tf.clip_by_global_norm(clipped, grad_norm_clipping) + for i, (grad, var) in enumerate(avg): + avg[i] = (clipped[i], var) + avgs.append(avg) + + # Gather update ops for any batch norm layers. + # TODO(ekl) here we + # will use all the ops found which won't work for DQN / DDPG, but + # those aren't supported with multi-gpu right now anyways. + self._update_ops = tf1.get_collection( + tf1.GraphKeys.UPDATE_OPS, scope=tf1.get_variable_scope().name + ) + for op in shared_ops: + self._update_ops.remove(op) # only care about tower update ops + if self._update_ops: + logger.debug( + "Update ops to run on apply gradient: {}".format(self._update_ops) + ) + + with tf1.control_dependencies(self._update_ops): + self._train_op = tf.group( + [o.apply_gradients(a) for o, a in zip(self.optimizers, avgs)] + ) + else: + avg = _average_gradients([t.grads for t in self._towers]) + if grad_norm_clipping: + clipped = [] + for grad, _ in avg: + clipped.append(grad) + clipped, _ = tf.clip_by_global_norm(clipped, grad_norm_clipping) + for i, (grad, var) in enumerate(avg): + avg[i] = (clipped[i], var) + + # Gather update ops for any batch norm layers. + # TODO(ekl) here we + # will use all the ops found which won't work for DQN / DDPG, but + # those aren't supported with multi-gpu right now anyways. + self._update_ops = tf1.get_collection( + tf1.GraphKeys.UPDATE_OPS, scope=tf1.get_variable_scope().name + ) + for op in shared_ops: + self._update_ops.remove(op) # only care about tower update ops + if self._update_ops: + logger.debug( + "Update ops to run on apply gradient: {}".format(self._update_ops) + ) + + with tf1.control_dependencies(self._update_ops): + self._train_op = self.optimizers[0].apply_gradients(avg) + + # The lifetime number of gradient updates that the policy having sent + # some data (SampleBatchType) into this tower stack's GPU buffer(s) has already + # undergone. + self.num_grad_updates = 0 + + def load_data(self, sess, inputs, state_inputs, num_grad_updates=None): + """Bulk loads the specified inputs into device memory. + + The shape of the inputs must conform to the shapes of the input + placeholders this optimizer was constructed with. + + The data is split equally across all the devices. If the data is not + evenly divisible by the batch size, excess data will be discarded. + + Args: + sess: TensorFlow session. + inputs: List of arrays matching the input placeholders, of shape + [BATCH_SIZE, ...]. + state_inputs: List of RNN input arrays. These arrays have size + [BATCH_SIZE / MAX_SEQ_LEN, ...]. + num_grad_updates: The lifetime number of gradient updates that the + policy having collected the data has already undergone. + + Returns: + The number of tuples loaded per device. + """ + self.num_grad_updates = num_grad_updates + + if log_once("load_data"): + logger.info( + "Training on concatenated sample batches:\n\n{}\n".format( + summarize( + { + "placeholders": self.loss_inputs, + "inputs": inputs, + "state_inputs": state_inputs, + } + ) + ) + ) + + feed_dict = {} + assert len(self.loss_inputs) == len(inputs + state_inputs), ( + self.loss_inputs, + inputs, + state_inputs, + ) + + # Let's suppose we have the following input data, and 2 devices: + # 1 2 3 4 5 6 7 <- state inputs shape + # A A A B B B C C C D D D E E E F F F G G G <- inputs shape + # The data is truncated and split across devices as follows: + # |---| seq len = 3 + # |---------------------------------| seq batch size = 6 seqs + # |----------------| per device batch size = 9 tuples + + if len(state_inputs) > 0: + smallest_array = state_inputs[0] + seq_len = len(inputs[0]) // len(state_inputs[0]) + self._loaded_max_seq_len = seq_len + else: + smallest_array = inputs[0] + self._loaded_max_seq_len = 1 + + sequences_per_minibatch = ( + self.max_per_device_batch_size + // self._loaded_max_seq_len + * len(self.devices) + ) + if sequences_per_minibatch < 1: + logger.warning( + ( + "Target minibatch size is {}, however the rollout sequence " + "length is {}, hence the minibatch size will be raised to " + "{}." + ).format( + self.max_per_device_batch_size, + self._loaded_max_seq_len, + self._loaded_max_seq_len * len(self.devices), + ) + ) + sequences_per_minibatch = 1 + + if len(smallest_array) < sequences_per_minibatch: + # Dynamically shrink the batch size if insufficient data + sequences_per_minibatch = _make_divisible_by( + len(smallest_array), len(self.devices) + ) + + if log_once("data_slicing"): + logger.info( + ( + "Divided {} rollout sequences, each of length {}, among " + "{} devices." + ).format( + len(smallest_array), self._loaded_max_seq_len, len(self.devices) + ) + ) + + if sequences_per_minibatch < len(self.devices): + raise ValueError( + "Must load at least 1 tuple sequence per device. Try " + "increasing `minibatch_size` or reducing `max_seq_len` " + "to ensure that at least one sequence fits per device." + ) + self._loaded_per_device_batch_size = ( + sequences_per_minibatch // len(self.devices) * self._loaded_max_seq_len + ) + + if len(state_inputs) > 0: + # First truncate the RNN state arrays to the sequences_per_minib. + state_inputs = [ + _make_divisible_by(arr, sequences_per_minibatch) for arr in state_inputs + ] + # Then truncate the data inputs to match + inputs = [arr[: len(state_inputs[0]) * seq_len] for arr in inputs] + assert len(state_inputs[0]) * seq_len == len(inputs[0]), ( + len(state_inputs[0]), + sequences_per_minibatch, + seq_len, + len(inputs[0]), + ) + for ph, arr in zip(self.loss_inputs, inputs + state_inputs): + feed_dict[ph] = arr + truncated_len = len(inputs[0]) + else: + truncated_len = 0 + for ph, arr in zip(self.loss_inputs, inputs): + truncated_arr = _make_divisible_by(arr, sequences_per_minibatch) + feed_dict[ph] = truncated_arr + if truncated_len == 0: + truncated_len = len(truncated_arr) + + sess.run([t.init_op for t in self._towers], feed_dict=feed_dict) + + self.num_tuples_loaded = truncated_len + samples_per_device = truncated_len // len(self.devices) + assert samples_per_device > 0, "No data loaded?" + assert samples_per_device % self._loaded_per_device_batch_size == 0 + # Return loaded samples per-device. + return samples_per_device + + def optimize(self, sess, batch_index): + """Run a single step of SGD. + + Runs a SGD step over a slice of the preloaded batch with size given by + self._loaded_per_device_batch_size and offset given by the batch_index + argument. + + Updates shared model weights based on the averaged per-device + gradients. + + Args: + sess: TensorFlow session. + batch_index: Offset into the preloaded data. This value must be + between `0` and `tuples_per_device`. The amount of data to + process is at most `max_per_device_batch_size`. + + Returns: + The outputs of extra_ops evaluated over the batch. + """ + feed_dict = { + self._batch_index: batch_index, + self._per_device_batch_size: self._loaded_per_device_batch_size, + self._max_seq_len: self._loaded_max_seq_len, + } + for tower in self._towers: + feed_dict.update(tower.loss_graph.extra_compute_grad_feed_dict()) + + fetches = {"train": self._train_op} + for tower_num, tower in enumerate(self._towers): + tower_fetch = tower.loss_graph._get_grad_and_stats_fetches() + fetches["tower_{}".format(tower_num)] = tower_fetch + + return sess.run(fetches, feed_dict=feed_dict) + + def get_device_losses(self): + return [t.loss_graph for t in self._towers] + + def _setup_device(self, tower_i, device, device_input_placeholders, num_data_in): + assert num_data_in <= len(device_input_placeholders) + with tf.device(device): + with tf1.name_scope(TOWER_SCOPE_NAME + f"_{tower_i}"): + device_input_batches = [] + device_input_slices = [] + for i, ph in enumerate(device_input_placeholders): + current_batch = tf1.Variable( + ph, trainable=False, validate_shape=False, collections=[] + ) + device_input_batches.append(current_batch) + if i < num_data_in: + scale = self._max_seq_len + granularity = self._max_seq_len + else: + scale = self._max_seq_len + granularity = 1 + current_slice = tf.slice( + current_batch, + ( + [self._batch_index // scale * granularity] + + [0] * len(ph.shape[1:]) + ), + ( + [self._per_device_batch_size // scale * granularity] + + [-1] * len(ph.shape[1:]) + ), + ) + current_slice.set_shape(ph.shape) + device_input_slices.append(current_slice) + graph_obj = self.policy_copy(device_input_slices) + device_grads = graph_obj.gradients(self.optimizers, graph_obj._losses) + return _Tower( + tf.group(*[batch.initializer for batch in device_input_batches]), + device_grads, + graph_obj, + ) + + +# Each tower is a copy of the loss graph pinned to a specific device. +_Tower = namedtuple("Tower", ["init_op", "grads", "loss_graph"]) + + +def _make_divisible_by(a, n): + if type(a) is int: + return a - a % n + return a[0 : a.shape[0] - a.shape[0] % n] + + +def _average_gradients(tower_grads): + """Averages gradients across towers. + + Calculate the average gradient for each shared variable across all towers. + Note that this function provides a synchronization point across all towers. + + Args: + tower_grads: List of lists of (gradient, variable) tuples. The outer + list is over individual gradients. The inner list is over the + gradient calculation for each tower. + + Returns: + List of pairs of (gradient, variable) where the gradient has been + averaged across all towers. + + TODO(ekl): We could use NCCL if this becomes a bottleneck. + """ + + average_grads = [] + for grad_and_vars in zip(*tower_grads): + # Note that each grad_and_vars looks like the following: + # ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN)) + grads = [] + for g, _ in grad_and_vars: + if g is not None: + # Add 0 dimension to the gradients to represent the tower. + expanded_g = tf.expand_dims(g, 0) + + # Append on a 'tower' dimension which we will average over + # below. + grads.append(expanded_g) + + if not grads: + continue + + # Average over the 'tower' dimension. + grad = tf.concat(axis=0, values=grads) + grad = tf.reduce_mean(grad, 0) + + # Keep in mind that the Variables are redundant because they are shared + # across towers. So .. we will just return the first tower's pointer to + # the Variable. + v = grad_and_vars[0][1] + grad_and_var = (grad, v) + average_grads.append(grad_and_var) + + return average_grads diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/dynamic_tf_policy_v2.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/dynamic_tf_policy_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..1b127f3bef21aae028c8e08c419c963433f97759 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/dynamic_tf_policy_v2.py @@ -0,0 +1,1047 @@ +from collections import OrderedDict +import gymnasium as gym +import logging +import re +import tree # pip install dm_tree +from typing import Dict, List, Optional, Tuple, Type, Union + +from ray.rllib.models.catalog import ModelCatalog +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.tf.tf_action_dist import TFActionDistribution +from ray.rllib.policy.dynamic_tf_policy import TFMultiGPUTowerStack +from ray.rllib.policy.policy import Policy +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy.tf_policy import TFPolicy +from ray.rllib.policy.view_requirement import ViewRequirement +from ray.rllib.utils import force_list +from ray.rllib.utils.annotations import ( + OldAPIStack, + OverrideToImplementCustomLogic, + OverrideToImplementCustomLogic_CallToSuperRecommended, + is_overridden, + override, +) +from ray.rllib.utils.debug import summarize +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.metrics import ( + DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY, + NUM_GRAD_UPDATES_LIFETIME, +) +from ray.rllib.utils.metrics.learner_info import LEARNER_STATS_KEY +from ray.rllib.utils.spaces.space_utils import get_dummy_batch_for_space +from ray.rllib.utils.tf_utils import get_placeholder +from ray.rllib.utils.typing import ( + AlgorithmConfigDict, + LocalOptimizer, + ModelGradients, + TensorType, +) +from ray.util.debug import log_once + +tf1, tf, tfv = try_import_tf() + +logger = logging.getLogger(__name__) + + +@OldAPIStack +class DynamicTFPolicyV2(TFPolicy): + """A TFPolicy that auto-defines placeholders dynamically at runtime. + + This class is intended to be used and extended by sub-classing. + """ + + def __init__( + self, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + config: AlgorithmConfigDict, + *, + existing_inputs: Optional[Dict[str, "tf1.placeholder"]] = None, + existing_model: Optional[ModelV2] = None, + ): + self.observation_space = obs_space + self.action_space = action_space + self.config = config + self.framework = "tf" + self._seq_lens = None + self._is_tower = existing_inputs is not None + + self.validate_spaces(obs_space, action_space, config) + + self.dist_class = self._init_dist_class() + # Setup self.model. + if existing_model and isinstance(existing_model, list): + self.model = existing_model[0] + # TODO: (sven) hack, but works for `target_[q_]?model`. + for i in range(1, len(existing_model)): + setattr(self, existing_model[i][0], existing_model[i][1]) + else: + self.model = self.make_model() + # Auto-update model's inference view requirements, if recurrent. + self._update_model_view_requirements_from_init_state() + + self._init_state_inputs(existing_inputs) + self._init_view_requirements() + timestep, explore = self._init_input_dict_and_dummy_batch(existing_inputs) + ( + sampled_action, + sampled_action_logp, + dist_inputs, + self._policy_extra_action_fetches, + ) = self._init_action_fetches(timestep, explore) + + # Phase 1 init. + sess = tf1.get_default_session() or tf1.Session( + config=tf1.ConfigProto(**self.config["tf_session_args"]) + ) + + batch_divisibility_req = self.get_batch_divisibility_req() + + prev_action_input = ( + self._input_dict[SampleBatch.PREV_ACTIONS] + if SampleBatch.PREV_ACTIONS in self._input_dict.accessed_keys + else None + ) + prev_reward_input = ( + self._input_dict[SampleBatch.PREV_REWARDS] + if SampleBatch.PREV_REWARDS in self._input_dict.accessed_keys + else None + ) + + super().__init__( + observation_space=obs_space, + action_space=action_space, + config=config, + sess=sess, + obs_input=self._input_dict[SampleBatch.OBS], + action_input=self._input_dict[SampleBatch.ACTIONS], + sampled_action=sampled_action, + sampled_action_logp=sampled_action_logp, + dist_inputs=dist_inputs, + dist_class=self.dist_class, + loss=None, # dynamically initialized on run + loss_inputs=[], + model=self.model, + state_inputs=self._state_inputs, + state_outputs=self._state_out, + prev_action_input=prev_action_input, + prev_reward_input=prev_reward_input, + seq_lens=self._seq_lens, + max_seq_len=config["model"].get("max_seq_len", 20), + batch_divisibility_req=batch_divisibility_req, + explore=explore, + timestep=timestep, + ) + + @staticmethod + def enable_eager_execution_if_necessary(): + # This is static graph TF policy. + # Simply do nothing. + pass + + @OverrideToImplementCustomLogic + def validate_spaces( + self, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + config: AlgorithmConfigDict, + ): + return {} + + @OverrideToImplementCustomLogic + @override(Policy) + def loss( + self, + model: Union[ModelV2, "tf.keras.Model"], + dist_class: Type[TFActionDistribution], + train_batch: SampleBatch, + ) -> Union[TensorType, List[TensorType]]: + """Constructs loss computation graph for this TF1 policy. + + Args: + model: The Model to calculate the loss for. + dist_class: The action distr. class. + train_batch: The training data. + + Returns: + A single loss tensor or a list of loss tensors. + """ + raise NotImplementedError + + @OverrideToImplementCustomLogic + def stats_fn(self, train_batch: SampleBatch) -> Dict[str, TensorType]: + """Stats function. Returns a dict of statistics. + + Args: + train_batch: The SampleBatch (already) used for training. + + Returns: + The stats dict. + """ + return {} + + @OverrideToImplementCustomLogic + def grad_stats_fn( + self, train_batch: SampleBatch, grads: ModelGradients + ) -> Dict[str, TensorType]: + """Gradient stats function. Returns a dict of statistics. + + Args: + train_batch: The SampleBatch (already) used for training. + + Returns: + The stats dict. + """ + return {} + + @OverrideToImplementCustomLogic + def make_model(self) -> ModelV2: + """Build underlying model for this Policy. + + Returns: + The Model for the Policy to use. + """ + # Default ModelV2 model. + _, logit_dim = ModelCatalog.get_action_dist( + self.action_space, self.config["model"] + ) + return ModelCatalog.get_model_v2( + obs_space=self.observation_space, + action_space=self.action_space, + num_outputs=logit_dim, + model_config=self.config["model"], + framework="tf", + ) + + @OverrideToImplementCustomLogic + def compute_gradients_fn( + self, optimizer: LocalOptimizer, loss: TensorType + ) -> ModelGradients: + """Gradients computing function (from loss tensor, using local optimizer). + + Args: + policy: The Policy object that generated the loss tensor and + that holds the given local optimizer. + optimizer: The tf (local) optimizer object to + calculate the gradients with. + loss: The loss tensor for which gradients should be + calculated. + + Returns: + ModelGradients: List of the possibly clipped gradients- and variable + tuples. + """ + return None + + @OverrideToImplementCustomLogic + def apply_gradients_fn( + self, + optimizer: "tf.keras.optimizers.Optimizer", + grads: ModelGradients, + ) -> "tf.Operation": + """Gradients computing function (from loss tensor, using local optimizer). + + Args: + optimizer: The tf (local) optimizer object to + calculate the gradients with. + grads: The gradient tensor to be applied. + + Returns: + "tf.Operation": TF operation that applies supplied gradients. + """ + return None + + @OverrideToImplementCustomLogic + def action_sampler_fn( + self, + model: ModelV2, + *, + obs_batch: TensorType, + state_batches: TensorType, + **kwargs, + ) -> Tuple[TensorType, TensorType, TensorType, List[TensorType]]: + """Custom function for sampling new actions given policy. + + Args: + model: Underlying model. + obs_batch: Observation tensor batch. + state_batches: Action sampling state batch. + + Returns: + Sampled action + Log-likelihood + Action distribution inputs + Updated state + """ + return None, None, None, None + + @OverrideToImplementCustomLogic + def action_distribution_fn( + self, + model: ModelV2, + *, + obs_batch: TensorType, + state_batches: TensorType, + **kwargs, + ) -> Tuple[TensorType, type, List[TensorType]]: + """Action distribution function for this Policy. + + Args: + model: Underlying model. + obs_batch: Observation tensor batch. + state_batches: Action sampling state batch. + + Returns: + Distribution input. + ActionDistribution class. + State outs. + """ + return None, None, None + + @OverrideToImplementCustomLogic + def get_batch_divisibility_req(self) -> int: + """Get batch divisibility request. + + Returns: + Size N. A sample batch must be of size K*N. + """ + # By default, any sized batch is ok, so simply return 1. + return 1 + + @override(TFPolicy) + @OverrideToImplementCustomLogic_CallToSuperRecommended + def extra_action_out_fn(self) -> Dict[str, TensorType]: + """Extra values to fetch and return from compute_actions(). + + Returns: + Dict[str, TensorType]: An extra fetch-dict to be passed to and + returned from the compute_actions() call. + """ + extra_action_fetches = super().extra_action_out_fn() + extra_action_fetches.update(self._policy_extra_action_fetches) + return extra_action_fetches + + @OverrideToImplementCustomLogic_CallToSuperRecommended + def extra_learn_fetches_fn(self) -> Dict[str, TensorType]: + """Extra stats to be reported after gradient computation. + + Returns: + Dict[str, TensorType]: An extra fetch-dict. + """ + return {} + + @override(TFPolicy) + def extra_compute_grad_fetches(self): + return dict({LEARNER_STATS_KEY: {}}, **self.extra_learn_fetches_fn()) + + @override(Policy) + @OverrideToImplementCustomLogic_CallToSuperRecommended + def postprocess_trajectory( + self, + sample_batch: SampleBatch, + other_agent_batches: Optional[SampleBatch] = None, + episode=None, + ): + """Post process trajectory in the format of a SampleBatch. + + Args: + sample_batch: sample_batch: batch of experiences for the policy, + which will contain at most one episode trajectory. + other_agent_batches: In a multi-agent env, this contains a + mapping of agent ids to (policy, agent_batch) tuples + containing the policy and experiences of the other agents. + episode: An optional multi-agent episode object to provide + access to all of the internal episode state, which may + be useful for model-based or multi-agent algorithms. + + Returns: + The postprocessed sample batch. + """ + return Policy.postprocess_trajectory(self, sample_batch) + + @override(TFPolicy) + @OverrideToImplementCustomLogic + def optimizer( + self, + ) -> Union["tf.keras.optimizers.Optimizer", List["tf.keras.optimizers.Optimizer"]]: + """TF optimizer to use for policy optimization. + + Returns: + A local optimizer or a list of local optimizers to use for this + Policy's Model. + """ + return super().optimizer() + + def _init_dist_class(self): + if is_overridden(self.action_sampler_fn) or is_overridden( + self.action_distribution_fn + ): + if not is_overridden(self.make_model): + raise ValueError( + "`make_model` is required if `action_sampler_fn` OR " + "`action_distribution_fn` is given" + ) + return None + else: + dist_class, _ = ModelCatalog.get_action_dist( + self.action_space, self.config["model"] + ) + return dist_class + + def _init_view_requirements(self): + # If ViewRequirements are explicitly specified. + if getattr(self, "view_requirements", None): + return + + # Use default settings. + # Add NEXT_OBS, STATE_IN_0.., and others. + self.view_requirements = self._get_default_view_requirements() + # Combine view_requirements for Model and Policy. + # TODO(jungong) : models will not carry view_requirements once they + # are migrated to be organic Keras models. + self.view_requirements.update(self.model.view_requirements) + # Disable env-info placeholder. + if SampleBatch.INFOS in self.view_requirements: + self.view_requirements[SampleBatch.INFOS].used_for_training = False + + def _init_state_inputs(self, existing_inputs: Dict[str, "tf1.placeholder"]): + """Initialize input placeholders. + + Args: + existing_inputs: existing placeholders. + """ + if existing_inputs: + self._state_inputs = [ + v for k, v in existing_inputs.items() if k.startswith("state_in_") + ] + # Placeholder for RNN time-chunk valid lengths. + if self._state_inputs: + self._seq_lens = existing_inputs[SampleBatch.SEQ_LENS] + # Create new input placeholders. + else: + self._state_inputs = [ + get_placeholder( + space=vr.space, + time_axis=not isinstance(vr.shift, int), + name=k, + ) + for k, vr in self.model.view_requirements.items() + if k.startswith("state_in_") + ] + # Placeholder for RNN time-chunk valid lengths. + if self._state_inputs: + self._seq_lens = tf1.placeholder( + dtype=tf.int32, shape=[None], name="seq_lens" + ) + + def _init_input_dict_and_dummy_batch( + self, existing_inputs: Dict[str, "tf1.placeholder"] + ) -> Tuple[Union[int, TensorType], Union[bool, TensorType]]: + """Initialized input_dict and dummy_batch data. + + Args: + existing_inputs: When copying a policy, this specifies an existing + dict of placeholders to use instead of defining new ones. + + Returns: + timestep: training timestep. + explore: whether this policy should explore. + """ + # Setup standard placeholders. + if self._is_tower: + assert existing_inputs is not None + timestep = existing_inputs["timestep"] + explore = False + ( + self._input_dict, + self._dummy_batch, + ) = self._create_input_dict_and_dummy_batch( + self.view_requirements, existing_inputs + ) + else: + # Placeholder for (sampling steps) timestep (int). + timestep = tf1.placeholder_with_default( + tf.zeros((), dtype=tf.int64), (), name="timestep" + ) + # Placeholder for `is_exploring` flag. + explore = tf1.placeholder_with_default(True, (), name="is_exploring") + ( + self._input_dict, + self._dummy_batch, + ) = self._create_input_dict_and_dummy_batch(self.view_requirements, {}) + + # Placeholder for `is_training` flag. + self._input_dict.set_training(self._get_is_training_placeholder()) + + return timestep, explore + + def _create_input_dict_and_dummy_batch(self, view_requirements, existing_inputs): + """Creates input_dict and dummy_batch for loss initialization. + + Used for managing the Policy's input placeholders and for loss + initialization. + Input_dict: Str -> tf.placeholders, dummy_batch: str -> np.arrays. + + Args: + view_requirements: The view requirements dict. + existing_inputs (Dict[str, tf.placeholder]): A dict of already + existing placeholders. + + Returns: + Tuple[Dict[str, tf.placeholder], Dict[str, np.ndarray]]: The + input_dict/dummy_batch tuple. + """ + input_dict = {} + for view_col, view_req in view_requirements.items(): + # Point state_in to the already existing self._state_inputs. + mo = re.match(r"state_in_(\d+)", view_col) + if mo is not None: + input_dict[view_col] = self._state_inputs[int(mo.group(1))] + # State-outs (no placeholders needed). + elif view_col.startswith("state_out_"): + continue + # Skip action dist inputs placeholder (do later). + elif view_col == SampleBatch.ACTION_DIST_INPUTS: + continue + # This is a tower: Input placeholders already exist. + elif view_col in existing_inputs: + input_dict[view_col] = existing_inputs[view_col] + # All others. + else: + time_axis = not isinstance(view_req.shift, int) + if view_req.used_for_training: + # Create a +time-axis placeholder if the shift is not an + # int (range or list of ints). + # Do not flatten actions if action flattening disabled. + if self.config.get("_disable_action_flattening") and view_col in [ + SampleBatch.ACTIONS, + SampleBatch.PREV_ACTIONS, + ]: + flatten = False + # Do not flatten observations if no preprocessor API used. + elif ( + view_col in [SampleBatch.OBS, SampleBatch.NEXT_OBS] + and self.config["_disable_preprocessor_api"] + ): + flatten = False + # Flatten everything else. + else: + flatten = True + input_dict[view_col] = get_placeholder( + space=view_req.space, + name=view_col, + time_axis=time_axis, + flatten=flatten, + ) + dummy_batch = self._get_dummy_batch_from_view_requirements(batch_size=32) + + return SampleBatch(input_dict, seq_lens=self._seq_lens), dummy_batch + + def _init_action_fetches( + self, timestep: Union[int, TensorType], explore: Union[bool, TensorType] + ) -> Tuple[TensorType, TensorType, TensorType, type, Dict[str, TensorType]]: + """Create action related fields for base Policy and loss initialization.""" + # Multi-GPU towers do not need any action computing/exploration + # graphs. + sampled_action = None + sampled_action_logp = None + dist_inputs = None + extra_action_fetches = {} + self._state_out = None + if not self._is_tower: + # Create the Exploration object to use for this Policy. + self.exploration = self._create_exploration() + + # Fully customized action generation (e.g., custom policy). + if is_overridden(self.action_sampler_fn): + ( + sampled_action, + sampled_action_logp, + dist_inputs, + self._state_out, + ) = self.action_sampler_fn( + self.model, + obs_batch=self._input_dict[SampleBatch.OBS], + state_batches=self._state_inputs, + seq_lens=self._seq_lens, + prev_action_batch=self._input_dict.get(SampleBatch.PREV_ACTIONS), + prev_reward_batch=self._input_dict.get(SampleBatch.PREV_REWARDS), + explore=explore, + is_training=self._input_dict.is_training, + ) + # Distribution generation is customized, e.g., DQN, DDPG. + else: + if is_overridden(self.action_distribution_fn): + # Try new action_distribution_fn signature, supporting + # state_batches and seq_lens. + in_dict = self._input_dict + ( + dist_inputs, + self.dist_class, + self._state_out, + ) = self.action_distribution_fn( + self.model, + obs_batch=in_dict[SampleBatch.OBS], + state_batches=self._state_inputs, + seq_lens=self._seq_lens, + explore=explore, + timestep=timestep, + is_training=in_dict.is_training, + ) + # Default distribution generation behavior: + # Pass through model. E.g., PG, PPO. + else: + if isinstance(self.model, tf.keras.Model): + dist_inputs, self._state_out, extra_action_fetches = self.model( + self._input_dict + ) + else: + dist_inputs, self._state_out = self.model(self._input_dict) + + action_dist = self.dist_class(dist_inputs, self.model) + + # Using exploration to get final action (e.g. via sampling). + ( + sampled_action, + sampled_action_logp, + ) = self.exploration.get_exploration_action( + action_distribution=action_dist, timestep=timestep, explore=explore + ) + + if dist_inputs is not None: + extra_action_fetches[SampleBatch.ACTION_DIST_INPUTS] = dist_inputs + + if sampled_action_logp is not None: + extra_action_fetches[SampleBatch.ACTION_LOGP] = sampled_action_logp + extra_action_fetches[SampleBatch.ACTION_PROB] = tf.exp( + tf.cast(sampled_action_logp, tf.float32) + ) + + return ( + sampled_action, + sampled_action_logp, + dist_inputs, + extra_action_fetches, + ) + + def _init_optimizers(self): + # Create the optimizer/exploration optimizer here. Some initialization + # steps (e.g. exploration postprocessing) may need this. + optimizers = force_list(self.optimizer()) + if self.exploration: + optimizers = self.exploration.get_exploration_optimizer(optimizers) + + # No optimizers produced -> Return. + if not optimizers: + return + + # The list of local (tf) optimizers (one per loss term). + self._optimizers = optimizers + # Backward compatibility. + self._optimizer = optimizers[0] + + def maybe_initialize_optimizer_and_loss(self): + # We don't need to initialize loss calculation for MultiGPUTowerStack. + if self._is_tower: + self.get_session().run(tf1.global_variables_initializer()) + return + + # Loss initialization and model/postprocessing test calls. + self._init_optimizers() + self._initialize_loss_from_dummy_batch(auto_remove_unneeded_view_reqs=True) + + # Create MultiGPUTowerStacks, if we have at least one actual + # GPU or >1 CPUs (fake GPUs). + if len(self.devices) > 1 or any("gpu" in d for d in self.devices): + # Per-GPU graph copies created here must share vars with the + # policy. Therefore, `reuse` is set to tf1.AUTO_REUSE because + # Adam nodes are created after all of the device copies are + # created. + with tf1.variable_scope("", reuse=tf1.AUTO_REUSE): + self.multi_gpu_tower_stacks = [ + TFMultiGPUTowerStack(policy=self) + for _ in range(self.config.get("num_multi_gpu_tower_stacks", 1)) + ] + + # Initialize again after loss and tower init. + self.get_session().run(tf1.global_variables_initializer()) + + @override(Policy) + def _initialize_loss_from_dummy_batch( + self, auto_remove_unneeded_view_reqs: bool = True + ) -> None: + # Test calls depend on variable init, so initialize model first. + self.get_session().run(tf1.global_variables_initializer()) + + # Fields that have not been accessed are not needed for action + # computations -> Tag them as `used_for_compute_actions=False`. + for key, view_req in self.view_requirements.items(): + if ( + not key.startswith("state_in_") + and key not in self._input_dict.accessed_keys + ): + view_req.used_for_compute_actions = False + for key, value in self.extra_action_out_fn().items(): + self._dummy_batch[key] = get_dummy_batch_for_space( + gym.spaces.Box( + -1.0, 1.0, shape=value.shape.as_list()[1:], dtype=value.dtype.name + ), + batch_size=len(self._dummy_batch), + ) + self._input_dict[key] = get_placeholder(value=value, name=key) + if key not in self.view_requirements: + logger.info("Adding extra-action-fetch `{}` to view-reqs.".format(key)) + self.view_requirements[key] = ViewRequirement( + space=gym.spaces.Box( + -1.0, + 1.0, + shape=value.shape.as_list()[1:], + dtype=value.dtype.name, + ), + used_for_compute_actions=False, + ) + dummy_batch = self._dummy_batch + + logger.info("Testing `postprocess_trajectory` w/ dummy batch.") + self.exploration.postprocess_trajectory(self, dummy_batch, self.get_session()) + _ = self.postprocess_trajectory(dummy_batch) + # Add new columns automatically to (loss) input_dict. + for key in dummy_batch.added_keys: + if key not in self._input_dict: + self._input_dict[key] = get_placeholder( + value=dummy_batch[key], name=key + ) + if key not in self.view_requirements: + self.view_requirements[key] = ViewRequirement( + space=gym.spaces.Box( + -1.0, + 1.0, + shape=dummy_batch[key].shape[1:], + dtype=dummy_batch[key].dtype, + ), + used_for_compute_actions=False, + ) + + train_batch = SampleBatch( + dict(self._input_dict, **self._loss_input_dict), + _is_training=True, + ) + + if self._state_inputs: + train_batch[SampleBatch.SEQ_LENS] = self._seq_lens + self._loss_input_dict.update( + {SampleBatch.SEQ_LENS: train_batch[SampleBatch.SEQ_LENS]} + ) + + self._loss_input_dict.update(dict(train_batch)) + + if log_once("loss_init"): + logger.debug( + "Initializing loss function with dummy input:\n\n{}\n".format( + summarize(train_batch) + ) + ) + + losses = self._do_loss_init(train_batch) + + all_accessed_keys = ( + train_batch.accessed_keys + | dummy_batch.accessed_keys + | dummy_batch.added_keys + | set(self.model.view_requirements.keys()) + ) + + TFPolicy._initialize_loss( + self, + losses, + [(k, v) for k, v in train_batch.items() if k in all_accessed_keys] + + ( + [(SampleBatch.SEQ_LENS, train_batch[SampleBatch.SEQ_LENS])] + if SampleBatch.SEQ_LENS in train_batch + else [] + ), + ) + + if "is_training" in self._loss_input_dict: + del self._loss_input_dict["is_training"] + + # Call the grads stats fn. + # TODO: (sven) rename to simply stats_fn to match eager and torch. + self._stats_fetches.update(self.grad_stats_fn(train_batch, self._grads)) + + # Add new columns automatically to view-reqs. + if auto_remove_unneeded_view_reqs: + # Add those needed for postprocessing and training. + all_accessed_keys = train_batch.accessed_keys | dummy_batch.accessed_keys + # Tag those only needed for post-processing (with some exceptions). + for key in dummy_batch.accessed_keys: + if ( + key not in train_batch.accessed_keys + and key not in self.model.view_requirements + and key + not in [ + SampleBatch.EPS_ID, + SampleBatch.AGENT_INDEX, + SampleBatch.UNROLL_ID, + SampleBatch.TERMINATEDS, + SampleBatch.TRUNCATEDS, + SampleBatch.REWARDS, + SampleBatch.INFOS, + SampleBatch.T, + SampleBatch.OBS_EMBEDS, + ] + ): + if key in self.view_requirements: + self.view_requirements[key].used_for_training = False + if key in self._loss_input_dict: + del self._loss_input_dict[key] + # Remove those not needed at all (leave those that are needed + # by Sampler to properly execute sample collection). + # Also always leave TERMINATEDS, TRUNCATEDS, REWARDS, and INFOS, + # no matter what. + for key in list(self.view_requirements.keys()): + if ( + key not in all_accessed_keys + and key + not in [ + SampleBatch.EPS_ID, + SampleBatch.AGENT_INDEX, + SampleBatch.UNROLL_ID, + SampleBatch.TERMINATEDS, + SampleBatch.TRUNCATEDS, + SampleBatch.REWARDS, + SampleBatch.INFOS, + SampleBatch.T, + ] + and key not in self.model.view_requirements + ): + # If user deleted this key manually in postprocessing + # fn, warn about it and do not remove from + # view-requirements. + if key in dummy_batch.deleted_keys: + logger.warning( + "SampleBatch key '{}' was deleted manually in " + "postprocessing function! RLlib will " + "automatically remove non-used items from the " + "data stream. Remove the `del` from your " + "postprocessing function.".format(key) + ) + # If we are not writing output to disk, safe to erase + # this key to save space in the sample batch. + elif self.config["output"] is None: + del self.view_requirements[key] + + if key in self._loss_input_dict: + del self._loss_input_dict[key] + # Add those data_cols (again) that are missing and have + # dependencies by view_cols. + for key in list(self.view_requirements.keys()): + vr = self.view_requirements[key] + if ( + vr.data_col is not None + and vr.data_col not in self.view_requirements + ): + used_for_training = vr.data_col in train_batch.accessed_keys + self.view_requirements[vr.data_col] = ViewRequirement( + space=vr.space, used_for_training=used_for_training + ) + + self._loss_input_dict_no_rnn = { + k: v + for k, v in self._loss_input_dict.items() + if (v not in self._state_inputs and v != self._seq_lens) + } + + def _do_loss_init(self, train_batch: SampleBatch): + losses = self.loss(self.model, self.dist_class, train_batch) + losses = force_list(losses) + self._stats_fetches.update(self.stats_fn(train_batch)) + # Override the update ops to be those of the model. + self._update_ops = [] + if not isinstance(self.model, tf.keras.Model): + self._update_ops = self.model.update_ops() + return losses + + @override(TFPolicy) + def copy(self, existing_inputs: List[Tuple[str, "tf1.placeholder"]]) -> TFPolicy: + """Creates a copy of self using existing input placeholders.""" + + flat_loss_inputs = tree.flatten(self._loss_input_dict) + flat_loss_inputs_no_rnn = tree.flatten(self._loss_input_dict_no_rnn) + + # Note that there might be RNN state inputs at the end of the list + if len(flat_loss_inputs) != len(existing_inputs): + raise ValueError( + "Tensor list mismatch", + self._loss_input_dict, + self._state_inputs, + existing_inputs, + ) + for i, v in enumerate(flat_loss_inputs_no_rnn): + if v.shape.as_list() != existing_inputs[i].shape.as_list(): + raise ValueError( + "Tensor shape mismatch", i, v.shape, existing_inputs[i].shape + ) + # By convention, the loss inputs are followed by state inputs and then + # the seq len tensor. + rnn_inputs = [] + for i in range(len(self._state_inputs)): + rnn_inputs.append( + ( + "state_in_{}".format(i), + existing_inputs[len(flat_loss_inputs_no_rnn) + i], + ) + ) + if rnn_inputs: + rnn_inputs.append((SampleBatch.SEQ_LENS, existing_inputs[-1])) + existing_inputs_unflattened = tree.unflatten_as( + self._loss_input_dict_no_rnn, + existing_inputs[: len(flat_loss_inputs_no_rnn)], + ) + input_dict = OrderedDict( + [("is_exploring", self._is_exploring), ("timestep", self._timestep)] + + [ + (k, existing_inputs_unflattened[k]) + for i, k in enumerate(self._loss_input_dict_no_rnn.keys()) + ] + + rnn_inputs + ) + + instance = self.__class__( + self.observation_space, + self.action_space, + self.config, + existing_inputs=input_dict, + existing_model=[ + self.model, + # Deprecated: Target models should all reside under + # `policy.target_model` now. + ("target_q_model", getattr(self, "target_q_model", None)), + ("target_model", getattr(self, "target_model", None)), + ], + ) + + instance._loss_input_dict = input_dict + losses = instance._do_loss_init(SampleBatch(input_dict)) + loss_inputs = [ + (k, existing_inputs_unflattened[k]) + for i, k in enumerate(self._loss_input_dict_no_rnn.keys()) + ] + + TFPolicy._initialize_loss(instance, losses, loss_inputs) + instance._stats_fetches.update( + instance.grad_stats_fn(input_dict, instance._grads) + ) + return instance + + @override(Policy) + def get_initial_state(self) -> List[TensorType]: + if self.model: + return self.model.get_initial_state() + else: + return [] + + @override(Policy) + def load_batch_into_buffer( + self, + batch: SampleBatch, + buffer_index: int = 0, + ) -> int: + # Set the is_training flag of the batch. + batch.set_training(True) + + # Shortcut for 1 CPU only: Store batch in + # `self._loaded_single_cpu_batch`. + if len(self.devices) == 1 and self.devices[0] == "/cpu:0": + assert buffer_index == 0 + self._loaded_single_cpu_batch = batch + return len(batch) + + input_dict = self._get_loss_inputs_dict(batch, shuffle=False) + data_keys = tree.flatten(self._loss_input_dict_no_rnn) + if self._state_inputs: + state_keys = self._state_inputs + [self._seq_lens] + else: + state_keys = [] + inputs = [input_dict[k] for k in data_keys] + state_inputs = [input_dict[k] for k in state_keys] + + return self.multi_gpu_tower_stacks[buffer_index].load_data( + sess=self.get_session(), + inputs=inputs, + state_inputs=state_inputs, + num_grad_updates=batch.num_grad_updates, + ) + + @override(Policy) + def get_num_samples_loaded_into_buffer(self, buffer_index: int = 0) -> int: + # Shortcut for 1 CPU only: Batch should already be stored in + # `self._loaded_single_cpu_batch`. + if len(self.devices) == 1 and self.devices[0] == "/cpu:0": + assert buffer_index == 0 + return ( + len(self._loaded_single_cpu_batch) + if self._loaded_single_cpu_batch is not None + else 0 + ) + + return self.multi_gpu_tower_stacks[buffer_index].num_tuples_loaded + + @override(Policy) + def learn_on_loaded_batch(self, offset: int = 0, buffer_index: int = 0): + # Shortcut for 1 CPU only: Batch should already be stored in + # `self._loaded_single_cpu_batch`. + if len(self.devices) == 1 and self.devices[0] == "/cpu:0": + assert buffer_index == 0 + if self._loaded_single_cpu_batch is None: + raise ValueError( + "Must call Policy.load_batch_into_buffer() before " + "Policy.learn_on_loaded_batch()!" + ) + # Get the correct slice of the already loaded batch to use, + # based on offset and batch size. + batch_size = self.config.get("minibatch_size") + if batch_size is None: + batch_size = self.config.get( + "sgd_minibatch_size", self.config["train_batch_size"] + ) + + if batch_size >= len(self._loaded_single_cpu_batch): + sliced_batch = self._loaded_single_cpu_batch + else: + sliced_batch = self._loaded_single_cpu_batch.slice( + start=offset, end=offset + batch_size + ) + return self.learn_on_batch(sliced_batch) + + tower_stack = self.multi_gpu_tower_stacks[buffer_index] + results = tower_stack.optimize(self.get_session(), offset) + self.num_grad_updates += 1 + + results.update( + { + NUM_GRAD_UPDATES_LIFETIME: self.num_grad_updates, + # -1, b/c we have to measure this diff before we do the update above. + DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY: ( + self.num_grad_updates - 1 - (tower_stack.num_grad_updates or 0) + ), + } + ) + + return results + + @override(TFPolicy) + def gradients(self, optimizer, loss): + optimizers = force_list(optimizer) + losses = force_list(loss) + + if is_overridden(self.compute_gradients_fn): + # New API: Allow more than one optimizer -> Return a list of + # lists of gradients. + if self.config["_tf_policy_handles_more_than_one_loss"]: + return self.compute_gradients_fn(optimizers, losses) + # Old API: Return a single List of gradients. + else: + return self.compute_gradients_fn(optimizers[0], losses[0]) + else: + return super().gradients(optimizers, losses) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/eager_tf_policy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/eager_tf_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c2e4fa33f1592d85aa14e1de9bfc916885856605 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/eager_tf_policy.py @@ -0,0 +1,1051 @@ +"""Eager mode TF policy built using build_tf_policy(). + +It supports both traced and non-traced eager execution modes.""" + +import functools +import logging +import os +import threading +from typing import Dict, List, Optional, Tuple, Union + +import tree # pip install dm_tree + +from ray.rllib.models.catalog import ModelCatalog +from ray.rllib.models.repeated_values import RepeatedValues +from ray.rllib.policy.policy import Policy, PolicyState +from ray.rllib.policy.rnn_sequencing import pad_batch_to_sequences_of_same_size +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils import add_mixins, force_list +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.deprecation import ( + DEPRECATED_VALUE, + deprecation_warning, +) +from ray.rllib.utils.error import ERR_MSG_TF_POLICY_CANNOT_SAVE_KERAS_MODEL +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.metrics import ( + DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY, + NUM_AGENT_STEPS_TRAINED, + NUM_GRAD_UPDATES_LIFETIME, +) +from ray.rllib.utils.metrics.learner_info import LEARNER_STATS_KEY +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.spaces.space_utils import normalize_action +from ray.rllib.utils.tf_utils import get_gpu_devices +from ray.rllib.utils.threading import with_lock +from ray.rllib.utils.typing import ( + LocalOptimizer, + ModelGradients, + TensorType, + TensorStructType, +) +from ray.util.debug import log_once + +tf1, tf, tfv = try_import_tf() +logger = logging.getLogger(__name__) + + +def _convert_to_tf(x, dtype=None): + if isinstance(x, SampleBatch): + dict_ = {k: v for k, v in x.items() if k != SampleBatch.INFOS} + return tree.map_structure(_convert_to_tf, dict_) + elif isinstance(x, Policy): + return x + # Special handling of "Repeated" values. + elif isinstance(x, RepeatedValues): + return RepeatedValues( + tree.map_structure(_convert_to_tf, x.values), x.lengths, x.max_len + ) + + if x is not None: + d = dtype + return tree.map_structure( + lambda f: _convert_to_tf(f, d) + if isinstance(f, RepeatedValues) + else tf.convert_to_tensor(f, d) + if f is not None and not tf.is_tensor(f) + else f, + x, + ) + + return x + + +def _convert_to_numpy(x): + def _map(x): + if isinstance(x, tf.Tensor): + return x.numpy() + return x + + try: + return tf.nest.map_structure(_map, x) + except AttributeError: + raise TypeError( + ("Object of type {} has no method to convert to numpy.").format(type(x)) + ) + + +def _convert_eager_inputs(func): + @functools.wraps(func) + def _func(*args, **kwargs): + if tf.executing_eagerly(): + eager_args = [_convert_to_tf(x) for x in args] + # TODO: (sven) find a way to remove key-specific hacks. + eager_kwargs = { + k: _convert_to_tf(v, dtype=tf.int64 if k == "timestep" else None) + for k, v in kwargs.items() + if k not in {"info_batch", "episodes"} + } + return func(*eager_args, **eager_kwargs) + else: + return func(*args, **kwargs) + + return _func + + +def _convert_eager_outputs(func): + @functools.wraps(func) + def _func(*args, **kwargs): + out = func(*args, **kwargs) + if tf.executing_eagerly(): + out = tf.nest.map_structure(_convert_to_numpy, out) + return out + + return _func + + +def _disallow_var_creation(next_creator, **kw): + v = next_creator(**kw) + raise ValueError( + "Detected a variable being created during an eager " + "forward pass. Variables should only be created during " + "model initialization: {}".format(v.name) + ) + + +def _check_too_many_retraces(obj): + """Asserts that a given number of re-traces is not breached.""" + + def _func(self_, *args, **kwargs): + if ( + self_.config.get("eager_max_retraces") is not None + and self_._re_trace_counter > self_.config["eager_max_retraces"] + ): + raise RuntimeError( + "Too many tf-eager re-traces detected! This could lead to" + " significant slow-downs (even slower than running in " + "tf-eager mode w/ `eager_tracing=False`). To switch off " + "these re-trace counting checks, set `eager_max_retraces`" + " in your config to None." + ) + return obj(self_, *args, **kwargs) + + return _func + + +@OldAPIStack +class EagerTFPolicy(Policy): + """Dummy class to recognize any eagerized TFPolicy by its inheritance.""" + + pass + + +def _traced_eager_policy(eager_policy_cls): + """Wrapper class that enables tracing for all eager policy methods. + + This is enabled by the `--trace`/`eager_tracing=True` config when + framework=tf2. + """ + + class TracedEagerPolicy(eager_policy_cls): + def __init__(self, *args, **kwargs): + self._traced_learn_on_batch_helper = False + self._traced_compute_actions_helper = False + self._traced_compute_gradients_helper = False + self._traced_apply_gradients_helper = False + super(TracedEagerPolicy, self).__init__(*args, **kwargs) + + @_check_too_many_retraces + @override(Policy) + def compute_actions_from_input_dict( + self, + input_dict: Dict[str, TensorType], + explore: bool = None, + timestep: Optional[int] = None, + episodes=None, + **kwargs, + ) -> Tuple[TensorType, List[TensorType], Dict[str, TensorType]]: + """Traced version of Policy.compute_actions_from_input_dict.""" + + # Create a traced version of `self._compute_actions_helper`. + if self._traced_compute_actions_helper is False and not self._no_tracing: + self._compute_actions_helper = _convert_eager_inputs( + tf.function( + super(TracedEagerPolicy, self)._compute_actions_helper, + autograph=False, + reduce_retracing=True, + ) + ) + self._traced_compute_actions_helper = True + + # Now that the helper method is traced, call super's + # `compute_actions_from_input_dict()` (which will call the traced helper). + return super(TracedEagerPolicy, self).compute_actions_from_input_dict( + input_dict=input_dict, + explore=explore, + timestep=timestep, + episodes=episodes, + **kwargs, + ) + + @_check_too_many_retraces + @override(eager_policy_cls) + def learn_on_batch(self, samples): + """Traced version of Policy.learn_on_batch.""" + + # Create a traced version of `self._learn_on_batch_helper`. + if self._traced_learn_on_batch_helper is False and not self._no_tracing: + self._learn_on_batch_helper = _convert_eager_inputs( + tf.function( + super(TracedEagerPolicy, self)._learn_on_batch_helper, + autograph=False, + reduce_retracing=True, + ) + ) + self._traced_learn_on_batch_helper = True + + # Now that the helper method is traced, call super's + # apply_gradients (which will call the traced helper). + return super(TracedEagerPolicy, self).learn_on_batch(samples) + + @_check_too_many_retraces + @override(eager_policy_cls) + def compute_gradients(self, samples: SampleBatch) -> ModelGradients: + """Traced version of Policy.compute_gradients.""" + + # Create a traced version of `self._compute_gradients_helper`. + if self._traced_compute_gradients_helper is False and not self._no_tracing: + self._compute_gradients_helper = _convert_eager_inputs( + tf.function( + super(TracedEagerPolicy, self)._compute_gradients_helper, + autograph=False, + reduce_retracing=True, + ) + ) + self._traced_compute_gradients_helper = True + + # Now that the helper method is traced, call super's + # `compute_gradients()` (which will call the traced helper). + return super(TracedEagerPolicy, self).compute_gradients(samples) + + @_check_too_many_retraces + @override(Policy) + def apply_gradients(self, grads: ModelGradients) -> None: + """Traced version of Policy.apply_gradients.""" + + # Create a traced version of `self._apply_gradients_helper`. + if self._traced_apply_gradients_helper is False and not self._no_tracing: + self._apply_gradients_helper = _convert_eager_inputs( + tf.function( + super(TracedEagerPolicy, self)._apply_gradients_helper, + autograph=False, + reduce_retracing=True, + ) + ) + self._traced_apply_gradients_helper = True + + # Now that the helper method is traced, call super's + # `apply_gradients()` (which will call the traced helper). + return super(TracedEagerPolicy, self).apply_gradients(grads) + + @classmethod + def with_tracing(cls): + # Already traced -> Return same class. + return cls + + TracedEagerPolicy.__name__ = eager_policy_cls.__name__ + "_traced" + TracedEagerPolicy.__qualname__ = eager_policy_cls.__qualname__ + "_traced" + return TracedEagerPolicy + + +class _OptimizerWrapper: + def __init__(self, tape): + self.tape = tape + + def compute_gradients(self, loss, var_list): + return list(zip(self.tape.gradient(loss, var_list), var_list)) + + +@OldAPIStack +def _build_eager_tf_policy( + name, + loss_fn, + get_default_config=None, + postprocess_fn=None, + stats_fn=None, + optimizer_fn=None, + compute_gradients_fn=None, + apply_gradients_fn=None, + grad_stats_fn=None, + extra_learn_fetches_fn=None, + extra_action_out_fn=None, + validate_spaces=None, + before_init=None, + before_loss_init=None, + after_init=None, + make_model=None, + action_sampler_fn=None, + action_distribution_fn=None, + mixins=None, + get_batch_divisibility_req=None, + # Deprecated args. + obs_include_prev_action_reward=DEPRECATED_VALUE, + extra_action_fetches_fn=None, + gradients_fn=None, +): + """Build an eager TF policy. + + An eager policy runs all operations in eager mode, which makes debugging + much simpler, but has lower performance. + + You shouldn't need to call this directly. Rather, prefer to build a TF + graph policy and use set `.framework("tf2", eager_tracing=False) in your + AlgorithmConfig to have it automatically be converted to an eager policy. + + This has the same signature as build_tf_policy().""" + + base = add_mixins(EagerTFPolicy, mixins) + + if obs_include_prev_action_reward != DEPRECATED_VALUE: + deprecation_warning(old="obs_include_prev_action_reward", error=True) + + if extra_action_fetches_fn is not None: + deprecation_warning( + old="extra_action_fetches_fn", new="extra_action_out_fn", error=True + ) + + if gradients_fn is not None: + deprecation_warning(old="gradients_fn", new="compute_gradients_fn", error=True) + + class eager_policy_cls(base): + def __init__(self, observation_space, action_space, config): + # If this class runs as a @ray.remote actor, eager mode may not + # have been activated yet. + if not tf1.executing_eagerly(): + tf1.enable_eager_execution() + self.framework = config.get("framework", "tf2") + EagerTFPolicy.__init__(self, observation_space, action_space, config) + + # Global timestep should be a tensor. + self.global_timestep = tf.Variable(0, trainable=False, dtype=tf.int64) + self.explore = tf.Variable( + self.config["explore"], trainable=False, dtype=tf.bool + ) + + # Log device and worker index. + num_gpus = self._get_num_gpus_for_policy() + if num_gpus > 0: + gpu_ids = get_gpu_devices() + logger.info(f"Found {len(gpu_ids)} visible cuda devices.") + + self._is_training = False + + # Only for `config.eager_tracing=True`: A counter to keep track of + # how many times an eager-traced method (e.g. + # `self._compute_actions_helper`) has been re-traced by tensorflow. + # We will raise an error if more than n re-tracings have been + # detected, since this would considerably slow down execution. + # The variable below should only get incremented during the + # tf.function trace operations, never when calling the already + # traced function after that. + self._re_trace_counter = 0 + + self._loss_initialized = False + # To ensure backward compatibility: + # Old way: If `loss` provided here, use as-is (as a function). + if loss_fn is not None: + self._loss = loss_fn + # New way: Convert the overridden `self.loss` into a plain + # function, so it can be called the same way as `loss` would + # be, ensuring backward compatibility. + elif self.loss.__func__.__qualname__ != "Policy.loss": + self._loss = self.loss.__func__ + # `loss` not provided nor overridden from Policy -> Set to None. + else: + self._loss = None + + self.batch_divisibility_req = ( + get_batch_divisibility_req(self) + if callable(get_batch_divisibility_req) + else (get_batch_divisibility_req or 1) + ) + self._max_seq_len = config["model"]["max_seq_len"] + + if validate_spaces: + validate_spaces(self, observation_space, action_space, config) + + if before_init: + before_init(self, observation_space, action_space, config) + + self.config = config + self.dist_class = None + if action_sampler_fn or action_distribution_fn: + if not make_model: + raise ValueError( + "`make_model` is required if `action_sampler_fn` OR " + "`action_distribution_fn` is given" + ) + else: + self.dist_class, logit_dim = ModelCatalog.get_action_dist( + action_space, self.config["model"] + ) + + if make_model: + self.model = make_model(self, observation_space, action_space, config) + else: + self.model = ModelCatalog.get_model_v2( + observation_space, + action_space, + logit_dim, + config["model"], + framework=self.framework, + ) + # Lock used for locking some methods on the object-level. + # This prevents possible race conditions when calling the model + # first, then its value function (e.g. in a loss function), in + # between of which another model call is made (e.g. to compute an + # action). + self._lock = threading.RLock() + + # Auto-update model's inference view requirements, if recurrent. + self._update_model_view_requirements_from_init_state() + # Combine view_requirements for Model and Policy. + self.view_requirements.update(self.model.view_requirements) + + self.exploration = self._create_exploration() + self._state_inputs = self.model.get_initial_state() + self._is_recurrent = len(self._state_inputs) > 0 + + if before_loss_init: + before_loss_init(self, observation_space, action_space, config) + + if optimizer_fn: + optimizers = optimizer_fn(self, config) + else: + optimizers = tf.keras.optimizers.Adam(config["lr"]) + optimizers = force_list(optimizers) + if self.exploration: + optimizers = self.exploration.get_exploration_optimizer(optimizers) + + # The list of local (tf) optimizers (one per loss term). + self._optimizers: List[LocalOptimizer] = optimizers + # Backward compatibility: A user's policy may only support a single + # loss term and optimizer (no lists). + self._optimizer: LocalOptimizer = optimizers[0] if optimizers else None + + self._initialize_loss_from_dummy_batch( + auto_remove_unneeded_view_reqs=True, + stats_fn=stats_fn, + ) + self._loss_initialized = True + + if after_init: + after_init(self, observation_space, action_space, config) + + # Got to reset global_timestep again after fake run-throughs. + self.global_timestep.assign(0) + + @override(Policy) + def compute_actions_from_input_dict( + self, + input_dict: Dict[str, TensorType], + explore: bool = None, + timestep: Optional[int] = None, + episodes=None, + **kwargs, + ) -> Tuple[TensorType, List[TensorType], Dict[str, TensorType]]: + if not self.config.get("eager_tracing") and not tf1.executing_eagerly(): + tf1.enable_eager_execution() + + self._is_training = False + + explore = explore if explore is not None else self.explore + timestep = timestep if timestep is not None else self.global_timestep + if isinstance(timestep, tf.Tensor): + timestep = int(timestep.numpy()) + + # Pass lazy (eager) tensor dict to Model as `input_dict`. + input_dict = self._lazy_tensor_dict(input_dict) + input_dict.set_training(False) + + # Pack internal state inputs into (separate) list. + state_batches = [ + input_dict[k] for k in input_dict.keys() if "state_in" in k[:8] + ] + self._state_in = state_batches + self._is_recurrent = state_batches != [] + + # Call the exploration before_compute_actions hook. + self.exploration.before_compute_actions( + timestep=timestep, explore=explore, tf_sess=self.get_session() + ) + + ret = self._compute_actions_helper( + input_dict, + state_batches, + # TODO: Passing episodes into a traced method does not work. + None if self.config["eager_tracing"] else episodes, + explore, + timestep, + ) + # Update our global timestep by the batch size. + self.global_timestep.assign_add(tree.flatten(ret[0])[0].shape.as_list()[0]) + return convert_to_numpy(ret) + + @override(Policy) + def compute_actions( + self, + obs_batch: Union[List[TensorStructType], TensorStructType], + state_batches: Optional[List[TensorType]] = None, + prev_action_batch: Union[List[TensorStructType], TensorStructType] = None, + prev_reward_batch: Union[List[TensorStructType], TensorStructType] = None, + info_batch: Optional[Dict[str, list]] = None, + episodes: Optional[List] = None, + explore: Optional[bool] = None, + timestep: Optional[int] = None, + **kwargs, + ) -> Tuple[TensorType, List[TensorType], Dict[str, TensorType]]: + # Create input dict to simply pass the entire call to + # self.compute_actions_from_input_dict(). + input_dict = SampleBatch( + { + SampleBatch.CUR_OBS: obs_batch, + }, + _is_training=tf.constant(False), + ) + if state_batches is not None: + for i, s in enumerate(state_batches): + input_dict[f"state_in_{i}"] = s + if prev_action_batch is not None: + input_dict[SampleBatch.PREV_ACTIONS] = prev_action_batch + if prev_reward_batch is not None: + input_dict[SampleBatch.PREV_REWARDS] = prev_reward_batch + if info_batch is not None: + input_dict[SampleBatch.INFOS] = info_batch + + return self.compute_actions_from_input_dict( + input_dict=input_dict, + explore=explore, + timestep=timestep, + episodes=episodes, + **kwargs, + ) + + @with_lock + @override(Policy) + def compute_log_likelihoods( + self, + actions, + obs_batch, + state_batches=None, + prev_action_batch=None, + prev_reward_batch=None, + actions_normalized=True, + **kwargs, + ): + if action_sampler_fn and action_distribution_fn is None: + raise ValueError( + "Cannot compute log-prob/likelihood w/o an " + "`action_distribution_fn` and a provided " + "`action_sampler_fn`!" + ) + + seq_lens = tf.ones(len(obs_batch), dtype=tf.int32) + input_batch = SampleBatch( + {SampleBatch.CUR_OBS: tf.convert_to_tensor(obs_batch)}, + _is_training=False, + ) + if prev_action_batch is not None: + input_batch[SampleBatch.PREV_ACTIONS] = tf.convert_to_tensor( + prev_action_batch + ) + if prev_reward_batch is not None: + input_batch[SampleBatch.PREV_REWARDS] = tf.convert_to_tensor( + prev_reward_batch + ) + + if self.exploration: + # Exploration hook before each forward pass. + self.exploration.before_compute_actions(explore=False) + + # Action dist class and inputs are generated via custom function. + if action_distribution_fn: + dist_inputs, dist_class, _ = action_distribution_fn( + self, self.model, input_batch, explore=False, is_training=False + ) + # Default log-likelihood calculation. + else: + dist_inputs, _ = self.model(input_batch, state_batches, seq_lens) + dist_class = self.dist_class + + action_dist = dist_class(dist_inputs, self.model) + + # Normalize actions if necessary. + if not actions_normalized and self.config["normalize_actions"]: + actions = normalize_action(actions, self.action_space_struct) + + log_likelihoods = action_dist.logp(actions) + + return log_likelihoods + + @override(Policy) + def postprocess_trajectory( + self, sample_batch, other_agent_batches=None, episode=None + ): + assert tf.executing_eagerly() + # Call super's postprocess_trajectory first. + sample_batch = EagerTFPolicy.postprocess_trajectory(self, sample_batch) + if postprocess_fn: + return postprocess_fn(self, sample_batch, other_agent_batches, episode) + return sample_batch + + @with_lock + @override(Policy) + def learn_on_batch(self, postprocessed_batch): + # Callback handling. + learn_stats = {} + self.callbacks.on_learn_on_batch( + policy=self, train_batch=postprocessed_batch, result=learn_stats + ) + + pad_batch_to_sequences_of_same_size( + postprocessed_batch, + max_seq_len=self._max_seq_len, + shuffle=False, + batch_divisibility_req=self.batch_divisibility_req, + view_requirements=self.view_requirements, + ) + + self._is_training = True + postprocessed_batch = self._lazy_tensor_dict(postprocessed_batch) + postprocessed_batch.set_training(True) + stats = self._learn_on_batch_helper(postprocessed_batch) + self.num_grad_updates += 1 + + stats.update( + { + "custom_metrics": learn_stats, + NUM_AGENT_STEPS_TRAINED: postprocessed_batch.count, + NUM_GRAD_UPDATES_LIFETIME: self.num_grad_updates, + # -1, b/c we have to measure this diff before we do the update + # above. + DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY: ( + self.num_grad_updates + - 1 + - (postprocessed_batch.num_grad_updates or 0) + ), + } + ) + return convert_to_numpy(stats) + + @override(Policy) + def compute_gradients( + self, postprocessed_batch: SampleBatch + ) -> Tuple[ModelGradients, Dict[str, TensorType]]: + pad_batch_to_sequences_of_same_size( + postprocessed_batch, + shuffle=False, + max_seq_len=self._max_seq_len, + batch_divisibility_req=self.batch_divisibility_req, + view_requirements=self.view_requirements, + ) + + self._is_training = True + self._lazy_tensor_dict(postprocessed_batch) + postprocessed_batch.set_training(True) + grads_and_vars, grads, stats = self._compute_gradients_helper( + postprocessed_batch + ) + return convert_to_numpy((grads, stats)) + + @override(Policy) + def apply_gradients(self, gradients: ModelGradients) -> None: + self._apply_gradients_helper( + list( + zip( + [ + (tf.convert_to_tensor(g) if g is not None else None) + for g in gradients + ], + self.model.trainable_variables(), + ) + ) + ) + + @override(Policy) + def get_weights(self, as_dict=False): + variables = self.variables() + if as_dict: + return {v.name: v.numpy() for v in variables} + return [v.numpy() for v in variables] + + @override(Policy) + def set_weights(self, weights): + variables = self.variables() + assert len(weights) == len(variables), (len(weights), len(variables)) + for v, w in zip(variables, weights): + v.assign(w) + + @override(Policy) + def get_exploration_state(self): + return convert_to_numpy(self.exploration.get_state()) + + @override(Policy) + def is_recurrent(self): + return self._is_recurrent + + @override(Policy) + def num_state_tensors(self): + return len(self._state_inputs) + + @override(Policy) + def get_initial_state(self): + if hasattr(self, "model"): + return self.model.get_initial_state() + return [] + + @override(Policy) + def get_state(self) -> PolicyState: + # Legacy Policy state (w/o keras model and w/o PolicySpec). + state = super().get_state() + + state["global_timestep"] = state["global_timestep"].numpy() + if self._optimizer and len(self._optimizer.variables()) > 0: + state["_optimizer_variables"] = self._optimizer.variables() + # Add exploration state. + if self.exploration: + # This is not compatible with RLModules, which have a method + # `forward_exploration` to specify custom exploration behavior. + state["_exploration_state"] = self.exploration.get_state() + return state + + @override(Policy) + def set_state(self, state: PolicyState) -> None: + # Set optimizer vars first. + optimizer_vars = state.get("_optimizer_variables", None) + if optimizer_vars and self._optimizer.variables(): + if not type(self).__name__.endswith("_traced") and log_once( + "set_state_optimizer_vars_tf_eager_policy_v2" + ): + logger.warning( + "Cannot restore an optimizer's state for tf eager! Keras " + "is not able to save the v1.x optimizers (from " + "tf.compat.v1.train) since they aren't compatible with " + "checkpoints." + ) + for opt_var, value in zip(self._optimizer.variables(), optimizer_vars): + opt_var.assign(value) + # Set exploration's state. + if hasattr(self, "exploration") and "_exploration_state" in state: + self.exploration.set_state(state=state["_exploration_state"]) + + # Restore glbal timestep (tf vars). + self.global_timestep.assign(state["global_timestep"]) + + # Then the Policy's (NN) weights and connectors. + super().set_state(state) + + @override(Policy) + def export_model(self, export_dir, onnx: Optional[int] = None) -> None: + """Exports the Policy's Model to local directory for serving. + + Note: Since the TfModelV2 class that EagerTfPolicy uses is-NOT-a + tf.keras.Model, we need to assume that there is a `base_model` property + within this TfModelV2 class that is-a tf.keras.Model. This base model + will be used here for the export. + TODO (kourosh): This restriction will be resolved once we move Policy and + ModelV2 to the new Learner/RLModule APIs. + + Args: + export_dir: Local writable directory. + onnx: If given, will export model in ONNX format. The + value of this parameter set the ONNX OpSet version to use. + """ + if ( + hasattr(self, "model") + and hasattr(self.model, "base_model") + and isinstance(self.model.base_model, tf.keras.Model) + ): + # Store model in ONNX format. + if onnx: + try: + import tf2onnx + except ImportError as e: + raise RuntimeError( + "Converting a TensorFlow model to ONNX requires " + "`tf2onnx` to be installed. Install with " + "`pip install tf2onnx`." + ) from e + + model_proto, external_tensor_storage = tf2onnx.convert.from_keras( + self.model.base_model, + output_path=os.path.join(export_dir, "model.onnx"), + ) + # Save the tf.keras.Model (architecture and weights, so it can be + # retrieved w/o access to the original (custom) Model or Policy code). + else: + try: + self.model.base_model.save(export_dir, save_format="tf") + except Exception: + logger.warning(ERR_MSG_TF_POLICY_CANNOT_SAVE_KERAS_MODEL) + else: + logger.warning(ERR_MSG_TF_POLICY_CANNOT_SAVE_KERAS_MODEL) + + def variables(self): + """Return the list of all savable variables for this policy.""" + if isinstance(self.model, tf.keras.Model): + return self.model.variables + else: + return self.model.variables() + + def loss_initialized(self): + return self._loss_initialized + + @with_lock + def _compute_actions_helper( + self, input_dict, state_batches, episodes, explore, timestep + ): + # Increase the tracing counter to make sure we don't re-trace too + # often. If eager_tracing=True, this counter should only get + # incremented during the @tf.function trace operations, never when + # calling the already traced function after that. + self._re_trace_counter += 1 + + # Calculate RNN sequence lengths. + batch_size = tree.flatten(input_dict[SampleBatch.OBS])[0].shape[0] + seq_lens = tf.ones(batch_size, dtype=tf.int32) if state_batches else None + + # Add default and custom fetches. + extra_fetches = {} + + # Use Exploration object. + with tf.variable_creator_scope(_disallow_var_creation): + if action_sampler_fn: + action_sampler_outputs = action_sampler_fn( + self, + self.model, + input_dict[SampleBatch.CUR_OBS], + explore=explore, + timestep=timestep, + episodes=episodes, + ) + if len(action_sampler_outputs) == 4: + actions, logp, dist_inputs, state_out = action_sampler_outputs + else: + dist_inputs = None + state_out = [] + actions, logp = action_sampler_outputs + else: + if action_distribution_fn: + # Try new action_distribution_fn signature, supporting + # state_batches and seq_lens. + try: + ( + dist_inputs, + self.dist_class, + state_out, + ) = action_distribution_fn( + self, + self.model, + input_dict=input_dict, + state_batches=state_batches, + seq_lens=seq_lens, + explore=explore, + timestep=timestep, + is_training=False, + ) + # Trying the old way (to stay backward compatible). + # TODO: Remove in future. + except TypeError as e: + if ( + "positional argument" in e.args[0] + or "unexpected keyword argument" in e.args[0] + ): + ( + dist_inputs, + self.dist_class, + state_out, + ) = action_distribution_fn( + self, + self.model, + input_dict[SampleBatch.OBS], + explore=explore, + timestep=timestep, + is_training=False, + ) + else: + raise e + elif isinstance(self.model, tf.keras.Model): + input_dict = SampleBatch(input_dict, seq_lens=seq_lens) + if state_batches and "state_in_0" not in input_dict: + for i, s in enumerate(state_batches): + input_dict[f"state_in_{i}"] = s + self._lazy_tensor_dict(input_dict) + dist_inputs, state_out, extra_fetches = self.model(input_dict) + else: + dist_inputs, state_out = self.model( + input_dict, state_batches, seq_lens + ) + + action_dist = self.dist_class(dist_inputs, self.model) + + # Get the exploration action from the forward results. + actions, logp = self.exploration.get_exploration_action( + action_distribution=action_dist, + timestep=timestep, + explore=explore, + ) + + # Action-logp and action-prob. + if logp is not None: + extra_fetches[SampleBatch.ACTION_PROB] = tf.exp(logp) + extra_fetches[SampleBatch.ACTION_LOGP] = logp + # Action-dist inputs. + if dist_inputs is not None: + extra_fetches[SampleBatch.ACTION_DIST_INPUTS] = dist_inputs + # Custom extra fetches. + if extra_action_out_fn: + extra_fetches.update(extra_action_out_fn(self)) + + return actions, state_out, extra_fetches + + # TODO: Figure out, why _ray_trace_ctx=None helps to prevent a crash in + # AlphaStar w/ framework=tf2; eager_tracing=True on the policy learner actors. + # It seems there may be a clash between the traced-by-tf function and the + # traced-by-ray functions (for making the policy class a ray actor). + def _learn_on_batch_helper(self, samples, _ray_trace_ctx=None): + # Increase the tracing counter to make sure we don't re-trace too + # often. If eager_tracing=True, this counter should only get + # incremented during the @tf.function trace operations, never when + # calling the already traced function after that. + self._re_trace_counter += 1 + + with tf.variable_creator_scope(_disallow_var_creation): + grads_and_vars, _, stats = self._compute_gradients_helper(samples) + self._apply_gradients_helper(grads_and_vars) + return stats + + def _get_is_training_placeholder(self): + return tf.convert_to_tensor(self._is_training) + + @with_lock + def _compute_gradients_helper(self, samples): + """Computes and returns grads as eager tensors.""" + + # Increase the tracing counter to make sure we don't re-trace too + # often. If eager_tracing=True, this counter should only get + # incremented during the @tf.function trace operations, never when + # calling the already traced function after that. + self._re_trace_counter += 1 + + # Gather all variables for which to calculate losses. + if isinstance(self.model, tf.keras.Model): + variables = self.model.trainable_variables + else: + variables = self.model.trainable_variables() + + # Calculate the loss(es) inside a tf GradientTape. + with tf.GradientTape(persistent=compute_gradients_fn is not None) as tape: + losses = self._loss(self, self.model, self.dist_class, samples) + losses = force_list(losses) + + # User provided a compute_gradients_fn. + if compute_gradients_fn: + # Wrap our tape inside a wrapper, such that the resulting + # object looks like a "classic" tf.optimizer. This way, custom + # compute_gradients_fn will work on both tf static graph + # and tf-eager. + optimizer = _OptimizerWrapper(tape) + # More than one loss terms/optimizers. + if self.config["_tf_policy_handles_more_than_one_loss"]: + grads_and_vars = compute_gradients_fn( + self, [optimizer] * len(losses), losses + ) + # Only one loss and one optimizer. + else: + grads_and_vars = [compute_gradients_fn(self, optimizer, losses[0])] + # Default: Compute gradients using the above tape. + else: + grads_and_vars = [ + list(zip(tape.gradient(loss, variables), variables)) + for loss in losses + ] + + if log_once("grad_vars"): + for g_and_v in grads_and_vars: + for g, v in g_and_v: + if g is not None: + logger.info(f"Optimizing variable {v.name}") + + # `grads_and_vars` is returned a list (len=num optimizers/losses) + # of lists of (grad, var) tuples. + if self.config["_tf_policy_handles_more_than_one_loss"]: + grads = [[g for g, _ in g_and_v] for g_and_v in grads_and_vars] + # `grads_and_vars` is returned as a list of (grad, var) tuples. + else: + grads_and_vars = grads_and_vars[0] + grads = [g for g, _ in grads_and_vars] + + stats = self._stats(self, samples, grads) + return grads_and_vars, grads, stats + + def _apply_gradients_helper(self, grads_and_vars): + # Increase the tracing counter to make sure we don't re-trace too + # often. If eager_tracing=True, this counter should only get + # incremented during the @tf.function trace operations, never when + # calling the already traced function after that. + self._re_trace_counter += 1 + + if apply_gradients_fn: + if self.config["_tf_policy_handles_more_than_one_loss"]: + apply_gradients_fn(self, self._optimizers, grads_and_vars) + else: + apply_gradients_fn(self, self._optimizer, grads_and_vars) + else: + if self.config["_tf_policy_handles_more_than_one_loss"]: + for i, o in enumerate(self._optimizers): + o.apply_gradients( + [(g, v) for g, v in grads_and_vars[i] if g is not None] + ) + else: + self._optimizer.apply_gradients( + [(g, v) for g, v in grads_and_vars if g is not None] + ) + + def _stats(self, outputs, samples, grads): + fetches = {} + if stats_fn: + fetches[LEARNER_STATS_KEY] = dict(stats_fn(outputs, samples)) + else: + fetches[LEARNER_STATS_KEY] = {} + + if extra_learn_fetches_fn: + fetches.update(dict(extra_learn_fetches_fn(self))) + if grad_stats_fn: + fetches.update(dict(grad_stats_fn(self, samples, grads))) + return fetches + + def _lazy_tensor_dict(self, postprocessed_batch: SampleBatch): + # TODO: (sven): Keep for a while to ensure backward compatibility. + if not isinstance(postprocessed_batch, SampleBatch): + postprocessed_batch = SampleBatch(postprocessed_batch) + postprocessed_batch.set_get_interceptor(_convert_to_tf) + return postprocessed_batch + + @classmethod + def with_tracing(cls): + return _traced_eager_policy(cls) + + eager_policy_cls.__name__ = name + "_eager" + eager_policy_cls.__qualname__ = name + "_eager" + return eager_policy_cls diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/eager_tf_policy_v2.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/eager_tf_policy_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..a1323794de908460c8ed6c2c9731518abefd0497 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/eager_tf_policy_v2.py @@ -0,0 +1,968 @@ +"""Eager mode TF policy built using build_tf_policy(). + +It supports both traced and non-traced eager execution modes. +""" + +import logging +import os +import threading +from typing import Dict, List, Optional, Tuple, Type, Union + +import gymnasium as gym +import tree # pip install dm_tree + +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.models.catalog import ModelCatalog +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.tf.tf_action_dist import TFActionDistribution +from ray.rllib.policy.eager_tf_policy import ( + _convert_to_tf, + _disallow_var_creation, + _OptimizerWrapper, + _traced_eager_policy, +) +from ray.rllib.policy.policy import Policy, PolicyState +from ray.rllib.policy.rnn_sequencing import pad_batch_to_sequences_of_same_size +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils import force_list +from ray.rllib.utils.annotations import ( + is_overridden, + OldAPIStack, + OverrideToImplementCustomLogic, + OverrideToImplementCustomLogic_CallToSuperRecommended, + override, +) +from ray.rllib.utils.error import ERR_MSG_TF_POLICY_CANNOT_SAVE_KERAS_MODEL +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.metrics import ( + DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY, + NUM_AGENT_STEPS_TRAINED, + NUM_GRAD_UPDATES_LIFETIME, +) +from ray.rllib.utils.metrics.learner_info import LEARNER_STATS_KEY +from ray.rllib.utils.spaces.space_utils import normalize_action +from ray.rllib.utils.tf_utils import get_gpu_devices +from ray.rllib.utils.threading import with_lock +from ray.rllib.utils.typing import ( + AlgorithmConfigDict, + LocalOptimizer, + ModelGradients, + TensorType, +) +from ray.util.debug import log_once + +tf1, tf, tfv = try_import_tf() +logger = logging.getLogger(__name__) + + +@OldAPIStack +class EagerTFPolicyV2(Policy): + """A TF-eager / TF2 based tensorflow policy. + + This class is intended to be used and extended by sub-classing. + """ + + def __init__( + self, + observation_space: gym.spaces.Space, + action_space: gym.spaces.Space, + config: AlgorithmConfigDict, + **kwargs, + ): + self.framework = config.get("framework", "tf2") + + # Log device. + logger.info( + "Creating TF-eager policy running on {}.".format( + "GPU" if get_gpu_devices() else "CPU" + ) + ) + + Policy.__init__(self, observation_space, action_space, config) + + self._is_training = False + # Global timestep should be a tensor. + self.global_timestep = tf.Variable(0, trainable=False, dtype=tf.int64) + self.explore = tf.Variable( + self.config["explore"], trainable=False, dtype=tf.bool + ) + + # Log device and worker index. + num_gpus = self._get_num_gpus_for_policy() + if num_gpus > 0: + gpu_ids = get_gpu_devices() + logger.info(f"Found {len(gpu_ids)} visible cuda devices.") + + self._is_training = False + + self._loss_initialized = False + # Backward compatibility workaround so Policy will call self.loss() directly. + # TODO(jungong): clean up after all policies are migrated to new sub-class + # implementation. + self._loss = None + + self.batch_divisibility_req = self.get_batch_divisibility_req() + self._max_seq_len = self.config["model"]["max_seq_len"] + + self.validate_spaces(observation_space, action_space, self.config) + + # If using default make_model(), dist_class will get updated when + # the model is created next. + self.dist_class = self._init_dist_class() + self.model = self.make_model() + + self._init_view_requirements() + + self.exploration = self._create_exploration() + self._state_inputs = self.model.get_initial_state() + self._is_recurrent = len(self._state_inputs) > 0 + + # Got to reset global_timestep again after fake run-throughs. + self.global_timestep.assign(0) + + # Lock used for locking some methods on the object-level. + # This prevents possible race conditions when calling the model + # first, then its value function (e.g. in a loss function), in + # between of which another model call is made (e.g. to compute an + # action). + self._lock = threading.RLock() + + # Only for `config.eager_tracing=True`: A counter to keep track of + # how many times an eager-traced method (e.g. + # `self._compute_actions_helper`) has been re-traced by tensorflow. + # We will raise an error if more than n re-tracings have been + # detected, since this would considerably slow down execution. + # The variable below should only get incremented during the + # tf.function trace operations, never when calling the already + # traced function after that. + self._re_trace_counter = 0 + + @staticmethod + def enable_eager_execution_if_necessary(): + # If this class runs as a @ray.remote actor, eager mode may not + # have been activated yet. + if tf1 and not tf1.executing_eagerly(): + tf1.enable_eager_execution() + + @OverrideToImplementCustomLogic + def validate_spaces( + self, + obs_space: gym.spaces.Space, + action_space: gym.spaces.Space, + config: AlgorithmConfigDict, + ): + return {} + + @OverrideToImplementCustomLogic + @override(Policy) + def loss( + self, + model: Union[ModelV2, "tf.keras.Model"], + dist_class: Type[TFActionDistribution], + train_batch: SampleBatch, + ) -> Union[TensorType, List[TensorType]]: + """Compute loss for this policy using model, dist_class and a train_batch. + + Args: + model: The Model to calculate the loss for. + dist_class: The action distr. class. + train_batch: The training data. + + Returns: + A single loss tensor or a list of loss tensors. + """ + raise NotImplementedError + + @OverrideToImplementCustomLogic + def stats_fn(self, train_batch: SampleBatch) -> Dict[str, TensorType]: + """Stats function. Returns a dict of statistics. + + Args: + train_batch: The SampleBatch (already) used for training. + + Returns: + The stats dict. + """ + return {} + + @OverrideToImplementCustomLogic + def grad_stats_fn( + self, train_batch: SampleBatch, grads: ModelGradients + ) -> Dict[str, TensorType]: + """Gradient stats function. Returns a dict of statistics. + + Args: + train_batch: The SampleBatch (already) used for training. + + Returns: + The stats dict. + """ + return {} + + @OverrideToImplementCustomLogic + def make_model(self) -> ModelV2: + """Build underlying model for this Policy. + + Returns: + The Model for the Policy to use. + """ + # Default ModelV2 model. + _, logit_dim = ModelCatalog.get_action_dist( + self.action_space, self.config["model"] + ) + return ModelCatalog.get_model_v2( + self.observation_space, + self.action_space, + logit_dim, + self.config["model"], + framework=self.framework, + ) + + @OverrideToImplementCustomLogic + def compute_gradients_fn( + self, policy: Policy, optimizer: LocalOptimizer, loss: TensorType + ) -> ModelGradients: + """Gradients computing function (from loss tensor, using local optimizer). + + Args: + policy: The Policy object that generated the loss tensor and + that holds the given local optimizer. + optimizer: The tf (local) optimizer object to + calculate the gradients with. + loss: The loss tensor for which gradients should be + calculated. + + Returns: + ModelGradients: List of the possibly clipped gradients- and variable + tuples. + """ + return None + + @OverrideToImplementCustomLogic + def apply_gradients_fn( + self, + optimizer: "tf.keras.optimizers.Optimizer", + grads: ModelGradients, + ) -> "tf.Operation": + """Gradients computing function (from loss tensor, using local optimizer). + + Args: + optimizer: The tf (local) optimizer object to + calculate the gradients with. + grads: The gradient tensor to be applied. + + Returns: + "tf.Operation": TF operation that applies supplied gradients. + """ + return None + + @OverrideToImplementCustomLogic + def action_sampler_fn( + self, + model: ModelV2, + *, + obs_batch: TensorType, + state_batches: TensorType, + **kwargs, + ) -> Tuple[TensorType, TensorType, TensorType, List[TensorType]]: + """Custom function for sampling new actions given policy. + + Args: + model: Underlying model. + obs_batch: Observation tensor batch. + state_batches: Action sampling state batch. + + Returns: + Sampled action + Log-likelihood + Action distribution inputs + Updated state + """ + return None, None, None, None + + @OverrideToImplementCustomLogic + def action_distribution_fn( + self, + model: ModelV2, + *, + obs_batch: TensorType, + state_batches: TensorType, + **kwargs, + ) -> Tuple[TensorType, type, List[TensorType]]: + """Action distribution function for this Policy. + + Args: + model: Underlying model. + obs_batch: Observation tensor batch. + state_batches: Action sampling state batch. + + Returns: + Distribution input. + ActionDistribution class. + State outs. + """ + return None, None, None + + @OverrideToImplementCustomLogic + def get_batch_divisibility_req(self) -> int: + """Get batch divisibility request. + + Returns: + Size N. A sample batch must be of size K*N. + """ + # By default, any sized batch is ok, so simply return 1. + return 1 + + @OverrideToImplementCustomLogic_CallToSuperRecommended + def extra_action_out_fn(self) -> Dict[str, TensorType]: + """Extra values to fetch and return from compute_actions(). + + Returns: + Dict[str, TensorType]: An extra fetch-dict to be passed to and + returned from the compute_actions() call. + """ + return {} + + @OverrideToImplementCustomLogic_CallToSuperRecommended + def extra_learn_fetches_fn(self) -> Dict[str, TensorType]: + """Extra stats to be reported after gradient computation. + + Returns: + Dict[str, TensorType]: An extra fetch-dict. + """ + return {} + + @override(Policy) + @OverrideToImplementCustomLogic_CallToSuperRecommended + def postprocess_trajectory( + self, + sample_batch: SampleBatch, + other_agent_batches: Optional[SampleBatch] = None, + episode=None, + ): + """Post process trajectory in the format of a SampleBatch. + + Args: + sample_batch: sample_batch: batch of experiences for the policy, + which will contain at most one episode trajectory. + other_agent_batches: In a multi-agent env, this contains a + mapping of agent ids to (policy, agent_batch) tuples + containing the policy and experiences of the other agents. + episode: An optional multi-agent episode object to provide + access to all of the internal episode state, which may + be useful for model-based or multi-agent algorithms. + + Returns: + The postprocessed sample batch. + """ + assert tf.executing_eagerly() + return Policy.postprocess_trajectory(self, sample_batch) + + @OverrideToImplementCustomLogic + def optimizer( + self, + ) -> Union["tf.keras.optimizers.Optimizer", List["tf.keras.optimizers.Optimizer"]]: + """TF optimizer to use for policy optimization. + + Returns: + A local optimizer or a list of local optimizers to use for this + Policy's Model. + """ + return tf.keras.optimizers.Adam(self.config["lr"]) + + def _init_dist_class(self): + if is_overridden(self.action_sampler_fn) or is_overridden( + self.action_distribution_fn + ): + if not is_overridden(self.make_model): + raise ValueError( + "`make_model` is required if `action_sampler_fn` OR " + "`action_distribution_fn` is given" + ) + return None + else: + dist_class, _ = ModelCatalog.get_action_dist( + self.action_space, self.config["model"] + ) + return dist_class + + def _init_view_requirements(self): + # Auto-update model's inference view requirements, if recurrent. + self._update_model_view_requirements_from_init_state() + # Combine view_requirements for Model and Policy. + self.view_requirements.update(self.model.view_requirements) + + # Disable env-info placeholder. + if SampleBatch.INFOS in self.view_requirements: + self.view_requirements[SampleBatch.INFOS].used_for_training = False + + def maybe_initialize_optimizer_and_loss(self): + optimizers = force_list(self.optimizer()) + if self.exploration: + # Policies with RLModules don't have an exploration object. + optimizers = self.exploration.get_exploration_optimizer(optimizers) + + # The list of local (tf) optimizers (one per loss term). + self._optimizers: List[LocalOptimizer] = optimizers + # Backward compatibility: A user's policy may only support a single + # loss term and optimizer (no lists). + self._optimizer: LocalOptimizer = optimizers[0] if optimizers else None + + self._initialize_loss_from_dummy_batch( + auto_remove_unneeded_view_reqs=True, + ) + self._loss_initialized = True + + @override(Policy) + def compute_actions_from_input_dict( + self, + input_dict: Dict[str, TensorType], + explore: bool = None, + timestep: Optional[int] = None, + episodes=None, + **kwargs, + ) -> Tuple[TensorType, List[TensorType], Dict[str, TensorType]]: + self._is_training = False + + explore = explore if explore is not None else self.explore + timestep = timestep if timestep is not None else self.global_timestep + if isinstance(timestep, tf.Tensor): + timestep = int(timestep.numpy()) + + # Pass lazy (eager) tensor dict to Model as `input_dict`. + input_dict = self._lazy_tensor_dict(input_dict) + input_dict.set_training(False) + + # Pack internal state inputs into (separate) list. + state_batches = [ + input_dict[k] for k in input_dict.keys() if "state_in" in k[:8] + ] + self._state_in = state_batches + self._is_recurrent = len(tree.flatten(self._state_in)) > 0 + + # Call the exploration before_compute_actions hook. + if self.exploration: + # Policies with RLModules don't have an exploration object. + self.exploration.before_compute_actions( + timestep=timestep, explore=explore, tf_sess=self.get_session() + ) + + ret = self._compute_actions_helper( + input_dict, + state_batches, + # TODO: Passing episodes into a traced method does not work. + None if self.config["eager_tracing"] else episodes, + explore, + timestep, + ) + # Update our global timestep by the batch size. + self.global_timestep.assign_add(tree.flatten(ret[0])[0].shape.as_list()[0]) + return convert_to_numpy(ret) + + # TODO(jungong) : deprecate this API and make compute_actions_from_input_dict the + # only canonical entry point for inference. + @override(Policy) + def compute_actions( + self, + obs_batch, + state_batches=None, + prev_action_batch=None, + prev_reward_batch=None, + info_batch=None, + episodes=None, + explore=None, + timestep=None, + **kwargs, + ): + # Create input dict to simply pass the entire call to + # self.compute_actions_from_input_dict(). + input_dict = SampleBatch( + { + SampleBatch.CUR_OBS: obs_batch, + }, + _is_training=tf.constant(False), + ) + if state_batches is not None: + for s in enumerate(state_batches): + input_dict["state_in_{i}"] = s + if prev_action_batch is not None: + input_dict[SampleBatch.PREV_ACTIONS] = prev_action_batch + if prev_reward_batch is not None: + input_dict[SampleBatch.PREV_REWARDS] = prev_reward_batch + if info_batch is not None: + input_dict[SampleBatch.INFOS] = info_batch + + return self.compute_actions_from_input_dict( + input_dict=input_dict, + explore=explore, + timestep=timestep, + episodes=episodes, + **kwargs, + ) + + @with_lock + @override(Policy) + def compute_log_likelihoods( + self, + actions: Union[List[TensorType], TensorType], + obs_batch: Union[List[TensorType], TensorType], + state_batches: Optional[List[TensorType]] = None, + prev_action_batch: Optional[Union[List[TensorType], TensorType]] = None, + prev_reward_batch: Optional[Union[List[TensorType], TensorType]] = None, + actions_normalized: bool = True, + in_training: bool = True, + ) -> TensorType: + if is_overridden(self.action_sampler_fn) and not is_overridden( + self.action_distribution_fn + ): + raise ValueError( + "Cannot compute log-prob/likelihood w/o an " + "`action_distribution_fn` and a provided " + "`action_sampler_fn`!" + ) + + seq_lens = tf.ones(len(obs_batch), dtype=tf.int32) + input_batch = SampleBatch( + { + SampleBatch.CUR_OBS: tf.convert_to_tensor(obs_batch), + SampleBatch.ACTIONS: actions, + }, + _is_training=False, + ) + if prev_action_batch is not None: + input_batch[SampleBatch.PREV_ACTIONS] = tf.convert_to_tensor( + prev_action_batch + ) + if prev_reward_batch is not None: + input_batch[SampleBatch.PREV_REWARDS] = tf.convert_to_tensor( + prev_reward_batch + ) + + # Exploration hook before each forward pass. + if self.exploration: + # Policies with RLModules don't have an exploration object. + self.exploration.before_compute_actions(explore=False) + + # Action dist class and inputs are generated via custom function. + if is_overridden(self.action_distribution_fn): + dist_inputs, self.dist_class, _ = self.action_distribution_fn( + self, self.model, input_batch, explore=False, is_training=False + ) + action_dist = self.dist_class(dist_inputs, self.model) + # Default log-likelihood calculation. + else: + dist_inputs, _ = self.model(input_batch, state_batches, seq_lens) + action_dist = self.dist_class(dist_inputs, self.model) + + # Normalize actions if necessary. + if not actions_normalized and self.config["normalize_actions"]: + actions = normalize_action(actions, self.action_space_struct) + + log_likelihoods = action_dist.logp(actions) + + return log_likelihoods + + @with_lock + @override(Policy) + def learn_on_batch(self, postprocessed_batch): + # Callback handling. + learn_stats = {} + self.callbacks.on_learn_on_batch( + policy=self, train_batch=postprocessed_batch, result=learn_stats + ) + + pad_batch_to_sequences_of_same_size( + postprocessed_batch, + max_seq_len=self._max_seq_len, + shuffle=False, + batch_divisibility_req=self.batch_divisibility_req, + view_requirements=self.view_requirements, + ) + + self._is_training = True + postprocessed_batch = self._lazy_tensor_dict(postprocessed_batch) + postprocessed_batch.set_training(True) + stats = self._learn_on_batch_helper(postprocessed_batch) + self.num_grad_updates += 1 + + stats.update( + { + "custom_metrics": learn_stats, + NUM_AGENT_STEPS_TRAINED: postprocessed_batch.count, + NUM_GRAD_UPDATES_LIFETIME: self.num_grad_updates, + # -1, b/c we have to measure this diff before we do the update above. + DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY: ( + self.num_grad_updates + - 1 + - (postprocessed_batch.num_grad_updates or 0) + ), + } + ) + + return convert_to_numpy(stats) + + @override(Policy) + def compute_gradients( + self, postprocessed_batch: SampleBatch + ) -> Tuple[ModelGradients, Dict[str, TensorType]]: + + pad_batch_to_sequences_of_same_size( + postprocessed_batch, + shuffle=False, + max_seq_len=self._max_seq_len, + batch_divisibility_req=self.batch_divisibility_req, + view_requirements=self.view_requirements, + ) + + self._is_training = True + self._lazy_tensor_dict(postprocessed_batch) + postprocessed_batch.set_training(True) + grads_and_vars, grads, stats = self._compute_gradients_helper( + postprocessed_batch + ) + return convert_to_numpy((grads, stats)) + + @override(Policy) + def apply_gradients(self, gradients: ModelGradients) -> None: + self._apply_gradients_helper( + list( + zip( + [ + (tf.convert_to_tensor(g) if g is not None else None) + for g in gradients + ], + self.model.trainable_variables(), + ) + ) + ) + + @override(Policy) + def get_weights(self, as_dict=False): + variables = self.variables() + if as_dict: + return {v.name: v.numpy() for v in variables} + return [v.numpy() for v in variables] + + @override(Policy) + def set_weights(self, weights): + variables = self.variables() + assert len(weights) == len(variables), (len(weights), len(variables)) + for v, w in zip(variables, weights): + v.assign(w) + + @override(Policy) + def get_exploration_state(self): + return convert_to_numpy(self.exploration.get_state()) + + @override(Policy) + def is_recurrent(self): + return self._is_recurrent + + @override(Policy) + def num_state_tensors(self): + return len(self._state_inputs) + + @override(Policy) + def get_initial_state(self): + if hasattr(self, "model"): + return self.model.get_initial_state() + return [] + + @override(Policy) + @OverrideToImplementCustomLogic_CallToSuperRecommended + def get_state(self) -> PolicyState: + # Legacy Policy state (w/o keras model and w/o PolicySpec). + state = super().get_state() + + state["global_timestep"] = state["global_timestep"].numpy() + # In the new Learner API stack, the optimizers live in the learner. + state["_optimizer_variables"] = [] + if self._optimizer and len(self._optimizer.variables()) > 0: + state["_optimizer_variables"] = self._optimizer.variables() + + # Add exploration state. + if self.exploration: + # This is not compatible with RLModules, which have a method + # `forward_exploration` to specify custom exploration behavior. + state["_exploration_state"] = self.exploration.get_state() + + return state + + @override(Policy) + @OverrideToImplementCustomLogic_CallToSuperRecommended + def set_state(self, state: PolicyState) -> None: + # Set optimizer vars. + optimizer_vars = state.get("_optimizer_variables", None) + if optimizer_vars and self._optimizer.variables(): + if not type(self).__name__.endswith("_traced") and log_once( + "set_state_optimizer_vars_tf_eager_policy_v2" + ): + logger.warning( + "Cannot restore an optimizer's state for tf eager! Keras " + "is not able to save the v1.x optimizers (from " + "tf.compat.v1.train) since they aren't compatible with " + "checkpoints." + ) + for opt_var, value in zip(self._optimizer.variables(), optimizer_vars): + opt_var.assign(value) + # Set exploration's state. + if hasattr(self, "exploration") and "_exploration_state" in state: + self.exploration.set_state(state=state["_exploration_state"]) + + # Restore glbal timestep (tf vars). + self.global_timestep.assign(state["global_timestep"]) + + # Then the Policy's (NN) weights and connectors. + super().set_state(state) + + @override(Policy) + def export_model(self, export_dir, onnx: Optional[int] = None) -> None: + if onnx: + try: + import tf2onnx + except ImportError as e: + raise RuntimeError( + "Converting a TensorFlow model to ONNX requires " + "`tf2onnx` to be installed. Install with " + "`pip install tf2onnx`." + ) from e + + model_proto, external_tensor_storage = tf2onnx.convert.from_keras( + self.model.base_model, + output_path=os.path.join(export_dir, "model.onnx"), + ) + # Save the tf.keras.Model (architecture and weights, so it can be retrieved + # w/o access to the original (custom) Model or Policy code). + elif ( + hasattr(self, "model") + and hasattr(self.model, "base_model") + and isinstance(self.model.base_model, tf.keras.Model) + ): + try: + self.model.base_model.save(export_dir, save_format="tf") + except Exception: + logger.warning(ERR_MSG_TF_POLICY_CANNOT_SAVE_KERAS_MODEL) + else: + logger.warning(ERR_MSG_TF_POLICY_CANNOT_SAVE_KERAS_MODEL) + + def variables(self): + """Return the list of all savable variables for this policy.""" + if isinstance(self.model, tf.keras.Model): + return self.model.variables + else: + return self.model.variables() + + def loss_initialized(self): + return self._loss_initialized + + @with_lock + def _compute_actions_helper( + self, + input_dict, + state_batches, + episodes, + explore, + timestep, + _ray_trace_ctx=None, + ): + # Increase the tracing counter to make sure we don't re-trace too + # often. If eager_tracing=True, this counter should only get + # incremented during the @tf.function trace operations, never when + # calling the already traced function after that. + self._re_trace_counter += 1 + + # Calculate RNN sequence lengths. + if SampleBatch.SEQ_LENS in input_dict: + seq_lens = input_dict[SampleBatch.SEQ_LENS] + else: + batch_size = tree.flatten(input_dict[SampleBatch.OBS])[0].shape[0] + seq_lens = tf.ones(batch_size, dtype=tf.int32) if state_batches else None + + # Add default and custom fetches. + extra_fetches = {} + + with tf.variable_creator_scope(_disallow_var_creation): + + if is_overridden(self.action_sampler_fn): + actions, logp, dist_inputs, state_out = self.action_sampler_fn( + self.model, + obs_batch=input_dict[SampleBatch.OBS], + state_batches=state_batches, + seq_lens=seq_lens, + explore=explore, + timestep=timestep, + episodes=episodes, + ) + else: + # Try `action_distribution_fn`. + if is_overridden(self.action_distribution_fn): + ( + dist_inputs, + self.dist_class, + state_out, + ) = self.action_distribution_fn( + self.model, + obs_batch=input_dict[SampleBatch.OBS], + state_batches=state_batches, + seq_lens=seq_lens, + explore=explore, + timestep=timestep, + is_training=False, + ) + elif isinstance(self.model, tf.keras.Model): + if state_batches and "state_in_0" not in input_dict: + for i, s in enumerate(state_batches): + input_dict[f"state_in_{i}"] = s + self._lazy_tensor_dict(input_dict) + dist_inputs, state_out, extra_fetches = self.model(input_dict) + else: + dist_inputs, state_out = self.model( + input_dict, state_batches, seq_lens + ) + + action_dist = self.dist_class(dist_inputs, self.model) + + # Get the exploration action from the forward results. + actions, logp = self.exploration.get_exploration_action( + action_distribution=action_dist, + timestep=timestep, + explore=explore, + ) + + # Action-logp and action-prob. + if logp is not None: + extra_fetches[SampleBatch.ACTION_PROB] = tf.exp(logp) + extra_fetches[SampleBatch.ACTION_LOGP] = logp + # Action-dist inputs. + if dist_inputs is not None: + extra_fetches[SampleBatch.ACTION_DIST_INPUTS] = dist_inputs + # Custom extra fetches. + extra_fetches.update(self.extra_action_out_fn()) + + return actions, state_out, extra_fetches + + # TODO: Figure out, why _ray_trace_ctx=None helps to prevent a crash in + # AlphaStar w/ framework=tf2; eager_tracing=True on the policy learner actors. + # It seems there may be a clash between the traced-by-tf function and the + # traced-by-ray functions (for making the policy class a ray actor). + def _learn_on_batch_helper(self, samples, _ray_trace_ctx=None): + # Increase the tracing counter to make sure we don't re-trace too + # often. If eager_tracing=True, this counter should only get + # incremented during the @tf.function trace operations, never when + # calling the already traced function after that. + self._re_trace_counter += 1 + + with tf.variable_creator_scope(_disallow_var_creation): + grads_and_vars, _, stats = self._compute_gradients_helper(samples) + self._apply_gradients_helper(grads_and_vars) + return stats + + def _get_is_training_placeholder(self): + return tf.convert_to_tensor(self._is_training) + + @with_lock + def _compute_gradients_helper(self, samples): + """Computes and returns grads as eager tensors.""" + + # Increase the tracing counter to make sure we don't re-trace too + # often. If eager_tracing=True, this counter should only get + # incremented during the @tf.function trace operations, never when + # calling the already traced function after that. + self._re_trace_counter += 1 + + # Gather all variables for which to calculate losses. + if isinstance(self.model, tf.keras.Model): + variables = self.model.trainable_variables + else: + variables = self.model.trainable_variables() + + # Calculate the loss(es) inside a tf GradientTape. + with tf.GradientTape( + persistent=is_overridden(self.compute_gradients_fn) + ) as tape: + losses = self.loss(self.model, self.dist_class, samples) + losses = force_list(losses) + + # User provided a custom compute_gradients_fn. + if is_overridden(self.compute_gradients_fn): + # Wrap our tape inside a wrapper, such that the resulting + # object looks like a "classic" tf.optimizer. This way, custom + # compute_gradients_fn will work on both tf static graph + # and tf-eager. + optimizer = _OptimizerWrapper(tape) + # More than one loss terms/optimizers. + if self.config["_tf_policy_handles_more_than_one_loss"]: + grads_and_vars = self.compute_gradients_fn( + [optimizer] * len(losses), losses + ) + # Only one loss and one optimizer. + else: + grads_and_vars = [self.compute_gradients_fn(optimizer, losses[0])] + # Default: Compute gradients using the above tape. + else: + grads_and_vars = [ + list(zip(tape.gradient(loss, variables), variables)) for loss in losses + ] + + if log_once("grad_vars"): + for g_and_v in grads_and_vars: + for g, v in g_and_v: + if g is not None: + logger.info(f"Optimizing variable {v.name}") + + # `grads_and_vars` is returned a list (len=num optimizers/losses) + # of lists of (grad, var) tuples. + if self.config["_tf_policy_handles_more_than_one_loss"]: + grads = [[g for g, _ in g_and_v] for g_and_v in grads_and_vars] + # `grads_and_vars` is returned as a list of (grad, var) tuples. + else: + grads_and_vars = grads_and_vars[0] + grads = [g for g, _ in grads_and_vars] + + stats = self._stats(samples, grads) + return grads_and_vars, grads, stats + + def _apply_gradients_helper(self, grads_and_vars): + # Increase the tracing counter to make sure we don't re-trace too + # often. If eager_tracing=True, this counter should only get + # incremented during the @tf.function trace operations, never when + # calling the already traced function after that. + self._re_trace_counter += 1 + + if is_overridden(self.apply_gradients_fn): + if self.config["_tf_policy_handles_more_than_one_loss"]: + self.apply_gradients_fn(self._optimizers, grads_and_vars) + else: + self.apply_gradients_fn(self._optimizer, grads_and_vars) + else: + if self.config["_tf_policy_handles_more_than_one_loss"]: + for i, o in enumerate(self._optimizers): + o.apply_gradients( + [(g, v) for g, v in grads_and_vars[i] if g is not None] + ) + else: + self._optimizer.apply_gradients( + [(g, v) for g, v in grads_and_vars if g is not None] + ) + + def _stats(self, samples, grads): + fetches = {} + if is_overridden(self.stats_fn): + fetches[LEARNER_STATS_KEY] = dict(self.stats_fn(samples)) + else: + fetches[LEARNER_STATS_KEY] = {} + + fetches.update(dict(self.extra_learn_fetches_fn())) + fetches.update(dict(self.grad_stats_fn(samples, grads))) + return fetches + + def _lazy_tensor_dict(self, postprocessed_batch: SampleBatch): + # TODO: (sven): Keep for a while to ensure backward compatibility. + if not isinstance(postprocessed_batch, SampleBatch): + postprocessed_batch = SampleBatch(postprocessed_batch) + postprocessed_batch.set_get_interceptor(_convert_to_tf) + return postprocessed_batch + + @classmethod + def with_tracing(cls): + return _traced_eager_policy(cls) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/policy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..0b1db3653a8c1d9615167b528d5db556813d178b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/policy.py @@ -0,0 +1,1696 @@ +import json +import logging +import os +import platform +from abc import ABCMeta, abstractmethod +from typing import ( + Any, + Callable, + Collection, + Dict, + List, + Optional, + Tuple, + Type, + Union, +) + +import gymnasium as gym +import numpy as np +import tree # pip install dm_tree +from gymnasium.spaces import Box +from packaging import version + +import ray +import ray.cloudpickle as pickle +from ray.actor import ActorHandle +from ray.rllib.models.action_dist import ActionDistribution +from ray.rllib.models.catalog import ModelCatalog +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy.view_requirement import ViewRequirement +from ray.rllib.utils.annotations import ( + OldAPIStack, + OverrideToImplementCustomLogic, + OverrideToImplementCustomLogic_CallToSuperRecommended, + is_overridden, +) +from ray.rllib.utils.checkpoints import ( + CHECKPOINT_VERSION, + get_checkpoint_info, + try_import_msgpack, +) +from ray.rllib.utils.deprecation import ( + DEPRECATED_VALUE, + deprecation_warning, +) +from ray.rllib.utils.exploration.exploration import Exploration +from ray.rllib.utils.framework import try_import_tf, try_import_torch +from ray.rllib.utils.from_config import from_config +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.serialization import ( + deserialize_type, + space_from_dict, + space_to_dict, +) +from ray.rllib.utils.spaces.space_utils import ( + get_base_struct_from_space, + get_dummy_batch_for_space, + unbatch, +) +from ray.rllib.utils.tensor_dtype import get_np_dtype +from ray.rllib.utils.tf_utils import get_tf_eager_cls_if_necessary +from ray.rllib.utils.typing import ( + AgentID, + AlgorithmConfigDict, + ModelGradients, + ModelWeights, + PolicyID, + PolicyState, + T, + TensorStructType, + TensorType, +) +from ray.tune import Checkpoint + +tf1, tf, tfv = try_import_tf() +torch, _ = try_import_torch() + + +logger = logging.getLogger(__name__) + + +@OldAPIStack +class PolicySpec: + """A policy spec used in the "config.multiagent.policies" specification dict. + + As values (keys are the policy IDs (str)). E.g.: + config: + multiagent: + policies: { + "pol1": PolicySpec(None, Box, Discrete(2), {"lr": 0.0001}), + "pol2": PolicySpec(config={"lr": 0.001}), + } + """ + + def __init__( + self, policy_class=None, observation_space=None, action_space=None, config=None + ): + # If None, use the Algorithm's default policy class stored under + # `Algorithm._policy_class`. + self.policy_class = policy_class + # If None, use the env's observation space. If None and there is no Env + # (e.g. offline RL), an error is thrown. + self.observation_space = observation_space + # If None, use the env's action space. If None and there is no Env + # (e.g. offline RL), an error is thrown. + self.action_space = action_space + # Overrides defined keys in the main Algorithm config. + # If None, use {}. + self.config = config + + def __eq__(self, other: "PolicySpec"): + return ( + self.policy_class == other.policy_class + and self.observation_space == other.observation_space + and self.action_space == other.action_space + and self.config == other.config + ) + + def get_state(self) -> Dict[str, Any]: + """Returns the state of a `PolicyDict` as a dict.""" + return ( + self.policy_class, + self.observation_space, + self.action_space, + self.config, + ) + + @classmethod + def from_state(cls, state: Dict[str, Any]) -> "PolicySpec": + """Builds a `PolicySpec` from a state.""" + policy_spec = PolicySpec() + policy_spec.__dict__.update(state) + + return policy_spec + + def serialize(self) -> Dict: + from ray.rllib.algorithms.registry import get_policy_class_name + + # Try to figure out a durable name for this policy. + cls = get_policy_class_name(self.policy_class) + if cls is None: + logger.warning( + f"Can not figure out a durable policy name for {self.policy_class}. " + f"You are probably trying to checkpoint a custom policy. " + f"Raw policy class may cause problems when the checkpoint needs to " + "be loaded in the future. To fix this, make sure you add your " + "custom policy in rllib.algorithms.registry.POLICIES." + ) + cls = self.policy_class + + return { + "policy_class": cls, + "observation_space": space_to_dict(self.observation_space), + "action_space": space_to_dict(self.action_space), + # TODO(jungong) : try making the config dict durable by maybe + # getting rid of all the fields that are not JSON serializable. + "config": self.config, + } + + @classmethod + def deserialize(cls, spec: Dict) -> "PolicySpec": + if isinstance(spec["policy_class"], str): + # Try to recover the actual policy class from durable name. + from ray.rllib.algorithms.registry import get_policy_class + + policy_class = get_policy_class(spec["policy_class"]) + elif isinstance(spec["policy_class"], type): + # Policy spec is already a class type. Simply use it. + policy_class = spec["policy_class"] + else: + raise AttributeError(f"Unknown policy class spec {spec['policy_class']}") + + return cls( + policy_class=policy_class, + observation_space=space_from_dict(spec["observation_space"]), + action_space=space_from_dict(spec["action_space"]), + config=spec["config"], + ) + + +@OldAPIStack +class Policy(metaclass=ABCMeta): + """RLlib's base class for all Policy implementations. + + Policy is the abstract superclass for all DL-framework specific sub-classes + (e.g. TFPolicy or TorchPolicy). It exposes APIs to + + 1. Compute actions from observation (and possibly other) inputs. + + 2. Manage the Policy's NN model(s), like exporting and loading their weights. + + 3. Postprocess a given trajectory from the environment or other input via the + `postprocess_trajectory` method. + + 4. Compute losses from a train batch. + + 5. Perform updates from a train batch on the NN-models (this normally includes loss + calculations) either: + + a. in one monolithic step (`learn_on_batch`) + + b. via batch pre-loading, then n steps of actual loss computations and updates + (`load_batch_into_buffer` + `learn_on_loaded_batch`). + """ + + def __init__( + self, + observation_space: gym.Space, + action_space: gym.Space, + config: AlgorithmConfigDict, + ): + """Initializes a Policy instance. + + Args: + observation_space: Observation space of the policy. + action_space: Action space of the policy. + config: A complete Algorithm/Policy config dict. For the default + config keys and values, see rllib/algorithm/algorithm.py. + """ + self.observation_space: gym.Space = observation_space + self.action_space: gym.Space = action_space + # the policy id in the global context. + self.__policy_id = config.get("__policy_id") + # The base struct of the observation/action spaces. + # E.g. action-space = gym.spaces.Dict({"a": Discrete(2)}) -> + # action_space_struct = {"a": Discrete(2)} + self.observation_space_struct = get_base_struct_from_space(observation_space) + self.action_space_struct = get_base_struct_from_space(action_space) + + self.config: AlgorithmConfigDict = config + self.framework = self.config.get("framework") + + # Create the callbacks object to use for handling custom callbacks. + from ray.rllib.callbacks.callbacks import RLlibCallback + + callbacks = self.config.get("callbacks") + if isinstance(callbacks, RLlibCallback): + self.callbacks = callbacks() + elif isinstance(callbacks, (str, type)): + try: + self.callbacks: "RLlibCallback" = deserialize_type( + self.config.get("callbacks") + )() + except Exception: + pass # TEST + else: + self.callbacks: "RLlibCallback" = RLlibCallback() + + # The global timestep, broadcast down from time to time from the + # local worker to all remote workers. + self.global_timestep: int = 0 + # The number of gradient updates this policy has undergone. + self.num_grad_updates: int = 0 + + # The action distribution class to use for action sampling, if any. + # Child classes may set this. + self.dist_class: Optional[Type] = None + + # Initialize view requirements. + self.init_view_requirements() + + # Whether the Model's initial state (method) has been added + # automatically based on the given view requirements of the model. + self._model_init_state_automatically_added = False + + # Connectors. + self.agent_connectors = None + self.action_connectors = None + + @staticmethod + def from_checkpoint( + checkpoint: Union[str, Checkpoint], + policy_ids: Optional[Collection[PolicyID]] = None, + ) -> Union["Policy", Dict[PolicyID, "Policy"]]: + """Creates new Policy instance(s) from a given Policy or Algorithm checkpoint. + + Note: This method must remain backward compatible from 2.1.0 on, wrt. + checkpoints created with Ray 2.0.0 or later. + + Args: + checkpoint: The path (str) to a Policy or Algorithm checkpoint directory + or an AIR Checkpoint (Policy or Algorithm) instance to restore + from. + If checkpoint is a Policy checkpoint, `policy_ids` must be None + and only the Policy in that checkpoint is restored and returned. + If checkpoint is an Algorithm checkpoint and `policy_ids` is None, + will return a list of all Policy objects found in + the checkpoint, otherwise a list of those policies in `policy_ids`. + policy_ids: List of policy IDs to extract from a given Algorithm checkpoint. + If None and an Algorithm checkpoint is provided, will restore all + policies found in that checkpoint. If a Policy checkpoint is given, + this arg must be None. + + Returns: + An instantiated Policy, if `checkpoint` is a Policy checkpoint. A dict + mapping PolicyID to Policies, if `checkpoint` is an Algorithm checkpoint. + In the latter case, returns all policies within the Algorithm if + `policy_ids` is None, else a dict of only those Policies that are in + `policy_ids`. + """ + checkpoint_info = get_checkpoint_info(checkpoint) + + # Algorithm checkpoint: Extract one or more policies from it and return them + # in a dict (mapping PolicyID to Policy instances). + if checkpoint_info["type"] == "Algorithm": + from ray.rllib.algorithms.algorithm import Algorithm + + policies = {} + + # Old Algorithm checkpoints: State must be completely retrieved from: + # algo state file -> worker -> "state". + if checkpoint_info["checkpoint_version"] < version.Version("1.0"): + with open(checkpoint_info["state_file"], "rb") as f: + state = pickle.load(f) + # In older checkpoint versions, the policy states are stored under + # "state" within the worker state (which is pickled in itself). + worker_state = pickle.loads(state["worker"]) + policy_states = worker_state["state"] + for pid, policy_state in policy_states.items(): + # Get spec and config, merge config with + serialized_policy_spec = worker_state["policy_specs"][pid] + policy_config = Algorithm.merge_algorithm_configs( + worker_state["policy_config"], serialized_policy_spec["config"] + ) + serialized_policy_spec.update({"config": policy_config}) + policy_state.update({"policy_spec": serialized_policy_spec}) + policies[pid] = Policy.from_state(policy_state) + # Newer versions: Get policy states from "policies/" sub-dirs. + elif checkpoint_info["policy_ids"] is not None: + for policy_id in checkpoint_info["policy_ids"]: + if policy_ids is None or policy_id in policy_ids: + policy_checkpoint_info = get_checkpoint_info( + os.path.join( + checkpoint_info["checkpoint_dir"], + "policies", + policy_id, + ) + ) + assert policy_checkpoint_info["type"] == "Policy" + with open(policy_checkpoint_info["state_file"], "rb") as f: + policy_state = pickle.load(f) + policies[policy_id] = Policy.from_state(policy_state) + return policies + + # Policy checkpoint: Return a single Policy instance. + else: + msgpack = None + if checkpoint_info.get("format") == "msgpack": + msgpack = try_import_msgpack(error=True) + + with open(checkpoint_info["state_file"], "rb") as f: + if msgpack is not None: + state = msgpack.load(f) + else: + state = pickle.load(f) + return Policy.from_state(state) + + @staticmethod + def from_state(state: PolicyState) -> "Policy": + """Recovers a Policy from a state object. + + The `state` of an instantiated Policy can be retrieved by calling its + `get_state` method. This only works for the V2 Policy classes (EagerTFPolicyV2, + SynamicTFPolicyV2, and TorchPolicyV2). It contains all information necessary + to create the Policy. No access to the original code (e.g. configs, knowledge of + the policy's class, etc..) is needed. + + Args: + state: The state to recover a new Policy instance from. + + Returns: + A new Policy instance. + """ + serialized_pol_spec: Optional[dict] = state.get("policy_spec") + if serialized_pol_spec is None: + raise ValueError( + "No `policy_spec` key was found in given `state`! " + "Cannot create new Policy." + ) + pol_spec = PolicySpec.deserialize(serialized_pol_spec) + actual_class = get_tf_eager_cls_if_necessary( + pol_spec.policy_class, + pol_spec.config, + ) + + if pol_spec.config["framework"] == "tf": + from ray.rllib.policy.tf_policy import TFPolicy + + return TFPolicy._tf1_from_state_helper(state) + + # Create the new policy. + new_policy = actual_class( + # Note(jungong) : we are intentionally not using keyward arguments here + # because some policies name the observation space parameter obs_space, + # and some others name it observation_space. + pol_spec.observation_space, + pol_spec.action_space, + pol_spec.config, + ) + + # Set the new policy's state (weights, optimizer vars, exploration state, + # etc..). + new_policy.set_state(state) + # Return the new policy. + return new_policy + + def init_view_requirements(self): + """Maximal view requirements dict for `learn_on_batch()` and + `compute_actions` calls. + Specific policies can override this function to provide custom + list of view requirements. + """ + # Maximal view requirements dict for `learn_on_batch()` and + # `compute_actions` calls. + # View requirements will be automatically filtered out later based + # on the postprocessing and loss functions to ensure optimal data + # collection and transfer performance. + view_reqs = self._get_default_view_requirements() + if not hasattr(self, "view_requirements"): + self.view_requirements = view_reqs + else: + for k, v in view_reqs.items(): + if k not in self.view_requirements: + self.view_requirements[k] = v + + def get_connector_metrics(self) -> Dict: + """Get metrics on timing from connectors.""" + return { + "agent_connectors": { + name + "_ms": 1000 * timer.mean + for name, timer in self.agent_connectors.timers.items() + }, + "action_connectors": { + name + "_ms": 1000 * timer.mean + for name, timer in self.agent_connectors.timers.items() + }, + } + + def reset_connectors(self, env_id) -> None: + """Reset action- and agent-connectors for this policy.""" + self.agent_connectors.reset(env_id=env_id) + self.action_connectors.reset(env_id=env_id) + + def compute_single_action( + self, + obs: Optional[TensorStructType] = None, + state: Optional[List[TensorType]] = None, + *, + prev_action: Optional[TensorStructType] = None, + prev_reward: Optional[TensorStructType] = None, + info: dict = None, + input_dict: Optional[SampleBatch] = None, + episode=None, + explore: Optional[bool] = None, + timestep: Optional[int] = None, + # Kwars placeholder for future compatibility. + **kwargs, + ) -> Tuple[TensorStructType, List[TensorType], Dict[str, TensorType]]: + """Computes and returns a single (B=1) action value. + + Takes an input dict (usually a SampleBatch) as its main data input. + This allows for using this method in case a more complex input pattern + (view requirements) is needed, for example when the Model requires the + last n observations, the last m actions/rewards, or a combination + of any of these. + Alternatively, in case no complex inputs are required, takes a single + `obs` values (and possibly single state values, prev-action/reward + values, etc..). + + Args: + obs: Single observation. + state: List of RNN state inputs, if any. + prev_action: Previous action value, if any. + prev_reward: Previous reward, if any. + info: Info object, if any. + input_dict: A SampleBatch or input dict containing the + single (unbatched) Tensors to compute actions. If given, it'll + be used instead of `obs`, `state`, `prev_action|reward`, and + `info`. + episode: This provides access to all of the internal episode state, + which may be useful for model-based or multi-agent algorithms. + explore: Whether to pick an exploitation or + exploration action + (default: None -> use self.config["explore"]). + timestep: The current (sampling) time step. + + Keyword Args: + kwargs: Forward compatibility placeholder. + + Returns: + Tuple consisting of the action, the list of RNN state outputs (if + any), and a dictionary of extra features (if any). + """ + # Build the input-dict used for the call to + # `self.compute_actions_from_input_dict()`. + if input_dict is None: + input_dict = {SampleBatch.OBS: obs} + if state is not None: + for i, s in enumerate(state): + input_dict[f"state_in_{i}"] = s + if prev_action is not None: + input_dict[SampleBatch.PREV_ACTIONS] = prev_action + if prev_reward is not None: + input_dict[SampleBatch.PREV_REWARDS] = prev_reward + if info is not None: + input_dict[SampleBatch.INFOS] = info + + # Batch all data in input dict. + input_dict = tree.map_structure_with_path( + lambda p, s: ( + s + if p == "seq_lens" + else s.unsqueeze(0) + if torch and isinstance(s, torch.Tensor) + else np.expand_dims(s, 0) + ), + input_dict, + ) + + episodes = None + if episode is not None: + episodes = [episode] + + out = self.compute_actions_from_input_dict( + input_dict=SampleBatch(input_dict), + episodes=episodes, + explore=explore, + timestep=timestep, + ) + + # Some policies don't return a tuple, but always just a single action. + # E.g. ES and ARS. + if not isinstance(out, tuple): + single_action = out + state_out = [] + info = {} + # Normal case: Policy should return (action, state, info) tuple. + else: + batched_action, state_out, info = out + single_action = unbatch(batched_action) + assert len(single_action) == 1 + single_action = single_action[0] + + # Return action, internal state(s), infos. + return ( + single_action, + tree.map_structure(lambda x: x[0], state_out), + tree.map_structure(lambda x: x[0], info), + ) + + def compute_actions_from_input_dict( + self, + input_dict: Union[SampleBatch, Dict[str, TensorStructType]], + explore: Optional[bool] = None, + timestep: Optional[int] = None, + episodes=None, + **kwargs, + ) -> Tuple[TensorType, List[TensorType], Dict[str, TensorType]]: + """Computes actions from collected samples (across multiple-agents). + + Takes an input dict (usually a SampleBatch) as its main data input. + This allows for using this method in case a more complex input pattern + (view requirements) is needed, for example when the Model requires the + last n observations, the last m actions/rewards, or a combination + of any of these. + + Args: + input_dict: A SampleBatch or input dict containing the Tensors + to compute actions. `input_dict` already abides to the + Policy's as well as the Model's view requirements and can + thus be passed to the Model as-is. + explore: Whether to pick an exploitation or exploration + action (default: None -> use self.config["explore"]). + timestep: The current (sampling) time step. + episodes: This provides access to all of the internal episodes' + state, which may be useful for model-based or multi-agent + algorithms. + + Keyword Args: + kwargs: Forward compatibility placeholder. + + Returns: + actions: Batch of output actions, with shape like + [BATCH_SIZE, ACTION_SHAPE]. + state_outs: List of RNN state output + batches, if any, each with shape [BATCH_SIZE, STATE_SIZE]. + info: Dictionary of extra feature batches, if any, with shape like + {"f1": [BATCH_SIZE, ...], "f2": [BATCH_SIZE, ...]}. + """ + # Default implementation just passes obs, prev-a/r, and states on to + # `self.compute_actions()`. + state_batches = [s for k, s in input_dict.items() if k.startswith("state_in")] + return self.compute_actions( + input_dict[SampleBatch.OBS], + state_batches, + prev_action_batch=input_dict.get(SampleBatch.PREV_ACTIONS), + prev_reward_batch=input_dict.get(SampleBatch.PREV_REWARDS), + info_batch=input_dict.get(SampleBatch.INFOS), + explore=explore, + timestep=timestep, + episodes=episodes, + **kwargs, + ) + + @abstractmethod + def compute_actions( + self, + obs_batch: Union[List[TensorStructType], TensorStructType], + state_batches: Optional[List[TensorType]] = None, + prev_action_batch: Union[List[TensorStructType], TensorStructType] = None, + prev_reward_batch: Union[List[TensorStructType], TensorStructType] = None, + info_batch: Optional[Dict[str, list]] = None, + episodes: Optional[List] = None, + explore: Optional[bool] = None, + timestep: Optional[int] = None, + **kwargs, + ) -> Tuple[TensorType, List[TensorType], Dict[str, TensorType]]: + """Computes actions for the current policy. + + Args: + obs_batch: Batch of observations. + state_batches: List of RNN state input batches, if any. + prev_action_batch: Batch of previous action values. + prev_reward_batch: Batch of previous rewards. + info_batch: Batch of info objects. + episodes: List of Episode objects, one for each obs in + obs_batch. This provides access to all of the internal + episode state, which may be useful for model-based or + multi-agent algorithms. + explore: Whether to pick an exploitation or exploration action. + Set to None (default) for using the value of + `self.config["explore"]`. + timestep: The current (sampling) time step. + + Keyword Args: + kwargs: Forward compatibility placeholder + + Returns: + actions: Batch of output actions, with shape like + [BATCH_SIZE, ACTION_SHAPE]. + state_outs (List[TensorType]): List of RNN state output + batches, if any, each with shape [BATCH_SIZE, STATE_SIZE]. + info (List[dict]): Dictionary of extra feature batches, if any, + with shape like + {"f1": [BATCH_SIZE, ...], "f2": [BATCH_SIZE, ...]}. + """ + raise NotImplementedError + + def compute_log_likelihoods( + self, + actions: Union[List[TensorType], TensorType], + obs_batch: Union[List[TensorType], TensorType], + state_batches: Optional[List[TensorType]] = None, + prev_action_batch: Optional[Union[List[TensorType], TensorType]] = None, + prev_reward_batch: Optional[Union[List[TensorType], TensorType]] = None, + actions_normalized: bool = True, + in_training: bool = True, + ) -> TensorType: + """Computes the log-prob/likelihood for a given action and observation. + + The log-likelihood is calculated using this Policy's action + distribution class (self.dist_class). + + Args: + actions: Batch of actions, for which to retrieve the + log-probs/likelihoods (given all other inputs: obs, + states, ..). + obs_batch: Batch of observations. + state_batches: List of RNN state input batches, if any. + prev_action_batch: Batch of previous action values. + prev_reward_batch: Batch of previous rewards. + actions_normalized: Is the given `actions` already normalized + (between -1.0 and 1.0) or not? If not and + `normalize_actions=True`, we need to normalize the given + actions first, before calculating log likelihoods. + in_training: Whether to use the forward_train() or forward_exploration() of + the underlying RLModule. + Returns: + Batch of log probs/likelihoods, with shape: [BATCH_SIZE]. + """ + raise NotImplementedError + + @OverrideToImplementCustomLogic_CallToSuperRecommended + def postprocess_trajectory( + self, + sample_batch: SampleBatch, + other_agent_batches: Optional[ + Dict[AgentID, Tuple["Policy", SampleBatch]] + ] = None, + episode=None, + ) -> SampleBatch: + """Implements algorithm-specific trajectory postprocessing. + + This will be called on each trajectory fragment computed during policy + evaluation. Each fragment is guaranteed to be only from one episode. + The given fragment may or may not contain the end of this episode, + depending on the `batch_mode=truncate_episodes|complete_episodes`, + `rollout_fragment_length`, and other settings. + + Args: + sample_batch: batch of experiences for the policy, + which will contain at most one episode trajectory. + other_agent_batches: In a multi-agent env, this contains a + mapping of agent ids to (policy, agent_batch) tuples + containing the policy and experiences of the other agents. + episode: An optional multi-agent episode object to provide + access to all of the internal episode state, which may + be useful for model-based or multi-agent algorithms. + + Returns: + The postprocessed sample batch. + """ + # The default implementation just returns the same, unaltered batch. + return sample_batch + + @OverrideToImplementCustomLogic + def loss( + self, model: ModelV2, dist_class: ActionDistribution, train_batch: SampleBatch + ) -> Union[TensorType, List[TensorType]]: + """Loss function for this Policy. + + Override this method in order to implement custom loss computations. + + Args: + model: The model to calculate the loss(es). + dist_class: The action distribution class to sample actions + from the model's outputs. + train_batch: The input batch on which to calculate the loss. + + Returns: + Either a single loss tensor or a list of loss tensors. + """ + raise NotImplementedError + + def learn_on_batch(self, samples: SampleBatch) -> Dict[str, TensorType]: + """Perform one learning update, given `samples`. + + Either this method or the combination of `compute_gradients` and + `apply_gradients` must be implemented by subclasses. + + Args: + samples: The SampleBatch object to learn from. + + Returns: + Dictionary of extra metadata from `compute_gradients()`. + + .. testcode:: + :skipif: True + + policy, sample_batch = ... + policy.learn_on_batch(sample_batch) + """ + # The default implementation is simply a fused `compute_gradients` plus + # `apply_gradients` call. + grads, grad_info = self.compute_gradients(samples) + self.apply_gradients(grads) + return grad_info + + def learn_on_batch_from_replay_buffer( + self, replay_actor: ActorHandle, policy_id: PolicyID + ) -> Dict[str, TensorType]: + """Samples a batch from given replay actor and performs an update. + + Args: + replay_actor: The replay buffer actor to sample from. + policy_id: The ID of this policy. + + Returns: + Dictionary of extra metadata from `compute_gradients()`. + """ + # Sample a batch from the given replay actor. + # Note that for better performance (less data sent through the + # network), this policy should be co-located on the same node + # as `replay_actor`. Such a co-location step is usually done during + # the Algorithm's `setup()` phase. + batch = ray.get(replay_actor.replay.remote(policy_id=policy_id)) + if batch is None: + return {} + + # Send to own learn_on_batch method for updating. + # TODO: hack w/ `hasattr` + if hasattr(self, "devices") and len(self.devices) > 1: + self.load_batch_into_buffer(batch, buffer_index=0) + return self.learn_on_loaded_batch(offset=0, buffer_index=0) + else: + return self.learn_on_batch(batch) + + def load_batch_into_buffer(self, batch: SampleBatch, buffer_index: int = 0) -> int: + """Bulk-loads the given SampleBatch into the devices' memories. + + The data is split equally across all the Policy's devices. + If the data is not evenly divisible by the batch size, excess data + should be discarded. + + Args: + batch: The SampleBatch to load. + buffer_index: The index of the buffer (a MultiGPUTowerStack) to use + on the devices. The number of buffers on each device depends + on the value of the `num_multi_gpu_tower_stacks` config key. + + Returns: + The number of tuples loaded per device. + """ + raise NotImplementedError + + def get_num_samples_loaded_into_buffer(self, buffer_index: int = 0) -> int: + """Returns the number of currently loaded samples in the given buffer. + + Args: + buffer_index: The index of the buffer (a MultiGPUTowerStack) + to use on the devices. The number of buffers on each device + depends on the value of the `num_multi_gpu_tower_stacks` config + key. + + Returns: + The number of tuples loaded per device. + """ + raise NotImplementedError + + def learn_on_loaded_batch(self, offset: int = 0, buffer_index: int = 0): + """Runs a single step of SGD on an already loaded data in a buffer. + + Runs an SGD step over a slice of the pre-loaded batch, offset by + the `offset` argument (useful for performing n minibatch SGD + updates repeatedly on the same, already pre-loaded data). + + Updates the model weights based on the averaged per-device gradients. + + Args: + offset: Offset into the preloaded data. Used for pre-loading + a train-batch once to a device, then iterating over + (subsampling through) this batch n times doing minibatch SGD. + buffer_index: The index of the buffer (a MultiGPUTowerStack) + to take the already pre-loaded data from. The number of buffers + on each device depends on the value of the + `num_multi_gpu_tower_stacks` config key. + + Returns: + The outputs of extra_ops evaluated over the batch. + """ + raise NotImplementedError + + def compute_gradients( + self, postprocessed_batch: SampleBatch + ) -> Tuple[ModelGradients, Dict[str, TensorType]]: + """Computes gradients given a batch of experiences. + + Either this in combination with `apply_gradients()` or + `learn_on_batch()` must be implemented by subclasses. + + Args: + postprocessed_batch: The SampleBatch object to use + for calculating gradients. + + Returns: + grads: List of gradient output values. + grad_info: Extra policy-specific info values. + """ + raise NotImplementedError + + def apply_gradients(self, gradients: ModelGradients) -> None: + """Applies the (previously) computed gradients. + + Either this in combination with `compute_gradients()` or + `learn_on_batch()` must be implemented by subclasses. + + Args: + gradients: The already calculated gradients to apply to this + Policy. + """ + raise NotImplementedError + + def get_weights(self) -> ModelWeights: + """Returns model weights. + + Note: The return value of this method will reside under the "weights" + key in the return value of Policy.get_state(). Model weights are only + one part of a Policy's state. Other state information contains: + optimizer variables, exploration state, and global state vars such as + the sampling timestep. + + Returns: + Serializable copy or view of model weights. + """ + raise NotImplementedError + + def set_weights(self, weights: ModelWeights) -> None: + """Sets this Policy's model's weights. + + Note: Model weights are only one part of a Policy's state. Other + state information contains: optimizer variables, exploration state, + and global state vars such as the sampling timestep. + + Args: + weights: Serializable copy or view of model weights. + """ + raise NotImplementedError + + def get_exploration_state(self) -> Dict[str, TensorType]: + """Returns the state of this Policy's exploration component. + + Returns: + Serializable information on the `self.exploration` object. + """ + return self.exploration.get_state() + + def is_recurrent(self) -> bool: + """Whether this Policy holds a recurrent Model. + + Returns: + True if this Policy has-a RNN-based Model. + """ + return False + + def num_state_tensors(self) -> int: + """The number of internal states needed by the RNN-Model of the Policy. + + Returns: + int: The number of RNN internal states kept by this Policy's Model. + """ + return 0 + + def get_initial_state(self) -> List[TensorType]: + """Returns initial RNN state for the current policy. + + Returns: + List[TensorType]: Initial RNN state for the current policy. + """ + return [] + + @OverrideToImplementCustomLogic_CallToSuperRecommended + def get_state(self) -> PolicyState: + """Returns the entire current state of this Policy. + + Note: Not to be confused with an RNN model's internal state. + State includes the Model(s)' weights, optimizer weights, + the exploration component's state, as well as global variables, such + as sampling timesteps. + + Note that the state may contain references to the original variables. + This means that you may need to deepcopy() the state before mutating it. + + Returns: + Serialized local state. + """ + state = { + # All the policy's weights. + "weights": self.get_weights(), + # The current global timestep. + "global_timestep": self.global_timestep, + # The current num_grad_updates counter. + "num_grad_updates": self.num_grad_updates, + } + + # Add this Policy's spec so it can be retreived w/o access to the original + # code. + policy_spec = PolicySpec( + policy_class=type(self), + observation_space=self.observation_space, + action_space=self.action_space, + config=self.config, + ) + state["policy_spec"] = policy_spec.serialize() + + # Checkpoint connectors state as well if enabled. + connector_configs = {} + if self.agent_connectors: + connector_configs["agent"] = self.agent_connectors.to_state() + if self.action_connectors: + connector_configs["action"] = self.action_connectors.to_state() + state["connector_configs"] = connector_configs + + return state + + def restore_connectors(self, state: PolicyState): + """Restore agent and action connectors if configs available. + + Args: + state: The new state to set this policy to. Can be + obtained by calling `self.get_state()`. + """ + # To avoid a circular dependency problem cause by SampleBatch. + from ray.rllib.connectors.util import restore_connectors_for_policy + + connector_configs = state.get("connector_configs", {}) + if "agent" in connector_configs: + self.agent_connectors = restore_connectors_for_policy( + self, connector_configs["agent"] + ) + logger.debug("restoring agent connectors:") + logger.debug(self.agent_connectors.__str__(indentation=4)) + if "action" in connector_configs: + self.action_connectors = restore_connectors_for_policy( + self, connector_configs["action"] + ) + logger.debug("restoring action connectors:") + logger.debug(self.action_connectors.__str__(indentation=4)) + + @OverrideToImplementCustomLogic_CallToSuperRecommended + def set_state(self, state: PolicyState) -> None: + """Restores the entire current state of this Policy from `state`. + + Args: + state: The new state to set this policy to. Can be + obtained by calling `self.get_state()`. + """ + if "policy_spec" in state: + policy_spec = PolicySpec.deserialize(state["policy_spec"]) + # Assert spaces remained the same. + if ( + policy_spec.observation_space is not None + and policy_spec.observation_space != self.observation_space + ): + logger.warning( + "`observation_space` in given policy state (" + f"{policy_spec.observation_space}) does not match this Policy's " + f"observation space ({self.observation_space})." + ) + if ( + policy_spec.action_space is not None + and policy_spec.action_space != self.action_space + ): + logger.warning( + "`action_space` in given policy state (" + f"{policy_spec.action_space}) does not match this Policy's " + f"action space ({self.action_space})." + ) + # Override config, if part of the spec. + if policy_spec.config: + self.config = policy_spec.config + + # Override NN weights. + self.set_weights(state["weights"]) + self.restore_connectors(state) + + def apply( + self, + func: Callable[["Policy", Optional[Any], Optional[Any]], T], + *args, + **kwargs, + ) -> T: + """Calls the given function with this Policy instance. + + Useful for when the Policy class has been converted into a ActorHandle + and the user needs to execute some functionality (e.g. add a property) + on the underlying policy object. + + Args: + func: The function to call, with this Policy as first + argument, followed by args, and kwargs. + args: Optional additional args to pass to the function call. + kwargs: Optional additional kwargs to pass to the function call. + + Returns: + The return value of the function call. + """ + return func(self, *args, **kwargs) + + def on_global_var_update(self, global_vars: Dict[str, TensorType]) -> None: + """Called on an update to global vars. + + Args: + global_vars: Global variables by str key, broadcast from the + driver. + """ + # Store the current global time step (sum over all policies' sample + # steps). + # Make sure, we keep global_timestep as a Tensor for tf-eager + # (leads to memory leaks if not doing so). + if self.framework == "tf2": + self.global_timestep.assign(global_vars["timestep"]) + else: + self.global_timestep = global_vars["timestep"] + # Update our lifetime gradient update counter. + num_grad_updates = global_vars.get("num_grad_updates") + if num_grad_updates is not None: + self.num_grad_updates = num_grad_updates + + def export_checkpoint( + self, + export_dir: str, + filename_prefix=DEPRECATED_VALUE, + *, + policy_state: Optional[PolicyState] = None, + checkpoint_format: str = "cloudpickle", + ) -> None: + """Exports Policy checkpoint to a local directory and returns an AIR Checkpoint. + + Args: + export_dir: Local writable directory to store the AIR Checkpoint + information into. + policy_state: An optional PolicyState to write to disk. Used by + `Algorithm.save_checkpoint()` to save on the additional + `self.get_state()` calls of its different Policies. + checkpoint_format: Either one of 'cloudpickle' or 'msgpack'. + + .. testcode:: + :skipif: True + + from ray.rllib.algorithms.ppo import PPOTorchPolicy + policy = PPOTorchPolicy(...) + policy.export_checkpoint("/tmp/export_dir") + """ + # `filename_prefix` should not longer be used as new Policy checkpoints + # contain more than one file with a fixed filename structure. + if filename_prefix != DEPRECATED_VALUE: + deprecation_warning( + old="Policy.export_checkpoint(filename_prefix=...)", + error=True, + ) + if checkpoint_format not in ["cloudpickle", "msgpack"]: + raise ValueError( + f"Value of `checkpoint_format` ({checkpoint_format}) must either be " + "'cloudpickle' or 'msgpack'!" + ) + + if policy_state is None: + policy_state = self.get_state() + + # Write main policy state file. + os.makedirs(export_dir, exist_ok=True) + if checkpoint_format == "cloudpickle": + policy_state["checkpoint_version"] = CHECKPOINT_VERSION + state_file = "policy_state.pkl" + with open(os.path.join(export_dir, state_file), "w+b") as f: + pickle.dump(policy_state, f) + else: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + + msgpack = try_import_msgpack(error=True) + policy_state["checkpoint_version"] = str(CHECKPOINT_VERSION) + # Serialize the config for msgpack dump'ing. + policy_state["policy_spec"]["config"] = AlgorithmConfig._serialize_dict( + policy_state["policy_spec"]["config"] + ) + state_file = "policy_state.msgpck" + with open(os.path.join(export_dir, state_file), "w+b") as f: + msgpack.dump(policy_state, f) + + # Write RLlib checkpoint json. + with open(os.path.join(export_dir, "rllib_checkpoint.json"), "w") as f: + json.dump( + { + "type": "Policy", + "checkpoint_version": str(policy_state["checkpoint_version"]), + "format": checkpoint_format, + "state_file": state_file, + "ray_version": ray.__version__, + "ray_commit": ray.__commit__, + }, + f, + ) + + # Add external model files, if required. + if self.config["export_native_model_files"]: + self.export_model(os.path.join(export_dir, "model")) + + def export_model(self, export_dir: str, onnx: Optional[int] = None) -> None: + """Exports the Policy's Model to local directory for serving. + + Note: The file format will depend on the deep learning framework used. + See the child classed of Policy and their `export_model` + implementations for more details. + + Args: + export_dir: Local writable directory. + onnx: If given, will export model in ONNX format. The + value of this parameter set the ONNX OpSet version to use. + + Raises: + ValueError: If a native DL-framework based model (e.g. a keras Model) + cannot be saved to disk for various reasons. + """ + raise NotImplementedError + + def import_model_from_h5(self, import_file: str) -> None: + """Imports Policy from local file. + + Args: + import_file: Local readable file. + """ + raise NotImplementedError + + def get_session(self) -> Optional["tf1.Session"]: + """Returns tf.Session object to use for computing actions or None. + + Note: This method only applies to TFPolicy sub-classes. All other + sub-classes should expect a None to be returned from this method. + + Returns: + The tf Session to use for computing actions and losses with + this policy or None. + """ + return None + + def get_host(self) -> str: + """Returns the computer's network name. + + Returns: + The computer's networks name or an empty string, if the network + name could not be determined. + """ + return platform.node() + + def _get_num_gpus_for_policy(self) -> int: + """Decide on the number of CPU/GPU nodes this policy should run on. + + Return: + 0 if policy should run on CPU. >0 if policy should run on 1 or + more GPUs. + """ + worker_idx = self.config.get("worker_index", 0) + fake_gpus = self.config.get("_fake_gpus", False) + + if ( + ray._private.worker._mode() == ray._private.worker.LOCAL_MODE + and not fake_gpus + ): + # If in local debugging mode, and _fake_gpus is not on. + num_gpus = 0 + elif worker_idx == 0: + # If head node, take num_gpus. + num_gpus = self.config["num_gpus"] + else: + # If worker node, take `num_gpus_per_env_runner`. + num_gpus = self.config["num_gpus_per_env_runner"] + + if num_gpus == 0: + dev = "CPU" + else: + dev = "{} {}".format(num_gpus, "fake-GPUs" if fake_gpus else "GPUs") + + logger.info( + "Policy (worker={}) running on {}.".format( + worker_idx if worker_idx > 0 else "local", dev + ) + ) + + return num_gpus + + def _create_exploration(self) -> Exploration: + """Creates the Policy's Exploration object. + + This method only exists b/c some Algorithms do not use TfPolicy nor + TorchPolicy, but inherit directly from Policy. Others inherit from + TfPolicy w/o using DynamicTFPolicy. + + Returns: + Exploration: The Exploration object to be used by this Policy. + """ + if getattr(self, "exploration", None) is not None: + return self.exploration + + exploration = from_config( + Exploration, + self.config.get("exploration_config", {"type": "StochasticSampling"}), + action_space=self.action_space, + policy_config=self.config, + model=getattr(self, "model", None), + num_workers=self.config.get("num_env_runners", 0), + worker_index=self.config.get("worker_index", 0), + framework=getattr(self, "framework", self.config.get("framework", "tf")), + ) + return exploration + + def _get_default_view_requirements(self): + """Returns a default ViewRequirements dict. + + Note: This is the base/maximum requirement dict, from which later + some requirements will be subtracted again automatically to streamline + data collection, batch creation, and data transfer. + + Returns: + ViewReqDict: The default view requirements dict. + """ + + # Default view requirements (equal to those that we would use before + # the trajectory view API was introduced). + return { + SampleBatch.OBS: ViewRequirement(space=self.observation_space), + SampleBatch.NEXT_OBS: ViewRequirement( + data_col=SampleBatch.OBS, + shift=1, + space=self.observation_space, + used_for_compute_actions=False, + ), + SampleBatch.ACTIONS: ViewRequirement( + space=self.action_space, used_for_compute_actions=False + ), + # For backward compatibility with custom Models that don't specify + # these explicitly (will be removed by Policy if not used). + SampleBatch.PREV_ACTIONS: ViewRequirement( + data_col=SampleBatch.ACTIONS, shift=-1, space=self.action_space + ), + SampleBatch.REWARDS: ViewRequirement(), + # For backward compatibility with custom Models that don't specify + # these explicitly (will be removed by Policy if not used). + SampleBatch.PREV_REWARDS: ViewRequirement( + data_col=SampleBatch.REWARDS, shift=-1 + ), + SampleBatch.TERMINATEDS: ViewRequirement(), + SampleBatch.TRUNCATEDS: ViewRequirement(), + SampleBatch.INFOS: ViewRequirement(used_for_compute_actions=False), + SampleBatch.EPS_ID: ViewRequirement(), + SampleBatch.UNROLL_ID: ViewRequirement(), + SampleBatch.AGENT_INDEX: ViewRequirement(), + SampleBatch.T: ViewRequirement(), + } + + def _initialize_loss_from_dummy_batch( + self, + auto_remove_unneeded_view_reqs: bool = True, + stats_fn=None, + ) -> None: + """Performs test calls through policy's model and loss. + + NOTE: This base method should work for define-by-run Policies such as + torch and tf-eager policies. + + If required, will thereby detect automatically, which data views are + required by a) the forward pass, b) the postprocessing, and c) the loss + functions, and remove those from self.view_requirements that are not + necessary for these computations (to save data storage and transfer). + + Args: + auto_remove_unneeded_view_reqs: Whether to automatically + remove those ViewRequirements records from + self.view_requirements that are not needed. + stats_fn (Optional[Callable[[Policy, SampleBatch], Dict[str, + TensorType]]]): An optional stats function to be called after + the loss. + """ + + if self.config.get("_disable_initialize_loss_from_dummy_batch", False): + return + # Signal Policy that currently we do not like to eager/jit trace + # any function calls. This is to be able to track, which columns + # in the dummy batch are accessed by the different function (e.g. + # loss) such that we can then adjust our view requirements. + self._no_tracing = True + # Save for later so that loss init does not change global timestep + global_ts_before_init = int(convert_to_numpy(self.global_timestep)) + + sample_batch_size = min( + max(self.batch_divisibility_req * 4, 32), + self.config["train_batch_size"], # Don't go over the asked batch size. + ) + self._dummy_batch = self._get_dummy_batch_from_view_requirements( + sample_batch_size + ) + self._lazy_tensor_dict(self._dummy_batch) + explore = False + actions, state_outs, extra_outs = self.compute_actions_from_input_dict( + self._dummy_batch, explore=explore + ) + for key, view_req in self.view_requirements.items(): + if key not in self._dummy_batch.accessed_keys: + view_req.used_for_compute_actions = False + # Add all extra action outputs to view reqirements (these may be + # filtered out later again, if not needed for postprocessing or loss). + for key, value in extra_outs.items(): + self._dummy_batch[key] = value + if key not in self.view_requirements: + if isinstance(value, (dict, np.ndarray)): + # the assumption is that value is a nested_dict of np.arrays leaves + space = get_gym_space_from_struct_of_tensors(value) + self.view_requirements[key] = ViewRequirement( + space=space, used_for_compute_actions=False + ) + else: + raise ValueError( + "policy.compute_actions_from_input_dict() returns an " + "extra action output that is neither a numpy array nor a dict." + ) + + for key in self._dummy_batch.accessed_keys: + if key not in self.view_requirements: + self.view_requirements[key] = ViewRequirement() + self.view_requirements[key].used_for_compute_actions = False + # TODO (kourosh) Why did we use to make used_for_compute_actions True here? + new_batch = self._get_dummy_batch_from_view_requirements(sample_batch_size) + # Make sure the dummy_batch will return numpy arrays when accessed + self._dummy_batch.set_get_interceptor(None) + + # try to re-use the output of the previous run to avoid overriding things that + # would break (e.g. scale = 0 of Normal distribution cannot be zero) + for k in new_batch: + if k not in self._dummy_batch: + self._dummy_batch[k] = new_batch[k] + + # Make sure the book-keeping of dummy_batch keys are reset to correcly track + # what is accessed, what is added and what's deleted from now on. + self._dummy_batch.accessed_keys.clear() + self._dummy_batch.deleted_keys.clear() + self._dummy_batch.added_keys.clear() + + if self.exploration: + # Policies with RLModules don't have an exploration object. + self.exploration.postprocess_trajectory(self, self._dummy_batch) + + postprocessed_batch = self.postprocess_trajectory(self._dummy_batch) + seq_lens = None + if state_outs: + B = 4 # For RNNs, have B=4, T=[depends on sample_batch_size] + i = 0 + while "state_in_{}".format(i) in postprocessed_batch: + postprocessed_batch["state_in_{}".format(i)] = postprocessed_batch[ + "state_in_{}".format(i) + ][:B] + if "state_out_{}".format(i) in postprocessed_batch: + postprocessed_batch["state_out_{}".format(i)] = postprocessed_batch[ + "state_out_{}".format(i) + ][:B] + i += 1 + + seq_len = sample_batch_size // B + seq_lens = np.array([seq_len for _ in range(B)], dtype=np.int32) + postprocessed_batch[SampleBatch.SEQ_LENS] = seq_lens + + # Switch on lazy to-tensor conversion on `postprocessed_batch`. + train_batch = self._lazy_tensor_dict(postprocessed_batch) + # Calling loss, so set `is_training` to True. + train_batch.set_training(True) + if seq_lens is not None: + train_batch[SampleBatch.SEQ_LENS] = seq_lens + train_batch.count = self._dummy_batch.count + + # Call the loss function, if it exists. + # TODO(jungong) : clean up after all agents get migrated. + # We should simply do self.loss(...) here. + if self._loss is not None: + self._loss(self, self.model, self.dist_class, train_batch) + elif is_overridden(self.loss) and not self.config["in_evaluation"]: + self.loss(self.model, self.dist_class, train_batch) + # Call the stats fn, if given. + # TODO(jungong) : clean up after all agents get migrated. + # We should simply do self.stats_fn(train_batch) here. + if stats_fn is not None: + stats_fn(self, train_batch) + if hasattr(self, "stats_fn") and not self.config["in_evaluation"]: + self.stats_fn(train_batch) + + # Re-enable tracing. + self._no_tracing = False + + # Add new columns automatically to view-reqs. + if auto_remove_unneeded_view_reqs: + # Add those needed for postprocessing and training. + all_accessed_keys = ( + train_batch.accessed_keys + | self._dummy_batch.accessed_keys + | self._dummy_batch.added_keys + ) + for key in all_accessed_keys: + if key not in self.view_requirements and key != SampleBatch.SEQ_LENS: + self.view_requirements[key] = ViewRequirement( + used_for_compute_actions=False + ) + if self._loss or is_overridden(self.loss): + # Tag those only needed for post-processing (with some + # exceptions). + for key in self._dummy_batch.accessed_keys: + if ( + key not in train_batch.accessed_keys + and key in self.view_requirements + and key not in self.model.view_requirements + and key + not in [ + SampleBatch.EPS_ID, + SampleBatch.AGENT_INDEX, + SampleBatch.UNROLL_ID, + SampleBatch.TERMINATEDS, + SampleBatch.TRUNCATEDS, + SampleBatch.REWARDS, + SampleBatch.INFOS, + SampleBatch.T, + ] + ): + self.view_requirements[key].used_for_training = False + # Remove those not needed at all (leave those that are needed + # by Sampler to properly execute sample collection). Also always leave + # TERMINATEDS, TRUNCATEDS, REWARDS, INFOS, no matter what. + for key in list(self.view_requirements.keys()): + if ( + key not in all_accessed_keys + and key + not in [ + SampleBatch.EPS_ID, + SampleBatch.AGENT_INDEX, + SampleBatch.UNROLL_ID, + SampleBatch.TERMINATEDS, + SampleBatch.TRUNCATEDS, + SampleBatch.REWARDS, + SampleBatch.INFOS, + SampleBatch.T, + ] + and key not in self.model.view_requirements + ): + # If user deleted this key manually in postprocessing + # fn, warn about it and do not remove from + # view-requirements. + if key in self._dummy_batch.deleted_keys: + logger.warning( + "SampleBatch key '{}' was deleted manually in " + "postprocessing function! RLlib will " + "automatically remove non-used items from the " + "data stream. Remove the `del` from your " + "postprocessing function.".format(key) + ) + # If we are not writing output to disk, save to erase + # this key to save space in the sample batch. + elif self.config["output"] is None: + del self.view_requirements[key] + + if type(self.global_timestep) is int: + self.global_timestep = global_ts_before_init + elif isinstance(self.global_timestep, tf.Variable): + self.global_timestep.assign(global_ts_before_init) + else: + raise ValueError( + "Variable self.global_timestep of policy {} needs to be " + "either of type `int` or `tf.Variable`, " + "but is of type {}.".format(self, type(self.global_timestep)) + ) + + def maybe_remove_time_dimension(self, input_dict: Dict[str, TensorType]): + """Removes a time dimension for recurrent RLModules. + + Args: + input_dict: The input dict. + + Returns: + The input dict with a possibly removed time dimension. + """ + raise NotImplementedError + + def _get_dummy_batch_from_view_requirements( + self, batch_size: int = 1 + ) -> SampleBatch: + """Creates a numpy dummy batch based on the Policy's view requirements. + + Args: + batch_size: The size of the batch to create. + + Returns: + Dict[str, TensorType]: The dummy batch containing all zero values. + """ + ret = {} + for view_col, view_req in self.view_requirements.items(): + data_col = view_req.data_col or view_col + # Flattened dummy batch. + if (isinstance(view_req.space, (gym.spaces.Tuple, gym.spaces.Dict))) and ( + ( + data_col == SampleBatch.OBS + and not self.config["_disable_preprocessor_api"] + ) + or ( + data_col == SampleBatch.ACTIONS + and not self.config.get("_disable_action_flattening") + ) + ): + _, shape = ModelCatalog.get_action_shape( + view_req.space, framework=self.config["framework"] + ) + ret[view_col] = np.zeros((batch_size,) + shape[1:], np.float32) + # Non-flattened dummy batch. + else: + # Range of indices on time-axis, e.g. "-50:-1". + if isinstance(view_req.space, gym.spaces.Space): + time_size = ( + len(view_req.shift_arr) if len(view_req.shift_arr) > 1 else None + ) + ret[view_col] = get_dummy_batch_for_space( + view_req.space, batch_size=batch_size, time_size=time_size + ) + else: + ret[view_col] = [view_req.space for _ in range(batch_size)] + + # Due to different view requirements for the different columns, + # columns in the resulting batch may not all have the same batch size. + return SampleBatch(ret) + + def _update_model_view_requirements_from_init_state(self): + """Uses Model's (or this Policy's) init state to add needed ViewReqs. + + Can be called from within a Policy to make sure RNNs automatically + update their internal state-related view requirements. + Changes the `self.view_requirements` dict. + """ + self._model_init_state_automatically_added = True + model = getattr(self, "model", None) + + obj = model or self + if model and not hasattr(model, "view_requirements"): + model.view_requirements = { + SampleBatch.OBS: ViewRequirement(space=self.observation_space) + } + view_reqs = obj.view_requirements + # Add state-ins to this model's view. + init_state = [] + if hasattr(obj, "get_initial_state") and callable(obj.get_initial_state): + init_state = obj.get_initial_state() + else: + # Add this functionality automatically for new native model API. + if ( + tf + and isinstance(model, tf.keras.Model) + and "state_in_0" not in view_reqs + ): + obj.get_initial_state = lambda: [ + np.zeros_like(view_req.space.sample()) + for k, view_req in model.view_requirements.items() + if k.startswith("state_in_") + ] + else: + obj.get_initial_state = lambda: [] + if "state_in_0" in view_reqs: + self.is_recurrent = lambda: True + + # Make sure auto-generated init-state view requirements get added + # to both Policy and Model, no matter what. + view_reqs = [view_reqs] + ( + [self.view_requirements] if hasattr(self, "view_requirements") else [] + ) + + for i, state in enumerate(init_state): + # Allow `state` to be either a Space (use zeros as initial values) + # or any value (e.g. a dict or a non-zero tensor). + fw = ( + np + if isinstance(state, np.ndarray) + else torch + if torch and torch.is_tensor(state) + else None + ) + if fw: + space = ( + Box(-1.0, 1.0, shape=state.shape) if fw.all(state == 0.0) else state + ) + else: + space = state + for vr in view_reqs: + # Only override if user has not already provided + # custom view-requirements for state_in_n. + if "state_in_{}".format(i) not in vr: + vr["state_in_{}".format(i)] = ViewRequirement( + "state_out_{}".format(i), + shift=-1, + used_for_compute_actions=True, + batch_repeat_value=self.config.get("model", {}).get( + "max_seq_len", 1 + ), + space=space, + ) + # Only override if user has not already provided + # custom view-requirements for state_out_n. + if "state_out_{}".format(i) not in vr: + vr["state_out_{}".format(i)] = ViewRequirement( + space=space, used_for_training=True + ) + + def __repr__(self): + return type(self).__name__ + + +@OldAPIStack +def get_gym_space_from_struct_of_tensors( + value: Union[Dict, Tuple, List, TensorType], + batched_input=True, +) -> gym.Space: + start_idx = 1 if batched_input else 0 + struct = tree.map_structure( + lambda x: gym.spaces.Box( + -1.0, 1.0, shape=x.shape[start_idx:], dtype=get_np_dtype(x) + ), + value, + ) + space = get_gym_space_from_struct_of_spaces(struct) + return space + + +@OldAPIStack +def get_gym_space_from_struct_of_spaces(value: Union[Dict, Tuple]) -> gym.spaces.Dict: + if isinstance(value, dict): + return gym.spaces.Dict( + {k: get_gym_space_from_struct_of_spaces(v) for k, v in value.items()} + ) + elif isinstance(value, (tuple, list)): + return gym.spaces.Tuple([get_gym_space_from_struct_of_spaces(v) for v in value]) + else: + assert isinstance(value, gym.spaces.Space), ( + f"The struct of spaces should only contain dicts, tiples and primitive " + f"gym spaces. Space is of type {type(value)}" + ) + return value diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/policy_map.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/policy_map.py new file mode 100644 index 0000000000000000000000000000000000000000..b14b2a27056ed4bfee2d2e0f86bcc5f6e8c111d6 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/policy_map.py @@ -0,0 +1,294 @@ +from collections import deque +import threading +from typing import Dict, Set +import logging + +import ray +from ray.rllib.policy.policy import Policy +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.deprecation import deprecation_warning +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.threading import with_lock +from ray.rllib.utils.typing import PolicyID + +tf1, tf, tfv = try_import_tf() +logger = logging.getLogger(__name__) + + +@OldAPIStack +class PolicyMap(dict): + """Maps policy IDs to Policy objects. + + Thereby, keeps n policies in memory and - when capacity is reached - + writes the least recently used to disk. This allows adding 100s of + policies to a Algorithm for league-based setups w/o running out of memory. + """ + + def __init__( + self, + *, + capacity: int = 100, + policy_states_are_swappable: bool = False, + # Deprecated args. + worker_index=None, + num_workers=None, + policy_config=None, + session_creator=None, + seed=None, + ): + """Initializes a PolicyMap instance. + + Args: + capacity: The size of the Policy object cache. This is the maximum number + of policies that are held in RAM memory. When reaching this capacity, + the least recently used Policy's state will be stored in the Ray object + store and recovered from there when being accessed again. + policy_states_are_swappable: Whether all Policy objects in this map can be + "swapped out" via a simple `state = A.get_state(); B.set_state(state)`, + where `A` and `B` are policy instances in this map. You should set + this to True for significantly speeding up the PolicyMap's cache lookup + times, iff your policies all share the same neural network + architecture and optimizer types. If True, the PolicyMap will not + have to garbage collect old, least recently used policies, but instead + keep them in memory and simply override their state with the state of + the most recently accessed one. + For example, in a league-based training setup, you might have 100s of + the same policies in your map (playing against each other in various + combinations), but all of them share the same state structure + (are "swappable"). + """ + if policy_config is not None: + deprecation_warning( + old="PolicyMap(policy_config=..)", + error=True, + ) + + super().__init__() + + self.capacity = capacity + + if any( + i is not None + for i in [policy_config, worker_index, num_workers, session_creator, seed] + ): + deprecation_warning( + old="PolicyMap([deprecated args]...)", + new="PolicyMap(capacity=..., policy_states_are_swappable=...)", + error=False, + ) + + self.policy_states_are_swappable = policy_states_are_swappable + + # The actual cache with the in-memory policy objects. + self.cache: Dict[str, Policy] = {} + + # Set of keys that may be looked up (cached or not). + self._valid_keys: Set[str] = set() + # The doubly-linked list holding the currently in-memory objects. + self._deque = deque() + + # Ray object store references to the stashed Policy states. + self._policy_state_refs = {} + + # Lock used for locking some methods on the object-level. + # This prevents possible race conditions when accessing the map + # and the underlying structures, like self._deque and others. + self._lock = threading.RLock() + + @with_lock + @override(dict) + def __getitem__(self, item: PolicyID): + # Never seen this key -> Error. + if item not in self._valid_keys: + raise KeyError( + f"PolicyID '{item}' not found in this PolicyMap! " + f"IDs stored in this map: {self._valid_keys}." + ) + + # Item already in cache -> Rearrange deque (promote `item` to + # "most recently used") and return it. + if item in self.cache: + self._deque.remove(item) + self._deque.append(item) + return self.cache[item] + + # Item not currently in cache -> Get from stash and - if at capacity - + # remove leftmost one. + if item not in self._policy_state_refs: + raise AssertionError( + f"PolicyID {item} not found in internal Ray object store cache!" + ) + policy_state = ray.get(self._policy_state_refs[item]) + + policy = None + # We are at capacity: Remove the oldest policy from deque as well as the + # cache and return it. + if len(self._deque) == self.capacity: + policy = self._stash_least_used_policy() + + # All our policies have same NN-architecture (are "swappable"). + # -> Load new policy's state into the one that just got removed from the cache. + # This way, we save the costly re-creation step. + if policy is not None and self.policy_states_are_swappable: + logger.debug(f"restoring policy: {item}") + policy.set_state(policy_state) + else: + logger.debug(f"creating new policy: {item}") + policy = Policy.from_state(policy_state) + + self.cache[item] = policy + # Promote the item to most recently one. + self._deque.append(item) + + return policy + + @with_lock + @override(dict) + def __setitem__(self, key: PolicyID, value: Policy): + # Item already in cache -> Rearrange deque. + if key in self.cache: + self._deque.remove(key) + + # Item not currently in cache -> store new value and - if at capacity - + # remove leftmost one. + else: + # Cache at capacity -> Drop leftmost item. + if len(self._deque) == self.capacity: + self._stash_least_used_policy() + + # Promote `key` to "most recently used". + self._deque.append(key) + + # Update our cache. + self.cache[key] = value + self._valid_keys.add(key) + + @with_lock + @override(dict) + def __delitem__(self, key: PolicyID): + # Make key invalid. + self._valid_keys.remove(key) + # Remove policy from deque if contained + if key in self._deque: + self._deque.remove(key) + # Remove policy from memory if currently cached. + if key in self.cache: + policy = self.cache[key] + self._close_session(policy) + del self.cache[key] + # Remove Ray object store reference (if this ID has already been stored + # there), so the item gets garbage collected. + if key in self._policy_state_refs: + del self._policy_state_refs[key] + + @override(dict) + def __iter__(self): + return iter(self.keys()) + + @override(dict) + def items(self): + """Iterates over all policies, even the stashed ones.""" + + def gen(): + for key in self._valid_keys: + yield (key, self[key]) + + return gen() + + @override(dict) + def keys(self): + """Returns all valid keys, even the stashed ones.""" + self._lock.acquire() + ks = list(self._valid_keys) + self._lock.release() + + def gen(): + for key in ks: + yield key + + return gen() + + @override(dict) + def values(self): + """Returns all valid values, even the stashed ones.""" + self._lock.acquire() + vs = [self[k] for k in self._valid_keys] + self._lock.release() + + def gen(): + for value in vs: + yield value + + return gen() + + @with_lock + @override(dict) + def update(self, __m, **kwargs): + """Updates the map with the given dict and/or kwargs.""" + for k, v in __m.items(): + self[k] = v + for k, v in kwargs.items(): + self[k] = v + + @with_lock + @override(dict) + def get(self, key: PolicyID): + """Returns the value for the given key or None if not found.""" + if key not in self._valid_keys: + return None + return self[key] + + @with_lock + @override(dict) + def __len__(self) -> int: + """Returns number of all policies, including the stashed-to-disk ones.""" + return len(self._valid_keys) + + @with_lock + @override(dict) + def __contains__(self, item: PolicyID): + return item in self._valid_keys + + @override(dict) + def __str__(self) -> str: + # Only print out our keys (policy IDs), not values as this could trigger + # the LRU caching. + return ( + f"" + ) + + def _stash_least_used_policy(self) -> Policy: + """Writes the least-recently used policy's state to the Ray object store. + + Also closes the session - if applicable - of the stashed policy. + + Returns: + The least-recently used policy, that just got removed from the cache. + """ + # Get policy's state for writing to object store. + dropped_policy_id = self._deque.popleft() + assert dropped_policy_id in self.cache + policy = self.cache[dropped_policy_id] + policy_state = policy.get_state() + + # If we don't simply swap out vs an existing policy: + # Close the tf session, if any. + if not self.policy_states_are_swappable: + self._close_session(policy) + + # Remove from memory. This will clear the tf Graph as well. + del self.cache[dropped_policy_id] + + # Store state in Ray object store. + self._policy_state_refs[dropped_policy_id] = ray.put(policy_state) + + # Return the just removed policy, in case it's needed by the caller. + return policy + + @staticmethod + def _close_session(policy: Policy): + sess = policy.get_session() + # Closes the tf session, if any. + if sess is not None: + sess.close() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/policy_template.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/policy_template.py new file mode 100644 index 0000000000000000000000000000000000000000..18cfe5783b94acf562be4f32506d84b59a4fca88 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/policy_template.py @@ -0,0 +1,448 @@ +from typing import ( + Any, + Callable, + Dict, + List, + Optional, + Tuple, + Type, + Union, +) + +import gymnasium as gym + +from ray.rllib.models.catalog import ModelCatalog +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.torch.torch_action_dist import TorchDistributionWrapper +from ray.rllib.models.torch.torch_modelv2 import TorchModelV2 +from ray.rllib.policy.policy import Policy +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy.torch_policy import TorchPolicy +from ray.rllib.utils import add_mixins, NullContextManager +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.framework import try_import_torch, try_import_jax +from ray.rllib.utils.metrics.learner_info import LEARNER_STATS_KEY +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.typing import ModelGradients, TensorType, AlgorithmConfigDict + +jax, _ = try_import_jax() +torch, _ = try_import_torch() + + +@OldAPIStack +def build_policy_class( + name: str, + framework: str, + *, + loss_fn: Optional[ + Callable[ + [Policy, ModelV2, Type[TorchDistributionWrapper], SampleBatch], + Union[TensorType, List[TensorType]], + ] + ], + get_default_config: Optional[Callable[[], AlgorithmConfigDict]] = None, + stats_fn: Optional[Callable[[Policy, SampleBatch], Dict[str, TensorType]]] = None, + postprocess_fn: Optional[ + Callable[ + [ + Policy, + SampleBatch, + Optional[Dict[Any, SampleBatch]], + Optional[Any], + ], + SampleBatch, + ] + ] = None, + extra_action_out_fn: Optional[ + Callable[ + [ + Policy, + Dict[str, TensorType], + List[TensorType], + ModelV2, + TorchDistributionWrapper, + ], + Dict[str, TensorType], + ] + ] = None, + extra_grad_process_fn: Optional[ + Callable[[Policy, "torch.optim.Optimizer", TensorType], Dict[str, TensorType]] + ] = None, + # TODO: (sven) Replace "fetches" with "process". + extra_learn_fetches_fn: Optional[Callable[[Policy], Dict[str, TensorType]]] = None, + optimizer_fn: Optional[ + Callable[[Policy, AlgorithmConfigDict], "torch.optim.Optimizer"] + ] = None, + validate_spaces: Optional[ + Callable[[Policy, gym.Space, gym.Space, AlgorithmConfigDict], None] + ] = None, + before_init: Optional[ + Callable[[Policy, gym.Space, gym.Space, AlgorithmConfigDict], None] + ] = None, + before_loss_init: Optional[ + Callable[ + [Policy, gym.spaces.Space, gym.spaces.Space, AlgorithmConfigDict], None + ] + ] = None, + after_init: Optional[ + Callable[[Policy, gym.Space, gym.Space, AlgorithmConfigDict], None] + ] = None, + _after_loss_init: Optional[ + Callable[ + [Policy, gym.spaces.Space, gym.spaces.Space, AlgorithmConfigDict], None + ] + ] = None, + action_sampler_fn: Optional[ + Callable[[TensorType, List[TensorType]], Tuple[TensorType, TensorType]] + ] = None, + action_distribution_fn: Optional[ + Callable[ + [Policy, ModelV2, TensorType, TensorType, TensorType], + Tuple[TensorType, type, List[TensorType]], + ] + ] = None, + make_model: Optional[ + Callable[ + [Policy, gym.spaces.Space, gym.spaces.Space, AlgorithmConfigDict], ModelV2 + ] + ] = None, + make_model_and_action_dist: Optional[ + Callable[ + [Policy, gym.spaces.Space, gym.spaces.Space, AlgorithmConfigDict], + Tuple[ModelV2, Type[TorchDistributionWrapper]], + ] + ] = None, + compute_gradients_fn: Optional[ + Callable[[Policy, SampleBatch], Tuple[ModelGradients, dict]] + ] = None, + apply_gradients_fn: Optional[ + Callable[[Policy, "torch.optim.Optimizer"], None] + ] = None, + mixins: Optional[List[type]] = None, + get_batch_divisibility_req: Optional[Callable[[Policy], int]] = None, +) -> Type[TorchPolicy]: + """Helper function for creating a new Policy class at runtime. + + Supports frameworks JAX and PyTorch. + + Args: + name: name of the policy (e.g., "PPOTorchPolicy") + framework: Either "jax" or "torch". + loss_fn (Optional[Callable[[Policy, ModelV2, + Type[TorchDistributionWrapper], SampleBatch], Union[TensorType, + List[TensorType]]]]): Callable that returns a loss tensor. + get_default_config (Optional[Callable[[None], AlgorithmConfigDict]]): + Optional callable that returns the default config to merge with any + overrides. If None, uses only(!) the user-provided + PartialAlgorithmConfigDict as dict for this Policy. + postprocess_fn (Optional[Callable[[Policy, SampleBatch, + Optional[Dict[Any, SampleBatch]], Optional[Any]], + SampleBatch]]): Optional callable for post-processing experience + batches (called after the super's `postprocess_trajectory` method). + stats_fn (Optional[Callable[[Policy, SampleBatch], + Dict[str, TensorType]]]): Optional callable that returns a dict of + values given the policy and training batch. If None, + will use `TorchPolicy.extra_grad_info()` instead. The stats dict is + used for logging (e.g. in TensorBoard). + extra_action_out_fn (Optional[Callable[[Policy, Dict[str, TensorType], + List[TensorType], ModelV2, TorchDistributionWrapper]], Dict[str, + TensorType]]]): Optional callable that returns a dict of extra + values to include in experiences. If None, no extra computations + will be performed. + extra_grad_process_fn (Optional[Callable[[Policy, + "torch.optim.Optimizer", TensorType], Dict[str, TensorType]]]): + Optional callable that is called after gradients are computed and + returns a processing info dict. If None, will call the + `TorchPolicy.extra_grad_process()` method instead. + # TODO: (sven) dissolve naming mismatch between "learn" and "compute.." + extra_learn_fetches_fn (Optional[Callable[[Policy], + Dict[str, TensorType]]]): Optional callable that returns a dict of + extra tensors from the policy after loss evaluation. If None, + will call the `TorchPolicy.extra_compute_grad_fetches()` method + instead. + optimizer_fn (Optional[Callable[[Policy, AlgorithmConfigDict], + "torch.optim.Optimizer"]]): Optional callable that returns a + torch optimizer given the policy and config. If None, will call + the `TorchPolicy.optimizer()` method instead (which returns a + torch Adam optimizer). + validate_spaces (Optional[Callable[[Policy, gym.Space, gym.Space, + AlgorithmConfigDict], None]]): Optional callable that takes the + Policy, observation_space, action_space, and config to check for + correctness. If None, no spaces checking will be done. + before_init (Optional[Callable[[Policy, gym.Space, gym.Space, + AlgorithmConfigDict], None]]): Optional callable to run at the + beginning of `Policy.__init__` that takes the same arguments as + the Policy constructor. If None, this step will be skipped. + before_loss_init (Optional[Callable[[Policy, gym.spaces.Space, + gym.spaces.Space, AlgorithmConfigDict], None]]): Optional callable to + run prior to loss init. If None, this step will be skipped. + after_init (Optional[Callable[[Policy, gym.Space, gym.Space, + AlgorithmConfigDict], None]]): DEPRECATED: Use `before_loss_init` + instead. + _after_loss_init (Optional[Callable[[Policy, gym.spaces.Space, + gym.spaces.Space, AlgorithmConfigDict], None]]): Optional callable to + run after the loss init. If None, this step will be skipped. + This will be deprecated at some point and renamed into `after_init` + to match `build_tf_policy()` behavior. + action_sampler_fn (Optional[Callable[[TensorType, List[TensorType]], + Tuple[TensorType, TensorType]]]): Optional callable returning a + sampled action and its log-likelihood given some (obs and state) + inputs. If None, will either use `action_distribution_fn` or + compute actions by calling self.model, then sampling from the + so parameterized action distribution. + action_distribution_fn (Optional[Callable[[Policy, ModelV2, TensorType, + TensorType, TensorType], Tuple[TensorType, + Type[TorchDistributionWrapper], List[TensorType]]]]): A callable + that takes the Policy, Model, the observation batch, an + explore-flag, a timestep, and an is_training flag and returns a + tuple of a) distribution inputs (parameters), b) a dist-class to + generate an action distribution object from, and c) internal-state + outputs (empty list if not applicable). If None, will either use + `action_sampler_fn` or compute actions by calling self.model, + then sampling from the parameterized action distribution. + make_model (Optional[Callable[[Policy, gym.spaces.Space, + gym.spaces.Space, AlgorithmConfigDict], ModelV2]]): Optional callable + that takes the same arguments as Policy.__init__ and returns a + model instance. The distribution class will be determined + automatically. Note: Only one of `make_model` or + `make_model_and_action_dist` should be provided. If both are None, + a default Model will be created. + make_model_and_action_dist (Optional[Callable[[Policy, + gym.spaces.Space, gym.spaces.Space, AlgorithmConfigDict], + Tuple[ModelV2, Type[TorchDistributionWrapper]]]]): Optional + callable that takes the same arguments as Policy.__init__ and + returns a tuple of model instance and torch action distribution + class. + Note: Only one of `make_model` or `make_model_and_action_dist` + should be provided. If both are None, a default Model will be + created. + compute_gradients_fn (Optional[Callable[ + [Policy, SampleBatch], Tuple[ModelGradients, dict]]]): Optional + callable that the sampled batch an computes the gradients w.r. + to the loss function. + If None, will call the `TorchPolicy.compute_gradients()` method + instead. + apply_gradients_fn (Optional[Callable[[Policy, + "torch.optim.Optimizer"], None]]): Optional callable that + takes a grads list and applies these to the Model's parameters. + If None, will call the `TorchPolicy.apply_gradients()` method + instead. + mixins (Optional[List[type]]): Optional list of any class mixins for + the returned policy class. These mixins will be applied in order + and will have higher precedence than the TorchPolicy class. + get_batch_divisibility_req (Optional[Callable[[Policy], int]]): + Optional callable that returns the divisibility requirement for + sample batches. If None, will assume a value of 1. + + Returns: + Type[TorchPolicy]: TorchPolicy child class constructed from the + specified args. + """ + + original_kwargs = locals().copy() + parent_cls = TorchPolicy + base = add_mixins(parent_cls, mixins) + + class policy_cls(base): + def __init__(self, obs_space, action_space, config): + self.config = config + + # Set the DL framework for this Policy. + self.framework = self.config["framework"] = framework + + # Validate observation- and action-spaces. + if validate_spaces: + validate_spaces(self, obs_space, action_space, self.config) + + # Do some pre-initialization steps. + if before_init: + before_init(self, obs_space, action_space, self.config) + + # Model is customized (use default action dist class). + if make_model: + assert make_model_and_action_dist is None, ( + "Either `make_model` or `make_model_and_action_dist`" + " must be None!" + ) + self.model = make_model(self, obs_space, action_space, config) + dist_class, _ = ModelCatalog.get_action_dist( + action_space, self.config["model"], framework=framework + ) + # Model and action dist class are customized. + elif make_model_and_action_dist: + self.model, dist_class = make_model_and_action_dist( + self, obs_space, action_space, config + ) + # Use default model and default action dist. + else: + dist_class, logit_dim = ModelCatalog.get_action_dist( + action_space, self.config["model"], framework=framework + ) + self.model = ModelCatalog.get_model_v2( + obs_space=obs_space, + action_space=action_space, + num_outputs=logit_dim, + model_config=self.config["model"], + framework=framework, + ) + + # Make sure, we passed in a correct Model factory. + model_cls = TorchModelV2 + assert isinstance( + self.model, model_cls + ), "ERROR: Generated Model must be a TorchModelV2 object!" + + # Call the framework-specific Policy constructor. + self.parent_cls = parent_cls + self.parent_cls.__init__( + self, + observation_space=obs_space, + action_space=action_space, + config=config, + model=self.model, + loss=None if self.config["in_evaluation"] else loss_fn, + action_distribution_class=dist_class, + action_sampler_fn=action_sampler_fn, + action_distribution_fn=action_distribution_fn, + max_seq_len=config["model"]["max_seq_len"], + get_batch_divisibility_req=get_batch_divisibility_req, + ) + + # Merge Model's view requirements into Policy's. + self.view_requirements.update(self.model.view_requirements) + + _before_loss_init = before_loss_init or after_init + if _before_loss_init: + _before_loss_init( + self, self.observation_space, self.action_space, config + ) + + # Perform test runs through postprocessing- and loss functions. + self._initialize_loss_from_dummy_batch( + auto_remove_unneeded_view_reqs=True, + stats_fn=None if self.config["in_evaluation"] else stats_fn, + ) + + if _after_loss_init: + _after_loss_init(self, obs_space, action_space, config) + + # Got to reset global_timestep again after this fake run-through. + self.global_timestep = 0 + + @override(Policy) + def postprocess_trajectory( + self, sample_batch, other_agent_batches=None, episode=None + ): + # Do all post-processing always with no_grad(). + # Not using this here will introduce a memory leak + # in torch (issue #6962). + with self._no_grad_context(): + # Call super's postprocess_trajectory first. + sample_batch = super().postprocess_trajectory( + sample_batch, other_agent_batches, episode + ) + if postprocess_fn: + return postprocess_fn( + self, sample_batch, other_agent_batches, episode + ) + + return sample_batch + + @override(parent_cls) + def extra_grad_process(self, optimizer, loss): + """Called after optimizer.zero_grad() and loss.backward() calls. + + Allows for gradient processing before optimizer.step() is called. + E.g. for gradient clipping. + """ + if extra_grad_process_fn: + return extra_grad_process_fn(self, optimizer, loss) + else: + return parent_cls.extra_grad_process(self, optimizer, loss) + + @override(parent_cls) + def extra_compute_grad_fetches(self): + if extra_learn_fetches_fn: + fetches = convert_to_numpy(extra_learn_fetches_fn(self)) + # Auto-add empty learner stats dict if needed. + return dict({LEARNER_STATS_KEY: {}}, **fetches) + else: + return parent_cls.extra_compute_grad_fetches(self) + + @override(parent_cls) + def compute_gradients(self, batch): + if compute_gradients_fn: + return compute_gradients_fn(self, batch) + else: + return parent_cls.compute_gradients(self, batch) + + @override(parent_cls) + def apply_gradients(self, gradients): + if apply_gradients_fn: + apply_gradients_fn(self, gradients) + else: + parent_cls.apply_gradients(self, gradients) + + @override(parent_cls) + def extra_action_out(self, input_dict, state_batches, model, action_dist): + with self._no_grad_context(): + if extra_action_out_fn: + stats_dict = extra_action_out_fn( + self, input_dict, state_batches, model, action_dist + ) + else: + stats_dict = parent_cls.extra_action_out( + self, input_dict, state_batches, model, action_dist + ) + return self._convert_to_numpy(stats_dict) + + @override(parent_cls) + def optimizer(self): + if optimizer_fn: + optimizers = optimizer_fn(self, self.config) + else: + optimizers = parent_cls.optimizer(self) + return optimizers + + @override(parent_cls) + def extra_grad_info(self, train_batch): + with self._no_grad_context(): + if stats_fn: + stats_dict = stats_fn(self, train_batch) + else: + stats_dict = self.parent_cls.extra_grad_info(self, train_batch) + return self._convert_to_numpy(stats_dict) + + def _no_grad_context(self): + if self.framework == "torch": + return torch.no_grad() + return NullContextManager() + + def _convert_to_numpy(self, data): + if self.framework == "torch": + return convert_to_numpy(data) + return data + + def with_updates(**overrides): + """Creates a Torch|JAXPolicy cls based on settings of another one. + + Keyword Args: + **overrides: The settings (passed into `build_torch_policy`) that + should be different from the class that this method is called + on. + + Returns: + type: A new Torch|JAXPolicy sub-class. + + Examples: + >> MySpecialDQNPolicyClass = DQNTorchPolicy.with_updates( + .. name="MySpecialDQNPolicyClass", + .. loss_function=[some_new_loss_function], + .. ) + """ + return build_policy_class(**dict(original_kwargs, **overrides)) + + policy_cls.with_updates = staticmethod(with_updates) + policy_cls.__name__ = name + policy_cls.__qualname__ = name + return policy_cls diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/rnn_sequencing.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/rnn_sequencing.py new file mode 100644 index 0000000000000000000000000000000000000000..0f852261402c51c5f2a21ec560cdadfb5333790a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/rnn_sequencing.py @@ -0,0 +1,683 @@ +"""RNN utils for RLlib. + +The main trick here is that we add the time dimension at the last moment. +The non-LSTM layers of the model see their inputs as one flat batch. Before +the LSTM cell, we reshape the input to add the expected time dimension. During +postprocessing, we dynamically pad the experience batches so that this +reshaping is possible. + +Note that this padding strategy only works out if we assume zero inputs don't +meaningfully affect the loss function. This happens to be true for all the +current algorithms: https://github.com/ray-project/ray/issues/2992 +""" + +import logging +import numpy as np +import tree # pip install dm_tree +from typing import List, Optional +import functools + +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.debug import summarize +from ray.rllib.utils.framework import try_import_tf, try_import_torch +from ray.rllib.utils.typing import TensorType, ViewRequirementsDict +from ray.util import log_once +from ray.rllib.utils.typing import SampleBatchType + +tf1, tf, tfv = try_import_tf() +torch, _ = try_import_torch() + +logger = logging.getLogger(__name__) + + +@OldAPIStack +def pad_batch_to_sequences_of_same_size( + batch: SampleBatch, + max_seq_len: int, + shuffle: bool = False, + batch_divisibility_req: int = 1, + feature_keys: Optional[List[str]] = None, + view_requirements: Optional[ViewRequirementsDict] = None, + _enable_new_api_stack: bool = False, + padding: str = "zero", +): + """Applies padding to `batch` so it's choppable into same-size sequences. + + Shuffles `batch` (if desired), makes sure divisibility requirement is met, + then pads the batch ([B, ...]) into same-size chunks ([B, ...]) w/o + adding a time dimension (yet). + Padding depends on episodes found in batch and `max_seq_len`. + + Args: + batch: The SampleBatch object. All values in here have + the shape [B, ...]. + max_seq_len: The max. sequence length to use for chopping. + shuffle: Whether to shuffle batch sequences. Shuffle may + be done in-place. This only makes sense if you're further + applying minibatch SGD after getting the outputs. + batch_divisibility_req: The int by which the batch dimension + must be dividable. + feature_keys: An optional list of keys to apply sequence-chopping + to. If None, use all keys in batch that are not + "state_in/out_"-type keys. + view_requirements: An optional Policy ViewRequirements dict to + be able to infer whether e.g. dynamic max'ing should be + applied over the seq_lens. + _enable_new_api_stack: This is a temporary flag to enable the new RLModule API. + After a complete rollout of the new API, this flag will be removed. + padding: Padding type to use. Either "zero" or "last". Zero padding + will pad with zeros, last padding will pad with the last value. + """ + # If already zero-padded, skip. + if batch.zero_padded: + return + + batch.zero_padded = True + + if batch_divisibility_req > 1: + meets_divisibility_reqs = ( + len(batch[SampleBatch.CUR_OBS]) % batch_divisibility_req == 0 + # not multiagent + and max(batch[SampleBatch.AGENT_INDEX]) == 0 + ) + else: + meets_divisibility_reqs = True + + states_already_reduced_to_init = False + + # RNN/attention net case. Figure out whether we should apply dynamic + # max'ing over the list of sequence lengths. + if _enable_new_api_stack and ("state_in" in batch or "state_out" in batch): + # TODO (Kourosh): This is a temporary fix to enable the new RLModule API. + # We should think of a more elegant solution once we have confirmed that other + # parts of the API are stable and user-friendly. + seq_lens = batch.get(SampleBatch.SEQ_LENS) + + # state_in is a nested dict of tensors of states. We need to retreive the + # length of the inner most tensor (which should be already the same as the + # length of other tensors) and compare it to len(seq_lens). + state_ins = tree.flatten(batch["state_in"]) + if state_ins: + assert all( + len(state_in) == len(state_ins[0]) for state_in in state_ins + ), "All state_in tensors should have the same batch_dim size." + + # if the batch dim of states is the same as the number of sequences + if len(state_ins[0]) == len(seq_lens): + states_already_reduced_to_init = True + + # TODO (Kourosh): What is the use-case of DynamicMax functionality? + dynamic_max = True + else: + dynamic_max = False + + elif not _enable_new_api_stack and ( + "state_in_0" in batch or "state_out_0" in batch + ): + # Check, whether the state inputs have already been reduced to their + # init values at the beginning of each max_seq_len chunk. + if batch.get(SampleBatch.SEQ_LENS) is not None and len( + batch["state_in_0"] + ) == len(batch[SampleBatch.SEQ_LENS]): + states_already_reduced_to_init = True + + # RNN (or single timestep state-in): Set the max dynamically. + if view_requirements and view_requirements["state_in_0"].shift_from is None: + dynamic_max = True + # Attention Nets (state inputs are over some range): No dynamic maxing + # possible. + else: + dynamic_max = False + # Multi-agent case. + elif not meets_divisibility_reqs: + max_seq_len = batch_divisibility_req + dynamic_max = False + batch.max_seq_len = max_seq_len + # Simple case: No RNN/attention net, nor do we need to pad. + else: + if shuffle: + batch.shuffle() + return + + # RNN, attention net, or multi-agent case. + state_keys = [] + feature_keys_ = feature_keys or [] + for k, v in batch.items(): + if k.startswith("state_in"): + state_keys.append(k) + elif ( + not feature_keys + and (not k.startswith("state_out") if not _enable_new_api_stack else True) + and k not in [SampleBatch.SEQ_LENS] + ): + feature_keys_.append(k) + feature_sequences, initial_states, seq_lens = chop_into_sequences( + feature_columns=[batch[k] for k in feature_keys_], + state_columns=[batch[k] for k in state_keys], + episode_ids=batch.get(SampleBatch.EPS_ID), + unroll_ids=batch.get(SampleBatch.UNROLL_ID), + agent_indices=batch.get(SampleBatch.AGENT_INDEX), + seq_lens=batch.get(SampleBatch.SEQ_LENS), + max_seq_len=max_seq_len, + dynamic_max=dynamic_max, + states_already_reduced_to_init=states_already_reduced_to_init, + shuffle=shuffle, + handle_nested_data=True, + padding=padding, + pad_infos_with_empty_dicts=_enable_new_api_stack, + ) + for i, k in enumerate(feature_keys_): + batch[k] = tree.unflatten_as(batch[k], feature_sequences[i]) + for i, k in enumerate(state_keys): + batch[k] = initial_states[i] + batch[SampleBatch.SEQ_LENS] = np.array(seq_lens) + if dynamic_max: + batch.max_seq_len = max(seq_lens) + + if log_once("rnn_ma_feed_dict"): + logger.info( + "Padded input for RNN/Attn.Nets/MA:\n\n{}\n".format( + summarize( + { + "features": feature_sequences, + "initial_states": initial_states, + "seq_lens": seq_lens, + "max_seq_len": max_seq_len, + } + ) + ) + ) + + +@OldAPIStack +def add_time_dimension( + padded_inputs: TensorType, + *, + seq_lens: TensorType, + framework: str = "tf", + time_major: bool = False, +): + """Adds a time dimension to padded inputs. + + Args: + padded_inputs: a padded batch of sequences. That is, + for seq_lens=[1, 2, 2], then inputs=[A, *, B, B, C, C], where + A, B, C are sequence elements and * denotes padding. + seq_lens: A 1D tensor of sequence lengths, denoting the non-padded length + in timesteps of each rollout in the batch. + framework: The framework string ("tf2", "tf", "torch"). + time_major: Whether data should be returned in time-major (TxB) + format or not (BxT). + + Returns: + TensorType: Reshaped tensor of shape [B, T, ...] or [T, B, ...]. + """ + + # Sequence lengths have to be specified for LSTM batch inputs. The + # input batch must be padded to the max seq length given here. That is, + # batch_size == len(seq_lens) * max(seq_lens) + if framework in ["tf2", "tf"]: + assert time_major is False, "time-major not supported yet for tf!" + padded_inputs = tf.convert_to_tensor(padded_inputs) + padded_batch_size = tf.shape(padded_inputs)[0] + # Dynamically reshape the padded batch to introduce a time dimension. + new_batch_size = tf.shape(seq_lens)[0] + time_size = padded_batch_size // new_batch_size + new_shape = tf.concat( + [ + tf.expand_dims(new_batch_size, axis=0), + tf.expand_dims(time_size, axis=0), + tf.shape(padded_inputs)[1:], + ], + axis=0, + ) + return tf.reshape(padded_inputs, new_shape) + elif framework == "torch": + padded_inputs = torch.as_tensor(padded_inputs) + padded_batch_size = padded_inputs.shape[0] + + # Dynamically reshape the padded batch to introduce a time dimension. + new_batch_size = seq_lens.shape[0] + time_size = padded_batch_size // new_batch_size + batch_major_shape = (new_batch_size, time_size) + padded_inputs.shape[1:] + padded_outputs = padded_inputs.view(batch_major_shape) + + if time_major: + # Swap the batch and time dimensions + padded_outputs = padded_outputs.transpose(0, 1) + return padded_outputs + else: + assert framework == "np", "Unknown framework: {}".format(framework) + padded_inputs = np.asarray(padded_inputs) + padded_batch_size = padded_inputs.shape[0] + + # Dynamically reshape the padded batch to introduce a time dimension. + new_batch_size = seq_lens.shape[0] + time_size = padded_batch_size // new_batch_size + batch_major_shape = (new_batch_size, time_size) + padded_inputs.shape[1:] + padded_outputs = padded_inputs.reshape(batch_major_shape) + + if time_major: + # Swap the batch and time dimensions + padded_outputs = padded_outputs.transpose(0, 1) + return padded_outputs + + +@OldAPIStack +def chop_into_sequences( + *, + feature_columns, + state_columns, + max_seq_len, + episode_ids=None, + unroll_ids=None, + agent_indices=None, + dynamic_max=True, + shuffle=False, + seq_lens=None, + states_already_reduced_to_init=False, + handle_nested_data=False, + _extra_padding=0, + padding: str = "zero", + pad_infos_with_empty_dicts: bool = False, +): + """Truncate and pad experiences into fixed-length sequences. + + Args: + feature_columns: List of arrays containing features. + state_columns: List of arrays containing LSTM state values. + max_seq_len: Max length of sequences. Sequences longer than max_seq_len + will be split into subsequences that span the batch dimension + and sum to max_seq_len. + episode_ids (List[EpisodeID]): List of episode ids for each step. + unroll_ids (List[UnrollID]): List of identifiers for the sample batch. + This is used to make sure sequences are cut between sample batches. + agent_indices (List[AgentID]): List of agent ids for each step. Note + that this has to be combined with episode_ids for uniqueness. + dynamic_max: Whether to dynamically shrink the max seq len. + For example, if max len is 20 and the actual max seq len in the + data is 7, it will be shrunk to 7. + shuffle: Whether to shuffle the sequence outputs. + handle_nested_data: If True, assume that the data in + `feature_columns` could be nested structures (of data). + If False, assumes that all items in `feature_columns` are + only np.ndarrays (no nested structured of np.ndarrays). + _extra_padding: Add extra padding to the end of sequences. + padding: Padding type to use. Either "zero" or "last". Zero padding + will pad with zeros, last padding will pad with the last value. + pad_infos_with_empty_dicts: If True, will zero-pad INFOs with empty + dicts (instead of None). Used by the new API stack in the meantime, + however, as soon as the new ConnectorV2 API will be activated (as + part of the new API stack), we will no longer use this utility function + anyway. + + Returns: + f_pad: Padded feature columns. These will be of shape + [NUM_SEQUENCES * MAX_SEQ_LEN, ...]. + s_init: Initial states for each sequence, of shape + [NUM_SEQUENCES, ...]. + seq_lens: List of sequence lengths, of shape [NUM_SEQUENCES]. + + .. testcode:: + :skipif: True + + from ray.rllib.policy.rnn_sequencing import chop_into_sequences + f_pad, s_init, seq_lens = chop_into_sequences( + episode_ids=[1, 1, 5, 5, 5, 5], + unroll_ids=[4, 4, 4, 4, 4, 4], + agent_indices=[0, 0, 0, 0, 0, 0], + feature_columns=[[4, 4, 8, 8, 8, 8], + [1, 1, 0, 1, 1, 0]], + state_columns=[[4, 5, 4, 5, 5, 5]], + max_seq_len=3) + print(f_pad) + print(s_init) + print(seq_lens) + + + .. testoutput:: + + [[4, 4, 0, 8, 8, 8, 8, 0, 0], + [1, 1, 0, 0, 1, 1, 0, 0, 0]] + [[4, 4, 5]] + [2, 3, 1] + """ + + if seq_lens is None or len(seq_lens) == 0: + prev_id = None + seq_lens = [] + seq_len = 0 + unique_ids = np.add( + np.add(episode_ids, agent_indices), + np.array(unroll_ids, dtype=np.int64) << 32, + ) + for uid in unique_ids: + if (prev_id is not None and uid != prev_id) or seq_len >= max_seq_len: + seq_lens.append(seq_len) + seq_len = 0 + seq_len += 1 + prev_id = uid + if seq_len: + seq_lens.append(seq_len) + seq_lens = np.array(seq_lens, dtype=np.int32) + + # Dynamically shrink max len as needed to optimize memory usage + if dynamic_max: + max_seq_len = max(seq_lens) + _extra_padding + + length = len(seq_lens) * max_seq_len + + feature_sequences = [] + for col in feature_columns: + if isinstance(col, list): + col = np.array(col) + feature_sequences.append([]) + + for f in tree.flatten(col): + # Save unnecessary copy. + if not isinstance(f, np.ndarray): + f = np.array(f) + + # New stack behavior (temporarily until we move to ConnectorV2 API, where + # this (admitedly convoluted) function will no longer be used at all). + if ( + f.dtype == object + and pad_infos_with_empty_dicts + and isinstance(f[0], dict) + ): + f_pad = [{} for _ in range(length)] + # Old stack behavior: Pad INFOs with None. + elif f.dtype == object or f.dtype.type is np.str_: + f_pad = [None] * length + # Pad everything else with zeros. + else: + # Make sure type doesn't change. + f_pad = np.zeros((length,) + np.shape(f)[1:], dtype=f.dtype) + seq_base = 0 + i = 0 + for len_ in seq_lens: + for seq_offset in range(len_): + f_pad[seq_base + seq_offset] = f[i] + i += 1 + + if padding == "last": + for seq_offset in range(len_, max_seq_len): + f_pad[seq_base + seq_offset] = f[i - 1] + + seq_base += max_seq_len + + assert i == len(f), f + feature_sequences[-1].append(f_pad) + + if states_already_reduced_to_init: + initial_states = state_columns + else: + initial_states = [] + for state_column in state_columns: + if isinstance(state_column, list): + state_column = np.array(state_column) + initial_state_flat = [] + # state_column may have a nested structure (e.g. LSTM state). + for s in tree.flatten(state_column): + # Skip unnecessary copy. + if not isinstance(s, np.ndarray): + s = np.array(s) + s_init = [] + i = 0 + for len_ in seq_lens: + s_init.append(s[i]) + i += len_ + initial_state_flat.append(np.array(s_init)) + initial_states.append(tree.unflatten_as(state_column, initial_state_flat)) + + if shuffle: + permutation = np.random.permutation(len(seq_lens)) + for i, f in enumerate(tree.flatten(feature_sequences)): + orig_shape = f.shape + f = np.reshape(f, (len(seq_lens), -1) + f.shape[1:]) + f = f[permutation] + f = np.reshape(f, orig_shape) + feature_sequences[i] = f + for i, s in enumerate(initial_states): + s = s[permutation] + initial_states[i] = s + seq_lens = seq_lens[permutation] + + # Classic behavior: Don't assume data in feature_columns are nested + # structs. Don't return them as flattened lists, but as is (index 0). + if not handle_nested_data: + feature_sequences = [f[0] for f in feature_sequences] + + return feature_sequences, initial_states, seq_lens + + +@OldAPIStack +def timeslice_along_seq_lens_with_overlap( + sample_batch: SampleBatchType, + seq_lens: Optional[List[int]] = None, + zero_pad_max_seq_len: int = 0, + pre_overlap: int = 0, + zero_init_states: bool = True, +) -> List["SampleBatch"]: + """Slices batch along `seq_lens` (each seq-len item produces one batch). + + Args: + sample_batch: The SampleBatch to timeslice. + seq_lens (Optional[List[int]]): An optional list of seq_lens to slice + at. If None, use `sample_batch[SampleBatch.SEQ_LENS]`. + zero_pad_max_seq_len: If >0, already zero-pad the resulting + slices up to this length. NOTE: This max-len will include the + additional timesteps gained via setting pre_overlap (see Example). + pre_overlap: If >0, will overlap each two consecutive slices by + this many timesteps (toward the left side). This will cause + zero-padding at the very beginning of the batch. + zero_init_states: Whether initial states should always be + zero'd. If False, will use the state_outs of the batch to + populate state_in values. + + Returns: + List[SampleBatch]: The list of (new) SampleBatches. + + Examples: + assert seq_lens == [5, 5, 2] + assert sample_batch.count == 12 + # self = 0 1 2 3 4 | 5 6 7 8 9 | 10 11 <- timesteps + slices = timeslice_along_seq_lens_with_overlap( + sample_batch=sample_batch. + zero_pad_max_seq_len=10, + pre_overlap=3) + # Z = zero padding (at beginning or end). + # |pre (3)| seq | max-seq-len (up to 10) + # slices[0] = | Z Z Z | 0 1 2 3 4 | Z Z + # slices[1] = | 2 3 4 | 5 6 7 8 9 | Z Z + # slices[2] = | 7 8 9 | 10 11 Z Z Z | Z Z + # Note that `zero_pad_max_seq_len=10` includes the 3 pre-overlaps + # count (makes sure each slice has exactly length 10). + """ + if seq_lens is None: + seq_lens = sample_batch.get(SampleBatch.SEQ_LENS) + else: + if sample_batch.get(SampleBatch.SEQ_LENS) is not None and log_once( + "overriding_sequencing_information" + ): + logger.warning( + "Found sequencing information in a batch that will be " + "ignored when slicing. Ignore this warning if you know " + "what you are doing." + ) + + if seq_lens is None: + max_seq_len = zero_pad_max_seq_len - pre_overlap + if log_once("no_sequence_lengths_available_for_time_slicing"): + logger.warning( + "Trying to slice a batch along sequences without " + "sequence lengths being provided in the batch. Batch will " + "be sliced into slices of size " + "{} = {} - {} = zero_pad_max_seq_len - pre_overlap.".format( + max_seq_len, zero_pad_max_seq_len, pre_overlap + ) + ) + num_seq_lens, last_seq_len = divmod(len(sample_batch), max_seq_len) + seq_lens = [zero_pad_max_seq_len] * num_seq_lens + ( + [last_seq_len] if last_seq_len else [] + ) + + assert ( + seq_lens is not None and len(seq_lens) > 0 + ), "Cannot timeslice along `seq_lens` when `seq_lens` is empty or None!" + # Generate n slices based on seq_lens. + start = 0 + slices = [] + for seq_len in seq_lens: + pre_begin = start - pre_overlap + slice_begin = start + end = start + seq_len + slices.append((pre_begin, slice_begin, end)) + start += seq_len + + timeslices = [] + for begin, slice_begin, end in slices: + zero_length = None + data_begin = 0 + zero_init_states_ = zero_init_states + if begin < 0: + zero_length = pre_overlap + data_begin = slice_begin + zero_init_states_ = True + else: + eps_ids = sample_batch[SampleBatch.EPS_ID][begin if begin >= 0 else 0 : end] + is_last_episode_ids = eps_ids == eps_ids[-1] + if not is_last_episode_ids[0]: + zero_length = int(sum(1.0 - is_last_episode_ids)) + data_begin = begin + zero_length + zero_init_states_ = True + + if zero_length is not None: + data = { + k: np.concatenate( + [ + np.zeros(shape=(zero_length,) + v.shape[1:], dtype=v.dtype), + v[data_begin:end], + ] + ) + for k, v in sample_batch.items() + if k != SampleBatch.SEQ_LENS + } + else: + data = { + k: v[begin:end] + for k, v in sample_batch.items() + if k != SampleBatch.SEQ_LENS + } + + if zero_init_states_: + i = 0 + key = "state_in_{}".format(i) + while key in data: + data[key] = np.zeros_like(sample_batch[key][0:1]) + # Del state_out_n from data if exists. + data.pop("state_out_{}".format(i), None) + i += 1 + key = "state_in_{}".format(i) + # TODO: This will not work with attention nets as their state_outs are + # not compatible with state_ins. + else: + i = 0 + key = "state_in_{}".format(i) + while key in data: + data[key] = sample_batch["state_out_{}".format(i)][begin - 1 : begin] + del data["state_out_{}".format(i)] + i += 1 + key = "state_in_{}".format(i) + + timeslices.append(SampleBatch(data, seq_lens=[end - begin])) + + # Zero-pad each slice if necessary. + if zero_pad_max_seq_len > 0: + for ts in timeslices: + ts.right_zero_pad(max_seq_len=zero_pad_max_seq_len, exclude_states=True) + + return timeslices + + +@OldAPIStack +def get_fold_unfold_fns(b_dim: int, t_dim: int, framework: str): + """Produces two functions to fold/unfold any Tensors in a struct. + + Args: + b_dim: The batch dimension to use for folding. + t_dim: The time dimension to use for folding. + framework: The framework to use for folding. One of "tf2" or "torch". + + Returns: + fold: A function that takes a struct of torch.Tensors and reshapes + them to have a first dimension of `b_dim * t_dim`. + unfold: A function that takes a struct of torch.Tensors and reshapes + them to have a first dimension of `b_dim` and a second dimension + of `t_dim`. + """ + if framework in "tf2": + # TensorFlow traced eager complains if we don't convert these to tensors here + b_dim = tf.convert_to_tensor(b_dim) + t_dim = tf.convert_to_tensor(t_dim) + + def fold_mapping(item): + if item is None: + # Torch has no representation for `None`, so we return None + return item + item = tf.convert_to_tensor(item) + shape = tf.shape(item) + other_dims = shape[2:] + return tf.reshape(item, tf.concat([[b_dim * t_dim], other_dims], axis=0)) + + def unfold_mapping(item): + if item is None: + return item + item = tf.convert_to_tensor(item) + shape = item.shape + other_dims = shape[1:] + + return tf.reshape(item, tf.concat([[b_dim], [t_dim], other_dims], axis=0)) + + elif framework == "torch": + + def fold_mapping(item): + if item is None: + # Torch has no representation for `None`, so we return None + return item + item = torch.as_tensor(item) + size = list(item.size()) + current_b_dim, current_t_dim = list(size[:2]) + + assert (b_dim, t_dim) == (current_b_dim, current_t_dim), ( + "All tensors in the struct must have the same batch and time " + "dimensions. Got {} and {}.".format( + (b_dim, t_dim), (current_b_dim, current_t_dim) + ) + ) + + other_dims = size[2:] + return item.reshape([b_dim * t_dim] + other_dims) + + def unfold_mapping(item): + if item is None: + return item + item = torch.as_tensor(item) + size = list(item.size()) + current_b_dim = size[0] + other_dims = size[1:] + assert current_b_dim == b_dim * t_dim, ( + "The first dimension of the tensor must be equal to the product of " + "the desired batch and time dimensions. Got {} and {}.".format( + current_b_dim, b_dim * t_dim + ) + ) + return item.reshape([b_dim, t_dim] + other_dims) + + else: + raise ValueError(f"framework {framework} not implemented!") + + return functools.partial(tree.map_structure, fold_mapping), functools.partial( + tree.map_structure, unfold_mapping + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/sample_batch.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/sample_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..558140da82390432f455074eba6f021b6680b8a7 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/sample_batch.py @@ -0,0 +1,1844 @@ +import collections +from functools import partial +import itertools +import sys +from numbers import Number +from typing import Dict, Iterator, Set, Union +from typing import List, Optional + +import numpy as np +import tree # pip install dm_tree + +from ray.rllib.core.columns import Columns +from ray.rllib.utils.annotations import DeveloperAPI, ExperimentalAPI, PublicAPI +from ray.rllib.utils.compression import pack, unpack, is_compressed +from ray.rllib.utils.deprecation import Deprecated, deprecation_warning +from ray.rllib.utils.framework import try_import_tf, try_import_torch +from ray.rllib.utils.torch_utils import convert_to_torch_tensor +from ray.rllib.utils.typing import ( + ModuleID, + PolicyID, + TensorType, + SampleBatchType, + ViewRequirementsDict, +) +from ray.util import log_once + +tf1, tf, tfv = try_import_tf() +torch, _ = try_import_torch() + +# Default policy id for single agent environments +DEFAULT_POLICY_ID = "default_policy" + + +@DeveloperAPI +def attempt_count_timesteps(tensor_dict: dict): + """Attempt to count timesteps based on dimensions of individual elements. + + Returns the first successfully counted number of timesteps. + We do not attempt to count on INFOS or any state_in_* and state_out_* keys. The + number of timesteps we count in cases where we are unable to count is zero. + + Args: + tensor_dict: A SampleBatch or another dict. + + Returns: + count: The inferred number of timesteps >= 0. + """ + # Try to infer the "length" of the SampleBatch by finding the first + # value that is actually a ndarray/tensor. + # Skip manual counting routine if we can directly infer count from sequence lengths + seq_lens = tensor_dict.get(SampleBatch.SEQ_LENS) + if ( + seq_lens is not None + and not (tf and tf.is_tensor(seq_lens) and not hasattr(seq_lens, "numpy")) + and len(seq_lens) > 0 + ): + if torch and torch.is_tensor(seq_lens): + return int(seq_lens.sum().item()) + else: + return int(sum(seq_lens)) + + for k, v in tensor_dict.items(): + if k == SampleBatch.SEQ_LENS: + continue + + assert isinstance(k, str), tensor_dict + + if ( + k == SampleBatch.INFOS + or k.startswith("state_in_") + or k.startswith("state_out_") + ): + # Don't attempt to count on infos since we make no assumptions + # about its content + # Don't attempt to count on state since nesting can potentially mess + # things up + continue + + # If this is a nested dict (for example a nested observation), + # try to flatten it, assert that all elements have the same length (batch + # dimension) + v_list = tree.flatten(v) if isinstance(v, (dict, tuple)) else [v] + # TODO: Drop support for lists and Numbers as values. + # If v_list contains lists or Numbers, convert them to arrays, too. + v_list = [ + np.array(_v) if isinstance(_v, (Number, list)) else _v for _v in v_list + ] + try: + # Add one of the elements' length, since they are all the same + _len = len(v_list[0]) + if _len: + return _len + except Exception: + pass + + # Return zero if we are unable to count + return 0 + + +@PublicAPI +class SampleBatch(dict): + """Wrapper around a dictionary with string keys and array-like values. + + For example, {"obs": [1, 2, 3], "reward": [0, -1, 1]} is a batch of three + samples, each with an "obs" and "reward" attribute. + """ + + # On rows in SampleBatch: + # Each comment signifies how values relate to each other within a given row. + # A row generally signifies one timestep. Most importantly, at t=0, SampleBatch.OBS + # will usually be the reset-observation, while SampleBatch.ACTIONS will be the + # action based on the reset-observation and so on. This scheme is derived from + # RLlib's sampling logic. + + # The following fields have all been moved to `Columns` and are only left here + # for backward compatibility. + OBS = Columns.OBS + ACTIONS = Columns.ACTIONS + REWARDS = Columns.REWARDS + TERMINATEDS = Columns.TERMINATEDS + TRUNCATEDS = Columns.TRUNCATEDS + INFOS = Columns.INFOS + SEQ_LENS = Columns.SEQ_LENS + T = Columns.T + ACTION_DIST_INPUTS = Columns.ACTION_DIST_INPUTS + ACTION_PROB = Columns.ACTION_PROB + ACTION_LOGP = Columns.ACTION_LOGP + VF_PREDS = Columns.VF_PREDS + VALUES_BOOTSTRAPPED = Columns.VALUES_BOOTSTRAPPED + EPS_ID = Columns.EPS_ID + NEXT_OBS = Columns.NEXT_OBS + + # Action distribution object. + ACTION_DIST = "action_dist" + # Action chosen before SampleBatch.ACTIONS. + PREV_ACTIONS = "prev_actions" + # Reward received before SampleBatch.REWARDS. + PREV_REWARDS = "prev_rewards" + ENV_ID = "env_id" # An env ID (e.g. the index for a vectorized sub-env). + AGENT_INDEX = "agent_index" # Uniquely identifies an agent within an episode. + # Uniquely identifies a sample batch. This is important to distinguish RNN + # sequences from the same episode when multiple sample batches are + # concatenated (fusing sequences across batches can be unsafe). + UNROLL_ID = "unroll_id" + + # RE 3 + # This is only computed and used when RE3 exploration strategy is enabled. + OBS_EMBEDS = "obs_embeds" + # Decision Transformer + RETURNS_TO_GO = "returns_to_go" + ATTENTION_MASKS = "attention_masks" + # Do not set this key directly. Instead, the values under this key are + # auto-computed via the values of the TERMINATEDS and TRUNCATEDS keys. + DONES = "dones" + # Use SampleBatch.OBS instead. + CUR_OBS = "obs" + + @PublicAPI + def __init__(self, *args, **kwargs): + """Constructs a sample batch (same params as dict constructor). + + Note: All args and those kwargs not listed below will be passed + as-is to the parent dict constructor. + + Args: + _time_major: Whether data in this sample batch + is time-major. This is False by default and only relevant + if the data contains sequences. + _max_seq_len: The max sequence chunk length + if the data contains sequences. + _zero_padded: Whether the data in this batch + contains sequences AND these sequences are right-zero-padded + according to the `_max_seq_len` setting. + _is_training: Whether this batch is used for + training. If False, batch may be used for e.g. action + computations (inference). + """ + + if SampleBatch.DONES in kwargs: + raise KeyError( + "SampleBatch cannot be constructed anymore with a `DONES` key! " + "Instead, set the new TERMINATEDS and TRUNCATEDS keys. The values under" + " DONES will then be automatically computed using terminated|truncated." + ) + + # Possible seq_lens (TxB or BxT) setup. + self.time_major = kwargs.pop("_time_major", None) + # Maximum seq len value. + self.max_seq_len = kwargs.pop("_max_seq_len", None) + # Is alredy right-zero-padded? + self.zero_padded = kwargs.pop("_zero_padded", False) + # Whether this batch is used for training (vs inference). + self._is_training = kwargs.pop("_is_training", None) + # Weighted average number of grad updates that have been performed on the + # policy/ies that were used to collect this batch. + # E.g.: Two rollout workers collect samples of 50ts each + # (rollout_fragment_length=50). One of them has a policy that has undergone + # 2 updates thus far, the other worker uses a policy that has undergone 3 + # updates thus far. The train batch size is 100, so we concatenate these 2 + # batches to a new one that's 100ts long. This new 100ts batch will have its + # `num_gradient_updates` property set to 2.5 as it's the weighted average + # (both original batches contribute 50%). + self.num_grad_updates: Optional[float] = kwargs.pop("_num_grad_updates", None) + + # Call super constructor. This will make the actual data accessible + # by column name (str) via e.g. self["some-col"]. + dict.__init__(self, *args, **kwargs) + + # Indicates whether, for this batch, sequence lengths should be slices by + # their index in the batch or by their index as a sequence. + # This is useful if a batch contains tensors of shape (B, T, ...), where each + # index of B indicates one sequence. In this case, when slicing the batch, + # we want one sequence to be slices out per index in B ( + # `_slice_seq_lens_by_batch_index=True`. However, if the padded batch + # contains tensors of shape (B*T, ...), where each index of B*T indicates + # one timestep, we want one sequence to be sliced per T steps in B*T ( + # `self._slice_seq_lens_in_B=False`). + # ._slice_seq_lens_in_B = True is only meant to be used for batches that we + # feed into Learner._update(), all other places in RLlib are not expected to + # need this. + self._slice_seq_lens_in_B = False + + self.accessed_keys = set() + self.added_keys = set() + self.deleted_keys = set() + self.intercepted_values = {} + self.get_interceptor = None + + # Clear out None seq-lens. + seq_lens_ = self.get(SampleBatch.SEQ_LENS) + if seq_lens_ is None or (isinstance(seq_lens_, list) and len(seq_lens_) == 0): + self.pop(SampleBatch.SEQ_LENS, None) + # Numpyfy seq_lens if list. + elif isinstance(seq_lens_, list): + self[SampleBatch.SEQ_LENS] = seq_lens_ = np.array(seq_lens_, dtype=np.int32) + elif (torch and torch.is_tensor(seq_lens_)) or (tf and tf.is_tensor(seq_lens_)): + self[SampleBatch.SEQ_LENS] = seq_lens_ + + if ( + self.max_seq_len is None + and seq_lens_ is not None + and not (tf and tf.is_tensor(seq_lens_)) + and len(seq_lens_) > 0 + ): + if torch and torch.is_tensor(seq_lens_): + self.max_seq_len = seq_lens_.max().item() + else: + self.max_seq_len = max(seq_lens_) + + if self._is_training is None: + self._is_training = self.pop("is_training", False) + + for k, v in self.items(): + # TODO: Drop support for lists and Numbers as values. + # Convert lists of int|float into numpy arrays make sure all data + # has same length. + if isinstance(v, (Number, list)) and not k == SampleBatch.INFOS: + self[k] = np.array(v) + + self.count = attempt_count_timesteps(self) + + # A convenience map for slicing this batch into sub-batches along + # the time axis. This helps reduce repeated iterations through the + # batch's seq_lens array to find good slicing points. Built lazily + # when needed. + self._slice_map = [] + + @PublicAPI + def __len__(self) -> int: + """Returns the amount of samples in the sample batch.""" + return self.count + + @PublicAPI + def agent_steps(self) -> int: + """Returns the same as len(self) (number of steps in this batch). + + To make this compatible with `MultiAgentBatch.agent_steps()`. + """ + return len(self) + + @PublicAPI + def env_steps(self) -> int: + """Returns the same as len(self) (number of steps in this batch). + + To make this compatible with `MultiAgentBatch.env_steps()`. + """ + return len(self) + + @DeveloperAPI + def enable_slicing_by_batch_id(self): + self._slice_seq_lens_in_B = True + + @DeveloperAPI + def disable_slicing_by_batch_id(self): + self._slice_seq_lens_in_B = False + + @ExperimentalAPI + def is_terminated_or_truncated(self) -> bool: + """Returns True if `self` is either terminated or truncated at idx -1.""" + return self[SampleBatch.TERMINATEDS][-1] or ( + SampleBatch.TRUNCATEDS in self and self[SampleBatch.TRUNCATEDS][-1] + ) + + @ExperimentalAPI + def is_single_trajectory(self) -> bool: + """Returns True if this SampleBatch only contains one trajectory. + + This is determined by checking all timesteps (except for the last) for being + not terminated AND (if applicable) not truncated. + """ + return not any(self[SampleBatch.TERMINATEDS][:-1]) and ( + SampleBatch.TRUNCATEDS not in self + or not any(self[SampleBatch.TRUNCATEDS][:-1]) + ) + + @staticmethod + @PublicAPI + @Deprecated(new="concat_samples() from rllib.policy.sample_batch", error=True) + def concat_samples(samples): + pass + + @PublicAPI + def concat(self, other: "SampleBatch") -> "SampleBatch": + """Concatenates `other` to this one and returns a new SampleBatch. + + Args: + other: The other SampleBatch object to concat to this one. + + Returns: + The new SampleBatch, resulting from concating `other` to `self`. + + .. testcode:: + :skipif: True + + import numpy as np + from ray.rllib.policy.sample_batch import SampleBatch + b1 = SampleBatch({"a": np.array([1, 2])}) + b2 = SampleBatch({"a": np.array([3, 4, 5])}) + print(b1.concat(b2)) + + .. testoutput:: + + {"a": np.array([1, 2, 3, 4, 5])} + """ + return concat_samples([self, other]) + + @PublicAPI + def copy(self, shallow: bool = False) -> "SampleBatch": + """Creates a deep or shallow copy of this SampleBatch and returns it. + + Args: + shallow: Whether the copying should be done shallowly. + + Returns: + A deep or shallow copy of this SampleBatch object. + """ + copy_ = dict(self) + data = tree.map_structure( + lambda v: ( + np.array(v, copy=not shallow) if isinstance(v, np.ndarray) else v + ), + copy_, + ) + copy_ = SampleBatch( + data, + _time_major=self.time_major, + _zero_padded=self.zero_padded, + _max_seq_len=self.max_seq_len, + _num_grad_updates=self.num_grad_updates, + ) + copy_.set_get_interceptor(self.get_interceptor) + copy_.added_keys = self.added_keys + copy_.deleted_keys = self.deleted_keys + copy_.accessed_keys = self.accessed_keys + return copy_ + + @PublicAPI + def rows(self) -> Iterator[Dict[str, TensorType]]: + """Returns an iterator over data rows, i.e. dicts with column values. + + Note that if `seq_lens` is set in self, we set it to 1 in the rows. + + Yields: + The column values of the row in this iteration. + + .. testcode:: + :skipif: True + + from ray.rllib.policy.sample_batch import SampleBatch + batch = SampleBatch({ + "a": [1, 2, 3], + "b": [4, 5, 6], + "seq_lens": [1, 2] + }) + for row in batch.rows(): + print(row) + + .. testoutput:: + + {"a": 1, "b": 4, "seq_lens": 1} + {"a": 2, "b": 5, "seq_lens": 1} + {"a": 3, "b": 6, "seq_lens": 1} + """ + + seq_lens = None if self.get(SampleBatch.SEQ_LENS, 1) is None else 1 + + self_as_dict = dict(self) + + for i in range(self.count): + yield tree.map_structure_with_path( + lambda p, v, i=i: v[i] if p[0] != self.SEQ_LENS else seq_lens, + self_as_dict, + ) + + @PublicAPI + def columns(self, keys: List[str]) -> List[any]: + """Returns a list of the batch-data in the specified columns. + + Args: + keys: List of column names fo which to return the data. + + Returns: + The list of data items ordered by the order of column + names in `keys`. + + .. testcode:: + :skipif: True + + from ray.rllib.policy.sample_batch import SampleBatch + batch = SampleBatch({"a": [1], "b": [2], "c": [3]}) + print(batch.columns(["a", "b"])) + + .. testoutput:: + + [[1], [2]] + """ + + # TODO: (sven) Make this work for nested data as well. + out = [] + for k in keys: + out.append(self[k]) + return out + + @PublicAPI + def shuffle(self) -> "SampleBatch": + """Shuffles the rows of this batch in-place. + + Returns: + This very (now shuffled) SampleBatch. + + Raises: + ValueError: If self[SampleBatch.SEQ_LENS] is defined. + + .. testcode:: + :skipif: True + + from ray.rllib.policy.sample_batch import SampleBatch + batch = SampleBatch({"a": [1, 2, 3, 4]}) + print(batch.shuffle()) + + .. testoutput:: + + {"a": [4, 1, 3, 2]} + """ + has_time_rank = self.get(SampleBatch.SEQ_LENS) is not None + + # Shuffling the data when we have `seq_lens` defined is probably + # a bad idea! + if has_time_rank and not self.zero_padded: + raise ValueError( + "SampleBatch.shuffle not possible when your data has " + "`seq_lens` defined AND is not zero-padded yet!" + ) + + # Get a permutation over the single items once and use the same + # permutation for all the data (otherwise, data would become + # meaningless). + # - Shuffle by individual item. + if not has_time_rank: + permutation = np.random.permutation(self.count) + # - Shuffle along batch axis (leave axis=1/time-axis as-is). + else: + permutation = np.random.permutation(len(self[SampleBatch.SEQ_LENS])) + + self_as_dict = dict(self) + infos = self_as_dict.pop(Columns.INFOS, None) + shuffled = tree.map_structure(lambda v: v[permutation], self_as_dict) + if infos is not None: + self_as_dict[Columns.INFOS] = [infos[i] for i in permutation] + + self.update(shuffled) + + # Flush cache such that intercepted values are recalculated after the + # shuffling. + self.intercepted_values = {} + return self + + @PublicAPI + def split_by_episode(self, key: Optional[str] = None) -> List["SampleBatch"]: + """Splits by `eps_id` column and returns list of new batches. + If `eps_id` is not present, splits by `dones` instead. + + Args: + key: If specified, overwrite default and use key to split. + + Returns: + List of batches, one per distinct episode. + + Raises: + KeyError: If the `eps_id` AND `dones` columns are not present. + + .. testcode:: + :skipif: True + + from ray.rllib.policy.sample_batch import SampleBatch + # "eps_id" is present + batch = SampleBatch( + {"a": [1, 2, 3], "eps_id": [0, 0, 1]}) + print(batch.split_by_episode()) + + # "eps_id" not present, split by "dones" instead + batch = SampleBatch( + {"a": [1, 2, 3, 4, 5], "dones": [0, 0, 1, 0, 1]}) + print(batch.split_by_episode()) + + # The last episode is appended even if it does not end with done + batch = SampleBatch( + {"a": [1, 2, 3, 4, 5], "dones": [0, 0, 1, 0, 0]}) + print(batch.split_by_episode()) + + batch = SampleBatch( + {"a": [1, 2, 3, 4, 5], "dones": [0, 0, 0, 0, 0]}) + print(batch.split_by_episode()) + + + .. testoutput:: + + [{"a": [1, 2], "eps_id": [0, 0]}, {"a": [3], "eps_id": [1]}] + [{"a": [1, 2, 3], "dones": [0, 0, 1]}, {"a": [4, 5], "dones": [0, 1]}] + [{"a": [1, 2, 3], "dones": [0, 0, 1]}, {"a": [4, 5], "dones": [0, 0]}] + [{"a": [1, 2, 3, 4, 5], "dones": [0, 0, 0, 0, 0]}] + + + """ + + assert key is None or key in [SampleBatch.EPS_ID, SampleBatch.DONES], ( + f"`SampleBatch.split_by_episode(key={key})` invalid! " + f"Must be [None|'dones'|'eps_id']." + ) + + def slice_by_eps_id(): + slices = [] + # Produce a new slice whenever we find a new episode ID. + cur_eps_id = self[SampleBatch.EPS_ID][0] + offset = 0 + for i in range(self.count): + next_eps_id = self[SampleBatch.EPS_ID][i] + if next_eps_id != cur_eps_id: + slices.append(self[offset:i]) + offset = i + cur_eps_id = next_eps_id + # Add final slice. + slices.append(self[offset : self.count]) + return slices + + def slice_by_terminateds_or_truncateds(): + slices = [] + offset = 0 + for i in range(self.count): + if self[SampleBatch.TERMINATEDS][i] or ( + SampleBatch.TRUNCATEDS in self and self[SampleBatch.TRUNCATEDS][i] + ): + # Since self[i] is the last timestep of the episode, + # append it to the batch, then set offset to the start + # of the next batch + slices.append(self[offset : i + 1]) + offset = i + 1 + # Add final slice. + if offset != self.count: + slices.append(self[offset:]) + return slices + + key_to_method = { + SampleBatch.EPS_ID: slice_by_eps_id, + SampleBatch.DONES: slice_by_terminateds_or_truncateds, + } + + # If key not specified, default to this order. + key_resolve_order = [SampleBatch.EPS_ID, SampleBatch.DONES] + + slices = None + if key is not None: + # If key specified, directly use it. + if key == SampleBatch.EPS_ID and key not in self: + raise KeyError(f"{self} does not have key `{key}`!") + slices = key_to_method[key]() + else: + # If key not specified, go in order. + for key in key_resolve_order: + if key == SampleBatch.DONES or key in self: + slices = key_to_method[key]() + break + if slices is None: + raise KeyError(f"{self} does not have keys {key_resolve_order}!") + + assert ( + sum(s.count for s in slices) == self.count + ), f"Calling split_by_episode on {self} returns {slices}" + f"which should in total have {self.count} timesteps!" + return slices + + def slice( + self, start: int, end: int, state_start=None, state_end=None + ) -> "SampleBatch": + """Returns a slice of the row data of this batch (w/o copying). + + Args: + start: Starting index. If < 0, will left-zero-pad. + end: Ending index. + + Returns: + A new SampleBatch, which has a slice of this batch's data. + """ + if ( + self.get(SampleBatch.SEQ_LENS) is not None + and len(self[SampleBatch.SEQ_LENS]) > 0 + ): + if start < 0: + data = { + k: np.concatenate( + [ + np.zeros(shape=(-start,) + v.shape[1:], dtype=v.dtype), + v[0:end], + ] + ) + for k, v in self.items() + if k != SampleBatch.SEQ_LENS and not k.startswith("state_in_") + } + else: + data = { + k: tree.map_structure(lambda s: s[start:end], v) + for k, v in self.items() + if k != SampleBatch.SEQ_LENS and not k.startswith("state_in_") + } + if state_start is not None: + assert state_end is not None + state_idx = 0 + state_key = "state_in_{}".format(state_idx) + while state_key in self: + data[state_key] = self[state_key][state_start:state_end] + state_idx += 1 + state_key = "state_in_{}".format(state_idx) + seq_lens = list(self[SampleBatch.SEQ_LENS][state_start:state_end]) + # Adjust seq_lens if necessary. + data_len = len(data[next(iter(data))]) + if sum(seq_lens) != data_len: + assert sum(seq_lens) > data_len + seq_lens[-1] = data_len - sum(seq_lens[:-1]) + else: + # Fix state_in_x data. + count = 0 + state_start = None + seq_lens = None + for i, seq_len in enumerate(self[SampleBatch.SEQ_LENS]): + count += seq_len + if count >= end: + state_idx = 0 + state_key = "state_in_{}".format(state_idx) + if state_start is None: + state_start = i + while state_key in self: + data[state_key] = self[state_key][state_start : i + 1] + state_idx += 1 + state_key = "state_in_{}".format(state_idx) + seq_lens = list(self[SampleBatch.SEQ_LENS][state_start:i]) + [ + seq_len - (count - end) + ] + if start < 0: + seq_lens[0] += -start + diff = sum(seq_lens) - (end - start) + if diff > 0: + seq_lens[0] -= diff + assert sum(seq_lens) == (end - start) + break + elif state_start is None and count > start: + state_start = i + + return SampleBatch( + data, + seq_lens=seq_lens, + _is_training=self.is_training, + _time_major=self.time_major, + _num_grad_updates=self.num_grad_updates, + ) + else: + return SampleBatch( + tree.map_structure(lambda value: value[start:end], self), + _is_training=self.is_training, + _time_major=self.time_major, + _num_grad_updates=self.num_grad_updates, + ) + + def _batch_slice(self, slice_: slice) -> "SampleBatch": + """Helper method to handle SampleBatch slicing using a slice object. + + The returned SampleBatch uses the same underlying data object as + `self`, so changing the slice will also change `self`. + + Note that only zero or positive bounds are allowed for both start + and stop values. The slice step must be 1 (or None, which is the + same). + + Args: + slice_: The python slice object to slice by. + + Returns: + A new SampleBatch, however "linking" into the same data + (sliced) as self. + """ + start = slice_.start or 0 + stop = slice_.stop or len(self[SampleBatch.SEQ_LENS]) + # If stop goes beyond the length of this batch -> Make it go till the + # end only (including last item). + # Analogous to `l = [0, 1, 2]; l[:100] -> [0, 1, 2];`. + if stop > len(self): + stop = len(self) + assert start >= 0 and stop >= 0 and slice_.step in [1, None] + + # Exclude INFOs from regular array slicing as the data under this column might + # be a list (not good for `tree.map_structure` call). + # Furthermore, slicing does not work when the data in the column is + # singular (not a list or array). + infos = self.pop(SampleBatch.INFOS, None) + data = tree.map_structure(lambda value: value[start:stop], self) + if infos is not None: + # Slice infos according to SEQ_LENS. + info_slice_start = int(sum(self[SampleBatch.SEQ_LENS][:start])) + info_slice_stop = int(sum(self[SampleBatch.SEQ_LENS][start:stop])) + data[SampleBatch.INFOS] = infos[info_slice_start:info_slice_stop] + # Put infos back into `self`. + self[Columns.INFOS] = infos + + return SampleBatch( + data, + _is_training=self.is_training, + _time_major=self.time_major, + _num_grad_updates=self.num_grad_updates, + ) + + @PublicAPI + def timeslices( + self, + size: Optional[int] = None, + num_slices: Optional[int] = None, + k: Optional[int] = None, + ) -> List["SampleBatch"]: + """Returns SampleBatches, each one representing a k-slice of this one. + + Will start from timestep 0 and produce slices of size=k. + + Args: + size: The size (in timesteps) of each returned SampleBatch. + num_slices: The number of slices to produce. + k: Deprecated: Use size or num_slices instead. The size + (in timesteps) of each returned SampleBatch. + + Returns: + The list of `num_slices` (new) SampleBatches or n (new) + SampleBatches each one of size `size`. + """ + if size is None and num_slices is None: + deprecation_warning("k", "size or num_slices") + assert k is not None + size = k + + if size is None: + assert isinstance(num_slices, int) + + slices = [] + left = len(self) + start = 0 + while left: + len_ = left // (num_slices - len(slices)) + stop = start + len_ + slices.append(self[start:stop]) + left -= len_ + start = stop + + return slices + + else: + assert isinstance(size, int) + + slices = [] + left = len(self) + start = 0 + while left: + stop = start + size + slices.append(self[start:stop]) + left -= size + start = stop + + return slices + + @Deprecated(new="SampleBatch.right_zero_pad", error=True) + def zero_pad(self, max_seq_len, exclude_states=True): + pass + + def right_zero_pad(self, max_seq_len: int, exclude_states: bool = True): + """Right (adding zeros at end) zero-pads this SampleBatch in-place. + + This will set the `self.zero_padded` flag to True and + `self.max_seq_len` to the given `max_seq_len` value. + + Args: + max_seq_len: The max (total) length to zero pad to. + exclude_states: If False, also right-zero-pad all + `state_in_x` data. If True, leave `state_in_x` keys + as-is. + + Returns: + This very (now right-zero-padded) SampleBatch. + + Raises: + ValueError: If self[SampleBatch.SEQ_LENS] is None (not defined). + + .. testcode:: + :skipif: True + + from ray.rllib.policy.sample_batch import SampleBatch + batch = SampleBatch( + {"a": [1, 2, 3], "seq_lens": [1, 2]}) + print(batch.right_zero_pad(max_seq_len=4)) + + batch = SampleBatch({"a": [1, 2, 3], + "state_in_0": [1.0, 3.0], + "seq_lens": [1, 2]}) + print(batch.right_zero_pad(max_seq_len=5)) + + .. testoutput:: + + {"a": [1, 0, 0, 0, 2, 3, 0, 0], "seq_lens": [1, 2]} + {"a": [1, 0, 0, 0, 0, 2, 3, 0, 0, 0], + "state_in_0": [1.0, 3.0], # <- all state-ins remain as-is + "seq_lens": [1, 2]} + + """ + seq_lens = self.get(SampleBatch.SEQ_LENS) + if seq_lens is None: + raise ValueError( + "Cannot right-zero-pad SampleBatch if no `seq_lens` field " + f"present! SampleBatch={self}" + ) + + length = len(seq_lens) * max_seq_len + + def _zero_pad_in_place(path, value): + # Skip "state_in_..." columns and "seq_lens". + if (exclude_states is True and path[0].startswith("state_in_")) or path[ + 0 + ] == SampleBatch.SEQ_LENS: + return + # Generate zero-filled primer of len=max_seq_len. + if value.dtype == object or value.dtype.type is np.str_: + f_pad = [None] * length + else: + # Make sure type doesn't change. + f_pad = np.zeros((length,) + np.shape(value)[1:], dtype=value.dtype) + # Fill primer with data. + f_pad_base = f_base = 0 + for len_ in self[SampleBatch.SEQ_LENS]: + f_pad[f_pad_base : f_pad_base + len_] = value[f_base : f_base + len_] + f_pad_base += max_seq_len + f_base += len_ + assert f_base == len(value), value + + # Update our data in-place. + curr = self + for i, p in enumerate(path): + if i == len(path) - 1: + curr[p] = f_pad + curr = curr[p] + + self_as_dict = dict(self) + tree.map_structure_with_path(_zero_pad_in_place, self_as_dict) + + # Set flags to indicate, we are now zero-padded (and to what extend). + self.zero_padded = True + self.max_seq_len = max_seq_len + + return self + + @ExperimentalAPI + def to_device( + self, + device, + framework: str = "torch", + pin_memory: bool = False, + use_stream: bool = False, + stream: Optional[Union["torch.cuda.Stream", "torch.cuda.Stream"]] = None, + ): + """TODO: transfer batch to given device as framework tensor.""" + if framework == "torch": + assert torch is not None + for k, v in self.items(): + self[k] = convert_to_torch_tensor( + v, + device, + pin_memory=pin_memory, + use_stream=use_stream, + stream=stream, + ) + else: + raise NotImplementedError + return self + + @PublicAPI + def size_bytes(self) -> int: + """Returns sum over number of bytes of all data buffers. + + For numpy arrays, we use ``.nbytes``. For all other value types, we use + sys.getsizeof(...). + + Returns: + The overall size in bytes of the data buffer (all columns). + """ + return sum( + v.nbytes if isinstance(v, np.ndarray) else sys.getsizeof(v) + for v in tree.flatten(self) + ) + + def get(self, key, default=None): + """Returns one column (by key) from the data or a default value.""" + try: + return self.__getitem__(key) + except KeyError: + return default + + @PublicAPI + def as_multi_agent(self, module_id: Optional[ModuleID] = None) -> "MultiAgentBatch": + """Returns the respective MultiAgentBatch + + Note, if `module_id` is not provided uses `DEFAULT_POLICY`_ID`. + + Args; + module_id: An optional module ID. If `None` the `DEFAULT_POLICY_ID` + is used. + + Returns: + The MultiAgentBatch (using DEFAULT_POLICY_ID) corresponding + to this SampleBatch. + """ + return MultiAgentBatch({module_id or DEFAULT_POLICY_ID: self}, self.count) + + @PublicAPI + def __getitem__(self, key: Union[str, slice]) -> TensorType: + """Returns one column (by key) from the data or a sliced new batch. + + Args: + key: The key (column name) to return or + a slice object for slicing this SampleBatch. + + Returns: + The data under the given key or a sliced version of this batch. + """ + if isinstance(key, slice): + return self._slice(key) + + # Special key DONES -> Translate to `TERMINATEDS | TRUNCATEDS` to reflect + # the old meaning of DONES. + if key == SampleBatch.DONES: + return self[SampleBatch.TERMINATEDS] + # Backward compatibility for when "input-dicts" were used. + elif key == "is_training": + if log_once("SampleBatch['is_training']"): + deprecation_warning( + old="SampleBatch['is_training']", + new="SampleBatch.is_training", + error=False, + ) + return self.is_training + + if not hasattr(self, key) and key in self: + self.accessed_keys.add(key) + + value = dict.__getitem__(self, key) + if self.get_interceptor is not None: + if key not in self.intercepted_values: + self.intercepted_values[key] = self.get_interceptor(value) + value = self.intercepted_values[key] + return value + + @PublicAPI + def __setitem__(self, key, item) -> None: + """Inserts (overrides) an entire column (by key) in the data buffer. + + Args: + key: The column name to set a value for. + item: The data to insert. + """ + # Disallow setting DONES key directly. + if key == SampleBatch.DONES: + raise KeyError( + "Cannot set `DONES` anymore in a SampleBatch! " + "Instead, set the new TERMINATEDS and TRUNCATEDS keys. The values under" + " DONES will then be automatically computed using terminated|truncated." + ) + # Defend against creating SampleBatch via pickle (no property + # `added_keys` and first item is already set). + elif not hasattr(self, "added_keys"): + dict.__setitem__(self, key, item) + return + + # Backward compatibility for when "input-dicts" were used. + if key == "is_training": + if log_once("SampleBatch['is_training']"): + deprecation_warning( + old="SampleBatch['is_training']", + new="SampleBatch.is_training", + error=False, + ) + self._is_training = item + return + + if key not in self: + self.added_keys.add(key) + + dict.__setitem__(self, key, item) + if key in self.intercepted_values: + self.intercepted_values[key] = item + + @property + def is_training(self): + if self.get_interceptor is not None and isinstance(self._is_training, bool): + if "_is_training" not in self.intercepted_values: + self.intercepted_values["_is_training"] = self.get_interceptor( + self._is_training + ) + return self.intercepted_values["_is_training"] + return self._is_training + + def set_training(self, training: Union[bool, "tf1.placeholder"] = True): + """Sets the `is_training` flag for this SampleBatch.""" + self._is_training = training + self.intercepted_values.pop("_is_training", None) + + @PublicAPI + def __delitem__(self, key): + self.deleted_keys.add(key) + dict.__delitem__(self, key) + + @DeveloperAPI + def compress( + self, bulk: bool = False, columns: Set[str] = frozenset(["obs", "new_obs"]) + ) -> "SampleBatch": + """Compresses the data buffers (by column) in place. + + Args: + bulk: Whether to compress across the batch dimension (0) + as well. If False will compress n separate list items, where n + is the batch size. + columns: The columns to compress. Default: Only + compress the obs and new_obs columns. + + Returns: + This very (now compressed) SampleBatch. + """ + + def _compress_in_place(path, value): + if path[0] not in columns: + return + curr = self + for i, p in enumerate(path): + if i == len(path) - 1: + if bulk: + curr[p] = pack(value) + else: + curr[p] = np.array([pack(o) for o in value]) + curr = curr[p] + + tree.map_structure_with_path(_compress_in_place, self) + + return self + + @DeveloperAPI + def decompress_if_needed( + self, columns: Set[str] = frozenset(["obs", "new_obs"]) + ) -> "SampleBatch": + """Decompresses data buffers (per column if not compressed) in place. + + Args: + columns: The columns to decompress. Default: Only + decompress the obs and new_obs columns. + + Returns: + This very (now uncompressed) SampleBatch. + """ + + def _decompress_in_place(path, value): + if path[0] not in columns: + return + curr = self + for p in path[:-1]: + curr = curr[p] + # Bulk compressed. + if is_compressed(value): + curr[path[-1]] = unpack(value) + # Non bulk compressed. + elif len(value) > 0 and is_compressed(value[0]): + curr[path[-1]] = np.array([unpack(o) for o in value]) + + tree.map_structure_with_path(_decompress_in_place, self) + + return self + + @DeveloperAPI + def set_get_interceptor(self, fn): + """Sets a function to be called on every getitem.""" + # If get-interceptor changes, must erase old intercepted values. + if fn is not self.get_interceptor: + self.intercepted_values = {} + self.get_interceptor = fn + + def __repr__(self): + keys = list(self.keys()) + if self.get(SampleBatch.SEQ_LENS) is None: + return f"SampleBatch({self.count}: {keys})" + else: + keys.remove(SampleBatch.SEQ_LENS) + return ( + f"SampleBatch({self.count} " f"(seqs={len(self['seq_lens'])}): {keys})" + ) + + def _slice(self, slice_: slice) -> "SampleBatch": + """Helper method to handle SampleBatch slicing using a slice object. + + The returned SampleBatch uses the same underlying data object as + `self`, so changing the slice will also change `self`. + + Note that only zero or positive bounds are allowed for both start + and stop values. The slice step must be 1 (or None, which is the + same). + + Args: + slice_: The python slice object to slice by. + + Returns: + A new SampleBatch, however "linking" into the same data + (sliced) as self. + """ + if self._slice_seq_lens_in_B: + return self._batch_slice(slice_) + + start = slice_.start or 0 + stop = slice_.stop or len(self) + # If stop goes beyond the length of this batch -> Make it go till the + # end only (including last item). + # Analogous to `l = [0, 1, 2]; l[:100] -> [0, 1, 2];`. + if stop > len(self): + stop = len(self) + + if ( + self.get(SampleBatch.SEQ_LENS) is not None + and len(self[SampleBatch.SEQ_LENS]) > 0 + ): + # Build our slice-map, if not done already. + if not self._slice_map: + sum_ = 0 + for i, l in enumerate(map(int, self[SampleBatch.SEQ_LENS])): + self._slice_map.extend([(i, sum_)] * l) + sum_ = sum_ + l + # In case `stop` points to the very end (lengths of this + # batch), return the last sequence (the -1 here makes sure we + # never go beyond it; would result in an index error below). + self._slice_map.append((len(self[SampleBatch.SEQ_LENS]), sum_)) + + start_seq_len, start_unpadded = self._slice_map[start] + stop_seq_len, stop_unpadded = self._slice_map[stop] + start_padded = start_unpadded + stop_padded = stop_unpadded + if self.zero_padded: + start_padded = start_seq_len * self.max_seq_len + stop_padded = stop_seq_len * self.max_seq_len + + def map_(path, value): + if path[0] != SampleBatch.SEQ_LENS and not path[0].startswith( + "state_in_" + ): + return value[start_padded:stop_padded] + else: + return value[start_seq_len:stop_seq_len] + + infos = self.pop(SampleBatch.INFOS, None) + data = tree.map_structure_with_path(map_, self) + if infos is not None and isinstance(infos, (list, np.ndarray)): + self[SampleBatch.INFOS] = infos + data[SampleBatch.INFOS] = infos[start_unpadded:stop_unpadded] + + return SampleBatch( + data, + _is_training=self.is_training, + _time_major=self.time_major, + _zero_padded=self.zero_padded, + _max_seq_len=self.max_seq_len if self.zero_padded else None, + _num_grad_updates=self.num_grad_updates, + ) + else: + infos = self.pop(SampleBatch.INFOS, None) + data = tree.map_structure(lambda s: s[start:stop], self) + if infos is not None and isinstance(infos, (list, np.ndarray)): + self[SampleBatch.INFOS] = infos + data[SampleBatch.INFOS] = infos[start:stop] + + return SampleBatch( + data, + _is_training=self.is_training, + _time_major=self.time_major, + _num_grad_updates=self.num_grad_updates, + ) + + @Deprecated(error=False) + def _get_slice_indices(self, slice_size): + data_slices = [] + data_slices_states = [] + if ( + self.get(SampleBatch.SEQ_LENS) is not None + and len(self[SampleBatch.SEQ_LENS]) > 0 + ): + assert np.all(self[SampleBatch.SEQ_LENS] < slice_size), ( + "ERROR: `slice_size` must be larger than the max. seq-len " + "in the batch!" + ) + start_pos = 0 + current_slize_size = 0 + actual_slice_idx = 0 + start_idx = 0 + idx = 0 + while idx < len(self[SampleBatch.SEQ_LENS]): + seq_len = self[SampleBatch.SEQ_LENS][idx] + current_slize_size += seq_len + actual_slice_idx += ( + seq_len if not self.zero_padded else self.max_seq_len + ) + # Complete minibatch -> Append to data_slices. + if current_slize_size >= slice_size: + end_idx = idx + 1 + # We are not zero-padded yet; all sequences are + # back-to-back. + if not self.zero_padded: + data_slices.append((start_pos, start_pos + slice_size)) + start_pos += slice_size + if current_slize_size > slice_size: + overhead = current_slize_size - slice_size + start_pos -= seq_len - overhead + idx -= 1 + # We are already zero-padded: Cut in chunks of max_seq_len. + else: + data_slices.append((start_pos, actual_slice_idx)) + start_pos = actual_slice_idx + + data_slices_states.append((start_idx, end_idx)) + current_slize_size = 0 + start_idx = idx + 1 + idx += 1 + else: + i = 0 + while i < self.count: + data_slices.append((i, i + slice_size)) + i += slice_size + return data_slices, data_slices_states + + @ExperimentalAPI + def get_single_step_input_dict( + self, + view_requirements: ViewRequirementsDict, + index: Union[str, int] = "last", + ) -> "SampleBatch": + """Creates single ts SampleBatch at given index from `self`. + + For usage as input-dict for model (action or value function) calls. + + Args: + view_requirements: A view requirements dict from the model for + which to produce the input_dict. + index: An integer index value indicating the + position in the trajectory for which to generate the + compute_actions input dict. Set to "last" to generate the dict + at the very end of the trajectory (e.g. for value estimation). + Note that "last" is different from -1, as "last" will use the + final NEXT_OBS as observation input. + + Returns: + The (single-timestep) input dict for ModelV2 calls. + """ + last_mappings = { + SampleBatch.OBS: SampleBatch.NEXT_OBS, + SampleBatch.PREV_ACTIONS: SampleBatch.ACTIONS, + SampleBatch.PREV_REWARDS: SampleBatch.REWARDS, + } + + input_dict = {} + for view_col, view_req in view_requirements.items(): + if view_req.used_for_compute_actions is False: + continue + + # Create batches of size 1 (single-agent input-dict). + data_col = view_req.data_col or view_col + if index == "last": + data_col = last_mappings.get(data_col, data_col) + # Range needed. + if view_req.shift_from is not None: + # Batch repeat value > 1: We have single frames in the + # batch at each timestep (for the `data_col`). + data = self[view_col][-1] + traj_len = len(self[data_col]) + missing_at_end = traj_len % view_req.batch_repeat_value + # Index into the observations column must be shifted by + # -1 b/c index=0 for observations means the current (last + # seen) observation (after having taken an action). + obs_shift = ( + -1 if data_col in [SampleBatch.OBS, SampleBatch.NEXT_OBS] else 0 + ) + from_ = view_req.shift_from + obs_shift + to_ = view_req.shift_to + obs_shift + 1 + if to_ == 0: + to_ = None + input_dict[view_col] = np.array( + [ + np.concatenate([data, self[data_col][-missing_at_end:]])[ + from_:to_ + ] + ] + ) + # Single index. + else: + input_dict[view_col] = tree.map_structure( + lambda v: v[-1:], # keep as array (w/ 1 element) + self[data_col], + ) + # Single index somewhere inside the trajectory (non-last). + else: + input_dict[view_col] = self[data_col][ + index : index + 1 if index != -1 else None + ] + + return SampleBatch(input_dict, seq_lens=np.array([1], dtype=np.int32)) + + +@PublicAPI +class MultiAgentBatch: + """A batch of experiences from multiple agents in the environment. + + Attributes: + policy_batches (Dict[PolicyID, SampleBatch]): Dict mapping policy IDs to + SampleBatches of experiences. + count: The number of env steps in this batch. + """ + + @PublicAPI + def __init__(self, policy_batches: Dict[PolicyID, SampleBatch], env_steps: int): + """Initialize a MultiAgentBatch instance. + + Args: + policy_batches: Dict mapping policy IDs to SampleBatches of experiences. + env_steps: The number of environment steps in the environment + this batch contains. This will be less than the number of + transitions this batch contains across all policies in total. + """ + + for v in policy_batches.values(): + assert isinstance(v, SampleBatch) + self.policy_batches = policy_batches + # Called "count" for uniformity with SampleBatch. + # Prefer to access this via the `env_steps()` method when possible + # for clarity. + self.count = env_steps + + @PublicAPI + def env_steps(self) -> int: + """The number of env steps (there are >= 1 agent steps per env step). + + Returns: + The number of environment steps contained in this batch. + """ + return self.count + + @PublicAPI + def __len__(self) -> int: + """Same as `self.env_steps()`.""" + return self.count + + @PublicAPI + def agent_steps(self) -> int: + """The number of agent steps (there are >= 1 agent steps per env step). + + Returns: + The number of agent steps total in this batch. + """ + ct = 0 + for batch in self.policy_batches.values(): + ct += batch.count + return ct + + @PublicAPI + def timeslices(self, k: int) -> List["MultiAgentBatch"]: + """Returns k-step batches holding data for each agent at those steps. + + For examples, suppose we have agent1 observations [a1t1, a1t2, a1t3], + for agent2, [a2t1, a2t3], and for agent3, [a3t3] only. + + Calling timeslices(1) would return three MultiAgentBatches containing + [a1t1, a2t1], [a1t2], and [a1t3, a2t3, a3t3]. + + Calling timeslices(2) would return two MultiAgentBatches containing + [a1t1, a1t2, a2t1], and [a1t3, a2t3, a3t3]. + + This method is used to implement "lockstep" replay mode. Note that this + method does not guarantee each batch contains only data from a single + unroll. Batches might contain data from multiple different envs. + """ + from ray.rllib.evaluation.sample_batch_builder import SampleBatchBuilder + + # Build a sorted set of (eps_id, t, policy_id, data...) + steps = [] + for policy_id, batch in self.policy_batches.items(): + for row in batch.rows(): + steps.append( + ( + row[SampleBatch.EPS_ID], + row[SampleBatch.T], + row[SampleBatch.AGENT_INDEX], + policy_id, + row, + ) + ) + steps.sort() + + finished_slices = [] + cur_slice = collections.defaultdict(SampleBatchBuilder) + cur_slice_size = 0 + + def finish_slice(): + nonlocal cur_slice_size + assert cur_slice_size > 0 + batch = MultiAgentBatch( + {k: v.build_and_reset() for k, v in cur_slice.items()}, cur_slice_size + ) + cur_slice_size = 0 + cur_slice.clear() + finished_slices.append(batch) + + # For each unique env timestep. + for _, group in itertools.groupby(steps, lambda x: x[:2]): + # Accumulate into the current slice. + for _, _, _, policy_id, row in group: + cur_slice[policy_id].add_values(**row) + cur_slice_size += 1 + # Slice has reached target number of env steps. + if cur_slice_size >= k: + finish_slice() + assert cur_slice_size == 0 + + if cur_slice_size > 0: + finish_slice() + + assert len(finished_slices) > 0, finished_slices + return finished_slices + + @staticmethod + @PublicAPI + def wrap_as_needed( + policy_batches: Dict[PolicyID, SampleBatch], env_steps: int + ) -> Union[SampleBatch, "MultiAgentBatch"]: + """Returns SampleBatch or MultiAgentBatch, depending on given policies. + If policy_batches is empty (i.e. {}) it returns an empty MultiAgentBatch. + + Args: + policy_batches: Mapping from policy ids to SampleBatch. + env_steps: Number of env steps in the batch. + + Returns: + The single default policy's SampleBatch or a MultiAgentBatch + (more than one policy). + """ + if len(policy_batches) == 1 and DEFAULT_POLICY_ID in policy_batches: + return policy_batches[DEFAULT_POLICY_ID] + return MultiAgentBatch(policy_batches=policy_batches, env_steps=env_steps) + + @staticmethod + @PublicAPI + @Deprecated(new="concat_samples() from rllib.policy.sample_batch", error=True) + def concat_samples(samples: List["MultiAgentBatch"]) -> "MultiAgentBatch": + return concat_samples_into_ma_batch(samples) + + @PublicAPI + def copy(self) -> "MultiAgentBatch": + """Deep-copies self into a new MultiAgentBatch. + + Returns: + The copy of self with deep-copied data. + """ + return MultiAgentBatch( + {k: v.copy() for (k, v) in self.policy_batches.items()}, self.count + ) + + @ExperimentalAPI + def to_device( + self, + device, + framework="torch", + pin_memory: bool = False, + use_stream: bool = False, + stream: Optional[Union["torch.cuda.Stream", "torch.cuda.Stream"]] = None, + ): + """TODO: transfer batch to given device as framework tensor.""" + if framework == "torch": + assert torch is not None + for pid, policy_batch in self.policy_batches.items(): + self.policy_batches[pid] = policy_batch.to_device( + device, + framework=framework, + pin_memory=pin_memory, + use_stream=use_stream, + stream=stream, + ) + else: + raise NotImplementedError + return self + + @PublicAPI + def size_bytes(self) -> int: + """ + Returns: + The overall size in bytes of all policy batches (all columns). + """ + return sum(b.size_bytes() for b in self.policy_batches.values()) + + @DeveloperAPI + def compress( + self, bulk: bool = False, columns: Set[str] = frozenset(["obs", "new_obs"]) + ) -> None: + """Compresses each policy batch (per column) in place. + + Args: + bulk: Whether to compress across the batch dimension (0) + as well. If False will compress n separate list items, where n + is the batch size. + columns: Set of column names to compress. + """ + for batch in self.policy_batches.values(): + batch.compress(bulk=bulk, columns=columns) + + @DeveloperAPI + def decompress_if_needed( + self, columns: Set[str] = frozenset(["obs", "new_obs"]) + ) -> "MultiAgentBatch": + """Decompresses each policy batch (per column), if already compressed. + + Args: + columns: Set of column names to decompress. + + Returns: + Self. + """ + for batch in self.policy_batches.values(): + batch.decompress_if_needed(columns) + return self + + @DeveloperAPI + def as_multi_agent(self) -> "MultiAgentBatch": + """Simply returns `self` (already a MultiAgentBatch). + + Returns: + This very instance of MultiAgentBatch. + """ + return self + + def __getitem__(self, key: str) -> SampleBatch: + """Returns the SampleBatch for the given policy id.""" + return self.policy_batches[key] + + def __str__(self): + return "MultiAgentBatch({}, env_steps={})".format( + str(self.policy_batches), self.count + ) + + def __repr__(self): + return "MultiAgentBatch({}, env_steps={})".format( + str(self.policy_batches), self.count + ) + + +@PublicAPI +def concat_samples(samples: List[SampleBatchType]) -> SampleBatchType: + """Concatenates a list of SampleBatches or MultiAgentBatches. + + If all items in the list are or SampleBatch typ4, the output will be + a SampleBatch type. Otherwise, the output will be a MultiAgentBatch type. + If input is a mixture of SampleBatch and MultiAgentBatch types, it will treat + SampleBatch objects as MultiAgentBatch types with 'default_policy' key and + concatenate it with th rest of MultiAgentBatch objects. + Empty samples are simply ignored. + + Args: + samples: List of SampleBatches or MultiAgentBatches to be + concatenated. + + Returns: + A new (concatenated) SampleBatch or MultiAgentBatch. + + .. testcode:: + :skipif: True + + import numpy as np + from ray.rllib.policy.sample_batch import SampleBatch + b1 = SampleBatch({"a": np.array([1, 2]), + "b": np.array([10, 11])}) + b2 = SampleBatch({"a": np.array([3]), + "b": np.array([12])}) + print(concat_samples([b1, b2])) + + + c1 = MultiAgentBatch({'default_policy': { + "a": np.array([1, 2]), + "b": np.array([10, 11]) + }}, env_steps=2) + c2 = SampleBatch({"a": np.array([3]), + "b": np.array([12])}) + print(concat_samples([b1, b2])) + + .. testoutput:: + + {"a": np.array([1, 2, 3]), "b": np.array([10, 11, 12])} + MultiAgentBatch = {'default_policy': {"a": np.array([1, 2, 3]), + "b": np.array([10, 11, 12])}} + + """ + + if any(isinstance(s, MultiAgentBatch) for s in samples): + return concat_samples_into_ma_batch(samples) + + # the output is a SampleBatch type + concatd_seq_lens = [] + concatd_num_grad_updates = [0, 0.0] # [0]=count; [1]=weighted sum values + concated_samples = [] + # Make sure these settings are consistent amongst all batches. + zero_padded = max_seq_len = time_major = None + for s in samples: + if s.count <= 0: + continue + + if max_seq_len is None: + zero_padded = s.zero_padded + max_seq_len = s.max_seq_len + time_major = s.time_major + + # Make sure these settings are consistent amongst all batches. + if s.zero_padded != zero_padded or s.time_major != time_major: + raise ValueError( + "All SampleBatches' `zero_padded` and `time_major` settings " + "must be consistent!" + ) + if ( + s.max_seq_len is None or max_seq_len is None + ) and s.max_seq_len != max_seq_len: + raise ValueError( + "Samples must consistently either provide or omit `max_seq_len`!" + ) + elif zero_padded and s.max_seq_len != max_seq_len: + raise ValueError( + "For `zero_padded` SampleBatches, the values of `max_seq_len` " + "must be consistent!" + ) + + if max_seq_len is not None: + max_seq_len = max(max_seq_len, s.max_seq_len) + if s.get(SampleBatch.SEQ_LENS) is not None: + concatd_seq_lens.extend(s[SampleBatch.SEQ_LENS]) + if s.num_grad_updates is not None: + concatd_num_grad_updates[0] += s.count + concatd_num_grad_updates[1] += s.num_grad_updates * s.count + + concated_samples.append(s) + + # If we don't have any samples (0 or only empty SampleBatches), + # return an empty SampleBatch here. + if len(concated_samples) == 0: + return SampleBatch() + + # Collect the concat'd data. + concatd_data = {} + + for k in concated_samples[0].keys(): + if k == SampleBatch.INFOS: + concatd_data[k] = _concat_values( + *[s[k] for s in concated_samples], + time_major=time_major, + ) + else: + values_to_concat = [c[k] for c in concated_samples] + _concat_values_w_time = partial(_concat_values, time_major=time_major) + concatd_data[k] = tree.map_structure( + _concat_values_w_time, *values_to_concat + ) + + if concatd_seq_lens != [] and torch and torch.is_tensor(concatd_seq_lens[0]): + concatd_seq_lens = torch.Tensor(concatd_seq_lens) + elif concatd_seq_lens != [] and tf and tf.is_tensor(concatd_seq_lens[0]): + concatd_seq_lens = tf.convert_to_tensor(concatd_seq_lens) + + # Return a new (concat'd) SampleBatch. + return SampleBatch( + concatd_data, + seq_lens=concatd_seq_lens, + _time_major=time_major, + _zero_padded=zero_padded, + _max_seq_len=max_seq_len, + # Compute weighted average of the num_grad_updates for the batches + # (assuming they all come from the same policy). + _num_grad_updates=( + concatd_num_grad_updates[1] / (concatd_num_grad_updates[0] or 1.0) + ), + ) + + +@PublicAPI +def concat_samples_into_ma_batch(samples: List[SampleBatchType]) -> "MultiAgentBatch": + """Concatenates a list of SampleBatchTypes to a single MultiAgentBatch type. + + This function, as opposed to concat_samples() forces the output to always be + MultiAgentBatch which is more generic than SampleBatch. + + Args: + samples: List of SampleBatches or MultiAgentBatches to be + concatenated. + + Returns: + A new (concatenated) MultiAgentBatch. + + .. testcode:: + :skipif: True + + import numpy as np + from ray.rllib.policy.sample_batch import SampleBatch + b1 = MultiAgentBatch({'default_policy': { + "a": np.array([1, 2]), + "b": np.array([10, 11]) + }}, env_steps=2) + b2 = SampleBatch({"a": np.array([3]), + "b": np.array([12])}) + print(concat_samples([b1, b2])) + + .. testoutput:: + + {'default_policy': {"a": np.array([1, 2, 3]), + "b": np.array([10, 11, 12])}} + + """ + + policy_batches = collections.defaultdict(list) + env_steps = 0 + for s in samples: + # Some batches in `samples` may be SampleBatch. + if isinstance(s, SampleBatch): + # If empty SampleBatch: ok (just ignore). + if len(s) <= 0: + continue + else: + # if non-empty: just convert to MA-batch and move forward + s = s.as_multi_agent() + elif not isinstance(s, MultiAgentBatch): + # Otherwise: Error. + raise ValueError( + "`concat_samples_into_ma_batch` can only concat " + "SampleBatch|MultiAgentBatch objects, not {}!".format(type(s).__name__) + ) + + for key, batch in s.policy_batches.items(): + policy_batches[key].append(batch) + env_steps += s.env_steps() + + out = {} + for key, batches in policy_batches.items(): + out[key] = concat_samples(batches) + + return MultiAgentBatch(out, env_steps) + + +def _concat_values(*values, time_major=None) -> TensorType: + """Concatenates a list of values. + + Args: + values: The values to concatenate. + time_major: Whether to concatenate along the first axis + (time_major=False) or the second axis (time_major=True). + """ + if torch and torch.is_tensor(values[0]): + return torch.cat(values, dim=1 if time_major else 0) + elif isinstance(values[0], np.ndarray): + return np.concatenate(values, axis=1 if time_major else 0) + elif tf and tf.is_tensor(values[0]): + return tf.concat(values, axis=1 if time_major else 0) + elif isinstance(values[0], list): + concatenated_list = [] + for sublist in values: + concatenated_list.extend(sublist) + return concatenated_list + else: + raise ValueError( + f"Unsupported type for concatenation: {type(values[0])} " + f"first element: {values[0]}" + ) + + +@DeveloperAPI +def convert_ma_batch_to_sample_batch(batch: SampleBatchType) -> SampleBatch: + """Converts a MultiAgentBatch to a SampleBatch if neccessary. + + Args: + batch: The SampleBatchType to convert. + + Returns: + batch: the converted SampleBatch + + Raises: + ValueError if the MultiAgentBatch has more than one policy_id + or if the policy_id is not `DEFAULT_POLICY_ID` + """ + if isinstance(batch, MultiAgentBatch): + policy_keys = batch.policy_batches.keys() + if len(policy_keys) == 1 and DEFAULT_POLICY_ID in policy_keys: + batch = batch.policy_batches[DEFAULT_POLICY_ID] + else: + raise ValueError( + "RLlib tried to convert a multi agent-batch with data from more " + "than one policy to a single-agent batch. This is not supported and " + "may be due to a number of issues. Here are two possible ones:" + "1) Off-Policy Estimation is not implemented for " + "multi-agent batches. You can set `off_policy_estimation_methods: {}` " + "to resolve this." + "2) Loading multi-agent data for offline training is not implemented." + "Load single-agent data instead to resolve this." + ) + return batch diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/tf_mixins.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/tf_mixins.py new file mode 100644 index 0000000000000000000000000000000000000000..0b70d1a54ad523714b8c55c4186092edb484ab72 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/tf_mixins.py @@ -0,0 +1,389 @@ +import logging +from typing import Dict, List + +import numpy as np + + +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.policy.eager_tf_policy import EagerTFPolicy +from ray.rllib.policy.eager_tf_policy_v2 import EagerTFPolicyV2 +from ray.rllib.policy.policy import PolicyState +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy.tf_policy import TFPolicy +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.framework import get_variable, try_import_tf +from ray.rllib.utils.schedules import PiecewiseSchedule +from ray.rllib.utils.tf_utils import make_tf_callable +from ray.rllib.utils.typing import ( + AlgorithmConfigDict, + LocalOptimizer, + ModelGradients, + TensorType, +) + + +logger = logging.getLogger(__name__) +tf1, tf, tfv = try_import_tf() + + +@OldAPIStack +class LearningRateSchedule: + """Mixin for TFPolicy that adds a learning rate schedule.""" + + def __init__(self, lr, lr_schedule): + self._lr_schedule = None + if lr_schedule is None: + self.cur_lr = tf1.get_variable("lr", initializer=lr, trainable=False) + else: + self._lr_schedule = PiecewiseSchedule( + lr_schedule, outside_value=lr_schedule[-1][-1], framework=None + ) + self.cur_lr = tf1.get_variable( + "lr", initializer=self._lr_schedule.value(0), trainable=False + ) + if self.framework == "tf": + self._lr_placeholder = tf1.placeholder(dtype=tf.float32, name="lr") + self._lr_update = self.cur_lr.assign( + self._lr_placeholder, read_value=False + ) + + def on_global_var_update(self, global_vars): + super().on_global_var_update(global_vars) + if self._lr_schedule is not None: + new_val = self._lr_schedule.value(global_vars["timestep"]) + if self.framework == "tf": + self.get_session().run( + self._lr_update, feed_dict={self._lr_placeholder: new_val} + ) + else: + self.cur_lr.assign(new_val, read_value=False) + # This property (self._optimizer) is (still) accessible for + # both TFPolicy and any TFPolicy_eager. + self._optimizer.learning_rate.assign(self.cur_lr) + + def optimizer(self): + if self.framework == "tf": + return tf1.train.AdamOptimizer(learning_rate=self.cur_lr) + else: + return tf.keras.optimizers.Adam(self.cur_lr) + + +@OldAPIStack +class EntropyCoeffSchedule: + """Mixin for TFPolicy that adds entropy coeff decay.""" + + def __init__(self, entropy_coeff, entropy_coeff_schedule): + self._entropy_coeff_schedule = None + if entropy_coeff_schedule is None: + self.entropy_coeff = get_variable( + entropy_coeff, framework="tf", tf_name="entropy_coeff", trainable=False + ) + else: + # Allows for custom schedule similar to lr_schedule format + if isinstance(entropy_coeff_schedule, list): + self._entropy_coeff_schedule = PiecewiseSchedule( + entropy_coeff_schedule, + outside_value=entropy_coeff_schedule[-1][-1], + framework=None, + ) + else: + # Implements previous version but enforces outside_value + self._entropy_coeff_schedule = PiecewiseSchedule( + [[0, entropy_coeff], [entropy_coeff_schedule, 0.0]], + outside_value=0.0, + framework=None, + ) + + self.entropy_coeff = get_variable( + self._entropy_coeff_schedule.value(0), + framework="tf", + tf_name="entropy_coeff", + trainable=False, + ) + if self.framework == "tf": + self._entropy_coeff_placeholder = tf1.placeholder( + dtype=tf.float32, name="entropy_coeff" + ) + self._entropy_coeff_update = self.entropy_coeff.assign( + self._entropy_coeff_placeholder, read_value=False + ) + + def on_global_var_update(self, global_vars): + super().on_global_var_update(global_vars) + if self._entropy_coeff_schedule is not None: + new_val = self._entropy_coeff_schedule.value(global_vars["timestep"]) + if self.framework == "tf": + self.get_session().run( + self._entropy_coeff_update, + feed_dict={self._entropy_coeff_placeholder: new_val}, + ) + else: + self.entropy_coeff.assign(new_val, read_value=False) + + +@OldAPIStack +class KLCoeffMixin: + """Assigns the `update_kl()` and other KL-related methods to a TFPolicy. + + This is used in Algorithms to update the KL coefficient after each + learning step based on `config.kl_target` and the measured KL value + (from the train_batch). + """ + + def __init__(self, config: AlgorithmConfigDict): + # The current KL value (as python float). + self.kl_coeff_val = config["kl_coeff"] + # The current KL value (as tf Variable for in-graph operations). + self.kl_coeff = get_variable( + float(self.kl_coeff_val), + tf_name="kl_coeff", + trainable=False, + framework=config["framework"], + ) + # Constant target value. + self.kl_target = config["kl_target"] + if self.framework == "tf": + self._kl_coeff_placeholder = tf1.placeholder( + dtype=tf.float32, name="kl_coeff" + ) + self._kl_coeff_update = self.kl_coeff.assign( + self._kl_coeff_placeholder, read_value=False + ) + + def update_kl(self, sampled_kl): + # Update the current KL value based on the recently measured value. + # Increase. + if sampled_kl > 2.0 * self.kl_target: + self.kl_coeff_val *= 1.5 + # Decrease. + elif sampled_kl < 0.5 * self.kl_target: + self.kl_coeff_val *= 0.5 + # No change. + else: + return self.kl_coeff_val + + # Make sure, new value is also stored in graph/tf variable. + self._set_kl_coeff(self.kl_coeff_val) + + # Return the current KL value. + return self.kl_coeff_val + + def _set_kl_coeff(self, new_kl_coeff): + # Set the (off graph) value. + self.kl_coeff_val = new_kl_coeff + + # Update the tf/tf2 Variable (via session call for tf or `assign`). + if self.framework == "tf": + self.get_session().run( + self._kl_coeff_update, + feed_dict={self._kl_coeff_placeholder: self.kl_coeff_val}, + ) + else: + self.kl_coeff.assign(self.kl_coeff_val, read_value=False) + + def get_state(self) -> PolicyState: + state = super().get_state() + # Add current kl-coeff value. + state["current_kl_coeff"] = self.kl_coeff_val + return state + + def set_state(self, state: PolicyState) -> None: + # Set current kl-coeff value first. + self._set_kl_coeff(state.pop("current_kl_coeff", self.config["kl_coeff"])) + # Call super's set_state with rest of the state dict. + super().set_state(state) + + +@OldAPIStack +class TargetNetworkMixin: + """Assign the `update_target` method to the policy. + + The function is called every `target_network_update_freq` steps by the + master learner. + """ + + def __init__(self): + model_vars = self.model.trainable_variables() + target_model_vars = self.target_model.trainable_variables() + + @make_tf_callable(self.get_session()) + def update_target_fn(tau): + tau = tf.convert_to_tensor(tau, dtype=tf.float32) + update_target_expr = [] + assert len(model_vars) == len(target_model_vars), ( + model_vars, + target_model_vars, + ) + for var, var_target in zip(model_vars, target_model_vars): + update_target_expr.append( + var_target.assign(tau * var + (1.0 - tau) * var_target) + ) + logger.debug("Update target op {}".format(var_target)) + return tf.group(*update_target_expr) + + # Hard initial update. + self._do_update = update_target_fn + # TODO: The previous SAC implementation does an update(1.0) here. + # If this is changed to tau != 1.0 the sac_loss_function test fails. Why? + # Also the test is not very maintainable, we need to change that unittest + # anyway. + self.update_target(tau=1.0) # self.config.get("tau", 1.0)) + + @property + def q_func_vars(self): + if not hasattr(self, "_q_func_vars"): + self._q_func_vars = self.model.variables() + return self._q_func_vars + + @property + def target_q_func_vars(self): + if not hasattr(self, "_target_q_func_vars"): + self._target_q_func_vars = self.target_model.variables() + return self._target_q_func_vars + + # Support both hard and soft sync. + def update_target(self, tau: int = None) -> None: + self._do_update(np.float32(tau or self.config.get("tau", 1.0))) + + def variables(self) -> List[TensorType]: + return self.model.variables() + + def set_weights(self, weights): + if isinstance(self, TFPolicy): + TFPolicy.set_weights(self, weights) + elif isinstance(self, EagerTFPolicyV2): # Handle TF2V2 policies. + EagerTFPolicyV2.set_weights(self, weights) + elif isinstance(self, EagerTFPolicy): # Handle TF2 policies. + EagerTFPolicy.set_weights(self, weights) + self.update_target(self.config.get("tau", 1.0)) + + +@OldAPIStack +class ValueNetworkMixin: + """Assigns the `_value()` method to a TFPolicy. + + This way, Policy can call `_value()` to get the current VF estimate on a + single(!) observation (as done in `postprocess_trajectory_fn`). + Note: When doing this, an actual forward pass is being performed. + This is different from only calling `model.value_function()`, where + the result of the most recent forward pass is being used to return an + already calculated tensor. + """ + + def __init__(self, config): + # When doing GAE or vtrace, we need the value function estimate on the + # observation. + if config.get("use_gae") or config.get("vtrace"): + # Input dict is provided to us automatically via the Model's + # requirements. It's a single-timestep (last one in trajectory) + # input_dict. + @make_tf_callable(self.get_session()) + def value(**input_dict): + input_dict = SampleBatch(input_dict) + if isinstance(self.model, tf.keras.Model): + _, _, extra_outs = self.model(input_dict) + return extra_outs[SampleBatch.VF_PREDS][0] + else: + model_out, _ = self.model(input_dict) + # [0] = remove the batch dim. + return self.model.value_function()[0] + + # When not doing GAE, we do not require the value function's output. + else: + + @make_tf_callable(self.get_session()) + def value(*args, **kwargs): + return tf.constant(0.0) + + self._value = value + self._should_cache_extra_action = config["framework"] == "tf" + self._cached_extra_action_fetches = None + + def _extra_action_out_impl(self) -> Dict[str, TensorType]: + extra_action_out = super().extra_action_out_fn() + # Keras models return values for each call in third return argument + # (dict). + if isinstance(self.model, tf.keras.Model): + return extra_action_out + # Return value function outputs. VF estimates will hence be added to the + # SampleBatches produced by the sampler(s) to generate the train batches + # going into the loss function. + extra_action_out.update( + { + SampleBatch.VF_PREDS: self.model.value_function(), + } + ) + return extra_action_out + + def extra_action_out_fn(self) -> Dict[str, TensorType]: + if not self._should_cache_extra_action: + return self._extra_action_out_impl() + + # Note: there are 2 reasons we are caching the extra_action_fetches for + # TF1 static graph here. + # 1. for better performance, so we don't query base class and model for + # extra fetches every single time. + # 2. for correctness. TF1 is special because the static graph may contain + # two logical graphs. One created by DynamicTFPolicy for action + # computation, and one created by MultiGPUTower for GPU training. + # Depending on which logical graph ran last time, + # self.model.value_function() will point to the output tensor + # of the specific logical graph, causing problem if we try to + # fetch action (run inference) using the training output tensor. + # For that reason, we cache the action output tensor from the + # vanilla DynamicTFPolicy once and call it a day. + if self._cached_extra_action_fetches is not None: + return self._cached_extra_action_fetches + + self._cached_extra_action_fetches = self._extra_action_out_impl() + return self._cached_extra_action_fetches + + +@OldAPIStack +class GradStatsMixin: + def __init__(self): + pass + + def grad_stats_fn( + self, train_batch: SampleBatch, grads: ModelGradients + ) -> Dict[str, TensorType]: + # We have support for more than one loss (list of lists of grads). + if self.config.get("_tf_policy_handles_more_than_one_loss"): + grad_gnorm = [tf.linalg.global_norm(g) for g in grads] + # Old case: We have a single list of grads (only one loss term and + # optimizer). + else: + grad_gnorm = tf.linalg.global_norm(grads) + + return { + "grad_gnorm": grad_gnorm, + } + + +def compute_gradients( + policy, optimizer: LocalOptimizer, loss: TensorType +) -> ModelGradients: + # Compute the gradients. + variables = policy.model.trainable_variables + if isinstance(policy.model, ModelV2): + variables = variables() + grads_and_vars = optimizer.compute_gradients(loss, variables) + + # Clip by global norm, if necessary. + if policy.config.get("grad_clip") is not None: + # Defuse inf gradients (due to super large losses). + grads = [g for (g, v) in grads_and_vars] + grads, _ = tf.clip_by_global_norm(grads, policy.config["grad_clip"]) + # If the global_norm is inf -> All grads will be NaN. Stabilize this + # here by setting them to 0.0. This will simply ignore destructive loss + # calculations. + policy.grads = [] + for g in grads: + if g is not None: + policy.grads.append(tf.where(tf.math.is_nan(g), tf.zeros_like(g), g)) + else: + policy.grads.append(None) + clipped_grads_and_vars = list(zip(policy.grads, variables)) + return clipped_grads_and_vars + else: + return grads_and_vars diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/tf_policy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/tf_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..ff68aeed8a465d16212641345a68b330a4251c53 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/tf_policy.py @@ -0,0 +1,1197 @@ +import logging +import math +from typing import Dict, List, Optional, Tuple, Union + +import gymnasium as gym +import numpy as np +import tree # pip install dm_tree + +import ray +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.policy.policy import Policy, PolicyState, PolicySpec +from ray.rllib.policy.rnn_sequencing import pad_batch_to_sequences_of_same_size +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils import force_list +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.debug import summarize +from ray.rllib.utils.deprecation import Deprecated +from ray.rllib.utils.error import ERR_MSG_TF_POLICY_CANNOT_SAVE_KERAS_MODEL +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.metrics import ( + DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY, + NUM_AGENT_STEPS_TRAINED, + NUM_GRAD_UPDATES_LIFETIME, +) +from ray.rllib.utils.metrics.learner_info import LEARNER_STATS_KEY +from ray.rllib.utils.spaces.space_utils import normalize_action +from ray.rllib.utils.tf_run_builder import _TFRunBuilder +from ray.rllib.utils.tf_utils import get_gpu_devices, TensorFlowVariables +from ray.rllib.utils.typing import ( + AlgorithmConfigDict, + LocalOptimizer, + ModelGradients, + TensorType, +) +from ray.util.debug import log_once + +tf1, tf, tfv = try_import_tf() +logger = logging.getLogger(__name__) + + +@OldAPIStack +class TFPolicy(Policy): + """An agent policy and loss implemented in TensorFlow. + + Do not sub-class this class directly (neither should you sub-class + DynamicTFPolicy), but rather use + rllib.policy.tf_policy_template.build_tf_policy + to generate your custom tf (graph-mode or eager) Policy classes. + + Extending this class enables RLlib to perform TensorFlow specific + optimizations on the policy, e.g., parallelization across gpus or + fusing multiple graphs together in the multi-agent setting. + + Input tensors are typically shaped like [BATCH_SIZE, ...]. + + .. testcode:: + :skipif: True + + from ray.rllib.policy import TFPolicy + class TFPolicySubclass(TFPolicy): + ... + + sess, obs_input, sampled_action, loss, loss_inputs = ... + policy = TFPolicySubclass( + sess, obs_input, sampled_action, loss, loss_inputs) + print(policy.compute_actions([1, 0, 2])) + print(policy.postprocess_trajectory(SampleBatch({...}))) + + .. testoutput:: + + (array([0, 1, 1]), [], {}) + SampleBatch({"action": ..., "advantages": ..., ...}) + + """ + + # In order to create tf_policies from checkpoints, this class needs to separate + # variables into their own scopes. Normally, we would do this in the model + # catalog, but since Policy.from_state() can be called anywhere, we need to + # keep track of it here to not break the from_state API. + tf_var_creation_scope_counter = 0 + + @staticmethod + def next_tf_var_scope_name(): + # Tracks multiple instances that are spawned from this policy via .from_state() + TFPolicy.tf_var_creation_scope_counter += 1 + return f"var_scope_{TFPolicy.tf_var_creation_scope_counter}" + + def __init__( + self, + observation_space: gym.spaces.Space, + action_space: gym.spaces.Space, + config: AlgorithmConfigDict, + sess: "tf1.Session", + obs_input: TensorType, + sampled_action: TensorType, + loss: Union[TensorType, List[TensorType]], + loss_inputs: List[Tuple[str, TensorType]], + model: Optional[ModelV2] = None, + sampled_action_logp: Optional[TensorType] = None, + action_input: Optional[TensorType] = None, + log_likelihood: Optional[TensorType] = None, + dist_inputs: Optional[TensorType] = None, + dist_class: Optional[type] = None, + state_inputs: Optional[List[TensorType]] = None, + state_outputs: Optional[List[TensorType]] = None, + prev_action_input: Optional[TensorType] = None, + prev_reward_input: Optional[TensorType] = None, + seq_lens: Optional[TensorType] = None, + max_seq_len: int = 20, + batch_divisibility_req: int = 1, + update_ops: List[TensorType] = None, + explore: Optional[TensorType] = None, + timestep: Optional[TensorType] = None, + ): + """Initializes a Policy object. + + Args: + observation_space: Observation space of the policy. + action_space: Action space of the policy. + config: Policy-specific configuration data. + sess: The TensorFlow session to use. + obs_input: Input placeholder for observations, of shape + [BATCH_SIZE, obs...]. + sampled_action: Tensor for sampling an action, of shape + [BATCH_SIZE, action...] + loss: Scalar policy loss output tensor or a list thereof + (in case there is more than one loss). + loss_inputs: A (name, placeholder) tuple for each loss input + argument. Each placeholder name must + correspond to a SampleBatch column key returned by + postprocess_trajectory(), and has shape [BATCH_SIZE, data...]. + These keys will be read from postprocessed sample batches and + fed into the specified placeholders during loss computation. + model: The optional ModelV2 to use for calculating actions and + losses. If not None, TFPolicy will provide functionality for + getting variables, calling the model's custom loss (if + provided), and importing weights into the model. + sampled_action_logp: log probability of the sampled action. + action_input: Input placeholder for actions for + logp/log-likelihood calculations. + log_likelihood: Tensor to calculate the log_likelihood (given + action_input and obs_input). + dist_class: An optional ActionDistribution class to use for + generating a dist object from distribution inputs. + dist_inputs: Tensor to calculate the distribution + inputs/parameters. + state_inputs: List of RNN state input Tensors. + state_outputs: List of RNN state output Tensors. + prev_action_input: placeholder for previous actions. + prev_reward_input: placeholder for previous rewards. + seq_lens: Placeholder for RNN sequence lengths, of shape + [NUM_SEQUENCES]. + Note that NUM_SEQUENCES << BATCH_SIZE. See + policy/rnn_sequencing.py for more information. + max_seq_len: Max sequence length for LSTM training. + batch_divisibility_req: pad all agent experiences batches to + multiples of this value. This only has an effect if not using + a LSTM model. + update_ops: override the batchnorm update ops + to run when applying gradients. Otherwise we run all update + ops found in the current variable scope. + explore: Placeholder for `explore` parameter into call to + Exploration.get_exploration_action. Explicitly set this to + False for not creating any Exploration component. + timestep: Placeholder for the global sampling timestep. + """ + self.framework = "tf" + super().__init__(observation_space, action_space, config) + + # Get devices to build the graph on. + num_gpus = self._get_num_gpus_for_policy() + gpu_ids = get_gpu_devices() + logger.info(f"Found {len(gpu_ids)} visible cuda devices.") + + # Place on one or more CPU(s) when either: + # - Fake GPU mode. + # - num_gpus=0 (either set by user or we are in local_mode=True). + # - no GPUs available. + if config["_fake_gpus"] or num_gpus == 0 or not gpu_ids: + self.devices = ["/cpu:0" for _ in range(int(math.ceil(num_gpus)) or 1)] + # Place on one or more actual GPU(s), when: + # - num_gpus > 0 (set by user) AND + # - local_mode=False AND + # - actual GPUs available AND + # - non-fake GPU mode. + else: + # We are a remote worker (WORKER_MODE=1): + # GPUs should be assigned to us by ray. + if ray._private.worker._mode() == ray._private.worker.WORKER_MODE: + gpu_ids = ray.get_gpu_ids() + + if len(gpu_ids) < num_gpus: + raise ValueError( + "TFPolicy was not able to find enough GPU IDs! Found " + f"{gpu_ids}, but num_gpus={num_gpus}." + ) + + self.devices = [f"/gpu:{i}" for i, _ in enumerate(gpu_ids) if i < num_gpus] + + # Disable env-info placeholder. + if SampleBatch.INFOS in self.view_requirements: + self.view_requirements[SampleBatch.INFOS].used_for_compute_actions = False + self.view_requirements[SampleBatch.INFOS].used_for_training = False + # Optionally add `infos` to the output dataset + if self.config["output_config"].get("store_infos", False): + self.view_requirements[SampleBatch.INFOS].used_for_training = True + + assert model is None or isinstance(model, (ModelV2, tf.keras.Model)), ( + "Model classes for TFPolicy other than `ModelV2|tf.keras.Model` " + "not allowed! You passed in {}.".format(model) + ) + self.model = model + # Auto-update model's inference view requirements, if recurrent. + if self.model is not None: + self._update_model_view_requirements_from_init_state() + + # If `explore` is explicitly set to False, don't create an exploration + # component. + self.exploration = self._create_exploration() if explore is not False else None + + self._sess = sess + self._obs_input = obs_input + self._prev_action_input = prev_action_input + self._prev_reward_input = prev_reward_input + self._sampled_action = sampled_action + self._is_training = self._get_is_training_placeholder() + self._is_exploring = ( + explore + if explore is not None + else tf1.placeholder_with_default(True, (), name="is_exploring") + ) + self._sampled_action_logp = sampled_action_logp + self._sampled_action_prob = ( + tf.math.exp(self._sampled_action_logp) + if self._sampled_action_logp is not None + else None + ) + self._action_input = action_input # For logp calculations. + self._dist_inputs = dist_inputs + self.dist_class = dist_class + self._cached_extra_action_out = None + self._state_inputs = state_inputs or [] + self._state_outputs = state_outputs or [] + self._seq_lens = seq_lens + self._max_seq_len = max_seq_len + + if self._state_inputs and self._seq_lens is None: + raise ValueError( + "seq_lens tensor must be given if state inputs are defined" + ) + + self._batch_divisibility_req = batch_divisibility_req + self._update_ops = update_ops + self._apply_op = None + self._stats_fetches = {} + self._timestep = ( + timestep + if timestep is not None + else tf1.placeholder_with_default( + tf.zeros((), dtype=tf.int64), (), name="timestep" + ) + ) + + self._optimizers: List[LocalOptimizer] = [] + # Backward compatibility and for some code shared with tf-eager Policy. + self._optimizer = None + + self._grads_and_vars: Union[ModelGradients, List[ModelGradients]] = [] + self._grads: Union[ModelGradients, List[ModelGradients]] = [] + # Policy tf-variables (weights), whose values to get/set via + # get_weights/set_weights. + self._variables = None + # Local optimizer(s)' tf-variables (e.g. state vars for Adam). + # Will be stored alongside `self._variables` when checkpointing. + self._optimizer_variables: Optional[TensorFlowVariables] = None + + # The loss tf-op(s). Number of losses must match number of optimizers. + self._losses = [] + # Backward compatibility (in case custom child TFPolicies access this + # property). + self._loss = None + # A batch dict passed into loss function as input. + self._loss_input_dict = {} + losses = force_list(loss) + if len(losses) > 0: + self._initialize_loss(losses, loss_inputs) + + # The log-likelihood calculator op. + self._log_likelihood = log_likelihood + if ( + self._log_likelihood is None + and self._dist_inputs is not None + and self.dist_class is not None + ): + self._log_likelihood = self.dist_class(self._dist_inputs, self.model).logp( + self._action_input + ) + + @override(Policy) + def compute_actions_from_input_dict( + self, + input_dict: Union[SampleBatch, Dict[str, TensorType]], + explore: bool = None, + timestep: Optional[int] = None, + episode=None, + **kwargs, + ) -> Tuple[TensorType, List[TensorType], Dict[str, TensorType]]: + explore = explore if explore is not None else self.config["explore"] + timestep = timestep if timestep is not None else self.global_timestep + + # Switch off is_training flag in our batch. + if isinstance(input_dict, SampleBatch): + input_dict.set_training(False) + else: + # Deprecated dict input. + input_dict["is_training"] = False + + builder = _TFRunBuilder(self.get_session(), "compute_actions_from_input_dict") + obs_batch = input_dict[SampleBatch.OBS] + to_fetch = self._build_compute_actions( + builder, input_dict=input_dict, explore=explore, timestep=timestep + ) + + # Execute session run to get action (and other fetches). + fetched = builder.get(to_fetch) + + # Update our global timestep by the batch size. + self.global_timestep += ( + len(obs_batch) + if isinstance(obs_batch, list) + else len(input_dict) + if isinstance(input_dict, SampleBatch) + else obs_batch.shape[0] + ) + + return fetched + + @override(Policy) + def compute_actions( + self, + obs_batch: Union[List[TensorType], TensorType], + state_batches: Optional[List[TensorType]] = None, + prev_action_batch: Union[List[TensorType], TensorType] = None, + prev_reward_batch: Union[List[TensorType], TensorType] = None, + info_batch: Optional[Dict[str, list]] = None, + episodes=None, + explore: Optional[bool] = None, + timestep: Optional[int] = None, + **kwargs, + ): + explore = explore if explore is not None else self.config["explore"] + timestep = timestep if timestep is not None else self.global_timestep + + builder = _TFRunBuilder(self.get_session(), "compute_actions") + + input_dict = {SampleBatch.OBS: obs_batch, "is_training": False} + if state_batches: + for i, s in enumerate(state_batches): + input_dict[f"state_in_{i}"] = s + if prev_action_batch is not None: + input_dict[SampleBatch.PREV_ACTIONS] = prev_action_batch + if prev_reward_batch is not None: + input_dict[SampleBatch.PREV_REWARDS] = prev_reward_batch + + to_fetch = self._build_compute_actions( + builder, input_dict=input_dict, explore=explore, timestep=timestep + ) + + # Execute session run to get action (and other fetches). + fetched = builder.get(to_fetch) + + # Update our global timestep by the batch size. + self.global_timestep += ( + len(obs_batch) + if isinstance(obs_batch, list) + else tree.flatten(obs_batch)[0].shape[0] + ) + + return fetched + + @override(Policy) + def compute_log_likelihoods( + self, + actions: Union[List[TensorType], TensorType], + obs_batch: Union[List[TensorType], TensorType], + state_batches: Optional[List[TensorType]] = None, + prev_action_batch: Optional[Union[List[TensorType], TensorType]] = None, + prev_reward_batch: Optional[Union[List[TensorType], TensorType]] = None, + actions_normalized: bool = True, + **kwargs, + ) -> TensorType: + if self._log_likelihood is None: + raise ValueError( + "Cannot compute log-prob/likelihood w/o a self._log_likelihood op!" + ) + + # Exploration hook before each forward pass. + self.exploration.before_compute_actions( + explore=False, tf_sess=self.get_session() + ) + + builder = _TFRunBuilder(self.get_session(), "compute_log_likelihoods") + + # Normalize actions if necessary. + if actions_normalized is False and self.config["normalize_actions"]: + actions = normalize_action(actions, self.action_space_struct) + + # Feed actions (for which we want logp values) into graph. + builder.add_feed_dict({self._action_input: actions}) + # Feed observations. + builder.add_feed_dict({self._obs_input: obs_batch}) + # Internal states. + state_batches = state_batches or [] + if len(self._state_inputs) != len(state_batches): + raise ValueError( + "Must pass in RNN state batches for placeholders {}, got {}".format( + self._state_inputs, state_batches + ) + ) + builder.add_feed_dict(dict(zip(self._state_inputs, state_batches))) + if state_batches: + builder.add_feed_dict({self._seq_lens: np.ones(len(obs_batch))}) + # Prev-a and r. + if self._prev_action_input is not None and prev_action_batch is not None: + builder.add_feed_dict({self._prev_action_input: prev_action_batch}) + if self._prev_reward_input is not None and prev_reward_batch is not None: + builder.add_feed_dict({self._prev_reward_input: prev_reward_batch}) + # Fetch the log_likelihoods output and return. + fetches = builder.add_fetches([self._log_likelihood]) + return builder.get(fetches)[0] + + @override(Policy) + def learn_on_batch(self, postprocessed_batch: SampleBatch) -> Dict[str, TensorType]: + assert self.loss_initialized() + + # Switch on is_training flag in our batch. + postprocessed_batch.set_training(True) + + builder = _TFRunBuilder(self.get_session(), "learn_on_batch") + + # Callback handling. + learn_stats = {} + self.callbacks.on_learn_on_batch( + policy=self, train_batch=postprocessed_batch, result=learn_stats + ) + + fetches = self._build_learn_on_batch(builder, postprocessed_batch) + stats = builder.get(fetches) + self.num_grad_updates += 1 + + stats.update( + { + "custom_metrics": learn_stats, + NUM_AGENT_STEPS_TRAINED: postprocessed_batch.count, + NUM_GRAD_UPDATES_LIFETIME: self.num_grad_updates, + # -1, b/c we have to measure this diff before we do the update above. + DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY: ( + self.num_grad_updates + - 1 + - (postprocessed_batch.num_grad_updates or 0) + ), + } + ) + + return stats + + @override(Policy) + def compute_gradients( + self, postprocessed_batch: SampleBatch + ) -> Tuple[ModelGradients, Dict[str, TensorType]]: + assert self.loss_initialized() + # Switch on is_training flag in our batch. + postprocessed_batch.set_training(True) + builder = _TFRunBuilder(self.get_session(), "compute_gradients") + fetches = self._build_compute_gradients(builder, postprocessed_batch) + return builder.get(fetches) + + @staticmethod + def _tf1_from_state_helper(state: PolicyState) -> "Policy": + """Recovers a TFPolicy from a state object. + + The `state` of an instantiated TFPolicy can be retrieved by calling its + `get_state` method. Is meant to be used by the Policy.from_state() method to + aid with tracking variable creation. + + Args: + state: The state to recover a new TFPolicy instance from. + + Returns: + A new TFPolicy instance. + """ + serialized_pol_spec: Optional[dict] = state.get("policy_spec") + if serialized_pol_spec is None: + raise ValueError( + "No `policy_spec` key was found in given `state`! " + "Cannot create new Policy." + ) + pol_spec = PolicySpec.deserialize(serialized_pol_spec) + + with tf1.variable_scope(TFPolicy.next_tf_var_scope_name()): + # Create the new policy. + new_policy = pol_spec.policy_class( + # Note(jungong) : we are intentionally not using keyward arguments here + # because some policies name the observation space parameter obs_space, + # and some others name it observation_space. + pol_spec.observation_space, + pol_spec.action_space, + pol_spec.config, + ) + + # Set the new policy's state (weights, optimizer vars, exploration state, + # etc..). + new_policy.set_state(state) + + # Return the new policy. + return new_policy + + @override(Policy) + def apply_gradients(self, gradients: ModelGradients) -> None: + assert self.loss_initialized() + builder = _TFRunBuilder(self.get_session(), "apply_gradients") + fetches = self._build_apply_gradients(builder, gradients) + builder.get(fetches) + + @override(Policy) + def get_weights(self) -> Union[Dict[str, TensorType], List[TensorType]]: + return self._variables.get_weights() + + @override(Policy) + def set_weights(self, weights) -> None: + return self._variables.set_weights(weights) + + @override(Policy) + def get_exploration_state(self) -> Dict[str, TensorType]: + return self.exploration.get_state(sess=self.get_session()) + + @Deprecated(new="get_exploration_state", error=True) + def get_exploration_info(self) -> Dict[str, TensorType]: + return self.get_exploration_state() + + @override(Policy) + def is_recurrent(self) -> bool: + return len(self._state_inputs) > 0 + + @override(Policy) + def num_state_tensors(self) -> int: + return len(self._state_inputs) + + @override(Policy) + def get_state(self) -> PolicyState: + # For tf Policies, return Policy weights and optimizer var values. + state = super().get_state() + + if len(self._optimizer_variables.variables) > 0: + state["_optimizer_variables"] = self.get_session().run( + self._optimizer_variables.variables + ) + # Add exploration state. + state["_exploration_state"] = self.exploration.get_state(self.get_session()) + return state + + @override(Policy) + def set_state(self, state: PolicyState) -> None: + # Set optimizer vars first. + optimizer_vars = state.get("_optimizer_variables", None) + if optimizer_vars is not None: + self._optimizer_variables.set_weights(optimizer_vars) + # Set exploration's state. + if hasattr(self, "exploration") and "_exploration_state" in state: + self.exploration.set_state( + state=state["_exploration_state"], sess=self.get_session() + ) + + # Restore global timestep. + self.global_timestep = state["global_timestep"] + + # Then the Policy's (NN) weights and connectors. + super().set_state(state) + + @override(Policy) + def export_model(self, export_dir: str, onnx: Optional[int] = None) -> None: + """Export tensorflow graph to export_dir for serving.""" + if onnx: + try: + import tf2onnx + except ImportError as e: + raise RuntimeError( + "Converting a TensorFlow model to ONNX requires " + "`tf2onnx` to be installed. Install with " + "`pip install tf2onnx`." + ) from e + + with self.get_session().graph.as_default(): + signature_def_map = self._build_signature_def() + + sd = signature_def_map[ + tf1.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY # noqa: E501 + ] + inputs = [v.name for k, v in sd.inputs.items()] + outputs = [v.name for k, v in sd.outputs.items()] + + from tf2onnx import tf_loader + + frozen_graph_def = tf_loader.freeze_session( + self.get_session(), input_names=inputs, output_names=outputs + ) + + with tf1.Session(graph=tf.Graph()) as session: + tf.import_graph_def(frozen_graph_def, name="") + + g = tf2onnx.tfonnx.process_tf_graph( + session.graph, + input_names=inputs, + output_names=outputs, + inputs_as_nchw=inputs, + ) + + model_proto = g.make_model("onnx_model") + tf2onnx.utils.save_onnx_model( + export_dir, "model", feed_dict={}, model_proto=model_proto + ) + # Save the tf.keras.Model (architecture and weights, so it can be retrieved + # w/o access to the original (custom) Model or Policy code). + elif ( + hasattr(self, "model") + and hasattr(self.model, "base_model") + and isinstance(self.model.base_model, tf.keras.Model) + ): + with self.get_session().graph.as_default(): + try: + self.model.base_model.save(filepath=export_dir, save_format="tf") + except Exception: + logger.warning(ERR_MSG_TF_POLICY_CANNOT_SAVE_KERAS_MODEL) + else: + logger.warning(ERR_MSG_TF_POLICY_CANNOT_SAVE_KERAS_MODEL) + + @override(Policy) + def import_model_from_h5(self, import_file: str) -> None: + """Imports weights into tf model.""" + if self.model is None: + raise NotImplementedError("No `self.model` to import into!") + + # Make sure the session is the right one (see issue #7046). + with self.get_session().graph.as_default(): + with self.get_session().as_default(): + return self.model.import_from_h5(import_file) + + @override(Policy) + def get_session(self) -> Optional["tf1.Session"]: + """Returns a reference to the TF session for this policy.""" + return self._sess + + def variables(self): + """Return the list of all savable variables for this policy.""" + if self.model is None: + raise NotImplementedError("No `self.model` to get variables for!") + elif isinstance(self.model, tf.keras.Model): + return self.model.variables + else: + return self.model.variables() + + def get_placeholder(self, name) -> "tf1.placeholder": + """Returns the given action or loss input placeholder by name. + + If the loss has not been initialized and a loss input placeholder is + requested, an error is raised. + + Args: + name: The name of the placeholder to return. One of + SampleBatch.CUR_OBS|PREV_ACTION/REWARD or a valid key from + `self._loss_input_dict`. + + Returns: + tf1.placeholder: The placeholder under the given str key. + """ + if name == SampleBatch.CUR_OBS: + return self._obs_input + elif name == SampleBatch.PREV_ACTIONS: + return self._prev_action_input + elif name == SampleBatch.PREV_REWARDS: + return self._prev_reward_input + + assert self._loss_input_dict, ( + "You need to populate `self._loss_input_dict` before " + "`get_placeholder()` can be called" + ) + return self._loss_input_dict[name] + + def loss_initialized(self) -> bool: + """Returns whether the loss term(s) have been initialized.""" + return len(self._losses) > 0 + + def _initialize_loss( + self, losses: List[TensorType], loss_inputs: List[Tuple[str, TensorType]] + ) -> None: + """Initializes the loss op from given loss tensor and placeholders. + + Args: + loss (List[TensorType]): The list of loss ops returned by some + loss function. + loss_inputs (List[Tuple[str, TensorType]]): The list of Tuples: + (name, tf1.placeholders) needed for calculating the loss. + """ + self._loss_input_dict = dict(loss_inputs) + self._loss_input_dict_no_rnn = { + k: v + for k, v in self._loss_input_dict.items() + if (v not in self._state_inputs and v != self._seq_lens) + } + for i, ph in enumerate(self._state_inputs): + self._loss_input_dict["state_in_{}".format(i)] = ph + + if self.model and not isinstance(self.model, tf.keras.Model): + self._losses = force_list( + self.model.custom_loss(losses, self._loss_input_dict) + ) + self._stats_fetches.update({"model": self.model.metrics()}) + else: + self._losses = losses + # Backward compatibility. + self._loss = self._losses[0] if self._losses is not None else None + + if not self._optimizers: + self._optimizers = force_list(self.optimizer()) + # Backward compatibility. + self._optimizer = self._optimizers[0] if self._optimizers else None + + # Supporting more than one loss/optimizer. + if self.config["_tf_policy_handles_more_than_one_loss"]: + self._grads_and_vars = [] + self._grads = [] + for group in self.gradients(self._optimizers, self._losses): + g_and_v = [(g, v) for (g, v) in group if g is not None] + self._grads_and_vars.append(g_and_v) + self._grads.append([g for (g, _) in g_and_v]) + # Only one optimizer and and loss term. + else: + self._grads_and_vars = [ + (g, v) + for (g, v) in self.gradients(self._optimizer, self._loss) + if g is not None + ] + self._grads = [g for (g, _) in self._grads_and_vars] + + if self.model: + self._variables = TensorFlowVariables( + [], self.get_session(), self.variables() + ) + + # Gather update ops for any batch norm layers. + if len(self.devices) <= 1: + if not self._update_ops: + self._update_ops = tf1.get_collection( + tf1.GraphKeys.UPDATE_OPS, scope=tf1.get_variable_scope().name + ) + if self._update_ops: + logger.info( + "Update ops to run on apply gradient: {}".format(self._update_ops) + ) + with tf1.control_dependencies(self._update_ops): + self._apply_op = self.build_apply_op( + optimizer=self._optimizers + if self.config["_tf_policy_handles_more_than_one_loss"] + else self._optimizer, + grads_and_vars=self._grads_and_vars, + ) + + if log_once("loss_used"): + logger.debug( + "These tensors were used in the loss functions:" + f"\n{summarize(self._loss_input_dict)}\n" + ) + + self.get_session().run(tf1.global_variables_initializer()) + + # TensorFlowVariables holding a flat list of all our optimizers' + # variables. + self._optimizer_variables = TensorFlowVariables( + [v for o in self._optimizers for v in o.variables()], self.get_session() + ) + + def copy(self, existing_inputs: List[Tuple[str, "tf1.placeholder"]]) -> "TFPolicy": + """Creates a copy of self using existing input placeholders. + + Optional: Only required to work with the multi-GPU optimizer. + + Args: + existing_inputs (List[Tuple[str, tf1.placeholder]]): Dict mapping + names (str) to tf1.placeholders to re-use (share) with the + returned copy of self. + + Returns: + TFPolicy: A copy of self. + """ + raise NotImplementedError + + def extra_compute_action_feed_dict(self) -> Dict[TensorType, TensorType]: + """Extra dict to pass to the compute actions session run. + + Returns: + Dict[TensorType, TensorType]: A feed dict to be added to the + feed_dict passed to the compute_actions session.run() call. + """ + return {} + + def extra_compute_action_fetches(self) -> Dict[str, TensorType]: + # Cache graph fetches for action computation for better + # performance. + # This function is called every time the static graph is run + # to compute actions. + if not self._cached_extra_action_out: + self._cached_extra_action_out = self.extra_action_out_fn() + return self._cached_extra_action_out + + def extra_action_out_fn(self) -> Dict[str, TensorType]: + """Extra values to fetch and return from compute_actions(). + + By default we return action probability/log-likelihood info + and action distribution inputs (if present). + + Returns: + Dict[str, TensorType]: An extra fetch-dict to be passed to and + returned from the compute_actions() call. + """ + extra_fetches = {} + # Action-logp and action-prob. + if self._sampled_action_logp is not None: + extra_fetches[SampleBatch.ACTION_PROB] = self._sampled_action_prob + extra_fetches[SampleBatch.ACTION_LOGP] = self._sampled_action_logp + # Action-dist inputs. + if self._dist_inputs is not None: + extra_fetches[SampleBatch.ACTION_DIST_INPUTS] = self._dist_inputs + return extra_fetches + + def extra_compute_grad_feed_dict(self) -> Dict[TensorType, TensorType]: + """Extra dict to pass to the compute gradients session run. + + Returns: + Dict[TensorType, TensorType]: Extra feed_dict to be passed to the + compute_gradients Session.run() call. + """ + return {} # e.g, kl_coeff + + def extra_compute_grad_fetches(self) -> Dict[str, any]: + """Extra values to fetch and return from compute_gradients(). + + Returns: + Dict[str, any]: Extra fetch dict to be added to the fetch dict + of the compute_gradients Session.run() call. + """ + return {LEARNER_STATS_KEY: {}} # e.g, stats, td error, etc. + + def optimizer(self) -> "tf.keras.optimizers.Optimizer": + """TF optimizer to use for policy optimization. + + Returns: + tf.keras.optimizers.Optimizer: The local optimizer to use for this + Policy's Model. + """ + if hasattr(self, "config") and "lr" in self.config: + return tf1.train.AdamOptimizer(learning_rate=self.config["lr"]) + else: + return tf1.train.AdamOptimizer() + + def gradients( + self, + optimizer: Union[LocalOptimizer, List[LocalOptimizer]], + loss: Union[TensorType, List[TensorType]], + ) -> Union[List[ModelGradients], List[List[ModelGradients]]]: + """Override this for a custom gradient computation behavior. + + Args: + optimizer (Union[LocalOptimizer, List[LocalOptimizer]]): A single + LocalOptimizer of a list thereof to use for gradient + calculations. If more than one optimizer given, the number of + optimizers must match the number of losses provided. + loss (Union[TensorType, List[TensorType]]): A single loss term + or a list thereof to use for gradient calculations. + If more than one loss given, the number of loss terms must + match the number of optimizers provided. + + Returns: + Union[List[ModelGradients], List[List[ModelGradients]]]: List of + ModelGradients (grads and vars OR just grads) OR List of List + of ModelGradients in case we have more than one + optimizer/loss. + """ + optimizers = force_list(optimizer) + losses = force_list(loss) + + # We have more than one optimizers and loss terms. + if self.config["_tf_policy_handles_more_than_one_loss"]: + grads = [] + for optim, loss_ in zip(optimizers, losses): + grads.append(optim.compute_gradients(loss_)) + # We have only one optimizer and one loss term. + else: + return optimizers[0].compute_gradients(losses[0]) + + def build_apply_op( + self, + optimizer: Union[LocalOptimizer, List[LocalOptimizer]], + grads_and_vars: Union[ModelGradients, List[ModelGradients]], + ) -> "tf.Operation": + """Override this for a custom gradient apply computation behavior. + + Args: + optimizer (Union[LocalOptimizer, List[LocalOptimizer]]): The local + tf optimizer to use for applying the grads and vars. + grads_and_vars (Union[ModelGradients, List[ModelGradients]]): List + of tuples with grad values and the grad-value's corresponding + tf.variable in it. + + Returns: + tf.Operation: The tf op that applies all computed gradients + (`grads_and_vars`) to the model(s) via the given optimizer(s). + """ + optimizers = force_list(optimizer) + + # We have more than one optimizers and loss terms. + if self.config["_tf_policy_handles_more_than_one_loss"]: + ops = [] + for i, optim in enumerate(optimizers): + # Specify global_step (e.g. for TD3 which needs to count the + # num updates that have happened). + ops.append( + optim.apply_gradients( + grads_and_vars[i], + global_step=tf1.train.get_or_create_global_step(), + ) + ) + return tf.group(ops) + # We have only one optimizer and one loss term. + else: + return optimizers[0].apply_gradients( + grads_and_vars, global_step=tf1.train.get_or_create_global_step() + ) + + def _get_is_training_placeholder(self): + """Get the placeholder for _is_training, i.e., for batch norm layers. + + This can be called safely before __init__ has run. + """ + if not hasattr(self, "_is_training"): + self._is_training = tf1.placeholder_with_default( + False, (), name="is_training" + ) + return self._is_training + + def _debug_vars(self): + if log_once("grad_vars"): + if self.config["_tf_policy_handles_more_than_one_loss"]: + for group in self._grads_and_vars: + for _, v in group: + logger.info("Optimizing variable {}".format(v)) + else: + for _, v in self._grads_and_vars: + logger.info("Optimizing variable {}".format(v)) + + def _extra_input_signature_def(self): + """Extra input signatures to add when exporting tf model. + Inferred from extra_compute_action_feed_dict() + """ + feed_dict = self.extra_compute_action_feed_dict() + return { + k.name: tf1.saved_model.utils.build_tensor_info(k) for k in feed_dict.keys() + } + + def _extra_output_signature_def(self): + """Extra output signatures to add when exporting tf model. + Inferred from extra_compute_action_fetches() + """ + fetches = self.extra_compute_action_fetches() + return { + k: tf1.saved_model.utils.build_tensor_info(fetches[k]) + for k in fetches.keys() + } + + def _build_signature_def(self): + """Build signature def map for tensorflow SavedModelBuilder.""" + # build input signatures + input_signature = self._extra_input_signature_def() + input_signature["observations"] = tf1.saved_model.utils.build_tensor_info( + self._obs_input + ) + + if self._seq_lens is not None: + input_signature[ + SampleBatch.SEQ_LENS + ] = tf1.saved_model.utils.build_tensor_info(self._seq_lens) + if self._prev_action_input is not None: + input_signature["prev_action"] = tf1.saved_model.utils.build_tensor_info( + self._prev_action_input + ) + if self._prev_reward_input is not None: + input_signature["prev_reward"] = tf1.saved_model.utils.build_tensor_info( + self._prev_reward_input + ) + + input_signature["is_training"] = tf1.saved_model.utils.build_tensor_info( + self._is_training + ) + + if self._timestep is not None: + input_signature["timestep"] = tf1.saved_model.utils.build_tensor_info( + self._timestep + ) + + for state_input in self._state_inputs: + input_signature[state_input.name] = tf1.saved_model.utils.build_tensor_info( + state_input + ) + + # build output signatures + output_signature = self._extra_output_signature_def() + for i, a in enumerate(tf.nest.flatten(self._sampled_action)): + output_signature[ + "actions_{}".format(i) + ] = tf1.saved_model.utils.build_tensor_info(a) + + for state_output in self._state_outputs: + output_signature[ + state_output.name + ] = tf1.saved_model.utils.build_tensor_info(state_output) + signature_def = tf1.saved_model.signature_def_utils.build_signature_def( + input_signature, + output_signature, + tf1.saved_model.signature_constants.PREDICT_METHOD_NAME, + ) + signature_def_key = ( + tf1.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY + ) + signature_def_map = {signature_def_key: signature_def} + return signature_def_map + + def _build_compute_actions( + self, + builder, + *, + input_dict=None, + obs_batch=None, + state_batches=None, + prev_action_batch=None, + prev_reward_batch=None, + episodes=None, + explore=None, + timestep=None, + ): + explore = explore if explore is not None else self.config["explore"] + timestep = timestep if timestep is not None else self.global_timestep + + # Call the exploration before_compute_actions hook. + self.exploration.before_compute_actions( + timestep=timestep, explore=explore, tf_sess=self.get_session() + ) + + builder.add_feed_dict(self.extra_compute_action_feed_dict()) + + # `input_dict` given: Simply build what's in that dict. + if hasattr(self, "_input_dict"): + for key, value in input_dict.items(): + if key in self._input_dict: + # Handle complex/nested spaces as well. + tree.map_structure( + lambda k, v: builder.add_feed_dict({k: v}), + self._input_dict[key], + value, + ) + # For policies that inherit directly from TFPolicy. + else: + builder.add_feed_dict({self._obs_input: input_dict[SampleBatch.OBS]}) + if SampleBatch.PREV_ACTIONS in input_dict: + builder.add_feed_dict( + {self._prev_action_input: input_dict[SampleBatch.PREV_ACTIONS]} + ) + if SampleBatch.PREV_REWARDS in input_dict: + builder.add_feed_dict( + {self._prev_reward_input: input_dict[SampleBatch.PREV_REWARDS]} + ) + state_batches = [] + i = 0 + while "state_in_{}".format(i) in input_dict: + state_batches.append(input_dict["state_in_{}".format(i)]) + i += 1 + builder.add_feed_dict(dict(zip(self._state_inputs, state_batches))) + + if "state_in_0" in input_dict and SampleBatch.SEQ_LENS not in input_dict: + builder.add_feed_dict( + {self._seq_lens: np.ones(len(input_dict["state_in_0"]))} + ) + + builder.add_feed_dict({self._is_exploring: explore}) + if timestep is not None: + builder.add_feed_dict({self._timestep: timestep}) + + # Determine, what exactly to fetch from the graph. + to_fetch = ( + [self._sampled_action] + + self._state_outputs + + [self.extra_compute_action_fetches()] + ) + + # Add the ops to fetch for the upcoming session call. + fetches = builder.add_fetches(to_fetch) + return fetches[0], fetches[1:-1], fetches[-1] + + def _build_compute_gradients(self, builder, postprocessed_batch): + self._debug_vars() + builder.add_feed_dict(self.extra_compute_grad_feed_dict()) + builder.add_feed_dict( + self._get_loss_inputs_dict(postprocessed_batch, shuffle=False) + ) + fetches = builder.add_fetches([self._grads, self._get_grad_and_stats_fetches()]) + return fetches[0], fetches[1] + + def _build_apply_gradients(self, builder, gradients): + if len(gradients) != len(self._grads): + raise ValueError( + "Unexpected number of gradients to apply, got {} for {}".format( + gradients, self._grads + ) + ) + builder.add_feed_dict({self._is_training: True}) + builder.add_feed_dict(dict(zip(self._grads, gradients))) + fetches = builder.add_fetches([self._apply_op]) + return fetches[0] + + def _build_learn_on_batch(self, builder, postprocessed_batch): + self._debug_vars() + + builder.add_feed_dict(self.extra_compute_grad_feed_dict()) + builder.add_feed_dict( + self._get_loss_inputs_dict(postprocessed_batch, shuffle=False) + ) + fetches = builder.add_fetches( + [ + self._apply_op, + self._get_grad_and_stats_fetches(), + ] + ) + return fetches[1] + + def _get_grad_and_stats_fetches(self): + fetches = self.extra_compute_grad_fetches() + if LEARNER_STATS_KEY not in fetches: + raise ValueError("Grad fetches should contain 'stats': {...} entry") + if self._stats_fetches: + fetches[LEARNER_STATS_KEY] = dict( + self._stats_fetches, **fetches[LEARNER_STATS_KEY] + ) + return fetches + + def _get_loss_inputs_dict(self, train_batch: SampleBatch, shuffle: bool): + """Return a feed dict from a batch. + + Args: + train_batch: batch of data to derive inputs from. + shuffle: whether to shuffle batch sequences. Shuffle may + be done in-place. This only makes sense if you're further + applying minibatch SGD after getting the outputs. + + Returns: + Feed dict of data. + """ + + # Get batch ready for RNNs, if applicable. + if not isinstance(train_batch, SampleBatch) or not train_batch.zero_padded: + pad_batch_to_sequences_of_same_size( + train_batch, + max_seq_len=self._max_seq_len, + shuffle=shuffle, + batch_divisibility_req=self._batch_divisibility_req, + feature_keys=list(self._loss_input_dict_no_rnn.keys()), + view_requirements=self.view_requirements, + ) + + # Mark the batch as "is_training" so the Model can use this + # information. + train_batch.set_training(True) + + # Build the feed dict from the batch. + feed_dict = {} + for key, placeholders in self._loss_input_dict.items(): + a = tree.map_structure( + lambda ph, v: feed_dict.__setitem__(ph, v), + placeholders, + train_batch[key], + ) + del a + + state_keys = ["state_in_{}".format(i) for i in range(len(self._state_inputs))] + for key in state_keys: + feed_dict[self._loss_input_dict[key]] = train_batch[key] + if state_keys: + feed_dict[self._seq_lens] = train_batch[SampleBatch.SEQ_LENS] + + return feed_dict diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/tf_policy_template.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/tf_policy_template.py new file mode 100644 index 0000000000000000000000000000000000000000..d82e0691b362e7b54da439717d058638af5f899b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/tf_policy_template.py @@ -0,0 +1,365 @@ +import gymnasium as gym +from typing import Callable, Dict, List, Optional, Tuple, Type, Union + +from ray.rllib.models.tf.tf_action_dist import TFActionDistribution +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.policy.dynamic_tf_policy import DynamicTFPolicy +from ray.rllib.policy import eager_tf_policy +from ray.rllib.policy.policy import Policy +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy.tf_policy import TFPolicy +from ray.rllib.utils import add_mixins, force_list +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.deprecation import ( + deprecation_warning, + DEPRECATED_VALUE, +) +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.metrics.learner_info import LEARNER_STATS_KEY +from ray.rllib.utils.typing import ( + ModelGradients, + TensorType, + AlgorithmConfigDict, +) + +tf1, tf, tfv = try_import_tf() + + +@OldAPIStack +def build_tf_policy( + name: str, + *, + loss_fn: Callable[ + [Policy, ModelV2, Type[TFActionDistribution], SampleBatch], + Union[TensorType, List[TensorType]], + ], + get_default_config: Optional[Callable[[None], AlgorithmConfigDict]] = None, + postprocess_fn=None, + stats_fn: Optional[Callable[[Policy, SampleBatch], Dict[str, TensorType]]] = None, + optimizer_fn: Optional[ + Callable[[Policy, AlgorithmConfigDict], "tf.keras.optimizers.Optimizer"] + ] = None, + compute_gradients_fn: Optional[ + Callable[[Policy, "tf.keras.optimizers.Optimizer", TensorType], ModelGradients] + ] = None, + apply_gradients_fn: Optional[ + Callable[ + [Policy, "tf.keras.optimizers.Optimizer", ModelGradients], "tf.Operation" + ] + ] = None, + grad_stats_fn: Optional[ + Callable[[Policy, SampleBatch, ModelGradients], Dict[str, TensorType]] + ] = None, + extra_action_out_fn: Optional[Callable[[Policy], Dict[str, TensorType]]] = None, + extra_learn_fetches_fn: Optional[Callable[[Policy], Dict[str, TensorType]]] = None, + validate_spaces: Optional[ + Callable[[Policy, gym.Space, gym.Space, AlgorithmConfigDict], None] + ] = None, + before_init: Optional[ + Callable[[Policy, gym.Space, gym.Space, AlgorithmConfigDict], None] + ] = None, + before_loss_init: Optional[ + Callable[ + [Policy, gym.spaces.Space, gym.spaces.Space, AlgorithmConfigDict], None + ] + ] = None, + after_init: Optional[ + Callable[[Policy, gym.Space, gym.Space, AlgorithmConfigDict], None] + ] = None, + make_model: Optional[ + Callable[ + [Policy, gym.spaces.Space, gym.spaces.Space, AlgorithmConfigDict], ModelV2 + ] + ] = None, + action_sampler_fn: Optional[ + Callable[[TensorType, List[TensorType]], Tuple[TensorType, TensorType]] + ] = None, + action_distribution_fn: Optional[ + Callable[ + [Policy, ModelV2, TensorType, TensorType, TensorType], + Tuple[TensorType, type, List[TensorType]], + ] + ] = None, + mixins: Optional[List[type]] = None, + get_batch_divisibility_req: Optional[Callable[[Policy], int]] = None, + # Deprecated args. + obs_include_prev_action_reward=DEPRECATED_VALUE, + extra_action_fetches_fn=None, # Use `extra_action_out_fn`. + gradients_fn=None, # Use `compute_gradients_fn`. +) -> Type[DynamicTFPolicy]: + """Helper function for creating a dynamic tf policy at runtime. + + Functions will be run in this order to initialize the policy: + 1. Placeholder setup: postprocess_fn + 2. Loss init: loss_fn, stats_fn + 3. Optimizer init: optimizer_fn, gradients_fn, apply_gradients_fn, + grad_stats_fn + + This means that you can e.g., depend on any policy attributes created in + the running of `loss_fn` in later functions such as `stats_fn`. + + In eager mode, the following functions will be run repeatedly on each + eager execution: loss_fn, stats_fn, gradients_fn, apply_gradients_fn, + and grad_stats_fn. + + This means that these functions should not define any variables internally, + otherwise they will fail in eager mode execution. Variable should only + be created in make_model (if defined). + + Args: + name: Name of the policy (e.g., "PPOTFPolicy"). + loss_fn (Callable[[ + Policy, ModelV2, Type[TFActionDistribution], SampleBatch], + Union[TensorType, List[TensorType]]]): Callable for calculating a + loss tensor. + get_default_config (Optional[Callable[[None], AlgorithmConfigDict]]): + Optional callable that returns the default config to merge with any + overrides. If None, uses only(!) the user-provided + PartialAlgorithmConfigDict as dict for this Policy. + postprocess_fn (Optional[Callable[[Policy, SampleBatch, + Optional[Dict[AgentID, SampleBatch]], Episode], None]]): + Optional callable for post-processing experience batches (called + after the parent class' `postprocess_trajectory` method). + stats_fn (Optional[Callable[[Policy, SampleBatch], + Dict[str, TensorType]]]): Optional callable that returns a dict of + TF tensors to fetch given the policy and batch input tensors. If + None, will not compute any stats. + optimizer_fn (Optional[Callable[[Policy, AlgorithmConfigDict], + "tf.keras.optimizers.Optimizer"]]): Optional callable that returns + a tf.Optimizer given the policy and config. If None, will call + the base class' `optimizer()` method instead (which returns a + tf1.train.AdamOptimizer). + compute_gradients_fn (Optional[Callable[[Policy, + "tf.keras.optimizers.Optimizer", TensorType], ModelGradients]]): + Optional callable that returns a list of gradients. If None, + this defaults to optimizer.compute_gradients([loss]). + apply_gradients_fn (Optional[Callable[[Policy, + "tf.keras.optimizers.Optimizer", ModelGradients], + "tf.Operation"]]): Optional callable that returns an apply + gradients op given policy, tf-optimizer, and grads_and_vars. If + None, will call the base class' `build_apply_op()` method instead. + grad_stats_fn (Optional[Callable[[Policy, SampleBatch, ModelGradients], + Dict[str, TensorType]]]): Optional callable that returns a dict of + TF fetches given the policy, batch input, and gradient tensors. If + None, will not collect any gradient stats. + extra_action_out_fn (Optional[Callable[[Policy], + Dict[str, TensorType]]]): Optional callable that returns + a dict of TF fetches given the policy object. If None, will not + perform any extra fetches. + extra_learn_fetches_fn (Optional[Callable[[Policy], + Dict[str, TensorType]]]): Optional callable that returns a dict of + extra values to fetch and return when learning on a batch. If None, + will call the base class' `extra_compute_grad_fetches()` method + instead. + validate_spaces (Optional[Callable[[Policy, gym.Space, gym.Space, + AlgorithmConfigDict], None]]): Optional callable that takes the + Policy, observation_space, action_space, and config to check + the spaces for correctness. If None, no spaces checking will be + done. + before_init (Optional[Callable[[Policy, gym.Space, gym.Space, + AlgorithmConfigDict], None]]): Optional callable to run at the + beginning of policy init that takes the same arguments as the + policy constructor. If None, this step will be skipped. + before_loss_init (Optional[Callable[[Policy, gym.spaces.Space, + gym.spaces.Space, AlgorithmConfigDict], None]]): Optional callable to + run prior to loss init. If None, this step will be skipped. + after_init (Optional[Callable[[Policy, gym.Space, gym.Space, + AlgorithmConfigDict], None]]): Optional callable to run at the end of + policy init. If None, this step will be skipped. + make_model (Optional[Callable[[Policy, gym.spaces.Space, + gym.spaces.Space, AlgorithmConfigDict], ModelV2]]): Optional callable + that returns a ModelV2 object. + All policy variables should be created in this function. If None, + a default ModelV2 object will be created. + action_sampler_fn (Optional[Callable[[TensorType, List[TensorType]], + Tuple[TensorType, TensorType]]]): A callable returning a sampled + action and its log-likelihood given observation and state inputs. + If None, will either use `action_distribution_fn` or + compute actions by calling self.model, then sampling from the + so parameterized action distribution. + action_distribution_fn (Optional[Callable[[Policy, ModelV2, TensorType, + TensorType, TensorType], + Tuple[TensorType, type, List[TensorType]]]]): Optional callable + returning distribution inputs (parameters), a dist-class to + generate an action distribution object from, and internal-state + outputs (or an empty list if not applicable). If None, will either + use `action_sampler_fn` or compute actions by calling self.model, + then sampling from the so parameterized action distribution. + mixins (Optional[List[type]]): Optional list of any class mixins for + the returned policy class. These mixins will be applied in order + and will have higher precedence than the DynamicTFPolicy class. + get_batch_divisibility_req (Optional[Callable[[Policy], int]]): + Optional callable that returns the divisibility requirement for + sample batches. If None, will assume a value of 1. + + Returns: + Type[DynamicTFPolicy]: A child class of DynamicTFPolicy based on the + specified args. + """ + original_kwargs = locals().copy() + base = add_mixins(DynamicTFPolicy, mixins) + + if obs_include_prev_action_reward != DEPRECATED_VALUE: + deprecation_warning(old="obs_include_prev_action_reward", error=True) + + if extra_action_fetches_fn is not None: + deprecation_warning( + old="extra_action_fetches_fn", new="extra_action_out_fn", error=True + ) + + if gradients_fn is not None: + deprecation_warning(old="gradients_fn", new="compute_gradients_fn", error=True) + + class policy_cls(base): + def __init__( + self, + obs_space, + action_space, + config, + existing_model=None, + existing_inputs=None, + ): + if validate_spaces: + validate_spaces(self, obs_space, action_space, config) + + if before_init: + before_init(self, obs_space, action_space, config) + + def before_loss_init_wrapper(policy, obs_space, action_space, config): + if before_loss_init: + before_loss_init(policy, obs_space, action_space, config) + + if extra_action_out_fn is None or policy._is_tower: + extra_action_fetches = {} + else: + extra_action_fetches = extra_action_out_fn(policy) + + if hasattr(policy, "_extra_action_fetches"): + policy._extra_action_fetches.update(extra_action_fetches) + else: + policy._extra_action_fetches = extra_action_fetches + + DynamicTFPolicy.__init__( + self, + obs_space=obs_space, + action_space=action_space, + config=config, + loss_fn=loss_fn, + stats_fn=stats_fn, + grad_stats_fn=grad_stats_fn, + before_loss_init=before_loss_init_wrapper, + make_model=make_model, + action_sampler_fn=action_sampler_fn, + action_distribution_fn=action_distribution_fn, + existing_inputs=existing_inputs, + existing_model=existing_model, + get_batch_divisibility_req=get_batch_divisibility_req, + ) + + if after_init: + after_init(self, obs_space, action_space, config) + + # Got to reset global_timestep again after this fake run-through. + self.global_timestep = 0 + + @override(Policy) + def postprocess_trajectory( + self, sample_batch, other_agent_batches=None, episode=None + ): + # Call super's postprocess_trajectory first. + sample_batch = Policy.postprocess_trajectory(self, sample_batch) + if postprocess_fn: + return postprocess_fn(self, sample_batch, other_agent_batches, episode) + return sample_batch + + @override(TFPolicy) + def optimizer(self): + if optimizer_fn: + optimizers = optimizer_fn(self, self.config) + else: + optimizers = base.optimizer(self) + optimizers = force_list(optimizers) + if self.exploration: + optimizers = self.exploration.get_exploration_optimizer(optimizers) + + # No optimizers produced -> Return None. + if not optimizers: + return None + # New API: Allow more than one optimizer to be returned. + # -> Return list. + elif self.config["_tf_policy_handles_more_than_one_loss"]: + return optimizers + # Old API: Return a single LocalOptimizer. + else: + return optimizers[0] + + @override(TFPolicy) + def gradients(self, optimizer, loss): + optimizers = force_list(optimizer) + losses = force_list(loss) + + if compute_gradients_fn: + # New API: Allow more than one optimizer -> Return a list of + # lists of gradients. + if self.config["_tf_policy_handles_more_than_one_loss"]: + return compute_gradients_fn(self, optimizers, losses) + # Old API: Return a single List of gradients. + else: + return compute_gradients_fn(self, optimizers[0], losses[0]) + else: + return base.gradients(self, optimizers, losses) + + @override(TFPolicy) + def build_apply_op(self, optimizer, grads_and_vars): + if apply_gradients_fn: + return apply_gradients_fn(self, optimizer, grads_and_vars) + else: + return base.build_apply_op(self, optimizer, grads_and_vars) + + @override(TFPolicy) + def extra_compute_action_fetches(self): + return dict( + base.extra_compute_action_fetches(self), **self._extra_action_fetches + ) + + @override(TFPolicy) + def extra_compute_grad_fetches(self): + if extra_learn_fetches_fn: + # TODO: (sven) in torch, extra_learn_fetches do not exist. + # Hence, things like td_error are returned by the stats_fn + # and end up under the LEARNER_STATS_KEY. We should + # change tf to do this as well. However, this will confilct + # the handling of LEARNER_STATS_KEY inside the multi-GPU + # train op. + # Auto-add empty learner stats dict if needed. + return dict({LEARNER_STATS_KEY: {}}, **extra_learn_fetches_fn(self)) + else: + return base.extra_compute_grad_fetches(self) + + def with_updates(**overrides): + """Allows creating a TFPolicy cls based on settings of another one. + + Keyword Args: + **overrides: The settings (passed into `build_tf_policy`) that + should be different from the class that this method is called + on. + + Returns: + type: A new TFPolicy sub-class. + + Examples: + >> MySpecialDQNPolicyClass = DQNTFPolicy.with_updates( + .. name="MySpecialDQNPolicyClass", + .. loss_function=[some_new_loss_function], + .. ) + """ + return build_tf_policy(**dict(original_kwargs, **overrides)) + + def as_eager(): + return eager_tf_policy._build_eager_tf_policy(**original_kwargs) + + policy_cls.with_updates = staticmethod(with_updates) + policy_cls.as_eager = staticmethod(as_eager) + policy_cls.__name__ = name + policy_cls.__qualname__ = name + return policy_cls diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/torch_mixins.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/torch_mixins.py new file mode 100644 index 0000000000000000000000000000000000000000..a255f4e7a577cdc9bb4d0870457649b1f2e958e2 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/torch_mixins.py @@ -0,0 +1,221 @@ +from ray.rllib.policy.policy import PolicyState +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy.torch_policy import TorchPolicy +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.schedules import PiecewiseSchedule + +torch, nn = try_import_torch() + + +@OldAPIStack +class LearningRateSchedule: + """Mixin for TorchPolicy that adds a learning rate schedule.""" + + def __init__(self, lr, lr_schedule, lr2=None, lr2_schedule=None): + self._lr_schedule = None + self._lr2_schedule = None + # Disable any scheduling behavior related to learning if Learner API is active. + # Schedules are handled by Learner class. + if lr_schedule is None: + self.cur_lr = lr + else: + self._lr_schedule = PiecewiseSchedule( + lr_schedule, outside_value=lr_schedule[-1][-1], framework=None + ) + self.cur_lr = self._lr_schedule.value(0) + if lr2_schedule is None: + self.cur_lr2 = lr2 + else: + self._lr2_schedule = PiecewiseSchedule( + lr2_schedule, outside_value=lr2_schedule[-1][-1], framework=None + ) + self.cur_lr2 = self._lr2_schedule.value(0) + + def on_global_var_update(self, global_vars): + super().on_global_var_update(global_vars) + if self._lr_schedule: + self.cur_lr = self._lr_schedule.value(global_vars["timestep"]) + for opt in self._optimizers: + for p in opt.param_groups: + p["lr"] = self.cur_lr + if self._lr2_schedule: + assert len(self._optimizers) == 2 + self.cur_lr2 = self._lr2_schedule.value(global_vars["timestep"]) + opt = self._optimizers[1] + for p in opt.param_groups: + p["lr"] = self.cur_lr2 + + +@OldAPIStack +class EntropyCoeffSchedule: + """Mixin for TorchPolicy that adds entropy coeff decay.""" + + def __init__(self, entropy_coeff, entropy_coeff_schedule): + self._entropy_coeff_schedule = None + # Disable any scheduling behavior related to learning if Learner API is active. + # Schedules are handled by Learner class. + if entropy_coeff_schedule is None: + self.entropy_coeff = entropy_coeff + else: + # Allows for custom schedule similar to lr_schedule format + if isinstance(entropy_coeff_schedule, list): + self._entropy_coeff_schedule = PiecewiseSchedule( + entropy_coeff_schedule, + outside_value=entropy_coeff_schedule[-1][-1], + framework=None, + ) + else: + # Implements previous version but enforces outside_value + self._entropy_coeff_schedule = PiecewiseSchedule( + [[0, entropy_coeff], [entropy_coeff_schedule, 0.0]], + outside_value=0.0, + framework=None, + ) + self.entropy_coeff = self._entropy_coeff_schedule.value(0) + + def on_global_var_update(self, global_vars): + super(EntropyCoeffSchedule, self).on_global_var_update(global_vars) + if self._entropy_coeff_schedule is not None: + self.entropy_coeff = self._entropy_coeff_schedule.value( + global_vars["timestep"] + ) + + +@OldAPIStack +class KLCoeffMixin: + """Assigns the `update_kl()` method to a TorchPolicy. + + This is used by Algorithms to update the KL coefficient + after each learning step based on `config.kl_target` and + the measured KL value (from the train_batch). + """ + + def __init__(self, config): + # The current KL value (as python float). + self.kl_coeff = config["kl_coeff"] + # Constant target value. + self.kl_target = config["kl_target"] + + def update_kl(self, sampled_kl): + # Update the current KL value based on the recently measured value. + if sampled_kl > 2.0 * self.kl_target: + self.kl_coeff *= 1.5 + elif sampled_kl < 0.5 * self.kl_target: + self.kl_coeff *= 0.5 + # Return the current KL value. + return self.kl_coeff + + def get_state(self) -> PolicyState: + state = super().get_state() + # Add current kl-coeff value. + state["current_kl_coeff"] = self.kl_coeff + return state + + def set_state(self, state: PolicyState) -> None: + # Set current kl-coeff value first. + self.kl_coeff = state.pop("current_kl_coeff", self.config["kl_coeff"]) + # Call super's set_state with rest of the state dict. + super().set_state(state) + + +@OldAPIStack +class ValueNetworkMixin: + """Assigns the `_value()` method to a TorchPolicy. + + This way, Policy can call `_value()` to get the current VF estimate on a + single(!) observation (as done in `postprocess_trajectory_fn`). + Note: When doing this, an actual forward pass is being performed. + This is different from only calling `model.value_function()`, where + the result of the most recent forward pass is being used to return an + already calculated tensor. + """ + + def __init__(self, config): + # When doing GAE, we need the value function estimate on the + # observation. + if config.get("use_gae") or config.get("vtrace"): + # Input dict is provided to us automatically via the Model's + # requirements. It's a single-timestep (last one in trajectory) + # input_dict. + + def value(**input_dict): + input_dict = SampleBatch(input_dict) + input_dict = self._lazy_tensor_dict(input_dict) + model_out, _ = self.model(input_dict) + # [0] = remove the batch dim. + return self.model.value_function()[0].item() + + # When not doing GAE, we do not require the value function's output. + else: + + def value(*args, **kwargs): + return 0.0 + + self._value = value + + def extra_action_out(self, input_dict, state_batches, model, action_dist): + """Defines extra fetches per action computation. + + Args: + input_dict (Dict[str, TensorType]): The input dict used for the action + computing forward pass. + state_batches (List[TensorType]): List of state tensors (empty for + non-RNNs). + model (ModelV2): The Model object of the Policy. + action_dist: The instantiated distribution + object, resulting from the model's outputs and the given + distribution class. + + Returns: + Dict[str, TensorType]: Dict with extra tf fetches to perform per + action computation. + """ + # Return value function outputs. VF estimates will hence be added to + # the SampleBatches produced by the sampler(s) to generate the train + # batches going into the loss function. + return { + SampleBatch.VF_PREDS: model.value_function(), + } + + +@OldAPIStack +class TargetNetworkMixin: + """Mixin class adding a method for (soft) target net(s) synchronizations. + + - Adds the `update_target` method to the policy. + Calling `update_target` updates all target Q-networks' weights from their + respective "main" Q-networks, based on tau (smooth, partial updating). + """ + + def __init__(self): + # Hard initial update from Q-net(s) to target Q-net(s). + tau = self.config.get("tau", 1.0) + self.update_target(tau=tau) + + def update_target(self, tau=None): + # Update_target_fn will be called periodically to copy Q network to + # target Q network, using (soft) tau-synching. + tau = tau or self.config.get("tau", 1.0) + + model_state_dict = self.model.state_dict() + + # Support partial (soft) synching. + # If tau == 1.0: Full sync from Q-model to target Q-model. + # Support partial (soft) synching. + # If tau == 1.0: Full sync from Q-model to target Q-model. + target_state_dict = next(iter(self.target_models.values())).state_dict() + model_state_dict = { + k: tau * model_state_dict[k] + (1 - tau) * v + for k, v in target_state_dict.items() + } + + for target in self.target_models.values(): + target.load_state_dict(model_state_dict) + + def set_weights(self, weights): + # Makes sure that whenever we restore weights for this policy's + # model, we sync the target network (from the main model) + # at the same time. + TorchPolicy.set_weights(self, weights) + self.update_target() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/torch_policy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/torch_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..64eeb8374001983a4c9b6bb0782a203ad42199c3 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/torch_policy.py @@ -0,0 +1,1201 @@ +import copy +import functools +import logging +import math +import os +import threading +import time +from typing import ( + Any, + Callable, + Dict, + List, + Optional, + Set, + Tuple, + Type, + Union, +) + +import gymnasium as gym +import numpy as np +import tree # pip install dm_tree + +import ray +from ray.rllib.models.catalog import ModelCatalog +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.torch.torch_action_dist import TorchDistributionWrapper +from ray.rllib.models.torch.torch_modelv2 import TorchModelV2 +from ray.rllib.policy.policy import Policy, PolicyState +from ray.rllib.policy.rnn_sequencing import pad_batch_to_sequences_of_same_size +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils import NullContextManager, force_list +from ray.rllib.utils.annotations import OldAPIStack, override +from ray.rllib.utils.error import ERR_MSG_TORCH_POLICY_CANNOT_SAVE_MODEL +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.metrics import ( + DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY, + NUM_AGENT_STEPS_TRAINED, + NUM_GRAD_UPDATES_LIFETIME, +) +from ray.rllib.utils.metrics.learner_info import LEARNER_STATS_KEY +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.spaces.space_utils import normalize_action +from ray.rllib.utils.threading import with_lock +from ray.rllib.utils.torch_utils import convert_to_torch_tensor +from ray.rllib.utils.typing import ( + AlgorithmConfigDict, + GradInfoDict, + ModelGradients, + ModelWeights, + TensorStructType, + TensorType, +) + +torch, nn = try_import_torch() + +logger = logging.getLogger(__name__) + + +@OldAPIStack +class TorchPolicy(Policy): + """PyTorch specific Policy class to use with RLlib.""" + + def __init__( + self, + observation_space: gym.spaces.Space, + action_space: gym.spaces.Space, + config: AlgorithmConfigDict, + *, + model: Optional[TorchModelV2] = None, + loss: Optional[ + Callable[ + [Policy, ModelV2, Type[TorchDistributionWrapper], SampleBatch], + Union[TensorType, List[TensorType]], + ] + ] = None, + action_distribution_class: Optional[Type[TorchDistributionWrapper]] = None, + action_sampler_fn: Optional[ + Callable[ + [TensorType, List[TensorType]], + Union[ + Tuple[TensorType, TensorType, List[TensorType]], + Tuple[TensorType, TensorType, TensorType, List[TensorType]], + ], + ] + ] = None, + action_distribution_fn: Optional[ + Callable[ + [Policy, ModelV2, TensorType, TensorType, TensorType], + Tuple[TensorType, Type[TorchDistributionWrapper], List[TensorType]], + ] + ] = None, + max_seq_len: int = 20, + get_batch_divisibility_req: Optional[Callable[[Policy], int]] = None, + ): + """Initializes a TorchPolicy instance. + + Args: + observation_space: Observation space of the policy. + action_space: Action space of the policy. + config: The Policy's config dict. + model: PyTorch policy module. Given observations as + input, this module must return a list of outputs where the + first item is action logits, and the rest can be any value. + loss: Callable that returns one or more (a list of) scalar loss + terms. + action_distribution_class: Class for a torch action distribution. + action_sampler_fn: A callable returning either a sampled action, + its log-likelihood and updated state or a sampled action, its + log-likelihood, updated state and action distribution inputs + given Policy, ModelV2, input_dict, state batches (optional), + explore, and timestep. Provide `action_sampler_fn` if you would + like to have full control over the action computation step, + including the model forward pass, possible sampling from a + distribution, and exploration logic. + Note: If `action_sampler_fn` is given, `action_distribution_fn` + must be None. If both `action_sampler_fn` and + `action_distribution_fn` are None, RLlib will simply pass + inputs through `self.model` to get distribution inputs, create + the distribution object, sample from it, and apply some + exploration logic to the results. + The callable takes as inputs: Policy, ModelV2, input_dict + (SampleBatch), state_batches (optional), explore, and timestep. + action_distribution_fn: A callable returning distribution inputs + (parameters), a dist-class to generate an action distribution + object from, and internal-state outputs (or an empty list if + not applicable). + Provide `action_distribution_fn` if you would like to only + customize the model forward pass call. The resulting + distribution parameters are then used by RLlib to create a + distribution object, sample from it, and execute any + exploration logic. + Note: If `action_distribution_fn` is given, `action_sampler_fn` + must be None. If both `action_sampler_fn` and + `action_distribution_fn` are None, RLlib will simply pass + inputs through `self.model` to get distribution inputs, create + the distribution object, sample from it, and apply some + exploration logic to the results. + The callable takes as inputs: Policy, ModelV2, ModelInputDict, + explore, timestep, is_training. + max_seq_len: Max sequence length for LSTM training. + get_batch_divisibility_req: Optional callable that returns the + divisibility requirement for sample batches given the Policy. + """ + self.framework = config["framework"] = "torch" + self._loss_initialized = False + super().__init__(observation_space, action_space, config) + + # Create multi-GPU model towers, if necessary. + # - The central main model will be stored under self.model, residing + # on self.device (normally, a CPU). + # - Each GPU will have a copy of that model under + # self.model_gpu_towers, matching the devices in self.devices. + # - Parallelization is done by splitting the train batch and passing + # it through the model copies in parallel, then averaging over the + # resulting gradients, applying these averages on the main model and + # updating all towers' weights from the main model. + # - In case of just one device (1 (fake or real) GPU or 1 CPU), no + # parallelization will be done. + + # If no Model is provided, build a default one here. + if model is None: + dist_class, logit_dim = ModelCatalog.get_action_dist( + action_space, self.config["model"], framework=self.framework + ) + model = ModelCatalog.get_model_v2( + obs_space=self.observation_space, + action_space=self.action_space, + num_outputs=logit_dim, + model_config=self.config["model"], + framework=self.framework, + ) + if action_distribution_class is None: + action_distribution_class = dist_class + + # Get devices to build the graph on. + num_gpus = self._get_num_gpus_for_policy() + gpu_ids = list(range(torch.cuda.device_count())) + logger.info(f"Found {len(gpu_ids)} visible cuda devices.") + + # Place on one or more CPU(s) when either: + # - Fake GPU mode. + # - num_gpus=0 (either set by user or we are in local_mode=True). + # - No GPUs available. + if config["_fake_gpus"] or num_gpus == 0 or not gpu_ids: + self.device = torch.device("cpu") + self.devices = [self.device for _ in range(int(math.ceil(num_gpus)) or 1)] + self.model_gpu_towers = [ + model if i == 0 else copy.deepcopy(model) + for i in range(int(math.ceil(num_gpus)) or 1) + ] + if hasattr(self, "target_model"): + self.target_models = { + m: self.target_model for m in self.model_gpu_towers + } + self.model = model + # Place on one or more actual GPU(s), when: + # - num_gpus > 0 (set by user) AND + # - local_mode=False AND + # - actual GPUs available AND + # - non-fake GPU mode. + else: + # We are a remote worker (WORKER_MODE=1): + # GPUs should be assigned to us by ray. + if ray._private.worker._mode() == ray._private.worker.WORKER_MODE: + gpu_ids = ray.get_gpu_ids() + + if len(gpu_ids) < num_gpus: + raise ValueError( + "TorchPolicy was not able to find enough GPU IDs! Found " + f"{gpu_ids}, but num_gpus={num_gpus}." + ) + + self.devices = [ + torch.device("cuda:{}".format(i)) + for i, id_ in enumerate(gpu_ids) + if i < num_gpus + ] + self.device = self.devices[0] + ids = [id_ for i, id_ in enumerate(gpu_ids) if i < num_gpus] + self.model_gpu_towers = [] + for i, _ in enumerate(ids): + model_copy = copy.deepcopy(model) + self.model_gpu_towers.append(model_copy.to(self.devices[i])) + if hasattr(self, "target_model"): + self.target_models = { + m: copy.deepcopy(self.target_model).to(self.devices[i]) + for i, m in enumerate(self.model_gpu_towers) + } + self.model = self.model_gpu_towers[0] + + # Lock used for locking some methods on the object-level. + # This prevents possible race conditions when calling the model + # first, then its value function (e.g. in a loss function), in + # between of which another model call is made (e.g. to compute an + # action). + self._lock = threading.RLock() + + self._state_inputs = self.model.get_initial_state() + self._is_recurrent = len(self._state_inputs) > 0 + # Auto-update model's inference view requirements, if recurrent. + self._update_model_view_requirements_from_init_state() + # Combine view_requirements for Model and Policy. + self.view_requirements.update(self.model.view_requirements) + + self.exploration = self._create_exploration() + self.unwrapped_model = model # used to support DistributedDataParallel + # To ensure backward compatibility: + # Old way: If `loss` provided here, use as-is (as a function). + if loss is not None: + self._loss = loss + # New way: Convert the overridden `self.loss` into a plain function, + # so it can be called the same way as `loss` would be, ensuring + # backward compatibility. + elif self.loss.__func__.__qualname__ != "Policy.loss": + self._loss = self.loss.__func__ + # `loss` not provided nor overridden from Policy -> Set to None. + else: + self._loss = None + self._optimizers = force_list(self.optimizer()) + # Store, which params (by index within the model's list of + # parameters) should be updated per optimizer. + # Maps optimizer idx to set or param indices. + self.multi_gpu_param_groups: List[Set[int]] = [] + main_params = {p: i for i, p in enumerate(self.model.parameters())} + for o in self._optimizers: + param_indices = [] + for pg_idx, pg in enumerate(o.param_groups): + for p in pg["params"]: + param_indices.append(main_params[p]) + self.multi_gpu_param_groups.append(set(param_indices)) + + # Create n sample-batch buffers (num_multi_gpu_tower_stacks), each + # one with m towers (num_gpus). + num_buffers = self.config.get("num_multi_gpu_tower_stacks", 1) + self._loaded_batches = [[] for _ in range(num_buffers)] + + self.dist_class = action_distribution_class + self.action_sampler_fn = action_sampler_fn + self.action_distribution_fn = action_distribution_fn + + # If set, means we are using distributed allreduce during learning. + self.distributed_world_size = None + + self.max_seq_len = max_seq_len + self.batch_divisibility_req = ( + get_batch_divisibility_req(self) + if callable(get_batch_divisibility_req) + else (get_batch_divisibility_req or 1) + ) + + @override(Policy) + def compute_actions_from_input_dict( + self, + input_dict: Dict[str, TensorType], + explore: bool = None, + timestep: Optional[int] = None, + **kwargs, + ) -> Tuple[TensorType, List[TensorType], Dict[str, TensorType]]: + with torch.no_grad(): + # Pass lazy (torch) tensor dict to Model as `input_dict`. + input_dict = self._lazy_tensor_dict(input_dict) + input_dict.set_training(True) + # Pack internal state inputs into (separate) list. + state_batches = [ + input_dict[k] for k in input_dict.keys() if "state_in" in k[:8] + ] + # Calculate RNN sequence lengths. + seq_lens = ( + torch.tensor( + [1] * len(state_batches[0]), + dtype=torch.long, + device=state_batches[0].device, + ) + if state_batches + else None + ) + + return self._compute_action_helper( + input_dict, state_batches, seq_lens, explore, timestep + ) + + @override(Policy) + def compute_actions( + self, + obs_batch: Union[List[TensorStructType], TensorStructType], + state_batches: Optional[List[TensorType]] = None, + prev_action_batch: Union[List[TensorStructType], TensorStructType] = None, + prev_reward_batch: Union[List[TensorStructType], TensorStructType] = None, + info_batch: Optional[Dict[str, list]] = None, + episodes=None, + explore: Optional[bool] = None, + timestep: Optional[int] = None, + **kwargs, + ) -> Tuple[TensorStructType, List[TensorType], Dict[str, TensorType]]: + with torch.no_grad(): + seq_lens = torch.ones(len(obs_batch), dtype=torch.int32) + input_dict = self._lazy_tensor_dict( + { + SampleBatch.CUR_OBS: obs_batch, + "is_training": False, + } + ) + if prev_action_batch is not None: + input_dict[SampleBatch.PREV_ACTIONS] = np.asarray(prev_action_batch) + if prev_reward_batch is not None: + input_dict[SampleBatch.PREV_REWARDS] = np.asarray(prev_reward_batch) + state_batches = [ + convert_to_torch_tensor(s, self.device) for s in (state_batches or []) + ] + return self._compute_action_helper( + input_dict, state_batches, seq_lens, explore, timestep + ) + + @with_lock + @override(Policy) + def compute_log_likelihoods( + self, + actions: Union[List[TensorStructType], TensorStructType], + obs_batch: Union[List[TensorStructType], TensorStructType], + state_batches: Optional[List[TensorType]] = None, + prev_action_batch: Optional[ + Union[List[TensorStructType], TensorStructType] + ] = None, + prev_reward_batch: Optional[ + Union[List[TensorStructType], TensorStructType] + ] = None, + actions_normalized: bool = True, + **kwargs, + ) -> TensorType: + if self.action_sampler_fn and self.action_distribution_fn is None: + raise ValueError( + "Cannot compute log-prob/likelihood w/o an " + "`action_distribution_fn` and a provided " + "`action_sampler_fn`!" + ) + + with torch.no_grad(): + input_dict = self._lazy_tensor_dict( + {SampleBatch.CUR_OBS: obs_batch, SampleBatch.ACTIONS: actions} + ) + if prev_action_batch is not None: + input_dict[SampleBatch.PREV_ACTIONS] = prev_action_batch + if prev_reward_batch is not None: + input_dict[SampleBatch.PREV_REWARDS] = prev_reward_batch + seq_lens = torch.ones(len(obs_batch), dtype=torch.int32) + state_batches = [ + convert_to_torch_tensor(s, self.device) for s in (state_batches or []) + ] + + # Exploration hook before each forward pass. + self.exploration.before_compute_actions(explore=False) + + # Action dist class and inputs are generated via custom function. + if self.action_distribution_fn: + # Try new action_distribution_fn signature, supporting + # state_batches and seq_lens. + try: + dist_inputs, dist_class, state_out = self.action_distribution_fn( + self, + self.model, + input_dict=input_dict, + state_batches=state_batches, + seq_lens=seq_lens, + explore=False, + is_training=False, + ) + # Trying the old way (to stay backward compatible). + # TODO: Remove in future. + except TypeError as e: + if ( + "positional argument" in e.args[0] + or "unexpected keyword argument" in e.args[0] + ): + dist_inputs, dist_class, _ = self.action_distribution_fn( + policy=self, + model=self.model, + obs_batch=input_dict[SampleBatch.CUR_OBS], + explore=False, + is_training=False, + ) + else: + raise e + + # Default action-dist inputs calculation. + else: + dist_class = self.dist_class + dist_inputs, _ = self.model(input_dict, state_batches, seq_lens) + + action_dist = dist_class(dist_inputs, self.model) + + # Normalize actions if necessary. + actions = input_dict[SampleBatch.ACTIONS] + if not actions_normalized and self.config["normalize_actions"]: + actions = normalize_action(actions, self.action_space_struct) + + log_likelihoods = action_dist.logp(actions) + + return log_likelihoods + + @with_lock + @override(Policy) + def learn_on_batch(self, postprocessed_batch: SampleBatch) -> Dict[str, TensorType]: + # Set Model to train mode. + if self.model: + self.model.train() + # Callback handling. + learn_stats = {} + self.callbacks.on_learn_on_batch( + policy=self, train_batch=postprocessed_batch, result=learn_stats + ) + + # Compute gradients (will calculate all losses and `backward()` + # them to get the grads). + grads, fetches = self.compute_gradients(postprocessed_batch) + + # Step the optimizers. + self.apply_gradients(_directStepOptimizerSingleton) + + self.num_grad_updates += 1 + + if self.model: + fetches["model"] = self.model.metrics() + + fetches.update( + { + "custom_metrics": learn_stats, + NUM_AGENT_STEPS_TRAINED: postprocessed_batch.count, + NUM_GRAD_UPDATES_LIFETIME: self.num_grad_updates, + # -1, b/c we have to measure this diff before we do the update above. + DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY: ( + self.num_grad_updates + - 1 + - (postprocessed_batch.num_grad_updates or 0) + ), + } + ) + + return fetches + + @override(Policy) + def load_batch_into_buffer( + self, + batch: SampleBatch, + buffer_index: int = 0, + ) -> int: + # Set the is_training flag of the batch. + batch.set_training(True) + + # Shortcut for 1 CPU only: Store batch in `self._loaded_batches`. + if len(self.devices) == 1 and self.devices[0].type == "cpu": + assert buffer_index == 0 + pad_batch_to_sequences_of_same_size( + batch=batch, + max_seq_len=self.max_seq_len, + shuffle=False, + batch_divisibility_req=self.batch_divisibility_req, + view_requirements=self.view_requirements, + ) + self._lazy_tensor_dict(batch) + self._loaded_batches[0] = [batch] + return len(batch) + + # Batch (len=28, seq-lens=[4, 7, 4, 10, 3]): + # 0123 0123456 0123 0123456789ABC + + # 1) split into n per-GPU sub batches (n=2). + # [0123 0123456] [012] [3 0123456789 ABC] + # (len=14, 14 seq-lens=[4, 7, 3] [1, 10, 3]) + slices = batch.timeslices(num_slices=len(self.devices)) + + # 2) zero-padding (max-seq-len=10). + # - [0123000000 0123456000 0120000000] + # - [3000000000 0123456789 ABC0000000] + for slice in slices: + pad_batch_to_sequences_of_same_size( + batch=slice, + max_seq_len=self.max_seq_len, + shuffle=False, + batch_divisibility_req=self.batch_divisibility_req, + view_requirements=self.view_requirements, + ) + + # 3) Load splits into the given buffer (consisting of n GPUs). + slices = [slice.to_device(self.devices[i]) for i, slice in enumerate(slices)] + self._loaded_batches[buffer_index] = slices + + # Return loaded samples per-device. + return len(slices[0]) + + @override(Policy) + def get_num_samples_loaded_into_buffer(self, buffer_index: int = 0) -> int: + if len(self.devices) == 1 and self.devices[0] == "/cpu:0": + assert buffer_index == 0 + return sum(len(b) for b in self._loaded_batches[buffer_index]) + + @override(Policy) + def learn_on_loaded_batch(self, offset: int = 0, buffer_index: int = 0): + if not self._loaded_batches[buffer_index]: + raise ValueError( + "Must call Policy.load_batch_into_buffer() before " + "Policy.learn_on_loaded_batch()!" + ) + + # Get the correct slice of the already loaded batch to use, + # based on offset and batch size. + device_batch_size = self.config.get("minibatch_size") + if device_batch_size is None: + device_batch_size = self.config.get( + "sgd_minibatch_size", + self.config["train_batch_size"], + ) + device_batch_size //= len(self.devices) + + # Set Model to train mode. + if self.model_gpu_towers: + for t in self.model_gpu_towers: + t.train() + + # Shortcut for 1 CPU only: Batch should already be stored in + # `self._loaded_batches`. + if len(self.devices) == 1 and self.devices[0].type == "cpu": + assert buffer_index == 0 + if device_batch_size >= len(self._loaded_batches[0][0]): + batch = self._loaded_batches[0][0] + else: + batch = self._loaded_batches[0][0][offset : offset + device_batch_size] + return self.learn_on_batch(batch) + + if len(self.devices) > 1: + # Copy weights of main model (tower-0) to all other towers. + state_dict = self.model.state_dict() + # Just making sure tower-0 is really the same as self.model. + assert self.model_gpu_towers[0] is self.model + for tower in self.model_gpu_towers[1:]: + tower.load_state_dict(state_dict) + + if device_batch_size >= sum(len(s) for s in self._loaded_batches[buffer_index]): + device_batches = self._loaded_batches[buffer_index] + else: + device_batches = [ + b[offset : offset + device_batch_size] + for b in self._loaded_batches[buffer_index] + ] + + # Callback handling. + batch_fetches = {} + for i, batch in enumerate(device_batches): + custom_metrics = {} + self.callbacks.on_learn_on_batch( + policy=self, train_batch=batch, result=custom_metrics + ) + batch_fetches[f"tower_{i}"] = {"custom_metrics": custom_metrics} + + # Do the (maybe parallelized) gradient calculation step. + tower_outputs = self._multi_gpu_parallel_grad_calc(device_batches) + + # Mean-reduce gradients over GPU-towers (do this on CPU: self.device). + all_grads = [] + for i in range(len(tower_outputs[0][0])): + if tower_outputs[0][0][i] is not None: + all_grads.append( + torch.mean( + torch.stack([t[0][i].to(self.device) for t in tower_outputs]), + dim=0, + ) + ) + else: + all_grads.append(None) + # Set main model's grads to mean-reduced values. + for i, p in enumerate(self.model.parameters()): + p.grad = all_grads[i] + + self.apply_gradients(_directStepOptimizerSingleton) + + self.num_grad_updates += 1 + + for i, (model, batch) in enumerate(zip(self.model_gpu_towers, device_batches)): + batch_fetches[f"tower_{i}"].update( + { + LEARNER_STATS_KEY: self.extra_grad_info(batch), + "model": model.metrics(), + NUM_GRAD_UPDATES_LIFETIME: self.num_grad_updates, + # -1, b/c we have to measure this diff before we do the update + # above. + DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY: ( + self.num_grad_updates - 1 - (batch.num_grad_updates or 0) + ), + } + ) + batch_fetches.update(self.extra_compute_grad_fetches()) + + return batch_fetches + + @with_lock + @override(Policy) + def compute_gradients(self, postprocessed_batch: SampleBatch) -> ModelGradients: + assert len(self.devices) == 1 + + # If not done yet, see whether we have to zero-pad this batch. + if not postprocessed_batch.zero_padded: + pad_batch_to_sequences_of_same_size( + batch=postprocessed_batch, + max_seq_len=self.max_seq_len, + shuffle=False, + batch_divisibility_req=self.batch_divisibility_req, + view_requirements=self.view_requirements, + ) + + postprocessed_batch.set_training(True) + self._lazy_tensor_dict(postprocessed_batch, device=self.devices[0]) + + # Do the (maybe parallelized) gradient calculation step. + tower_outputs = self._multi_gpu_parallel_grad_calc([postprocessed_batch]) + + all_grads, grad_info = tower_outputs[0] + + grad_info["allreduce_latency"] /= len(self._optimizers) + grad_info.update(self.extra_grad_info(postprocessed_batch)) + + fetches = self.extra_compute_grad_fetches() + + return all_grads, dict(fetches, **{LEARNER_STATS_KEY: grad_info}) + + @override(Policy) + def apply_gradients(self, gradients: ModelGradients) -> None: + if gradients == _directStepOptimizerSingleton: + for i, opt in enumerate(self._optimizers): + opt.step() + else: + # TODO(sven): Not supported for multiple optimizers yet. + assert len(self._optimizers) == 1 + for g, p in zip(gradients, self.model.parameters()): + if g is not None: + if torch.is_tensor(g): + p.grad = g.to(self.device) + else: + p.grad = torch.from_numpy(g).to(self.device) + + self._optimizers[0].step() + + def get_tower_stats(self, stats_name: str) -> List[TensorStructType]: + """Returns list of per-tower stats, copied to this Policy's device. + + Args: + stats_name: The name of the stats to average over (this str + must exist as a key inside each tower's `tower_stats` dict). + + Returns: + The list of stats tensor (structs) of all towers, copied to this + Policy's device. + + Raises: + AssertionError: If the `stats_name` cannot be found in any one + of the tower's `tower_stats` dicts. + """ + data = [] + for tower in self.model_gpu_towers: + if stats_name in tower.tower_stats: + data.append( + tree.map_structure( + lambda s: s.to(self.device), tower.tower_stats[stats_name] + ) + ) + assert len(data) > 0, ( + f"Stats `{stats_name}` not found in any of the towers (you have " + f"{len(self.model_gpu_towers)} towers in total)! Make " + "sure you call the loss function on at least one of the towers." + ) + return data + + @override(Policy) + def get_weights(self) -> ModelWeights: + return {k: v.cpu().detach().numpy() for k, v in self.model.state_dict().items()} + + @override(Policy) + def set_weights(self, weights: ModelWeights) -> None: + weights = convert_to_torch_tensor(weights, device=self.device) + self.model.load_state_dict(weights) + + @override(Policy) + def is_recurrent(self) -> bool: + return self._is_recurrent + + @override(Policy) + def num_state_tensors(self) -> int: + return len(self.model.get_initial_state()) + + @override(Policy) + def get_initial_state(self) -> List[TensorType]: + return [s.detach().cpu().numpy() for s in self.model.get_initial_state()] + + @override(Policy) + def get_state(self) -> PolicyState: + state = super().get_state() + + state["_optimizer_variables"] = [] + for i, o in enumerate(self._optimizers): + optim_state_dict = convert_to_numpy(o.state_dict()) + state["_optimizer_variables"].append(optim_state_dict) + # Add exploration state. + if self.exploration: + # This is not compatible with RLModules, which have a method + # `forward_exploration` to specify custom exploration behavior. + state["_exploration_state"] = self.exploration.get_state() + return state + + @override(Policy) + def set_state(self, state: PolicyState) -> None: + # Set optimizer vars first. + optimizer_vars = state.get("_optimizer_variables", None) + if optimizer_vars: + assert len(optimizer_vars) == len(self._optimizers) + for o, s in zip(self._optimizers, optimizer_vars): + # Torch optimizer param_groups include things like beta, etc. These + # parameters should be left as scalar and not converted to tensors. + # otherwise, torch.optim.step() will start to complain. + optim_state_dict = {"param_groups": s["param_groups"]} + optim_state_dict["state"] = convert_to_torch_tensor( + s["state"], device=self.device + ) + o.load_state_dict(optim_state_dict) + # Set exploration's state. + if hasattr(self, "exploration") and "_exploration_state" in state: + self.exploration.set_state(state=state["_exploration_state"]) + + # Restore global timestep. + self.global_timestep = state["global_timestep"] + + # Then the Policy's (NN) weights and connectors. + super().set_state(state) + + def extra_grad_process( + self, optimizer: "torch.optim.Optimizer", loss: TensorType + ) -> Dict[str, TensorType]: + """Called after each optimizer.zero_grad() + loss.backward() call. + + Called for each self._optimizers/loss-value pair. + Allows for gradient processing before optimizer.step() is called. + E.g. for gradient clipping. + + Args: + optimizer: A torch optimizer object. + loss: The loss tensor associated with the optimizer. + + Returns: + An dict with information on the gradient processing step. + """ + return {} + + def extra_compute_grad_fetches(self) -> Dict[str, Any]: + """Extra values to fetch and return from compute_gradients(). + + Returns: + Extra fetch dict to be added to the fetch dict of the + `compute_gradients` call. + """ + return {LEARNER_STATS_KEY: {}} # e.g, stats, td error, etc. + + def extra_action_out( + self, + input_dict: Dict[str, TensorType], + state_batches: List[TensorType], + model: TorchModelV2, + action_dist: TorchDistributionWrapper, + ) -> Dict[str, TensorType]: + """Returns dict of extra info to include in experience batch. + + Args: + input_dict: Dict of model input tensors. + state_batches: List of state tensors. + model: Reference to the model object. + action_dist: Torch action dist object + to get log-probs (e.g. for already sampled actions). + + Returns: + Extra outputs to return in a `compute_actions_from_input_dict()` + call (3rd return value). + """ + return {} + + def extra_grad_info(self, train_batch: SampleBatch) -> Dict[str, TensorType]: + """Return dict of extra grad info. + + Args: + train_batch: The training batch for which to produce + extra grad info for. + + Returns: + The info dict carrying grad info per str key. + """ + return {} + + def optimizer( + self, + ) -> Union[List["torch.optim.Optimizer"], "torch.optim.Optimizer"]: + """Custom the local PyTorch optimizer(s) to use. + + Returns: + The local PyTorch optimizer(s) to use for this Policy. + """ + if hasattr(self, "config"): + optimizers = [ + torch.optim.Adam(self.model.parameters(), lr=self.config["lr"]) + ] + else: + optimizers = [torch.optim.Adam(self.model.parameters())] + if self.exploration: + optimizers = self.exploration.get_exploration_optimizer(optimizers) + return optimizers + + @override(Policy) + def export_model(self, export_dir: str, onnx: Optional[int] = None) -> None: + """Exports the Policy's Model to local directory for serving. + + Creates a TorchScript model and saves it. + + Args: + export_dir: Local writable directory or filename. + onnx: If given, will export model in ONNX format. The + value of this parameter set the ONNX OpSet version to use. + """ + os.makedirs(export_dir, exist_ok=True) + + if onnx: + self._lazy_tensor_dict(self._dummy_batch) + # Provide dummy state inputs if not an RNN (torch cannot jit with + # returned empty internal states list). + if "state_in_0" not in self._dummy_batch: + self._dummy_batch["state_in_0"] = self._dummy_batch[ + SampleBatch.SEQ_LENS + ] = np.array([1.0]) + seq_lens = self._dummy_batch[SampleBatch.SEQ_LENS] + + state_ins = [] + i = 0 + while "state_in_{}".format(i) in self._dummy_batch: + state_ins.append(self._dummy_batch["state_in_{}".format(i)]) + i += 1 + dummy_inputs = { + k: self._dummy_batch[k] + for k in self._dummy_batch.keys() + if k != "is_training" + } + + file_name = os.path.join(export_dir, "model.onnx") + torch.onnx.export( + self.model, + (dummy_inputs, state_ins, seq_lens), + file_name, + export_params=True, + opset_version=onnx, + do_constant_folding=True, + input_names=list(dummy_inputs.keys()) + + ["state_ins", SampleBatch.SEQ_LENS], + output_names=["output", "state_outs"], + dynamic_axes={ + k: {0: "batch_size"} + for k in list(dummy_inputs.keys()) + + ["state_ins", SampleBatch.SEQ_LENS] + }, + ) + # Save the torch.Model (architecture and weights, so it can be retrieved + # w/o access to the original (custom) Model or Policy code). + else: + filename = os.path.join(export_dir, "model.pt") + try: + torch.save(self.model, f=filename) + except Exception: + if os.path.exists(filename): + os.remove(filename) + logger.warning(ERR_MSG_TORCH_POLICY_CANNOT_SAVE_MODEL) + + @override(Policy) + def import_model_from_h5(self, import_file: str) -> None: + """Imports weights into torch model.""" + return self.model.import_from_h5(import_file) + + @with_lock + def _compute_action_helper( + self, input_dict, state_batches, seq_lens, explore, timestep + ): + """Shared forward pass logic (w/ and w/o trajectory view API). + + Returns: + A tuple consisting of a) actions, b) state_out, c) extra_fetches. + """ + explore = explore if explore is not None else self.config["explore"] + timestep = timestep if timestep is not None else self.global_timestep + self._is_recurrent = state_batches is not None and state_batches != [] + + # Switch to eval mode. + if self.model: + self.model.eval() + + if self.action_sampler_fn: + action_dist = dist_inputs = None + action_sampler_outputs = self.action_sampler_fn( + self, + self.model, + input_dict, + state_batches, + explore=explore, + timestep=timestep, + ) + if len(action_sampler_outputs) == 4: + actions, logp, dist_inputs, state_out = action_sampler_outputs + else: + actions, logp, state_out = action_sampler_outputs + else: + # Call the exploration before_compute_actions hook. + self.exploration.before_compute_actions(explore=explore, timestep=timestep) + if self.action_distribution_fn: + # Try new action_distribution_fn signature, supporting + # state_batches and seq_lens. + try: + dist_inputs, dist_class, state_out = self.action_distribution_fn( + self, + self.model, + input_dict=input_dict, + state_batches=state_batches, + seq_lens=seq_lens, + explore=explore, + timestep=timestep, + is_training=False, + ) + # Trying the old way (to stay backward compatible). + # TODO: Remove in future. + except TypeError as e: + if ( + "positional argument" in e.args[0] + or "unexpected keyword argument" in e.args[0] + ): + ( + dist_inputs, + dist_class, + state_out, + ) = self.action_distribution_fn( + self, + self.model, + input_dict[SampleBatch.CUR_OBS], + explore=explore, + timestep=timestep, + is_training=False, + ) + else: + raise e + else: + dist_class = self.dist_class + dist_inputs, state_out = self.model(input_dict, state_batches, seq_lens) + + if not ( + isinstance(dist_class, functools.partial) + or issubclass(dist_class, TorchDistributionWrapper) + ): + raise ValueError( + "`dist_class` ({}) not a TorchDistributionWrapper " + "subclass! Make sure your `action_distribution_fn` or " + "`make_model_and_action_dist` return a correct " + "distribution class.".format(dist_class.__name__) + ) + action_dist = dist_class(dist_inputs, self.model) + + # Get the exploration action from the forward results. + actions, logp = self.exploration.get_exploration_action( + action_distribution=action_dist, timestep=timestep, explore=explore + ) + + input_dict[SampleBatch.ACTIONS] = actions + + # Add default and custom fetches. + extra_fetches = self.extra_action_out( + input_dict, state_batches, self.model, action_dist + ) + + # Action-dist inputs. + if dist_inputs is not None: + extra_fetches[SampleBatch.ACTION_DIST_INPUTS] = dist_inputs + + # Action-logp and action-prob. + if logp is not None: + extra_fetches[SampleBatch.ACTION_PROB] = torch.exp(logp.float()) + extra_fetches[SampleBatch.ACTION_LOGP] = logp + + # Update our global timestep by the batch size. + self.global_timestep += len(input_dict[SampleBatch.CUR_OBS]) + + return convert_to_numpy((actions, state_out, extra_fetches)) + + def _lazy_tensor_dict(self, postprocessed_batch: SampleBatch, device=None): + # TODO: (sven): Keep for a while to ensure backward compatibility. + if not isinstance(postprocessed_batch, SampleBatch): + postprocessed_batch = SampleBatch(postprocessed_batch) + postprocessed_batch.set_get_interceptor( + functools.partial(convert_to_torch_tensor, device=device or self.device) + ) + return postprocessed_batch + + def _multi_gpu_parallel_grad_calc( + self, sample_batches: List[SampleBatch] + ) -> List[Tuple[List[TensorType], GradInfoDict]]: + """Performs a parallelized loss and gradient calculation over the batch. + + Splits up the given train batch into n shards (n=number of this + Policy's devices) and passes each data shard (in parallel) through + the loss function using the individual devices' models + (self.model_gpu_towers). Then returns each tower's outputs. + + Args: + sample_batches: A list of SampleBatch shards to + calculate loss and gradients for. + + Returns: + A list (one item per device) of 2-tuples, each with 1) gradient + list and 2) grad info dict. + """ + assert len(self.model_gpu_towers) == len(sample_batches) + lock = threading.Lock() + results = {} + grad_enabled = torch.is_grad_enabled() + + def _worker(shard_idx, model, sample_batch, device): + torch.set_grad_enabled(grad_enabled) + try: + with NullContextManager() if device.type == "cpu" else torch.cuda.device( # noqa: E501 + device + ): + loss_out = force_list( + self._loss(self, model, self.dist_class, sample_batch) + ) + + # Call Model's custom-loss with Policy loss outputs and + # train_batch. + loss_out = model.custom_loss(loss_out, sample_batch) + + assert len(loss_out) == len(self._optimizers) + + # Loop through all optimizers. + grad_info = {"allreduce_latency": 0.0} + + parameters = list(model.parameters()) + all_grads = [None for _ in range(len(parameters))] + for opt_idx, opt in enumerate(self._optimizers): + # Erase gradients in all vars of the tower that this + # optimizer would affect. + param_indices = self.multi_gpu_param_groups[opt_idx] + for param_idx, param in enumerate(parameters): + if param_idx in param_indices and param.grad is not None: + param.grad.data.zero_() + # Recompute gradients of loss over all variables. + loss_out[opt_idx].backward(retain_graph=True) + grad_info.update( + self.extra_grad_process(opt, loss_out[opt_idx]) + ) + + grads = [] + # Note that return values are just references; + # Calling zero_grad would modify the values. + for param_idx, param in enumerate(parameters): + if param_idx in param_indices: + if param.grad is not None: + grads.append(param.grad) + all_grads[param_idx] = param.grad + + if self.distributed_world_size: + start = time.time() + if torch.cuda.is_available(): + # Sadly, allreduce_coalesced does not work with + # CUDA yet. + for g in grads: + torch.distributed.all_reduce( + g, op=torch.distributed.ReduceOp.SUM + ) + else: + torch.distributed.all_reduce_coalesced( + grads, op=torch.distributed.ReduceOp.SUM + ) + + for param_group in opt.param_groups: + for p in param_group["params"]: + if p.grad is not None: + p.grad /= self.distributed_world_size + + grad_info["allreduce_latency"] += time.time() - start + + with lock: + results[shard_idx] = (all_grads, grad_info) + except Exception as e: + import traceback + + with lock: + results[shard_idx] = ( + ValueError( + f"Error In tower {shard_idx} on device " + f"{device} during multi GPU parallel gradient " + f"calculation:" + f": {e}\n" + f"Traceback: \n" + f"{traceback.format_exc()}\n" + ), + e, + ) + + # Single device (GPU) or fake-GPU case (serialize for better + # debugging). + if len(self.devices) == 1 or self.config["_fake_gpus"]: + for shard_idx, (model, sample_batch, device) in enumerate( + zip(self.model_gpu_towers, sample_batches, self.devices) + ): + _worker(shard_idx, model, sample_batch, device) + # Raise errors right away for better debugging. + last_result = results[len(results) - 1] + if isinstance(last_result[0], ValueError): + raise last_result[0] from last_result[1] + # Multi device (GPU) case: Parallelize via threads. + else: + threads = [ + threading.Thread( + target=_worker, args=(shard_idx, model, sample_batch, device) + ) + for shard_idx, (model, sample_batch, device) in enumerate( + zip(self.model_gpu_towers, sample_batches, self.devices) + ) + ] + + for thread in threads: + thread.start() + for thread in threads: + thread.join() + + # Gather all threads' outputs and return. + outputs = [] + for shard_idx in range(len(sample_batches)): + output = results[shard_idx] + if isinstance(output[0], Exception): + raise output[0] from output[1] + outputs.append(results[shard_idx]) + return outputs + + +@OldAPIStack +class DirectStepOptimizer: + """Typesafe method for indicating `apply_gradients` can directly step the + optimizers with in-place gradients. + """ + + _instance = None + + def __new__(cls): + if DirectStepOptimizer._instance is None: + DirectStepOptimizer._instance = super().__new__(cls) + return DirectStepOptimizer._instance + + def __eq__(self, other): + return type(self) is type(other) + + def __repr__(self): + return "DirectStepOptimizer" + + +_directStepOptimizerSingleton = DirectStepOptimizer() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/torch_policy_v2.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/torch_policy_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..08216eb6d5da68cdd58ccec664ed6916ed5dbc34 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/torch_policy_v2.py @@ -0,0 +1,1260 @@ +import copy +import functools +import logging +import math +import os +import threading +import time +from typing import Any, Dict, List, Optional, Set, Tuple, Type, Union + +import gymnasium as gym +import numpy as np +from packaging import version +import tree # pip install dm_tree + +import ray +from ray.rllib.models.catalog import ModelCatalog +from ray.rllib.models.modelv2 import ModelV2 +from ray.rllib.models.torch.torch_action_dist import TorchDistributionWrapper +from ray.rllib.models.torch.torch_modelv2 import TorchModelV2 +from ray.rllib.policy.policy import Policy +from ray.rllib.policy.rnn_sequencing import pad_batch_to_sequences_of_same_size +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy.torch_policy import _directStepOptimizerSingleton +from ray.rllib.utils import NullContextManager, force_list +from ray.rllib.utils.annotations import ( + OldAPIStack, + OverrideToImplementCustomLogic, + OverrideToImplementCustomLogic_CallToSuperRecommended, + is_overridden, + override, +) +from ray.rllib.utils.error import ERR_MSG_TORCH_POLICY_CANNOT_SAVE_MODEL +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.metrics import ( + DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY, + NUM_AGENT_STEPS_TRAINED, + NUM_GRAD_UPDATES_LIFETIME, +) +from ray.rllib.utils.metrics.learner_info import LEARNER_STATS_KEY +from ray.rllib.utils.numpy import convert_to_numpy +from ray.rllib.utils.spaces.space_utils import normalize_action +from ray.rllib.utils.threading import with_lock +from ray.rllib.utils.torch_utils import ( + convert_to_torch_tensor, + TORCH_COMPILE_REQUIRED_VERSION, +) +from ray.rllib.utils.typing import ( + AlgorithmConfigDict, + GradInfoDict, + ModelGradients, + ModelWeights, + PolicyState, + TensorStructType, + TensorType, +) + +torch, nn = try_import_torch() + +logger = logging.getLogger(__name__) + + +@OldAPIStack +class TorchPolicyV2(Policy): + """PyTorch specific Policy class to use with RLlib.""" + + def __init__( + self, + observation_space: gym.spaces.Space, + action_space: gym.spaces.Space, + config: AlgorithmConfigDict, + *, + max_seq_len: int = 20, + ): + """Initializes a TorchPolicy instance. + + Args: + observation_space: Observation space of the policy. + action_space: Action space of the policy. + config: The Policy's config dict. + max_seq_len: Max sequence length for LSTM training. + """ + self.framework = config["framework"] = "torch" + + self._loss_initialized = False + super().__init__(observation_space, action_space, config) + + # Create model. + model, dist_class = self._init_model_and_dist_class() + + # Create multi-GPU model towers, if necessary. + # - The central main model will be stored under self.model, residing + # on self.device (normally, a CPU). + # - Each GPU will have a copy of that model under + # self.model_gpu_towers, matching the devices in self.devices. + # - Parallelization is done by splitting the train batch and passing + # it through the model copies in parallel, then averaging over the + # resulting gradients, applying these averages on the main model and + # updating all towers' weights from the main model. + # - In case of just one device (1 (fake or real) GPU or 1 CPU), no + # parallelization will be done. + + # Get devices to build the graph on. + num_gpus = self._get_num_gpus_for_policy() + gpu_ids = list(range(torch.cuda.device_count())) + logger.info(f"Found {len(gpu_ids)} visible cuda devices.") + + # Place on one or more CPU(s) when either: + # - Fake GPU mode. + # - num_gpus=0 (either set by user or we are in local_mode=True). + # - No GPUs available. + if config["_fake_gpus"] or num_gpus == 0 or not gpu_ids: + self.device = torch.device("cpu") + self.devices = [self.device for _ in range(int(math.ceil(num_gpus)) or 1)] + self.model_gpu_towers = [ + model if i == 0 else copy.deepcopy(model) + for i in range(int(math.ceil(num_gpus)) or 1) + ] + if hasattr(self, "target_model"): + self.target_models = { + m: self.target_model for m in self.model_gpu_towers + } + self.model = model + # Place on one or more actual GPU(s), when: + # - num_gpus > 0 (set by user) AND + # - local_mode=False AND + # - actual GPUs available AND + # - non-fake GPU mode. + else: + # We are a remote worker (WORKER_MODE=1): + # GPUs should be assigned to us by ray. + if ray._private.worker._mode() == ray._private.worker.WORKER_MODE: + gpu_ids = ray.get_gpu_ids() + + if len(gpu_ids) < num_gpus: + raise ValueError( + "TorchPolicy was not able to find enough GPU IDs! Found " + f"{gpu_ids}, but num_gpus={num_gpus}." + ) + + self.devices = [ + torch.device("cuda:{}".format(i)) + for i, id_ in enumerate(gpu_ids) + if i < num_gpus + ] + self.device = self.devices[0] + ids = [id_ for i, id_ in enumerate(gpu_ids) if i < num_gpus] + self.model_gpu_towers = [] + for i, _ in enumerate(ids): + model_copy = copy.deepcopy(model) + self.model_gpu_towers.append(model_copy.to(self.devices[i])) + if hasattr(self, "target_model"): + self.target_models = { + m: copy.deepcopy(self.target_model).to(self.devices[i]) + for i, m in enumerate(self.model_gpu_towers) + } + self.model = self.model_gpu_towers[0] + + self.dist_class = dist_class + self.unwrapped_model = model # used to support DistributedDataParallel + + # Lock used for locking some methods on the object-level. + # This prevents possible race conditions when calling the model + # first, then its value function (e.g. in a loss function), in + # between of which another model call is made (e.g. to compute an + # action). + self._lock = threading.RLock() + + self._state_inputs = self.model.get_initial_state() + self._is_recurrent = len(tree.flatten(self._state_inputs)) > 0 + # Auto-update model's inference view requirements, if recurrent. + self._update_model_view_requirements_from_init_state() + # Combine view_requirements for Model and Policy. + self.view_requirements.update(self.model.view_requirements) + + self.exploration = self._create_exploration() + self._optimizers = force_list(self.optimizer()) + + # Backward compatibility workaround so Policy will call self.loss() + # directly. + # TODO (jungong): clean up after all policies are migrated to new sub-class + # implementation. + self._loss = None + + # Store, which params (by index within the model's list of + # parameters) should be updated per optimizer. + # Maps optimizer idx to set or param indices. + self.multi_gpu_param_groups: List[Set[int]] = [] + main_params = {p: i for i, p in enumerate(self.model.parameters())} + for o in self._optimizers: + param_indices = [] + for pg_idx, pg in enumerate(o.param_groups): + for p in pg["params"]: + param_indices.append(main_params[p]) + self.multi_gpu_param_groups.append(set(param_indices)) + + # Create n sample-batch buffers (num_multi_gpu_tower_stacks), each + # one with m towers (num_gpus). + num_buffers = self.config.get("num_multi_gpu_tower_stacks", 1) + self._loaded_batches = [[] for _ in range(num_buffers)] + + # If set, means we are using distributed allreduce during learning. + self.distributed_world_size = None + + self.batch_divisibility_req = self.get_batch_divisibility_req() + self.max_seq_len = max_seq_len + + # If model is an RLModule it won't have tower_stats instead there will be a + # self.tower_state[model] -> dict for each tower. + self.tower_stats = {} + if not hasattr(self.model, "tower_stats"): + for model in self.model_gpu_towers: + self.tower_stats[model] = {} + + def loss_initialized(self): + return self._loss_initialized + + @OverrideToImplementCustomLogic + @override(Policy) + def loss( + self, + model: ModelV2, + dist_class: Type[TorchDistributionWrapper], + train_batch: SampleBatch, + ) -> Union[TensorType, List[TensorType]]: + """Constructs the loss function. + + Args: + model: The Model to calculate the loss for. + dist_class: The action distr. class. + train_batch: The training data. + + Returns: + Loss tensor given the input batch. + """ + raise NotImplementedError + + @OverrideToImplementCustomLogic + def action_sampler_fn( + self, + model: ModelV2, + *, + obs_batch: TensorType, + state_batches: TensorType, + **kwargs, + ) -> Tuple[TensorType, TensorType, TensorType, List[TensorType]]: + """Custom function for sampling new actions given policy. + + Args: + model: Underlying model. + obs_batch: Observation tensor batch. + state_batches: Action sampling state batch. + + Returns: + Sampled action + Log-likelihood + Action distribution inputs + Updated state + """ + return None, None, None, None + + @OverrideToImplementCustomLogic + def action_distribution_fn( + self, + model: ModelV2, + *, + obs_batch: TensorType, + state_batches: TensorType, + **kwargs, + ) -> Tuple[TensorType, type, List[TensorType]]: + """Action distribution function for this Policy. + + Args: + model: Underlying model. + obs_batch: Observation tensor batch. + state_batches: Action sampling state batch. + + Returns: + Distribution input. + ActionDistribution class. + State outs. + """ + return None, None, None + + @OverrideToImplementCustomLogic + def make_model(self) -> ModelV2: + """Create model. + + Note: only one of make_model or make_model_and_action_dist + can be overridden. + + Returns: + ModelV2 model. + """ + return None + + @OverrideToImplementCustomLogic + def make_model_and_action_dist( + self, + ) -> Tuple[ModelV2, Type[TorchDistributionWrapper]]: + """Create model and action distribution function. + + Returns: + ModelV2 model. + ActionDistribution class. + """ + return None, None + + @OverrideToImplementCustomLogic + def get_batch_divisibility_req(self) -> int: + """Get batch divisibility request. + + Returns: + Size N. A sample batch must be of size K*N. + """ + # By default, any sized batch is ok, so simply return 1. + return 1 + + @OverrideToImplementCustomLogic + def stats_fn(self, train_batch: SampleBatch) -> Dict[str, TensorType]: + """Stats function. Returns a dict of statistics. + + Args: + train_batch: The SampleBatch (already) used for training. + + Returns: + The stats dict. + """ + return {} + + @OverrideToImplementCustomLogic_CallToSuperRecommended + def extra_grad_process( + self, optimizer: "torch.optim.Optimizer", loss: TensorType + ) -> Dict[str, TensorType]: + """Called after each optimizer.zero_grad() + loss.backward() call. + + Called for each self._optimizers/loss-value pair. + Allows for gradient processing before optimizer.step() is called. + E.g. for gradient clipping. + + Args: + optimizer: A torch optimizer object. + loss: The loss tensor associated with the optimizer. + + Returns: + An dict with information on the gradient processing step. + """ + return {} + + @OverrideToImplementCustomLogic_CallToSuperRecommended + def extra_compute_grad_fetches(self) -> Dict[str, Any]: + """Extra values to fetch and return from compute_gradients(). + + Returns: + Extra fetch dict to be added to the fetch dict of the + `compute_gradients` call. + """ + return {LEARNER_STATS_KEY: {}} # e.g, stats, td error, etc. + + @OverrideToImplementCustomLogic_CallToSuperRecommended + def extra_action_out( + self, + input_dict: Dict[str, TensorType], + state_batches: List[TensorType], + model: TorchModelV2, + action_dist: TorchDistributionWrapper, + ) -> Dict[str, TensorType]: + """Returns dict of extra info to include in experience batch. + + Args: + input_dict: Dict of model input tensors. + state_batches: List of state tensors. + model: Reference to the model object. + action_dist: Torch action dist object + to get log-probs (e.g. for already sampled actions). + + Returns: + Extra outputs to return in a `compute_actions_from_input_dict()` + call (3rd return value). + """ + return {} + + @override(Policy) + @OverrideToImplementCustomLogic_CallToSuperRecommended + def postprocess_trajectory( + self, + sample_batch: SampleBatch, + other_agent_batches: Optional[Dict[Any, SampleBatch]] = None, + episode=None, + ) -> SampleBatch: + """Postprocesses a trajectory and returns the processed trajectory. + + The trajectory contains only data from one episode and from one agent. + - If `config.batch_mode=truncate_episodes` (default), sample_batch may + contain a truncated (at-the-end) episode, in case the + `config.rollout_fragment_length` was reached by the sampler. + - If `config.batch_mode=complete_episodes`, sample_batch will contain + exactly one episode (no matter how long). + New columns can be added to sample_batch and existing ones may be altered. + + Args: + sample_batch: The SampleBatch to postprocess. + other_agent_batches (Optional[Dict[PolicyID, SampleBatch]]): Optional + dict of AgentIDs mapping to other agents' trajectory data (from the + same episode). NOTE: The other agents use the same policy. + episode (Optional[Episode]): Optional multi-agent episode + object in which the agents operated. + + Returns: + SampleBatch: The postprocessed, modified SampleBatch (or a new one). + """ + return sample_batch + + @OverrideToImplementCustomLogic + def optimizer( + self, + ) -> Union[List["torch.optim.Optimizer"], "torch.optim.Optimizer"]: + """Custom the local PyTorch optimizer(s) to use. + + Returns: + The local PyTorch optimizer(s) to use for this Policy. + """ + if hasattr(self, "config"): + optimizers = [ + torch.optim.Adam(self.model.parameters(), lr=self.config["lr"]) + ] + else: + optimizers = [torch.optim.Adam(self.model.parameters())] + if self.exploration: + optimizers = self.exploration.get_exploration_optimizer(optimizers) + return optimizers + + def _init_model_and_dist_class(self): + if is_overridden(self.make_model) and is_overridden( + self.make_model_and_action_dist + ): + raise ValueError( + "Only one of make_model or make_model_and_action_dist " + "can be overridden." + ) + + if is_overridden(self.make_model): + model = self.make_model() + dist_class, _ = ModelCatalog.get_action_dist( + self.action_space, self.config["model"], framework=self.framework + ) + elif is_overridden(self.make_model_and_action_dist): + model, dist_class = self.make_model_and_action_dist() + else: + dist_class, logit_dim = ModelCatalog.get_action_dist( + self.action_space, self.config["model"], framework=self.framework + ) + model = ModelCatalog.get_model_v2( + obs_space=self.observation_space, + action_space=self.action_space, + num_outputs=logit_dim, + model_config=self.config["model"], + framework=self.framework, + ) + + # Compile the model, if requested by the user. + if self.config.get("torch_compile_learner"): + if ( + torch is not None + and version.parse(torch.__version__) < TORCH_COMPILE_REQUIRED_VERSION + ): + raise ValueError("`torch.compile` is not supported for torch < 2.0.0!") + + lw = "learner" if self.config.get("worker_index") else "worker" + model = torch.compile( + model, + backend=self.config.get( + f"torch_compile_{lw}_dynamo_backend", "inductor" + ), + dynamic=False, + mode=self.config.get(f"torch_compile_{lw}_dynamo_mode"), + ) + return model, dist_class + + @override(Policy) + def compute_actions_from_input_dict( + self, + input_dict: Dict[str, TensorType], + explore: bool = None, + timestep: Optional[int] = None, + **kwargs, + ) -> Tuple[TensorType, List[TensorType], Dict[str, TensorType]]: + + seq_lens = None + with torch.no_grad(): + # Pass lazy (torch) tensor dict to Model as `input_dict`. + input_dict = self._lazy_tensor_dict(input_dict) + input_dict.set_training(True) + # Pack internal state inputs into (separate) list. + state_batches = [ + input_dict[k] for k in input_dict.keys() if "state_in" in k[:8] + ] + # Calculate RNN sequence lengths. + if state_batches: + seq_lens = torch.tensor( + [1] * len(state_batches[0]), + dtype=torch.long, + device=state_batches[0].device, + ) + + return self._compute_action_helper( + input_dict, state_batches, seq_lens, explore, timestep + ) + + @override(Policy) + def compute_actions( + self, + obs_batch: Union[List[TensorStructType], TensorStructType], + state_batches: Optional[List[TensorType]] = None, + prev_action_batch: Union[List[TensorStructType], TensorStructType] = None, + prev_reward_batch: Union[List[TensorStructType], TensorStructType] = None, + info_batch: Optional[Dict[str, list]] = None, + episodes=None, + explore: Optional[bool] = None, + timestep: Optional[int] = None, + **kwargs, + ) -> Tuple[TensorStructType, List[TensorType], Dict[str, TensorType]]: + + with torch.no_grad(): + seq_lens = torch.ones(len(obs_batch), dtype=torch.int32) + input_dict = self._lazy_tensor_dict( + { + SampleBatch.CUR_OBS: obs_batch, + "is_training": False, + } + ) + if prev_action_batch is not None: + input_dict[SampleBatch.PREV_ACTIONS] = np.asarray(prev_action_batch) + if prev_reward_batch is not None: + input_dict[SampleBatch.PREV_REWARDS] = np.asarray(prev_reward_batch) + state_batches = [ + convert_to_torch_tensor(s, self.device) for s in (state_batches or []) + ] + return self._compute_action_helper( + input_dict, state_batches, seq_lens, explore, timestep + ) + + @with_lock + @override(Policy) + def compute_log_likelihoods( + self, + actions: Union[List[TensorStructType], TensorStructType], + obs_batch: Union[List[TensorStructType], TensorStructType], + state_batches: Optional[List[TensorType]] = None, + prev_action_batch: Optional[ + Union[List[TensorStructType], TensorStructType] + ] = None, + prev_reward_batch: Optional[ + Union[List[TensorStructType], TensorStructType] + ] = None, + actions_normalized: bool = True, + in_training: bool = True, + ) -> TensorType: + + if is_overridden(self.action_sampler_fn) and not is_overridden( + self.action_distribution_fn + ): + raise ValueError( + "Cannot compute log-prob/likelihood w/o an " + "`action_distribution_fn` and a provided " + "`action_sampler_fn`!" + ) + + with torch.no_grad(): + input_dict = self._lazy_tensor_dict( + {SampleBatch.CUR_OBS: obs_batch, SampleBatch.ACTIONS: actions} + ) + if prev_action_batch is not None: + input_dict[SampleBatch.PREV_ACTIONS] = prev_action_batch + if prev_reward_batch is not None: + input_dict[SampleBatch.PREV_REWARDS] = prev_reward_batch + seq_lens = torch.ones(len(obs_batch), dtype=torch.int32) + state_batches = [ + convert_to_torch_tensor(s, self.device) for s in (state_batches or []) + ] + + if self.exploration: + # Exploration hook before each forward pass. + self.exploration.before_compute_actions(explore=False) + + # Action dist class and inputs are generated via custom function. + if is_overridden(self.action_distribution_fn): + dist_inputs, dist_class, state_out = self.action_distribution_fn( + self.model, + obs_batch=input_dict, + state_batches=state_batches, + seq_lens=seq_lens, + explore=False, + is_training=False, + ) + action_dist = dist_class(dist_inputs, self.model) + # Default action-dist inputs calculation. + else: + dist_class = self.dist_class + dist_inputs, _ = self.model(input_dict, state_batches, seq_lens) + + action_dist = dist_class(dist_inputs, self.model) + + # Normalize actions if necessary. + actions = input_dict[SampleBatch.ACTIONS] + if not actions_normalized and self.config["normalize_actions"]: + actions = normalize_action(actions, self.action_space_struct) + + log_likelihoods = action_dist.logp(actions) + + return log_likelihoods + + @with_lock + @override(Policy) + def learn_on_batch(self, postprocessed_batch: SampleBatch) -> Dict[str, TensorType]: + + # Set Model to train mode. + if self.model: + self.model.train() + # Callback handling. + learn_stats = {} + self.callbacks.on_learn_on_batch( + policy=self, train_batch=postprocessed_batch, result=learn_stats + ) + + # Compute gradients (will calculate all losses and `backward()` + # them to get the grads). + grads, fetches = self.compute_gradients(postprocessed_batch) + + # Step the optimizers. + self.apply_gradients(_directStepOptimizerSingleton) + + self.num_grad_updates += 1 + if self.model and hasattr(self.model, "metrics"): + fetches["model"] = self.model.metrics() + else: + fetches["model"] = {} + + fetches.update( + { + "custom_metrics": learn_stats, + NUM_AGENT_STEPS_TRAINED: postprocessed_batch.count, + NUM_GRAD_UPDATES_LIFETIME: self.num_grad_updates, + # -1, b/c we have to measure this diff before we do the update above. + DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY: ( + self.num_grad_updates + - 1 + - (postprocessed_batch.num_grad_updates or 0) + ), + } + ) + + return fetches + + @override(Policy) + def load_batch_into_buffer( + self, + batch: SampleBatch, + buffer_index: int = 0, + ) -> int: + # Set the is_training flag of the batch. + batch.set_training(True) + + # Shortcut for 1 CPU only: Store batch in `self._loaded_batches`. + if len(self.devices) == 1 and self.devices[0].type == "cpu": + assert buffer_index == 0 + pad_batch_to_sequences_of_same_size( + batch=batch, + max_seq_len=self.max_seq_len, + shuffle=False, + batch_divisibility_req=self.batch_divisibility_req, + view_requirements=self.view_requirements, + _enable_new_api_stack=False, + padding="zero", + ) + self._lazy_tensor_dict(batch) + self._loaded_batches[0] = [batch] + return len(batch) + + # Batch (len=28, seq-lens=[4, 7, 4, 10, 3]): + # 0123 0123456 0123 0123456789ABC + + # 1) split into n per-GPU sub batches (n=2). + # [0123 0123456] [012] [3 0123456789 ABC] + # (len=14, 14 seq-lens=[4, 7, 3] [1, 10, 3]) + slices = batch.timeslices(num_slices=len(self.devices)) + + # 2) zero-padding (max-seq-len=10). + # - [0123000000 0123456000 0120000000] + # - [3000000000 0123456789 ABC0000000] + for slice in slices: + pad_batch_to_sequences_of_same_size( + batch=slice, + max_seq_len=self.max_seq_len, + shuffle=False, + batch_divisibility_req=self.batch_divisibility_req, + view_requirements=self.view_requirements, + _enable_new_api_stack=False, + padding="zero", + ) + + # 3) Load splits into the given buffer (consisting of n GPUs). + slices = [slice.to_device(self.devices[i]) for i, slice in enumerate(slices)] + self._loaded_batches[buffer_index] = slices + + # Return loaded samples per-device. + return len(slices[0]) + + @override(Policy) + def get_num_samples_loaded_into_buffer(self, buffer_index: int = 0) -> int: + if len(self.devices) == 1 and self.devices[0] == "/cpu:0": + assert buffer_index == 0 + return sum(len(b) for b in self._loaded_batches[buffer_index]) + + @override(Policy) + def learn_on_loaded_batch(self, offset: int = 0, buffer_index: int = 0): + if not self._loaded_batches[buffer_index]: + raise ValueError( + "Must call Policy.load_batch_into_buffer() before " + "Policy.learn_on_loaded_batch()!" + ) + + # Get the correct slice of the already loaded batch to use, + # based on offset and batch size. + device_batch_size = self.config.get("minibatch_size") + if device_batch_size is None: + device_batch_size = self.config.get( + "sgd_minibatch_size", + self.config["train_batch_size"], + ) + device_batch_size //= len(self.devices) + + # Set Model to train mode. + if self.model_gpu_towers: + for t in self.model_gpu_towers: + t.train() + + # Shortcut for 1 CPU only: Batch should already be stored in + # `self._loaded_batches`. + if len(self.devices) == 1 and self.devices[0].type == "cpu": + assert buffer_index == 0 + if device_batch_size >= len(self._loaded_batches[0][0]): + batch = self._loaded_batches[0][0] + else: + batch = self._loaded_batches[0][0][offset : offset + device_batch_size] + + return self.learn_on_batch(batch) + + if len(self.devices) > 1: + # Copy weights of main model (tower-0) to all other towers. + state_dict = self.model.state_dict() + # Just making sure tower-0 is really the same as self.model. + assert self.model_gpu_towers[0] is self.model + for tower in self.model_gpu_towers[1:]: + tower.load_state_dict(state_dict) + + if device_batch_size >= sum(len(s) for s in self._loaded_batches[buffer_index]): + device_batches = self._loaded_batches[buffer_index] + else: + device_batches = [ + b[offset : offset + device_batch_size] + for b in self._loaded_batches[buffer_index] + ] + + # Callback handling. + batch_fetches = {} + for i, batch in enumerate(device_batches): + custom_metrics = {} + self.callbacks.on_learn_on_batch( + policy=self, train_batch=batch, result=custom_metrics + ) + batch_fetches[f"tower_{i}"] = {"custom_metrics": custom_metrics} + + # Do the (maybe parallelized) gradient calculation step. + tower_outputs = self._multi_gpu_parallel_grad_calc(device_batches) + + # Mean-reduce gradients over GPU-towers (do this on CPU: self.device). + all_grads = [] + for i in range(len(tower_outputs[0][0])): + if tower_outputs[0][0][i] is not None: + all_grads.append( + torch.mean( + torch.stack([t[0][i].to(self.device) for t in tower_outputs]), + dim=0, + ) + ) + else: + all_grads.append(None) + # Set main model's grads to mean-reduced values. + for i, p in enumerate(self.model.parameters()): + p.grad = all_grads[i] + + self.apply_gradients(_directStepOptimizerSingleton) + + self.num_grad_updates += 1 + + for i, (model, batch) in enumerate(zip(self.model_gpu_towers, device_batches)): + batch_fetches[f"tower_{i}"].update( + { + LEARNER_STATS_KEY: self.stats_fn(batch), + "model": model.metrics(), + NUM_GRAD_UPDATES_LIFETIME: self.num_grad_updates, + # -1, b/c we have to measure this diff before we do the update + # above. + DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY: ( + self.num_grad_updates - 1 - (batch.num_grad_updates or 0) + ), + } + ) + batch_fetches.update(self.extra_compute_grad_fetches()) + + return batch_fetches + + @with_lock + @override(Policy) + def compute_gradients(self, postprocessed_batch: SampleBatch) -> ModelGradients: + + assert len(self.devices) == 1 + + # If not done yet, see whether we have to zero-pad this batch. + if not postprocessed_batch.zero_padded: + pad_batch_to_sequences_of_same_size( + batch=postprocessed_batch, + max_seq_len=self.max_seq_len, + shuffle=False, + batch_divisibility_req=self.batch_divisibility_req, + view_requirements=self.view_requirements, + _enable_new_api_stack=False, + padding="zero", + ) + + postprocessed_batch.set_training(True) + self._lazy_tensor_dict(postprocessed_batch, device=self.devices[0]) + + # Do the (maybe parallelized) gradient calculation step. + tower_outputs = self._multi_gpu_parallel_grad_calc([postprocessed_batch]) + + all_grads, grad_info = tower_outputs[0] + + grad_info["allreduce_latency"] /= len(self._optimizers) + grad_info.update(self.stats_fn(postprocessed_batch)) + + fetches = self.extra_compute_grad_fetches() + + return all_grads, dict(fetches, **{LEARNER_STATS_KEY: grad_info}) + + @override(Policy) + def apply_gradients(self, gradients: ModelGradients) -> None: + if gradients == _directStepOptimizerSingleton: + for i, opt in enumerate(self._optimizers): + opt.step() + else: + # TODO(sven): Not supported for multiple optimizers yet. + assert len(self._optimizers) == 1 + for g, p in zip(gradients, self.model.parameters()): + if g is not None: + if torch.is_tensor(g): + p.grad = g.to(self.device) + else: + p.grad = torch.from_numpy(g).to(self.device) + + self._optimizers[0].step() + + def get_tower_stats(self, stats_name: str) -> List[TensorStructType]: + """Returns list of per-tower stats, copied to this Policy's device. + + Args: + stats_name: The name of the stats to average over (this str + must exist as a key inside each tower's `tower_stats` dict). + + Returns: + The list of stats tensor (structs) of all towers, copied to this + Policy's device. + + Raises: + AssertionError: If the `stats_name` cannot be found in any one + of the tower's `tower_stats` dicts. + """ + data = [] + for model in self.model_gpu_towers: + if self.tower_stats: + tower_stats = self.tower_stats[model] + else: + tower_stats = model.tower_stats + + if stats_name in tower_stats: + data.append( + tree.map_structure( + lambda s: s.to(self.device), tower_stats[stats_name] + ) + ) + + assert len(data) > 0, ( + f"Stats `{stats_name}` not found in any of the towers (you have " + f"{len(self.model_gpu_towers)} towers in total)! Make " + "sure you call the loss function on at least one of the towers." + ) + return data + + @override(Policy) + def get_weights(self) -> ModelWeights: + return {k: v.cpu().detach().numpy() for k, v in self.model.state_dict().items()} + + @override(Policy) + def set_weights(self, weights: ModelWeights) -> None: + weights = convert_to_torch_tensor(weights, device=self.device) + self.model.load_state_dict(weights) + + @override(Policy) + def is_recurrent(self) -> bool: + return self._is_recurrent + + @override(Policy) + def num_state_tensors(self) -> int: + return len(self.model.get_initial_state()) + + @override(Policy) + def get_initial_state(self) -> List[TensorType]: + return [s.detach().cpu().numpy() for s in self.model.get_initial_state()] + + @override(Policy) + @OverrideToImplementCustomLogic_CallToSuperRecommended + def get_state(self) -> PolicyState: + # Legacy Policy state (w/o torch.nn.Module and w/o PolicySpec). + state = super().get_state() + + state["_optimizer_variables"] = [] + for i, o in enumerate(self._optimizers): + optim_state_dict = convert_to_numpy(o.state_dict()) + state["_optimizer_variables"].append(optim_state_dict) + # Add exploration state. + if self.exploration: + # This is not compatible with RLModules, which have a method + # `forward_exploration` to specify custom exploration behavior. + state["_exploration_state"] = self.exploration.get_state() + return state + + @override(Policy) + @OverrideToImplementCustomLogic_CallToSuperRecommended + def set_state(self, state: PolicyState) -> None: + # Set optimizer vars first. + optimizer_vars = state.get("_optimizer_variables", None) + if optimizer_vars: + assert len(optimizer_vars) == len(self._optimizers) + for o, s in zip(self._optimizers, optimizer_vars): + # Torch optimizer param_groups include things like beta, etc. These + # parameters should be left as scalar and not converted to tensors. + # otherwise, torch.optim.step() will start to complain. + optim_state_dict = {"param_groups": s["param_groups"]} + optim_state_dict["state"] = convert_to_torch_tensor( + s["state"], device=self.device + ) + o.load_state_dict(optim_state_dict) + # Set exploration's state. + if hasattr(self, "exploration") and "_exploration_state" in state: + self.exploration.set_state(state=state["_exploration_state"]) + + # Restore global timestep. + self.global_timestep = state["global_timestep"] + + # Then the Policy's (NN) weights and connectors. + super().set_state(state) + + @override(Policy) + def export_model(self, export_dir: str, onnx: Optional[int] = None) -> None: + """Exports the Policy's Model to local directory for serving. + + Creates a TorchScript model and saves it. + + Args: + export_dir: Local writable directory or filename. + onnx: If given, will export model in ONNX format. The + value of this parameter set the ONNX OpSet version to use. + """ + + os.makedirs(export_dir, exist_ok=True) + + if onnx: + self._lazy_tensor_dict(self._dummy_batch) + # Provide dummy state inputs if not an RNN (torch cannot jit with + # returned empty internal states list). + if "state_in_0" not in self._dummy_batch: + self._dummy_batch["state_in_0"] = self._dummy_batch[ + SampleBatch.SEQ_LENS + ] = np.array([1.0]) + seq_lens = self._dummy_batch[SampleBatch.SEQ_LENS] + + state_ins = [] + i = 0 + while "state_in_{}".format(i) in self._dummy_batch: + state_ins.append(self._dummy_batch["state_in_{}".format(i)]) + i += 1 + dummy_inputs = { + k: self._dummy_batch[k] + for k in self._dummy_batch.keys() + if k != "is_training" + } + + file_name = os.path.join(export_dir, "model.onnx") + torch.onnx.export( + self.model, + (dummy_inputs, state_ins, seq_lens), + file_name, + export_params=True, + opset_version=onnx, + do_constant_folding=True, + input_names=list(dummy_inputs.keys()) + + ["state_ins", SampleBatch.SEQ_LENS], + output_names=["output", "state_outs"], + dynamic_axes={ + k: {0: "batch_size"} + for k in list(dummy_inputs.keys()) + + ["state_ins", SampleBatch.SEQ_LENS] + }, + ) + # Save the torch.Model (architecture and weights, so it can be retrieved + # w/o access to the original (custom) Model or Policy code). + else: + filename = os.path.join(export_dir, "model.pt") + try: + torch.save(self.model, f=filename) + except Exception: + if os.path.exists(filename): + os.remove(filename) + logger.warning(ERR_MSG_TORCH_POLICY_CANNOT_SAVE_MODEL) + + @override(Policy) + def import_model_from_h5(self, import_file: str) -> None: + """Imports weights into torch model.""" + return self.model.import_from_h5(import_file) + + @with_lock + def _compute_action_helper( + self, input_dict, state_batches, seq_lens, explore, timestep + ): + """Shared forward pass logic (w/ and w/o trajectory view API). + + Returns: + A tuple consisting of a) actions, b) state_out, c) extra_fetches. + The input_dict is modified in-place to include a numpy copy of the computed + actions under `SampleBatch.ACTIONS`. + """ + explore = explore if explore is not None else self.config["explore"] + timestep = timestep if timestep is not None else self.global_timestep + + # Switch to eval mode. + if self.model: + self.model.eval() + + extra_fetches = dist_inputs = logp = None + + if is_overridden(self.action_sampler_fn): + action_dist = None + actions, logp, dist_inputs, state_out = self.action_sampler_fn( + self.model, + obs_batch=input_dict, + state_batches=state_batches, + explore=explore, + timestep=timestep, + ) + else: + # Call the exploration before_compute_actions hook. + self.exploration.before_compute_actions(explore=explore, timestep=timestep) + if is_overridden(self.action_distribution_fn): + dist_inputs, dist_class, state_out = self.action_distribution_fn( + self.model, + obs_batch=input_dict, + state_batches=state_batches, + seq_lens=seq_lens, + explore=explore, + timestep=timestep, + is_training=False, + ) + else: + dist_class = self.dist_class + dist_inputs, state_out = self.model(input_dict, state_batches, seq_lens) + + if not ( + isinstance(dist_class, functools.partial) + or issubclass(dist_class, TorchDistributionWrapper) + ): + raise ValueError( + "`dist_class` ({}) not a TorchDistributionWrapper " + "subclass! Make sure your `action_distribution_fn` or " + "`make_model_and_action_dist` return a correct " + "distribution class.".format(dist_class.__name__) + ) + action_dist = dist_class(dist_inputs, self.model) + + # Get the exploration action from the forward results. + actions, logp = self.exploration.get_exploration_action( + action_distribution=action_dist, timestep=timestep, explore=explore + ) + + # Add default and custom fetches. + if extra_fetches is None: + extra_fetches = self.extra_action_out( + input_dict, state_batches, self.model, action_dist + ) + + # Action-dist inputs. + if dist_inputs is not None: + extra_fetches[SampleBatch.ACTION_DIST_INPUTS] = dist_inputs + + # Action-logp and action-prob. + if logp is not None: + extra_fetches[SampleBatch.ACTION_PROB] = torch.exp(logp.float()) + extra_fetches[SampleBatch.ACTION_LOGP] = logp + + # Update our global timestep by the batch size. + self.global_timestep += len(input_dict[SampleBatch.CUR_OBS]) + return convert_to_numpy((actions, state_out, extra_fetches)) + + def _lazy_tensor_dict(self, postprocessed_batch: SampleBatch, device=None): + if not isinstance(postprocessed_batch, SampleBatch): + postprocessed_batch = SampleBatch(postprocessed_batch) + postprocessed_batch.set_get_interceptor( + functools.partial(convert_to_torch_tensor, device=device or self.device) + ) + return postprocessed_batch + + def _multi_gpu_parallel_grad_calc( + self, sample_batches: List[SampleBatch] + ) -> List[Tuple[List[TensorType], GradInfoDict]]: + """Performs a parallelized loss and gradient calculation over the batch. + + Splits up the given train batch into n shards (n=number of this + Policy's devices) and passes each data shard (in parallel) through + the loss function using the individual devices' models + (self.model_gpu_towers). Then returns each tower's outputs. + + Args: + sample_batches: A list of SampleBatch shards to + calculate loss and gradients for. + + Returns: + A list (one item per device) of 2-tuples, each with 1) gradient + list and 2) grad info dict. + """ + assert len(self.model_gpu_towers) == len(sample_batches) + lock = threading.Lock() + results = {} + grad_enabled = torch.is_grad_enabled() + + def _worker(shard_idx, model, sample_batch, device): + torch.set_grad_enabled(grad_enabled) + try: + with NullContextManager() if device.type == "cpu" else torch.cuda.device( # noqa: E501 + device + ): + loss_out = force_list( + self.loss(model, self.dist_class, sample_batch) + ) + + # Call Model's custom-loss with Policy loss outputs and + # train_batch. + if hasattr(model, "custom_loss"): + loss_out = model.custom_loss(loss_out, sample_batch) + + assert len(loss_out) == len(self._optimizers) + + # Loop through all optimizers. + grad_info = {"allreduce_latency": 0.0} + + parameters = list(model.parameters()) + all_grads = [None for _ in range(len(parameters))] + for opt_idx, opt in enumerate(self._optimizers): + # Erase gradients in all vars of the tower that this + # optimizer would affect. + param_indices = self.multi_gpu_param_groups[opt_idx] + for param_idx, param in enumerate(parameters): + if param_idx in param_indices and param.grad is not None: + param.grad.data.zero_() + # Recompute gradients of loss over all variables. + loss_out[opt_idx].backward(retain_graph=True) + grad_info.update( + self.extra_grad_process(opt, loss_out[opt_idx]) + ) + + grads = [] + # Note that return values are just references; + # Calling zero_grad would modify the values. + for param_idx, param in enumerate(parameters): + if param_idx in param_indices: + if param.grad is not None: + grads.append(param.grad) + all_grads[param_idx] = param.grad + + if self.distributed_world_size: + start = time.time() + if torch.cuda.is_available(): + # Sadly, allreduce_coalesced does not work with + # CUDA yet. + for g in grads: + torch.distributed.all_reduce( + g, op=torch.distributed.ReduceOp.SUM + ) + else: + torch.distributed.all_reduce_coalesced( + grads, op=torch.distributed.ReduceOp.SUM + ) + + for param_group in opt.param_groups: + for p in param_group["params"]: + if p.grad is not None: + p.grad /= self.distributed_world_size + + grad_info["allreduce_latency"] += time.time() - start + + with lock: + results[shard_idx] = (all_grads, grad_info) + except Exception as e: + import traceback + + with lock: + results[shard_idx] = ( + ValueError( + e.args[0] + + "\n traceback" + + traceback.format_exc() + + "\n" + + "In tower {} on device {}".format(shard_idx, device) + ), + e, + ) + + # Single device (GPU) or fake-GPU case (serialize for better + # debugging). + if len(self.devices) == 1 or self.config["_fake_gpus"]: + for shard_idx, (model, sample_batch, device) in enumerate( + zip(self.model_gpu_towers, sample_batches, self.devices) + ): + _worker(shard_idx, model, sample_batch, device) + # Raise errors right away for better debugging. + last_result = results[len(results) - 1] + if isinstance(last_result[0], ValueError): + raise last_result[0] from last_result[1] + # Multi device (GPU) case: Parallelize via threads. + else: + threads = [ + threading.Thread( + target=_worker, args=(shard_idx, model, sample_batch, device) + ) + for shard_idx, (model, sample_batch, device) in enumerate( + zip(self.model_gpu_towers, sample_batches, self.devices) + ) + ] + + for thread in threads: + thread.start() + for thread in threads: + thread.join() + + # Gather all threads' outputs and return. + outputs = [] + for shard_idx in range(len(sample_batches)): + output = results[shard_idx] + if isinstance(output[0], Exception): + raise output[0] from output[1] + outputs.append(results[shard_idx]) + return outputs diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/view_requirement.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/view_requirement.py new file mode 100644 index 0000000000000000000000000000000000000000..ef360e3ddf3a053a088a42e74afa51bdce1bda2b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/policy/view_requirement.py @@ -0,0 +1,152 @@ +import dataclasses +import gymnasium as gym +from typing import Dict, List, Optional, Union +import numpy as np + +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.serialization import ( + gym_space_to_dict, + gym_space_from_dict, +) + +torch, _ = try_import_torch() + + +@OldAPIStack +@dataclasses.dataclass +class ViewRequirement: + """Single view requirement (for one column in an SampleBatch/input_dict). + + Policies and ModelV2s return a Dict[str, ViewRequirement] upon calling + their `[train|inference]_view_requirements()` methods, where the str key + represents the column name (C) under which the view is available in the + input_dict/SampleBatch and ViewRequirement specifies the actual underlying + column names (in the original data buffer), timestep shifts, and other + options to build the view. + + .. testcode:: + :skipif: True + + from ray.rllib.models.modelv2 import ModelV2 + # The default ViewRequirement for a Model is: + req = ModelV2(...).view_requirements + print(req) + + .. testoutput:: + + {"obs": ViewRequirement(shift=0)} + + Args: + data_col: The data column name from the SampleBatch + (str key). If None, use the dict key under which this + ViewRequirement resides. + space: The gym Space used in case we need to pad data + in inaccessible areas of the trajectory (t<0 or t>H). + Default: Simple box space, e.g. rewards. + shift: Single shift value or + list of relative positions to use (relative to the underlying + `data_col`). + Example: For a view column "prev_actions", you can set + `data_col="actions"` and `shift=-1`. + Example: For a view column "obs" in an Atari framestacking + fashion, you can set `data_col="obs"` and + `shift=[-3, -2, -1, 0]`. + Example: For the obs input to an attention net, you can specify + a range via a str: `shift="-100:0"`, which will pass in + the past 100 observations plus the current one. + index: An optional absolute position arg, + used e.g. for the location of a requested inference dict within + the trajectory. Negative values refer to counting from the end + of a trajectory. (#TODO: Is this still used?) + batch_repeat_value: determines how many time steps we should skip + before we repeat the view indexing for the next timestep. For RNNs this + number is usually the sequence length that we will rollout over. + Example: + view_col = "state_in_0", data_col = "state_out_0" + batch_repeat_value = 5, shift = -1 + buffer["state_out_0"] = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + output["state_in_0"] = [-1, 4, 9] + Explanation: For t=0, we output buffer["state_out_0"][-1]. We then skip 5 + time steps and repeat the view. for t=5, we output buffer["state_out_0"][4] + . Continuing on this pattern, for t=10, we output buffer["state_out_0"][9]. + used_for_compute_actions: Whether the data will be used for + creating input_dicts for `Policy.compute_actions()` calls (or + `Policy.compute_actions_from_input_dict()`). + used_for_training: Whether the data will be used for + training. If False, the column will not be copied into the + final train batch. + """ + + data_col: Optional[str] = None + space: gym.Space = None + shift: Union[int, str, List[int]] = 0 + index: Optional[int] = None + batch_repeat_value: int = 1 + used_for_compute_actions: bool = True + used_for_training: bool = True + shift_arr: Optional[np.ndarray] = dataclasses.field(init=False) + + def __post_init__(self): + """Initializes a ViewRequirement object. + + shift_arr is infered from the shift value. + + For example: + - if shift is -1, then shift_arr is np.array([-1]). + - if shift is [-1, -2], then shift_arr is np.array([-2, -1]). + - if shift is "-2:2", then shift_arr is np.array([-2, -1, 0, 1, 2]). + """ + + if self.space is None: + self.space = gym.spaces.Box(float("-inf"), float("inf"), shape=()) + + # TODO: ideally we won't need shift_from and shift_to, and shift_step. + # all of them should be captured within shift_arr. + # Special case: Providing a (probably larger) range of indices, e.g. + # "-100:0" (past 100 timesteps plus current one). + self.shift_from = self.shift_to = self.shift_step = None + if isinstance(self.shift, str): + split = self.shift.split(":") + assert len(split) in [2, 3], f"Invalid shift str format: {self.shift}" + if len(split) == 2: + f, t = split + self.shift_step = 1 + else: + f, t, s = split + self.shift_step = int(s) + + self.shift_from = int(f) + self.shift_to = int(t) + + shift = self.shift + self.shfit_arr = None + if self.shift_from: + self.shift_arr = np.arange( + self.shift_from, self.shift_to + 1, self.shift_step + ) + else: + if isinstance(shift, int): + self.shift_arr = np.array([shift]) + elif isinstance(shift, list): + self.shift_arr = np.array(shift) + else: + ValueError(f'unrecognized shift type: "{shift}"') + + def to_dict(self) -> Dict: + """Return a dict for this ViewRequirement that can be JSON serialized.""" + return { + "data_col": self.data_col, + "space": gym_space_to_dict(self.space), + "shift": self.shift, + "index": self.index, + "batch_repeat_value": self.batch_repeat_value, + "used_for_training": self.used_for_training, + "used_for_compute_actions": self.used_for_compute_actions, + } + + @classmethod + def from_dict(cls, d: Dict): + """Construct a ViewRequirement instance from JSON deserialized dict.""" + d["space"] = gym_space_from_dict(d["space"]) + return cls(**d) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/cleanup_experiment.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/cleanup_experiment.py new file mode 100644 index 0000000000000000000000000000000000000000..370568db79959b64b4232caeaf879219c71c050f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/tuned_examples/cleanup_experiment.py @@ -0,0 +1,186 @@ +""" +This script automates cleaning up a benchmark/experiment run of some algo +against some config (with possibly more than one tune trial, +e.g. torch=grid_search([True, False])). + +Run `python cleanup_experiment.py --help` for more information. + +Use on an input directory with trial contents e.g.: +.. +IMPALA_BreakoutNoFrameskip-v4_0_use_pytorch=False_2020-05-11_10-17-54topr3h9k +IMPALA_BreakoutNoFrameskip-v4_0_use_pytorch=False_2020-05-11_13-59-35dqaetxnf +IMPALA_BreakoutNoFrameskip-v4_0_use_pytorch=False_2020-05-11_17-21-28tbhedw72 +IMPALA_BreakoutNoFrameskip-v4_2_use_pytorch=True_2020-05-11_10-17-54lv20cgn_ +IMPALA_BreakoutNoFrameskip-v4_2_use_pytorch=True_2020-05-11_13-59-35kwzhax_y +IMPALA_BreakoutNoFrameskip-v4_2_use_pytorch=True_2020-05-11_17-21-28a5j0s7za + +Then run: +>> python cleanup_experiment.py --experiment-dir [parent dir w/ trial sub-dirs] +>> --output-dir [your out dir] --results-filter dumb_col_2,superfluous_col3 +>> --results-max-size [max results file size in kb before(!) zipping] + +The script will create one output sub-dir for each trial and only copy +the configuration and the csv results (filtered and every nth row removed +based on the given args). +""" + +import argparse +import json +import os +import re +import shutil +import yaml + +parser = argparse.ArgumentParser() +parser.add_argument( + "--experiment-dir", + type=str, + help="Experiment dir in which all sub-runs (seeds) are " + "located (as sub-dirs). Each sub0-run dir must contain the files: " + "params.json and progress.csv.", +) +parser.add_argument( + "--output-dir", + type=str, + help="The output dir, in which the cleaned up output will be placed.", +) +parser.add_argument( + "--results-filter", + type=str, + help="comma-separated list of csv fields to exclude.", + default="experiment_id,pid,hostname,node_ip,trial_id,hist_stats/episode_" + "reward,hist_stats/episode_lengths,experiment_tag", +) +parser.add_argument( + "--results-max-size", + type=int, + help="the max. size of the final results.csv file (in kb). Will erase " + "every nth line in the original input to reach that goal. " + "Use 0 for no limit (default=100).", + default=100, +) + + +def process_single_run(in_dir, out_dir): + exp_dir = os.listdir(in_dir) + + # Make sure trials dir is ok. + assert ( + "params.json" in exp_dir and "progress.csv" in exp_dir + ), "params.json or progress.csv not found in {}!".format(in_dir) + + os.makedirs(out_dir, exist_ok=True) + + for file in exp_dir: + absfile = os.path.join(in_dir, file) + # Config file -> Convert to yaml and move to output dir. + if file == "params.json": + assert os.path.isfile(absfile), "{} not a file!".format(file) + with open(absfile) as fp: + contents = json.load(fp) + with open(os.path.join(out_dir, "config.yaml"), "w") as fp: + yaml.dump(contents, fp) + # Progress csv file -> Filter out some columns, cut, and write to + # output_dir. + elif file == "progress.csv": + assert os.path.isfile(absfile), "{} not a file!".format(file) + col_idx_to_filter = [] + with open(absfile) as fp: + # Get column names. + col_names_orig = fp.readline().strip().split(",") + # Split by comma (abiding to quotes), filter out + # unwanted columns, then write to disk. + cols_to_filter = args.results_filter.split(",") + for i, c in enumerate(col_names_orig): + if c in cols_to_filter: + col_idx_to_filter.insert(0, i) + col_names = col_names_orig.copy() + for idx in col_idx_to_filter: + col_names.pop(idx) + absfile_out = os.path.join(out_dir, "progress.csv") + with open(absfile_out, "w") as out_fp: + print(",".join(col_names), file=out_fp) + while True: + line = fp.readline().strip() + if not line: + break + line = re.sub( + "(,{2,})", + lambda m: ",None" * (len(m.group()) - 1) + ",", + line, + ) + cols = re.findall('".+?"|[^,]+', line) + if len(cols) != len(col_names_orig): + continue + for idx in col_idx_to_filter: + cols.pop(idx) + print(",".join(cols), file=out_fp) + + # Reduce the size of the output file if necessary. + out_size = os.path.getsize(absfile_out) + max_size = args.results_max_size * 1024 + if 0 < max_size < out_size: + # Figure out roughly every which line we have to drop. + ratio = out_size / max_size + # If ratio > 2.0, we'll have to keep only every nth line. + if ratio > 2.0: + nth = out_size // max_size + os.system( + "awk 'NR==1||NR%{}==0' {} > {}.new".format( + nth, absfile_out, absfile_out + ) + ) + # If ratio < 2.0 (>1.0), we'll have to drop every nth line. + else: + nth = out_size // (out_size - max_size) + os.system( + "awk 'NR==1||NR%{}!=0' {} > {}.new".format( + nth, absfile_out, absfile_out + ) + ) + os.remove(absfile_out) + os.rename(absfile_out + ".new", absfile_out) + + # Zip progress.csv into results.zip. + zip_file = os.path.join(out_dir, "results.zip") + try: + os.remove(zip_file) + except FileNotFoundError: + pass + os.system( + "zip -j {} {}".format(zip_file, os.path.join(out_dir, "progress.csv")) + ) + os.remove(os.path.join(out_dir, "progress.csv")) + + # TBX events file -> Move as is. + elif re.search("^(events\\.out\\.|params\\.pkl)", file): + assert os.path.isfile(absfile), "{} not a file!".format(file) + shutil.copyfile(absfile, os.path.join(out_dir, file)) + + +if __name__ == "__main__": + args = parser.parse_args() + exp_dir = os.listdir(args.experiment_dir) + # Loop through all sub-directories. + for i, sub_run in enumerate(sorted(exp_dir)): + abspath = os.path.join(args.experiment_dir, sub_run) + # This is a seed run. + if os.path.isdir(abspath) and re.search( + "^(\\w+?)_(\\w+?-v\\d+)(_\\d+)", sub_run + ): + # Create meaningful output dir name: + # [algo]_[env]_[trial #]_[trial-config]_[date YYYY-MM-DD]. + cleaned_up_out = re.sub( + "^(\\w+?)_(\\w+?-v\\d+)(_\\d+)(_.+)?(_\\d{4}-\\d{2}-\\d{2})" + "_\\d{2}-\\d{2}-\\w+", + "{:02}_\\1_\\2\\4\\5".format(i), + sub_run, + ) + # Remove superflous `env=` specifier (anv always included in name). + cleaned_up_out = re.sub( + "^(.+)env=\\w+?-v\\d+,?(.+)", "\\1\\2", cleaned_up_out + ) + out_path = os.path.join(args.output_dir, cleaned_up_out) + process_single_run(abspath, out_path) + # Done. + print("done") diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7adcf6f7ca51dcbe641438cbfdafac5ab4cb0dba --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/__init__.py @@ -0,0 +1,205 @@ +from collections import deque +import contextlib +from functools import partial +import tree +from typing import Any, Dict, List, Optional, Tuple, Union + +from ray.rllib.utils.annotations import override, PublicAPI, DeveloperAPI +from ray.rllib.utils.deprecation import deprecation_warning +from ray.rllib.utils.filter import Filter +from ray.rllib.utils.filter_manager import FilterManager +from ray.rllib.utils.framework import ( + try_import_jax, + try_import_tf, + try_import_tfp, + try_import_torch, +) +from ray.rllib.utils.numpy import ( + sigmoid, + softmax, + relu, + one_hot, + fc, + lstm, + SMALL_NUMBER, + LARGE_INTEGER, + MIN_LOG_NN_OUTPUT, + MAX_LOG_NN_OUTPUT, +) +from ray.rllib.utils.schedules import ( + LinearSchedule, + PiecewiseSchedule, + PolynomialSchedule, + ExponentialSchedule, + ConstantSchedule, +) +from ray.rllib.utils.test_utils import ( + check, + check_compute_single_action, + check_train_results, +) +from ray.tune.utils import merge_dicts, deep_update + + +@DeveloperAPI +def add_mixins(base, mixins, reversed=False): + """Returns a new class with mixins applied in priority order.""" + + mixins = list(mixins or []) + + while mixins: + if reversed: + + class new_base(base, mixins.pop()): + pass + + else: + + class new_base(mixins.pop(), base): + pass + + base = new_base + + return base + + +@DeveloperAPI +def force_list( + elements: Optional[Any] = None, to_tuple: bool = False +) -> Union[List, Tuple]: + """ + Makes sure `elements` is returned as a list, whether `elements` is a single + item, already a list, or a tuple. + + Args: + elements: The inputs as a single item, a list/tuple/deque of items, or None, + to be converted to a list/tuple. If None, returns empty list/tuple. + to_tuple: Whether to use tuple (instead of list). + + Returns: + The provided item in a list of size 1, or the provided items as a + list. If `elements` is None, returns an empty list. If `to_tuple` is True, + returns a tuple instead of a list. + """ + ctor = list + if to_tuple is True: + ctor = tuple + return ( + ctor() + if elements is None + else ctor(elements) + if type(elements) in [list, set, tuple, deque] + else ctor([elements]) + ) + + +@DeveloperAPI +def flatten_dict(nested: Dict[str, Any], sep="/", env_steps=0) -> Dict[str, Any]: + """ + Flattens a nested dict into a flat dict with joined keys. + + Note, this is used for better serialization of nested dictionaries + in `OfflinePreLearner.__call__` when called inside + `ray.data.Dataset.map_batches`. + + Note, this is used to return a `Dict[str, numpy.ndarray] from the + `__call__` method which is expected by Ray Data. + + Args: + nested: A nested dictionary. + sep: Separator to use when joining keys. + + Returns: + A flat dictionary where each key is a path of keys in the nested dict. + """ + flat = {} + # `dm_tree.flatten_with_path`` returns a list of `(path, leaf)` tuples. + for path, leaf in tree.flatten_with_path(nested): + # Create a single string key from the path. + key = sep.join(map(str, path)) + flat[key] = leaf + + return flat + + +@DeveloperAPI +def unflatten_dict(flat: Dict[str, Any], sep="/") -> Dict[str, Any]: + """ + Reconstructs a nested dict from a flat dict with joined keys. + + Note, this is used for better deserialization ofr nested dictionaries + in `Learner.update' calls in which a `ray.data.DataIterator` is used. + + Args: + flat: A flat dictionary with keys that are paths joined by `sep`. + sep: The separator used in the flat dictionary keys. + + Returns: + A nested dictionary. + """ + nested = {} + for compound_key, value in flat.items(): + # Split all keys by the separator. + keys = compound_key.split(sep) + current = nested + # Nest by the separated keys. + for key in keys[:-1]: + if key not in current: + current[key] = {} + current = current[key] + current[keys[-1]] = value + + return nested + + +@DeveloperAPI +class NullContextManager(contextlib.AbstractContextManager): + """No-op context manager""" + + def __init__(self): + pass + + def __enter__(self): + pass + + def __exit__(self, *args): + pass + + +force_tuple = partial(force_list, to_tuple=True) + +__all__ = [ + "add_mixins", + "check", + "check_compute_single_action", + "check_train_results", + "deep_update", + "deprecation_warning", + "fc", + "force_list", + "force_tuple", + "lstm", + "merge_dicts", + "one_hot", + "override", + "relu", + "sigmoid", + "softmax", + "try_import_jax", + "try_import_tf", + "try_import_tfp", + "try_import_torch", + "ConstantSchedule", + "DeveloperAPI", + "ExponentialSchedule", + "Filter", + "FilterManager", + "LARGE_INTEGER", + "LinearSchedule", + "MAX_LOG_NN_OUTPUT", + "MIN_LOG_NN_OUTPUT", + "PiecewiseSchedule", + "PolynomialSchedule", + "PublicAPI", + "SMALL_NUMBER", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/actor_manager.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/actor_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..dd483e7b1fed95c80ca28c2c800254d1e4b20fac --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/actor_manager.py @@ -0,0 +1,995 @@ +from collections import defaultdict +import copy +from dataclasses import dataclass +import logging +import sys +import time +from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Union + +import ray +from ray.actor import ActorHandle +from ray.exceptions import RayError, RayTaskError +from ray.rllib.utils.typing import T +from ray.util.annotations import DeveloperAPI + + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +class ResultOrError: + """A wrapper around a result or a RayError thrown during remote task/actor calls. + + This is used to return data from `FaultTolerantActorManager` that allows us to + distinguish between RayErrors (remote actor related) and valid results. + """ + + def __init__(self, result: Any = None, error: Exception = None): + """One and only one of result or error should be set. + + Args: + result: The result of the computation. Note that None is a valid result if + the remote function does not return anything. + error: Alternatively, the error that occurred during the computation. + """ + self._result = result + self._error = ( + # Easier to handle if we show the user the original error. + error.as_instanceof_cause() + if isinstance(error, RayTaskError) + else error + ) + + @property + def ok(self): + return self._error is None + + def get(self): + """Returns the result or the error.""" + if self._error: + return self._error + else: + return self._result + + +@DeveloperAPI +@dataclass +class CallResult: + """Represents a single result from a call to an actor. + + Each CallResult contains the index of the actor that was called + plus the result or error from the call. + """ + + actor_id: int + result_or_error: ResultOrError + tag: str + + @property + def ok(self): + """Passes through the ok property from the result_or_error.""" + return self.result_or_error.ok + + def get(self): + """Passes through the get method from the result_or_error.""" + return self.result_or_error.get() + + +@DeveloperAPI +class RemoteCallResults: + """Represents a list of results from calls to a set of actors. + + CallResults provides convenient APIs to iterate over the results + while skipping errors, etc. + + .. testcode:: + :skipif: True + + manager = FaultTolerantActorManager( + actors, max_remote_requests_in_flight_per_actor=2, + ) + results = manager.foreach_actor(lambda w: w.call()) + + # Iterate over all results ignoring errors. + for result in results.ignore_errors(): + print(result.get()) + """ + + class _Iterator: + """An iterator over the results of a remote call.""" + + def __init__(self, call_results: List[CallResult]): + self._call_results = call_results + + def __iter__(self) -> Iterator[CallResult]: + return self + + def __next__(self) -> CallResult: + if not self._call_results: + raise StopIteration + return self._call_results.pop(0) + + def __init__(self): + self.result_or_errors: List[CallResult] = [] + + def add_result(self, actor_id: int, result_or_error: ResultOrError, tag: str): + """Add index of a remote actor plus the call result to the list. + + Args: + actor_id: ID of the remote actor. + result_or_error: The result or error from the call. + tag: A description to identify the call. + """ + self.result_or_errors.append(CallResult(actor_id, result_or_error, tag)) + + def __iter__(self) -> Iterator[ResultOrError]: + """Return an iterator over the results.""" + # Shallow copy the list. + return self._Iterator(copy.copy(self.result_or_errors)) + + def __len__(self) -> int: + return len(self.result_or_errors) + + def ignore_errors(self) -> Iterator[ResultOrError]: + """Return an iterator over the results, skipping all errors.""" + return self._Iterator([r for r in self.result_or_errors if r.ok]) + + def ignore_ray_errors(self) -> Iterator[ResultOrError]: + """Return an iterator over the results, skipping only Ray errors. + + Similar to ignore_errors, but only skips Errors raised because of + remote actor problems (often get restored automatcially). + This is useful for callers that want to handle application errors differently + from Ray errors. + """ + return self._Iterator( + [r for r in self.result_or_errors if not isinstance(r.get(), RayError)] + ) + + +@DeveloperAPI +class FaultAwareApply: + @DeveloperAPI + def ping(self) -> str: + """Ping the actor. Can be used as a health check. + + Returns: + "pong" if actor is up and well. + """ + return "pong" + + @DeveloperAPI + def apply( + self, + func: Callable[[Any, Optional[Any], Optional[Any]], T], + *args, + **kwargs, + ) -> T: + """Calls the given function with this Actor instance. + + A generic interface for applying arbitrary member functions on a + remote actor. + + Args: + func: The function to call, with this actor as first + argument, followed by args, and kwargs. + args: Optional additional args to pass to the function call. + kwargs: Optional additional kwargs to pass to the function call. + + Returns: + The return value of the function call. + """ + try: + return func(self, *args, **kwargs) + except Exception as e: + # Actor should be recreated by Ray. + if self.config.restart_failed_env_runners: + logger.exception(f"Worker exception caught during `apply()`: {e}") + # Small delay to allow logs messages to propagate. + time.sleep(self.config.delay_between_env_runner_restarts_s) + # Kill this worker so Ray Core can restart it. + sys.exit(1) + # Actor should be left dead. + else: + raise e + + +@DeveloperAPI +class FaultTolerantActorManager: + """A manager that is aware of the healthiness of remote actors. + + .. testcode:: + + import time + import ray + from ray.rllib.utils.actor_manager import FaultTolerantActorManager + + @ray.remote + class MyActor: + def apply(self, fn): + return fn(self) + + def do_something(self): + return True + + actors = [MyActor.remote() for _ in range(3)] + manager = FaultTolerantActorManager( + actors, max_remote_requests_in_flight_per_actor=2, + ) + + # Synchronous remote calls. + results = manager.foreach_actor(lambda actor: actor.do_something()) + # Print results ignoring returned errors. + print([r.get() for r in results.ignore_errors()]) + + # Asynchronous remote calls. + manager.foreach_actor_async(lambda actor: actor.do_something()) + time.sleep(2) # Wait for the tasks to finish. + for r in manager.fetch_ready_async_reqs(): + # Handle result and errors. + if r.ok: + print(r.get()) + else: + print("Error: {}".format(r.get())) + """ + + @dataclass + class _ActorState: + """State of a single actor.""" + + # Num of outstanding async requests for this actor. + num_in_flight_async_requests: int = 0 + # Whether this actor is in a healthy state. + is_healthy: bool = True + + def __init__( + self, + actors: Optional[List[ActorHandle]] = None, + max_remote_requests_in_flight_per_actor: int = 2, + init_id: int = 0, + ): + """Construct a FaultTolerantActorManager. + + Args: + actors: A list of ray remote actors to manage on. These actors must have an + ``apply`` method which takes a function with only one parameter (the + actor instance itself). + max_remote_requests_in_flight_per_actor: The maximum number of remote + requests that can be in flight per actor. Any requests made to the pool + that cannot be scheduled because the limit has been reached will be + dropped. This only applies to the asynchronous remote call mode. + init_id: The initial ID to use for the next remote actor. Default is 0. + """ + # For round-robin style async requests, keep track of which actor to send + # a new func next (current). + self._next_id = self._current_actor_id = init_id + + # Actors are stored in a map and indexed by a unique (int) ID. + self._actors: Dict[int, ActorHandle] = {} + self._remote_actor_states: Dict[int, self._ActorState] = {} + self._restored_actors = set() + self.add_actors(actors or []) + + # Maps outstanding async requests to the IDs of the actor IDs that + # are executing them. + self._in_flight_req_to_actor_id: Dict[ray.ObjectRef, int] = {} + + self._max_remote_requests_in_flight_per_actor = ( + max_remote_requests_in_flight_per_actor + ) + + # Useful metric. + self._num_actor_restarts = 0 + + @DeveloperAPI + def actor_ids(self) -> List[int]: + """Returns a list of all worker IDs (healthy or not).""" + return list(self._actors.keys()) + + @DeveloperAPI + def healthy_actor_ids(self) -> List[int]: + """Returns a list of worker IDs that are healthy.""" + return [k for k, v in self._remote_actor_states.items() if v.is_healthy] + + @DeveloperAPI + def add_actors(self, actors: List[ActorHandle]): + """Add a list of actors to the pool. + + Args: + actors: A list of ray remote actors to be added to the pool. + """ + for actor in actors: + self._actors[self._next_id] = actor + self._remote_actor_states[self._next_id] = self._ActorState() + self._next_id += 1 + + @DeveloperAPI + def remove_actor(self, actor_id: int) -> ActorHandle: + """Remove an actor from the pool. + + Args: + actor_id: ID of the actor to remove. + + Returns: + Handle to the actor that was removed. + """ + actor = self._actors[actor_id] + + # Remove the actor from the pool. + del self._actors[actor_id] + del self._remote_actor_states[actor_id] + self._restored_actors.discard(actor_id) + self._remove_async_state(actor_id) + + return actor + + @DeveloperAPI + def num_actors(self) -> int: + """Return the total number of actors in the pool.""" + return len(self._actors) + + @DeveloperAPI + def num_healthy_actors(self) -> int: + """Return the number of healthy remote actors.""" + return sum(s.is_healthy for s in self._remote_actor_states.values()) + + @DeveloperAPI + def total_num_restarts(self) -> int: + """Return the number of remote actors that have been restarted.""" + return self._num_actor_restarts + + @DeveloperAPI + def num_outstanding_async_reqs(self) -> int: + """Return the number of outstanding async requests.""" + return len(self._in_flight_req_to_actor_id) + + @DeveloperAPI + def is_actor_healthy(self, actor_id: int) -> bool: + """Whether a remote actor is in healthy state. + + Args: + actor_id: ID of the remote actor. + + Returns: + True if the actor is healthy, False otherwise. + """ + if actor_id not in self._remote_actor_states: + raise ValueError(f"Unknown actor id: {actor_id}") + return self._remote_actor_states[actor_id].is_healthy + + @DeveloperAPI + def set_actor_state(self, actor_id: int, healthy: bool) -> None: + """Update activate state for a specific remote actor. + + Args: + actor_id: ID of the remote actor. + healthy: Whether the remote actor is healthy. + """ + if actor_id not in self._remote_actor_states: + raise ValueError(f"Unknown actor id: {actor_id}") + + was_healthy = self._remote_actor_states[actor_id].is_healthy + # Set from unhealthy to healthy -> Add to restored set. + if not was_healthy and healthy: + self._restored_actors.add(actor_id) + # Set from healthy to unhealthy -> Remove from restored set. + elif was_healthy and not healthy: + self._restored_actors.discard(actor_id) + + self._remote_actor_states[actor_id].is_healthy = healthy + + if not healthy: + # Remove any async states. + self._remove_async_state(actor_id) + + @DeveloperAPI + def clear(self): + """Clean up managed actors.""" + for actor in self._actors.values(): + ray.kill(actor) + self._actors.clear() + self._remote_actor_states.clear() + self._restored_actors.clear() + self._in_flight_req_to_actor_id.clear() + + @DeveloperAPI + def foreach_actor( + self, + func: Union[Callable[[Any], Any], List[Callable[[Any], Any]], str, List[str]], + *, + kwargs: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, + healthy_only: bool = True, + remote_actor_ids: Optional[List[int]] = None, + timeout_seconds: Optional[float] = None, + return_obj_refs: bool = False, + mark_healthy: bool = False, + ) -> RemoteCallResults: + """Calls the given function with each actor instance as arg. + + Automatically marks actors unhealthy if they crash during the remote call. + + Args: + func: A single Callable applied to all specified remote actors or a list + of Callables, that get applied on the list of specified remote actors. + In the latter case, both list of Callables and list of specified actors + must have the same length. Alternatively, you can use the name of the + remote method to be called, instead, or a list of remote method names. + kwargs: An optional single kwargs dict or a list of kwargs dict matching the + list of provided `func` or `remote_actor_ids`. In the first case (single + dict), use `kwargs` on all remote calls. The latter case (list of + dicts) allows you to define individualized kwarg dicts per actor. + healthy_only: If True, applies `func` only to actors currently tagged + "healthy", otherwise to all actors. If `healthy_only=False` and + `mark_healthy=True`, will send `func` to all actors and mark those + actors "healthy" that respond to the request within `timeout_seconds` + and are currently tagged as "unhealthy". + remote_actor_ids: Apply func on a selected set of remote actors. Use None + (default) for all actors. + timeout_seconds: Time to wait (in seconds) for results. Set this to 0.0 for + fire-and-forget. Set this to None (default) to wait infinitely (i.e. for + synchronous execution). + return_obj_refs: whether to return ObjectRef instead of actual results. + Note, for fault tolerance reasons, these returned ObjectRefs should + never be resolved with ray.get() outside of the context of this manager. + mark_healthy: Whether to mark all those actors healthy again that are + currently marked unhealthy AND that returned results from the remote + call (within the given `timeout_seconds`). + Note that actors are NOT set unhealthy, if they simply time out + (only if they return a RayActorError). + Also not that this setting is ignored if `healthy_only=True` (b/c this + setting only affects actors that are currently tagged as unhealthy). + + Returns: + The list of return values of all calls to `func(actor)`. The values may be + actual data returned or exceptions raised during the remote call in the + format of RemoteCallResults. + """ + remote_actor_ids = remote_actor_ids or self.actor_ids() + if healthy_only: + func, kwargs, remote_actor_ids = self._filter_by_healthy_state( + func=func, kwargs=kwargs, remote_actor_ids=remote_actor_ids + ) + + # Send out remote requests. + remote_calls = self._call_actors( + func=func, + kwargs=kwargs, + remote_actor_ids=remote_actor_ids, + ) + + # Collect remote request results (if available given timeout and/or errors). + _, remote_results = self._fetch_result( + remote_actor_ids=remote_actor_ids, + remote_calls=remote_calls, + tags=[None] * len(remote_calls), + timeout_seconds=timeout_seconds, + return_obj_refs=return_obj_refs, + mark_healthy=mark_healthy, + ) + + return remote_results + + @DeveloperAPI + def foreach_actor_async( + self, + func: Union[Callable[[Any], Any], List[Callable[[Any], Any]], str, List[str]], + tag: Optional[str] = None, + *, + kwargs: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, + healthy_only: bool = True, + remote_actor_ids: Optional[List[int]] = None, + ) -> int: + """Calls given functions against each actors without waiting for results. + + Args: + func: A single Callable applied to all specified remote actors or a list + of Callables, that get applied on the list of specified remote actors. + In the latter case, both list of Callables and list of specified actors + must have the same length. Alternatively, you can use the name of the + remote method to be called, instead, or a list of remote method names. + tag: A tag to identify the results from this async call. + kwargs: An optional single kwargs dict or a list of kwargs dict matching the + list of provided `func` or `remote_actor_ids`. In the first case (single + dict), use `kwargs` on all remote calls. The latter case (list of + dicts) allows you to define individualized kwarg dicts per actor. + healthy_only: If True, applies `func` only to actors currently tagged + "healthy", otherwise to all actors. If `healthy_only=False` and + later, `self.fetch_ready_async_reqs()` is called with + `mark_healthy=True`, will send `func` to all actors and mark those + actors "healthy" that respond to the request within `timeout_seconds` + and are currently tagged as "unhealthy". + remote_actor_ids: Apply func on a selected set of remote actors. + Note, for fault tolerance reasons, these returned ObjectRefs should + never be resolved with ray.get() outside of the context of this manager. + + Returns: + The number of async requests that are actually fired. + """ + # TODO(avnishn, jungong): so thinking about this a bit more, it would be the + # best if we can attach multiple tags to an async all, like basically this + # parameter should be tags: + # For sync calls, tags would be (). + # For async call users, they can attached multiple tags for a single call, like + # ("rollout_worker", "sync_weight"). + # For async fetch result, we can also specify a single, or list of tags. For + # example, ("eval", "sample") will fetch all the sample() calls on eval + # workers. + if not remote_actor_ids: + remote_actor_ids = self.actor_ids() + + num_calls = ( + len(func) + if isinstance(func, list) + else len(kwargs) + if isinstance(kwargs, list) + else len(remote_actor_ids) + ) + + # Perform round-robin assignment of all provided calls for any number of our + # actors. Note that this way, some actors might receive more than 1 request in + # this call. + if num_calls != len(remote_actor_ids): + remote_actor_ids = [ + (self._current_actor_id + i) % self.num_actors() + for i in range(num_calls) + ] + # Update our round-robin pointer. + self._current_actor_id += num_calls + self._current_actor_id %= self.num_actors() + + if healthy_only: + func, kwargs, remote_actor_ids = self._filter_by_healthy_state( + func=func, kwargs=kwargs, remote_actor_ids=remote_actor_ids + ) + + num_calls_to_make: Dict[int, int] = defaultdict(lambda: 0) + # Drop calls to actors that are too busy. + if isinstance(func, list): + assert len(func) == len(remote_actor_ids) + limited_func = [] + limited_kwargs = [] + limited_remote_actor_ids = [] + for i, (f, raid) in enumerate(zip(func, remote_actor_ids)): + num_outstanding_reqs = self._remote_actor_states[ + raid + ].num_in_flight_async_requests + if ( + num_outstanding_reqs + num_calls_to_make[raid] + < self._max_remote_requests_in_flight_per_actor + ): + num_calls_to_make[raid] += 1 + k = kwargs[i] if isinstance(kwargs, list) else (kwargs or {}) + limited_func.append(f) + limited_kwargs.append(k) + limited_remote_actor_ids.append(raid) + else: + limited_func = func + limited_kwargs = kwargs + limited_remote_actor_ids = [] + for raid in remote_actor_ids: + num_outstanding_reqs = self._remote_actor_states[ + raid + ].num_in_flight_async_requests + if ( + num_outstanding_reqs + num_calls_to_make[raid] + < self._max_remote_requests_in_flight_per_actor + ): + num_calls_to_make[raid] += 1 + limited_remote_actor_ids.append(raid) + + if not limited_remote_actor_ids: + return 0 + + remote_calls = self._call_actors( + func=limited_func, + kwargs=limited_kwargs, + remote_actor_ids=limited_remote_actor_ids, + ) + + # Save these as outstanding requests. + for id, call in zip(limited_remote_actor_ids, remote_calls): + self._remote_actor_states[id].num_in_flight_async_requests += 1 + self._in_flight_req_to_actor_id[call] = (tag, id) + + return len(remote_calls) + + @DeveloperAPI + def fetch_ready_async_reqs( + self, + *, + tags: Union[str, List[str], Tuple[str]] = (), + timeout_seconds: Optional[float] = 0.0, + return_obj_refs: bool = False, + mark_healthy: bool = False, + ) -> RemoteCallResults: + """Get results from outstanding async requests that are ready. + + Automatically mark actors unhealthy if they fail to respond. + + Note: If tags is an empty tuple then results from all ready async requests are + returned. + + Args: + timeout_seconds: ray.get() timeout. Default is 0, which only fetched those + results (immediately) that are already ready. + tags: A tag or a list of tags to identify the results from this async call. + return_obj_refs: Whether to return ObjectRef instead of actual results. + mark_healthy: Whether to mark all those actors healthy again that are + currently marked unhealthy AND that returned results from the remote + call (within the given `timeout_seconds`). + Note that actors are NOT set to unhealthy, if they simply time out, + meaning take a longer time to fulfil the remote request. We only ever + mark an actor unhealthy, if they raise a RayActorError inside the remote + request. + Also note that this settings is ignored if the preceding + `foreach_actor_async()` call used the `healthy_only=True` argument (b/c + `mark_healthy` only affects actors that are currently tagged as + unhealthy). + + Returns: + A list of return values of all calls to `func(actor)` that are ready. + The values may be actual data returned or exceptions raised during the + remote call in the format of RemoteCallResults. + """ + # Construct the list of in-flight requests filtered by tag. + remote_calls, remote_actor_ids, valid_tags = self._filter_calls_by_tag(tags) + ready, remote_results = self._fetch_result( + remote_actor_ids=remote_actor_ids, + remote_calls=remote_calls, + tags=valid_tags, + timeout_seconds=timeout_seconds, + return_obj_refs=return_obj_refs, + mark_healthy=mark_healthy, + ) + + for obj_ref, result in zip(ready, remote_results): + # Decrease outstanding request on this actor by 1. + self._remote_actor_states[result.actor_id].num_in_flight_async_requests -= 1 + # Also, remove this call here from the in-flight list, + # obj_refs may have already been removed when we disable an actor. + if obj_ref in self._in_flight_req_to_actor_id: + del self._in_flight_req_to_actor_id[obj_ref] + + return remote_results + + @staticmethod + def handle_remote_call_result_errors( + results_or_errors: RemoteCallResults, + *, + ignore_ray_errors: bool, + ) -> None: + """Checks given results for application errors and raises them if necessary. + + Args: + results_or_errors: The results or errors to check. + ignore_ray_errors: Whether to ignore RayErrors within the elements of + `results_or_errors`. + """ + for result_or_error in results_or_errors: + # Good result. + if result_or_error.ok: + continue + # RayError, but we ignore it. + elif ignore_ray_errors: + logger.exception(result_or_error.get()) + # Raise RayError. + else: + raise result_or_error.get() + + @DeveloperAPI + def probe_unhealthy_actors( + self, + timeout_seconds: Optional[float] = None, + mark_healthy: bool = False, + ) -> List[int]: + """Ping all unhealthy actors to try bringing them back. + + Args: + timeout_seconds: Timeout in seconds (to avoid pinging hanging workers + indefinitely). + mark_healthy: Whether to mark all those actors healthy again that are + currently marked unhealthy AND that respond to the `ping` remote request + (within the given `timeout_seconds`). + Note that actors are NOT set to unhealthy, if they simply time out, + meaning take a longer time to fulfil the remote request. We only ever + mark and actor unhealthy, if they return a RayActorError from the remote + request. + Also note that this settings is ignored if `healthy_only=True` (b/c this + setting only affects actors that are currently tagged as unhealthy). + + Returns: + A list of actor IDs that were restored by the `ping.remote()` call PLUS + those actors that were previously restored via other remote requests. + The cached set of such previously restored actors will be erased in this + call. + """ + # Collect recently restored actors (from `self._fetch_result` calls other than + # the one triggered here via the `ping`). + already_restored_actors = list(self._restored_actors) + + # Which actors are currently marked unhealthy? + unhealthy_actor_ids = [ + actor_id + for actor_id in self.actor_ids() + if not self.is_actor_healthy(actor_id) + ] + # Some unhealthy actors -> `ping()` all of them to trigger a new fetch and + # gather the just restored ones (b/c of a successful `ping` response). + just_restored_actors = [] + if unhealthy_actor_ids: + remote_results = self.foreach_actor( + func=lambda actor: actor.ping(), + remote_actor_ids=unhealthy_actor_ids, + healthy_only=False, # We specifically want to ping unhealthy actors. + timeout_seconds=timeout_seconds, + return_obj_refs=False, + mark_healthy=mark_healthy, + ) + just_restored_actors = [ + result.actor_id for result in remote_results if result.ok + ] + + # Clear out previously restored actors (b/c of other successful request + # responses, outside of this method). + self._restored_actors.clear() + + # Return all restored actors (previously and just). + return already_restored_actors + just_restored_actors + + def _call_actors( + self, + func: Union[Callable[[Any], Any], List[Callable[[Any], Any]], str, List[str]], + *, + kwargs: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, + remote_actor_ids: List[int] = None, + ) -> List[ray.ObjectRef]: + """Apply functions on a list of remote actors. + + Args: + func: A single Callable applied to all specified remote actors or a list + of Callables, that get applied on the list of specified remote actors. + In the latter case, both list of Callables and list of specified actors + must have the same length. Alternatively, you can use the name of the + remote method to be called, instead, or a list of remote method names. + kwargs: An optional single kwargs dict or a list of kwargs dict matching the + list of provided `func` or `remote_actor_ids`. In the first case (single + dict), use `kwargs` on all remote calls. The latter case (list of + dicts) allows you to define individualized kwarg dicts per actor. + remote_actor_ids: Apply func on this selected set of remote actors. + + Returns: + A list of ObjectRefs returned from the remote calls. + """ + if remote_actor_ids is None: + remote_actor_ids = self.actor_ids() + + if isinstance(func, list): + assert len(remote_actor_ids) == len( + func + ), "Funcs must have the same number of callables as actor indices." + + calls = [] + if isinstance(func, list): + for i, (raid, f) in enumerate(zip(remote_actor_ids, func)): + if isinstance(f, str): + calls.append( + getattr(self._actors[raid], f).remote( + **( + kwargs[i] + if isinstance(kwargs, list) + else (kwargs or {}) + ) + ) + ) + else: + calls.append(self._actors[raid].apply.remote(f)) + elif isinstance(func, str): + for i, raid in enumerate(remote_actor_ids): + calls.append( + getattr(self._actors[raid], func).remote( + **(kwargs[i] if isinstance(kwargs, list) else (kwargs or {})) + ) + ) + else: + for raid in remote_actor_ids: + calls.append(self._actors[raid].apply.remote(func)) + + return calls + + @DeveloperAPI + def _fetch_result( + self, + *, + remote_actor_ids: List[int], + remote_calls: List[ray.ObjectRef], + tags: List[str], + timeout_seconds: Optional[float] = None, + return_obj_refs: bool = False, + mark_healthy: bool = False, + ) -> Tuple[List[ray.ObjectRef], RemoteCallResults]: + """Try fetching results from remote actor calls. + + Mark whether an actor is healthy or not accordingly. + + Args: + remote_actor_ids: IDs of the actors these remote + calls were fired against. + remote_calls: List of remote calls to fetch. + tags: List of tags used for identifying the remote calls. + timeout_seconds: Timeout (in sec) for the ray.wait() call. Default is None, + meaning wait indefinitely for all results. + return_obj_refs: Whether to return ObjectRef instead of actual results. + mark_healthy: Whether to mark certain actors healthy based on the results + of these remote calls. Useful, for example, to make sure actors + do not come back without proper state restoration. + + Returns: + A list of ready ObjectRefs mapping to the results of those calls. + """ + # Notice that we do not return the refs to any unfinished calls to the + # user, since it is not safe to handle such remote actor calls outside the + # context of this actor manager. These requests are simply dropped. + timeout = float(timeout_seconds) if timeout_seconds is not None else None + + # This avoids calling ray.init() in the case of 0 remote calls. + # This is useful if the number of remote workers is 0. + if not remote_calls: + return [], RemoteCallResults() + + readies, _ = ray.wait( + remote_calls, + num_returns=len(remote_calls), + timeout=timeout, + # Make sure remote results are fetched locally in parallel. + fetch_local=not return_obj_refs, + ) + + # Remote data should already be fetched to local object store at this point. + remote_results = RemoteCallResults() + for ready in readies: + # Find the corresponding actor ID for this remote call. + actor_id = remote_actor_ids[remote_calls.index(ready)] + tag = tags[remote_calls.index(ready)] + + # If caller wants ObjectRefs, return directly without resolving. + if return_obj_refs: + remote_results.add_result(actor_id, ResultOrError(result=ready), tag) + continue + + # Try getting the ready results. + try: + result = ray.get(ready) + + # Any error type other than `RayError` happening during ray.get() -> + # Throw exception right here (we don't know how to handle these non-remote + # worker issues and should therefore crash). + except RayError as e: + # Return error to the user. + remote_results.add_result(actor_id, ResultOrError(error=e), tag) + + # Mark the actor as unhealthy, take it out of service, and wait for + # Ray Core to restore it. + if self.is_actor_healthy(actor_id): + logger.error( + f"Ray error ({str(e)}), taking actor {actor_id} out of service." + ) + self.set_actor_state(actor_id, healthy=False) + + # If no errors, add result to `RemoteCallResults` to be returned. + else: + # Return valid result to the user. + remote_results.add_result(actor_id, ResultOrError(result=result), tag) + + # Actor came back from an unhealthy state. Mark this actor as healthy + # and add it to our healthy set. + if mark_healthy and not self.is_actor_healthy(actor_id): + logger.warning( + f"Bringing previously unhealthy, now-healthy actor {actor_id} " + "back into service." + ) + self.set_actor_state(actor_id, healthy=True) + self._num_actor_restarts += 1 + + # Make sure, to-be-returned results are sound. + assert len(readies) == len(remote_results) + + return readies, remote_results + + def _filter_by_healthy_state( + self, + *, + func: Union[Callable[[Any], Any], List[Callable[[Any], Any]]], + kwargs: Optional[Union[Dict, List[Dict]]] = None, + remote_actor_ids: List[int], + ): + """Filter out func and remote worker ids by actor state. + + Args: + func: A single, or a list of Callables. + kwargs: An optional single kwargs dict or a list of kwargs dicts matching + the list of provided `func` or `remote_actor_ids`. In case of a single + dict, uses `kwargs` on all remote calls. In case of a list of dicts, + the given kwarg dicts are per actor `func` or per `remote_actor_ids`. + remote_actor_ids: IDs of potential remote workers to apply func on. + + Returns: + A tuple of (filtered func, filtered remote worker ids). + """ + if isinstance(func, list): + assert len(remote_actor_ids) == len( + func + ), "Func must have the same number of callables as remote actor ids." + # We are given a list of functions to apply. + # Need to filter the functions together with worker IDs. + temp_func = [] + temp_remote_actor_ids = [] + temp_kwargs = [] + for i, (f, raid) in enumerate(zip(func, remote_actor_ids)): + if self.is_actor_healthy(raid): + k = kwargs[i] if isinstance(kwargs, list) else (kwargs or {}) + temp_func.append(f) + temp_kwargs.append(k) + temp_remote_actor_ids.append(raid) + func = temp_func + kwargs = temp_kwargs + remote_actor_ids = temp_remote_actor_ids + else: + # Simply filter the worker IDs. + remote_actor_ids = [i for i in remote_actor_ids if self.is_actor_healthy(i)] + + return func, kwargs, remote_actor_ids + + def _filter_calls_by_tag( + self, tags: Union[str, List[str], Tuple[str]] + ) -> Tuple[List[ray.ObjectRef], List[ActorHandle], List[str]]: + """Return all the in flight requests that match the given tags, if any. + + Args: + tags: A str or a list/tuple of str. If tags is empty, return all the in + flight requests. + + Returns: + A tuple consisting of a list of the remote calls that match the tag(s), + a list of the corresponding remote actor IDs for these calls (same length), + and a list of the tags corresponding to these calls (same length). + """ + if isinstance(tags, str): + tags = {tags} + elif isinstance(tags, (list, tuple)): + tags = set(tags) + else: + raise ValueError( + f"tags must be either a str or a list/tuple of str, got {type(tags)}." + ) + remote_calls = [] + remote_actor_ids = [] + valid_tags = [] + for call, (tag, actor_id) in self._in_flight_req_to_actor_id.items(): + # the default behavior is to return all ready results. + if len(tags) == 0 or tag in tags: + remote_calls.append(call) + remote_actor_ids.append(actor_id) + valid_tags.append(tag) + + return remote_calls, remote_actor_ids, valid_tags + + def _remove_async_state(self, actor_id: int): + """Remove internal async state of for a given actor. + + This is called when an actor is removed from the pool or being marked + unhealthy. + + Args: + actor_id: The id of the actor. + """ + # Remove any outstanding async requests for this actor. + # Use `list` here to not change a looped generator while we mutate the + # underlying dict. + for id, req in list(self._in_flight_req_to_actor_id.items()): + if id == actor_id: + del self._in_flight_req_to_actor_id[req] + + def actors(self): + # TODO(jungong) : remove this API once EnvRunnerGroup.remote_workers() + # and EnvRunnerGroup._remote_workers() are removed. + return self._actors diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/actors.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/actors.py new file mode 100644 index 0000000000000000000000000000000000000000..d56dcdbd773f920e6b922eeeceb71e4eb663d68c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/actors.py @@ -0,0 +1,258 @@ +from collections import defaultdict, deque +import logging +import platform +from typing import Any, Dict, List, Optional, Sequence, Tuple, Type + +import ray +from ray.actor import ActorClass, ActorHandle + +logger = logging.getLogger(__name__) + + +class TaskPool: + """Helper class for tracking the status of many in-flight actor tasks.""" + + def __init__(self): + self._tasks = {} + self._objects = {} + self._fetching = deque() + + def add(self, worker, all_obj_refs): + if isinstance(all_obj_refs, list): + obj_ref = all_obj_refs[0] + else: + obj_ref = all_obj_refs + self._tasks[obj_ref] = worker + self._objects[obj_ref] = all_obj_refs + + def completed(self, blocking_wait=False): + pending = list(self._tasks) + if pending: + ready, _ = ray.wait(pending, num_returns=len(pending), timeout=0) + if not ready and blocking_wait: + ready, _ = ray.wait(pending, num_returns=1, timeout=10.0) + for obj_ref in ready: + yield (self._tasks.pop(obj_ref), self._objects.pop(obj_ref)) + + def completed_prefetch(self, blocking_wait=False, max_yield=999): + """Similar to completed but only returns once the object is local. + + Assumes obj_ref only is one id.""" + + for worker, obj_ref in self.completed(blocking_wait=blocking_wait): + self._fetching.append((worker, obj_ref)) + + for _ in range(max_yield): + if not self._fetching: + break + + yield self._fetching.popleft() + + def reset_workers(self, workers): + """Notify that some workers may be removed.""" + for obj_ref, ev in self._tasks.copy().items(): + if ev not in workers: + del self._tasks[obj_ref] + del self._objects[obj_ref] + + # We want to keep the same deque reference so that we don't suffer from + # stale references in generators that are still in flight + for _ in range(len(self._fetching)): + ev, obj_ref = self._fetching.popleft() + if ev in workers: + # Re-queue items that are still valid + self._fetching.append((ev, obj_ref)) + + @property + def count(self): + return len(self._tasks) + + +def create_colocated_actors( + actor_specs: Sequence[Tuple[Type, Any, Any, int]], + node: Optional[str] = "localhost", + max_attempts: int = 10, +) -> Dict[Type, List[ActorHandle]]: + """Create co-located actors of any type(s) on any node. + + Args: + actor_specs: Tuple/list with tuples consisting of: 1) The + (already @ray.remote) class(es) to construct, 2) c'tor args, + 3) c'tor kwargs, and 4) the number of actors of that class with + given args/kwargs to construct. + node: The node to co-locate the actors on. By default ("localhost"), + place the actors on the node the caller of this function is + located on. Use None for indicating that any (resource fulfilling) + node in the cluster may be used. + max_attempts: The maximum number of co-location attempts to + perform before throwing an error. + + Returns: + A dict mapping the created types to the list of n ActorHandles + created (and co-located) for that type. + """ + if node == "localhost": + node = platform.node() + + # Maps each entry in `actor_specs` to lists of already co-located actors. + ok = [[] for _ in range(len(actor_specs))] + + # Try n times to co-locate all given actor types (`actor_specs`). + # With each (failed) attempt, increase the number of actors we try to + # create (on the same node), then kill the ones that have been created in + # excess. + for attempt in range(max_attempts): + # If any attempt to co-locate fails, set this to False and we'll do + # another attempt. + all_good = True + # Process all `actor_specs` in sequence. + for i, (typ, args, kwargs, count) in enumerate(actor_specs): + args = args or [] # Allow None. + kwargs = kwargs or {} # Allow None. + # We don't have enough actors yet of this spec co-located on + # the desired node. + if len(ok[i]) < count: + co_located = try_create_colocated( + cls=typ, + args=args, + kwargs=kwargs, + count=count * (attempt + 1), + node=node, + ) + # If node did not matter (None), from here on, use the host + # that the first actor(s) are already co-located on. + if node is None: + node = ray.get(co_located[0].get_host.remote()) + # Add the newly co-located actors to the `ok` list. + ok[i].extend(co_located) + # If we still don't have enough -> We'll have to do another + # attempt. + if len(ok[i]) < count: + all_good = False + # We created too many actors for this spec -> Kill/truncate + # the excess ones. + if len(ok[i]) > count: + for a in ok[i][count:]: + a.__ray_terminate__.remote() + ok[i] = ok[i][:count] + + # All `actor_specs` have been fulfilled, return lists of + # co-located actors. + if all_good: + return ok + + raise Exception("Unable to create enough colocated actors -> aborting.") + + +def try_create_colocated( + cls: Type[ActorClass], + args: List[Any], + count: int, + kwargs: Optional[List[Any]] = None, + node: Optional[str] = "localhost", +) -> List[ActorHandle]: + """Tries to co-locate (same node) a set of Actors of the same type. + + Returns a list of successfully co-located actors. All actors that could + not be co-located (with the others on the given node) will not be in this + list. + + Creates each actor via it's remote() constructor and then checks, whether + it has been co-located (on the same node) with the other (already created) + ones. If not, terminates the just created actor. + + Args: + cls: The Actor class to use (already @ray.remote "converted"). + args: List of args to pass to the Actor's constructor. One item + per to-be-created actor (`count`). + count: Number of actors of the given `cls` to construct. + kwargs: Optional list of kwargs to pass to the Actor's constructor. + One item per to-be-created actor (`count`). + node: The node to co-locate the actors on. By default ("localhost"), + place the actors on the node the caller of this function is + located on. If None, will try to co-locate all actors on + any available node. + + Returns: + List containing all successfully co-located actor handles. + """ + if node == "localhost": + node = platform.node() + + kwargs = kwargs or {} + actors = [cls.remote(*args, **kwargs) for _ in range(count)] + co_located, non_co_located = split_colocated(actors, node=node) + logger.info("Got {} colocated actors of {}".format(len(co_located), count)) + for a in non_co_located: + a.__ray_terminate__.remote() + return co_located + + +def split_colocated( + actors: List[ActorHandle], + node: Optional[str] = "localhost", +) -> Tuple[List[ActorHandle], List[ActorHandle]]: + """Splits up given actors into colocated (on same node) and non colocated. + + The co-location criterion depends on the `node` given: + If given (or default: platform.node()): Consider all actors that are on + that node "colocated". + If None: Consider the largest sub-set of actors that are all located on + the same node (whatever that node is) as "colocated". + + Args: + actors: The list of actor handles to split into "colocated" and + "non colocated". + node: The node defining "colocation" criterion. If provided, consider + thos actors "colocated" that sit on this node. If None, use the + largest subset within `actors` that are sitting on the same + (any) node. + + Returns: + Tuple of two lists: 1) Co-located ActorHandles, 2) non co-located + ActorHandles. + """ + if node == "localhost": + node = platform.node() + + # Get nodes of all created actors. + hosts = ray.get([a.get_host.remote() for a in actors]) + + # If `node` not provided, use the largest group of actors that sit on the + # same node, regardless of what that node is. + if node is None: + node_groups = defaultdict(set) + for host, actor in zip(hosts, actors): + node_groups[host].add(actor) + max_ = -1 + largest_group = None + for host in node_groups: + if max_ < len(node_groups[host]): + max_ = len(node_groups[host]) + largest_group = host + non_co_located = [] + for host in node_groups: + if host != largest_group: + non_co_located.extend(list(node_groups[host])) + return list(node_groups[largest_group]), non_co_located + # Node provided (or default: localhost): Consider those actors "colocated" + # that were placed on `node`. + else: + # Split into co-located (on `node) and non-co-located (not on `node`). + co_located = [] + non_co_located = [] + for host, a in zip(hosts, actors): + # This actor has been placed on the correct node. + if host == node: + co_located.append(a) + # This actor has been placed on a different node. + else: + non_co_located.append(a) + return co_located, non_co_located + + +def drop_colocated(actors: List[ActorHandle]) -> List[ActorHandle]: + colocated, non_colocated = split_colocated(actors) + for a in colocated: + a.__ray_terminate__.remote() + return non_colocated diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/annotations.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/annotations.py new file mode 100644 index 0000000000000000000000000000000000000000..6824412b354f1f18df9d7a663e99471835680994 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/annotations.py @@ -0,0 +1,213 @@ +from ray.rllib.utils.deprecation import Deprecated +from ray.util.annotations import _mark_annotated + + +def override(parent_cls): + """Decorator for documenting method overrides. + + Args: + parent_cls: The superclass that provides the overridden method. If + `parent_class` does not actually have the method or the class, in which + method is defined is not a subclass of `parent_class`, an error is raised. + + .. testcode:: + :skipif: True + + from ray.rllib.policy import Policy + class TorchPolicy(Policy): + ... + # Indicates that `TorchPolicy.loss()` overrides the parent + # Policy class' own `loss method. Leads to an error if Policy + # does not have a `loss` method. + + @override(Policy) + def loss(self, model, action_dist, train_batch): + ... + + """ + + class OverrideCheck: + def __init__(self, func, expected_parent_cls): + self.func = func + self.expected_parent_cls = expected_parent_cls + + def __set_name__(self, owner, name): + # Check if the owner (the class) is a subclass of the expected base class + if not issubclass(owner, self.expected_parent_cls): + raise TypeError( + f"When using the @override decorator, {owner.__name__} must be a " + f"subclass of {parent_cls.__name__}!" + ) + # Set the function as a regular method on the class. + setattr(owner, name, self.func) + + def decorator(method): + # Check, whether `method` is actually defined by the parent class. + if method.__name__ not in dir(parent_cls): + raise NameError( + f"When using the @override decorator, {method.__name__} must override " + f"the respective method (with the same name) of {parent_cls.__name__}!" + ) + + # Check if the class is a subclass of the expected base class + OverrideCheck(method, parent_cls) + return method + + return decorator + + +def PublicAPI(obj): + """Decorator for documenting public APIs. + + Public APIs are classes and methods exposed to end users of RLlib. You + can expect these APIs to remain stable across RLlib releases. + + Subclasses that inherit from a ``@PublicAPI`` base class can be + assumed part of the RLlib public API as well (e.g., all Algorithm classes + are in public API because Algorithm is ``@PublicAPI``). + + In addition, you can assume all algo configurations are part of their + public API as well. + + .. testcode:: + :skipif: True + + # Indicates that the `Algorithm` class is exposed to end users + # of RLlib and will remain stable across RLlib releases. + from ray import tune + @PublicAPI + class Algorithm(tune.Trainable): + ... + """ + + _mark_annotated(obj) + return obj + + +def DeveloperAPI(obj): + """Decorator for documenting developer APIs. + + Developer APIs are classes and methods explicitly exposed to developers + for the purposes of building custom algorithms or advanced training + strategies on top of RLlib internals. You can generally expect these APIs + to be stable sans minor changes (but less stable than public APIs). + + Subclasses that inherit from a ``@DeveloperAPI`` base class can be + assumed part of the RLlib developer API as well. + + .. testcode:: + :skipif: True + + # Indicates that the `TorchPolicy` class is exposed to end users + # of RLlib and will remain (relatively) stable across RLlib + # releases. + from ray.rllib.policy import Policy + @DeveloperAPI + class TorchPolicy(Policy): + ... + """ + + _mark_annotated(obj) + return obj + + +def ExperimentalAPI(obj): + """Decorator for documenting experimental APIs. + + Experimental APIs are classes and methods that are in development and may + change at any time in their development process. You should not expect + these APIs to be stable until their tag is changed to `DeveloperAPI` or + `PublicAPI`. + + Subclasses that inherit from a ``@ExperimentalAPI`` base class can be + assumed experimental as well. + + .. testcode:: + :skipif: True + + from ray.rllib.policy import Policy + class TorchPolicy(Policy): + ... + # Indicates that the `TorchPolicy.loss` method is a new and + # experimental API and may change frequently in future + # releases. + @ExperimentalAPI + def loss(self, model, action_dist, train_batch): + ... + """ + + _mark_annotated(obj) + return obj + + +def OldAPIStack(obj): + """Decorator for classes/methods/functions belonging to the old API stack. + + These should be deprecated at some point after Ray 3.0 (RLlib GA). + It is recommended for users to start exploring (and coding against) the new API + stack instead. + """ + # No effect yet. + + _mark_annotated(obj) + return obj + + +def OverrideToImplementCustomLogic(obj): + """Users should override this in their sub-classes to implement custom logic. + + Used in Algorithm and Policy to tag methods that need overriding, e.g. + `Policy.loss()`. + + .. testcode:: + :skipif: True + + from ray.rllib.policy.torch_policy import TorchPolicy + @overrides(TorchPolicy) + @OverrideToImplementCustomLogic + def loss(self, ...): + # implement custom loss function here ... + # ... w/o calling the corresponding `super().loss()` method. + ... + + """ + obj.__is_overridden__ = False + return obj + + +def OverrideToImplementCustomLogic_CallToSuperRecommended(obj): + """Users should override this in their sub-classes to implement custom logic. + + Thereby, it is recommended (but not required) to call the super-class' + corresponding method. + + Used in Algorithm and Policy to tag methods that need overriding, but the + super class' method should still be called, e.g. + `Algorithm.setup()`. + + .. testcode:: + :skipif: True + + from ray import tune + @overrides(tune.Trainable) + @OverrideToImplementCustomLogic_CallToSuperRecommended + def setup(self, config): + # implement custom setup logic here ... + super().setup(config) + # ... or here (after having called super()'s setup method. + """ + obj.__is_overridden__ = False + return obj + + +def is_overridden(obj): + """Check whether a function has been overridden. + + Note, this only works for API calls decorated with OverrideToImplementCustomLogic + or OverrideToImplementCustomLogic_CallToSuperRecommended. + """ + return getattr(obj, "__is_overridden__", True) + + +# Backward compatibility. +Deprecated = Deprecated diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/checkpoints.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/checkpoints.py new file mode 100644 index 0000000000000000000000000000000000000000..99cd5ef3846f052fd1ba9ff140a94e1c4395b14e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/checkpoints.py @@ -0,0 +1,1059 @@ +import abc +import inspect +import json +import logging +import os +from packaging import version +import pathlib +import re +import tempfile +from types import MappingProxyType +from typing import Any, Collection, Dict, List, Optional, Tuple, Union + +import pyarrow.fs + +import ray +import ray.cloudpickle as pickle +from ray.rllib.core import ( + COMPONENT_LEARNER, + COMPONENT_LEARNER_GROUP, + COMPONENT_RL_MODULE, +) +from ray.rllib.utils import force_list +from ray.rllib.utils.actor_manager import FaultTolerantActorManager +from ray.rllib.utils.annotations import ( + OldAPIStack, + OverrideToImplementCustomLogic_CallToSuperRecommended, +) +from ray.rllib.utils.serialization import NOT_SERIALIZABLE, serialize_type +from ray.rllib.utils.typing import StateDict +from ray.train import Checkpoint as Checkpoint_train +from ray.tune import Checkpoint as Checkpoint_tune +from ray.tune.utils.file_transfer import sync_dir_between_nodes +from ray.util import log_once +from ray.util.annotations import PublicAPI + +logger = logging.getLogger(__name__) + +# The current checkpoint version used by RLlib for Algorithm and Policy checkpoints. +# History: +# 0.1: Ray 2.0.0 +# A single `checkpoint-[iter num]` file for Algorithm checkpoints +# within the checkpoint directory. Policy checkpoints not supported across all +# DL frameworks. + +# 1.0: Ray >=2.1.0 +# An algorithm_state.pkl file for the state of the Algorithm (excluding +# individual policy states). +# One sub-dir inside the "policies" sub-dir for each policy with a +# dedicated policy_state.pkl in it for the policy state. + +# 1.1: Same as 1.0, but has a new "format" field in the rllib_checkpoint.json file +# indicating, whether the checkpoint is `cloudpickle` (default) or `msgpack`. + +# 1.2: Introduces the checkpoint for the new Learner API if the Learner API is enabled. + +# 2.0: Introduces the Checkpointable API for all components on the new API stack +# (if the Learner-, RLModule, EnvRunner, and ConnectorV2 APIs are enabled). + +CHECKPOINT_VERSION = version.Version("1.1") +CHECKPOINT_VERSION_LEARNER_AND_ENV_RUNNER = version.Version("2.1") + + +@PublicAPI(stability="alpha") +class Checkpointable(abc.ABC): + """Abstract base class for a component of RLlib that can be checkpointed to disk. + + Subclasses must implement the following APIs: + - save_to_path() + - restore_from_path() + - from_checkpoint() + - get_state() + - set_state() + - get_ctor_args_and_kwargs() + - get_metadata() + - get_checkpointable_components() + """ + + # The state file for the implementing class. + # This file contains any state information that does NOT belong to any subcomponent + # of the implementing class (which are `Checkpointable` themselves and thus should + # have their own state- and metadata files). + # After a `save_to_path([path])` this file can be found directly in: `path/`. + STATE_FILE_NAME = "state" + + # The filename of the pickle file that contains the class information of the + # Checkpointable as well as all constructor args to be passed to such a class in + # order to construct a new instance. + CLASS_AND_CTOR_ARGS_FILE_NAME = "class_and_ctor_args.pkl" + + # Subclasses may set this to their own metadata filename. + # The dict returned by self.get_metadata() is stored in this JSON file. + METADATA_FILE_NAME = "metadata.json" + + def save_to_path( + self, + path: Optional[Union[str, pathlib.Path]] = None, + *, + state: Optional[StateDict] = None, + filesystem: Optional["pyarrow.fs.FileSystem"] = None, + use_msgpack: bool = False, + ) -> str: + """Saves the state of the implementing class (or `state`) to `path`. + + The state of the implementing class is always saved in the following format: + + .. testcode:: + :skipif: True + + path/ + [component1]/ + [component1 subcomponentA]/ + ... + [component1 subcomponentB]/ + ... + [component2]/ + ... + [cls.METADATA_FILE_NAME] (json) + [cls.STATE_FILE_NAME] (pkl|msgpack) + + The main logic is to loop through all subcomponents of this Checkpointable + and call their respective `save_to_path` methods. Then save the remaining + (non subcomponent) state to this Checkpointable's STATE_FILE_NAME. + In the exception that a component is a FaultTolerantActorManager instance, + instead of calling `save_to_path` directly on that manager, the first healthy + actor is interpreted as the component and its `save_to_path` method is called. + Even if that actor is located on another node, the created file is automatically + synced to the local node. + + Args: + path: The path to the directory to save the state of the implementing class + to. If `path` doesn't exist or is None, then a new directory will be + created (and returned). + state: An optional state dict to be used instead of getting a new state of + the implementing class through `self.get_state()`. + filesystem: PyArrow FileSystem to use to access data at the `path`. + If not specified, this is inferred from the URI scheme of `path`. + use_msgpack: Whether the state file should be written using msgpack and + msgpack_numpy (file extension is `.msgpack`), rather than pickle (file + extension is `.pkl`). + + Returns: + The path (str) where the state has been saved. + """ + + # If no path is given create a local temporary directory. + if path is None: + import uuid + + # Get the location of the temporary directory on the OS. + tmp_dir = pathlib.Path(tempfile.gettempdir()) + # Create a random directory name. + random_dir_name = str(uuid.uuid4()) + # Create the path, but do not craet the directory on the + # filesystem, yet. This is done by `PyArrow`. + path = path or tmp_dir / random_dir_name + + # We need a string path for `pyarrow.fs.FileSystem.from_uri`. + path = path if isinstance(path, str) else path.as_posix() + + # If we have no filesystem, figure it out. + if path and not filesystem: + # Note the path needs to be a path that is relative to the + # filesystem (e.g. `gs://tmp/...` -> `tmp/...`). + filesystem, path = pyarrow.fs.FileSystem.from_uri(path) + + # Make sure, path exists. + filesystem.create_dir(path, recursive=True) + + # Convert to `pathlib.Path` for easy handling. + path = pathlib.Path(path) + + # Write metadata file to disk. + metadata = self.get_metadata() + if "checkpoint_version" not in metadata: + metadata["checkpoint_version"] = str( + CHECKPOINT_VERSION_LEARNER_AND_ENV_RUNNER + ) + with filesystem.open_output_stream( + (path / self.METADATA_FILE_NAME).as_posix() + ) as f: + f.write(json.dumps(metadata).encode("utf-8")) + + # Write the class and constructor args information to disk. Always use pickle + # for this, because this information contains classes and maybe other + # non-serializable data. + with filesystem.open_output_stream( + (path / self.CLASS_AND_CTOR_ARGS_FILE_NAME).as_posix() + ) as f: + pickle.dump( + { + "class": type(self), + "ctor_args_and_kwargs": self.get_ctor_args_and_kwargs(), + }, + f, + ) + + # Get the entire state of this Checkpointable, or use provided `state`. + _state_provided = state is not None + # Get only the non-checkpointable components of the state. Checkpointable + # components are saved to path by their own `save_to_path` in the loop below. + state = state or self.get_state( + not_components=[c[0] for c in self.get_checkpointable_components()] + ) + + # Write components of `self` that themselves are `Checkpointable`. + for comp_name, comp in self.get_checkpointable_components(): + # If subcomponent's name is not in `state`, ignore it and don't write this + # subcomponent's state to disk. + if _state_provided and comp_name not in state: + continue + comp_path = path / comp_name + + # If component is an ActorManager, save the manager's first healthy + # actor's state to disk (even if it's on another node, in which case, we'll + # sync the generated file(s) back to this node). + if isinstance(comp, FaultTolerantActorManager): + actor_to_use = comp.healthy_actor_ids()[0] + + def _get_ip(_=None): + import ray + + return ray.util.get_node_ip_address() + + _result = next( + iter( + comp.foreach_actor( + _get_ip, + remote_actor_ids=[actor_to_use], + ) + ) + ) + if not _result.ok: + raise _result.get() + worker_ip_addr = _result.get() + self_ip_addr = _get_ip() + + # Save the state to a temporary location on the `actor_to_use`'s + # node. + comp_state_ref = None + if _state_provided: + comp_state_ref = ray.put(state.pop(comp_name)) + + if worker_ip_addr == self_ip_addr: + comp.foreach_actor( + lambda w, _path=comp_path, _state=comp_state_ref, _use_msgpack=use_msgpack: ( # noqa + w.save_to_path( + _path, + state=( + ray.get(_state) + if _state is not None + else w.get_state() + ), + use_msgpack=_use_msgpack, + ) + ), + remote_actor_ids=[actor_to_use], + ) + else: + # Save the checkpoint to the temporary directory on the worker. + def _save(w, _state=comp_state_ref, _use_msgpack=use_msgpack): + import tempfile + + # Create a temporary directory on the worker. + tmpdir = tempfile.mkdtemp() + w.save_to_path( + tmpdir, + state=( + ray.get(_state) if _state is not None else w.get_state() + ), + use_msgpack=_use_msgpack, + ) + return tmpdir + + _result = next( + iter(comp.foreach_actor(_save, remote_actor_ids=[actor_to_use])) + ) + if not _result.ok: + raise _result.get() + worker_temp_dir = _result.get() + + # Sync the temporary directory from the worker to this node. + sync_dir_between_nodes( + worker_ip_addr, + worker_temp_dir, + self_ip_addr, + str(comp_path), + ) + + # Remove the temporary directory on the worker. + def _rmdir(_, _dir=worker_temp_dir): + import shutil + + shutil.rmtree(_dir) + + comp.foreach_actor(_rmdir, remote_actor_ids=[actor_to_use]) + + # Local component (instance stored in a property of `self`). + else: + if _state_provided: + comp_state = state.pop(comp_name) + else: + comp_state = self.get_state(components=comp_name)[comp_name] + # By providing the `state` arg, we make sure that the component does not + # have to call its own `get_state()` anymore, but uses what's provided + # here. + comp.save_to_path( + comp_path, + filesystem=filesystem, + state=comp_state, + use_msgpack=use_msgpack, + ) + + # Write all the remaining state to disk. + filename = path / ( + self.STATE_FILE_NAME + (".msgpack" if use_msgpack else ".pkl") + ) + with filesystem.open_output_stream(filename.as_posix()) as f: + if use_msgpack: + msgpack = try_import_msgpack(error=True) + msgpack.dump(state, f) + else: + pickle.dump(state, f) + + return str(path) + + def restore_from_path( + self, + path: Union[str, pathlib.Path], + *, + component: Optional[str] = None, + filesystem: Optional["pyarrow.fs.FileSystem"] = None, + **kwargs, + ) -> None: + """Restores the state of the implementing class from the given path. + + If the `component` arg is provided, `path` refers to a checkpoint of a + subcomponent of `self`, thus allowing the user to load only the subcomponent's + state into `self` without affecting any of the other state information (for + example, loading only the NN state into a Checkpointable, which contains such + an NN, but also has other state information that should NOT be changed by + calling this method). + + The given `path` should have the following structure and contain the following + files: + + .. testcode:: + :skipif: True + + path/ + [component1]/ + [component1 subcomponentA]/ + ... + [component1 subcomponentB]/ + ... + [component2]/ + ... + [cls.METADATA_FILE_NAME] (json) + [cls.STATE_FILE_NAME] (pkl|msgpack) + + Note that the self.METADATA_FILE_NAME file is not required to restore the state. + + Args: + path: The path to load the implementing class' state from or to load the + state of only one subcomponent's state of the implementing class (if + `component` is provided). + component: If provided, `path` is interpreted as the checkpoint path of only + the subcomponent and thus, only that subcomponent's state is + restored/loaded. All other state of `self` remains unchanged in this + case. + filesystem: PyArrow FileSystem to use to access data at the `path`. If not + specified, this is inferred from the URI scheme of `path`. + **kwargs: Forward compatibility kwargs. + """ + path = path if isinstance(path, str) else path.as_posix() + + if path and not filesystem: + # Note the path needs to be a path that is relative to the + # filesystem (e.g. `gs://tmp/...` -> `tmp/...`). + filesystem, path = pyarrow.fs.FileSystem.from_uri(path) + # Only here convert to a `Path` instance b/c otherwise + # cloud path gets broken (i.e. 'gs://' -> 'gs:/'). + path = pathlib.Path(path) + + if not _exists_at_fs_path(filesystem, path.as_posix()): + raise FileNotFoundError(f"`path` ({path}) not found!") + + # Restore components of `self` that themselves are `Checkpointable`. + orig_comp_names = {c[0] for c in self.get_checkpointable_components()} + self._restore_all_subcomponents_from_path( + path, filesystem, component=component, **kwargs + ) + + # Restore the "base" state (not individual subcomponents). + if component is None: + filename = path / self.STATE_FILE_NAME + if filename.with_suffix(".msgpack").is_file(): + msgpack = try_import_msgpack(error=True) + with filesystem.open_input_stream( + filename.with_suffix(".msgpack").as_posix() + ) as f: + state = msgpack.load(f, strict_map_key=False) + else: + with filesystem.open_input_stream( + filename.with_suffix(".pkl").as_posix() + ) as f: + state = pickle.load(f) + self.set_state(state) + + new_comp_names = {c[0] for c in self.get_checkpointable_components()} + diff_comp_names = new_comp_names - orig_comp_names + if diff_comp_names: + self._restore_all_subcomponents_from_path( + path, filesystem, only_comp_names=diff_comp_names, **kwargs + ) + + @classmethod + def from_checkpoint( + cls, + path: Union[str, pathlib.Path], + filesystem: Optional["pyarrow.fs.FileSystem"] = None, + **kwargs, + ) -> "Checkpointable": + """Creates a new Checkpointable instance from the given location and returns it. + + Args: + path: The checkpoint path to load (a) the information on how to construct + a new instance of the implementing class and (b) the state to restore + the created instance to. + filesystem: PyArrow FileSystem to use to access data at the `path`. If not + specified, this is inferred from the URI scheme of `path`. + kwargs: Forward compatibility kwargs. Note that these kwargs are sent to + each subcomponent's `from_checkpoint()` call. + + Returns: + A new instance of the implementing class, already set to the state stored + under `path`. + """ + # We need a string path for the `PyArrow` filesystem. + path = path if isinstance(path, str) else path.as_posix() + + # If no filesystem is passed in create one. + if path and not filesystem: + # Note the path needs to be a path that is relative to the + # filesystem (e.g. `gs://tmp/...` -> `tmp/...`). + filesystem, path = pyarrow.fs.FileSystem.from_uri(path) + # Only here convert to a `Path` instance b/c otherwise + # cloud path gets broken (i.e. 'gs://' -> 'gs:/'). + path = pathlib.Path(path) + + # Get the class constructor to call and its args/kwargs. + # Try reading the pickle file first. + try: + with filesystem.open_input_stream( + (path / cls.CLASS_AND_CTOR_ARGS_FILE_NAME).as_posix() + ) as f: + ctor_info = pickle.load(f) + ctor = ctor_info["class"] + ctor_args = force_list(ctor_info["ctor_args_and_kwargs"][0]) + ctor_kwargs = ctor_info["ctor_args_and_kwargs"][1] + + # Inspect the ctor to see, which arguments in ctor_info should be replaced + # with the user provided **kwargs. + for i, (param_name, param) in enumerate( + inspect.signature(ctor).parameters.items() + ): + if param_name in kwargs: + val = kwargs.pop(param_name) + if ( + param.kind == inspect._ParameterKind.POSITIONAL_OR_KEYWORD + and len(ctor_args) > i + ): + ctor_args[i] = val + else: + ctor_kwargs[param_name] = val + + # If the pickle file is from another python version, use provided + # args instead. + except Exception: + # Use class that this method was called on. + ctor = cls + # Use only user provided **kwargs. + ctor_args = [] + ctor_kwargs = kwargs + + # Check, whether the constructor actually goes together with `cls`. + if not issubclass(ctor, cls): + raise ValueError( + f"The class ({ctor}) stored in checkpoint ({path}) does not seem to be " + f"a subclass of `cls` ({cls})!" + ) + elif not issubclass(ctor, Checkpointable): + raise ValueError( + f"The class ({ctor}) stored in checkpoint ({path}) does not seem to be " + "an implementer of the `Checkpointable` API!" + ) + + # Construct the initial object (without any particular state). + obj = ctor(*ctor_args, **ctor_kwargs) + # Restore the state of the constructed object. + obj.restore_from_path(path, filesystem=filesystem, **kwargs) + # Return the new object. + return obj + + @abc.abstractmethod + def get_state( + self, + components: Optional[Union[str, Collection[str]]] = None, + *, + not_components: Optional[Union[str, Collection[str]]] = None, + **kwargs, + ) -> StateDict: + """Returns the implementing class's current state as a dict. + + The returned dict must only contain msgpack-serializable data if you want to + use the `AlgorithmConfig._msgpack_checkpoints` option. Consider returning your + non msgpack-serializable data from the `Checkpointable.get_ctor_args_and_kwargs` + method, instead. + + Args: + components: An optional collection of string keys to be included in the + returned state. This might be useful, if getting certain components + of the state is expensive (e.g. reading/compiling the weights of a large + NN) and at the same time, these components are not required by the + caller. + not_components: An optional list of string keys to be excluded in the + returned state, even if the same string is part of `components`. + This is useful to get the complete state of the class, except + one or a few components. + kwargs: Forward-compatibility kwargs. + + Returns: + The current state of the implementing class (or only the `components` + specified, w/o those in `not_components`). + """ + + @abc.abstractmethod + def set_state(self, state: StateDict) -> None: + """Sets the implementing class' state to the given state dict. + + If component keys are missing in `state`, these components of the implementing + class will not be updated/set. + + Args: + state: The state dict to restore the state from. Maps component keys + to the corresponding subcomponent's own state. + """ + + @abc.abstractmethod + def get_ctor_args_and_kwargs(self) -> Tuple[Tuple, Dict[str, Any]]: + """Returns the args/kwargs used to create `self` from its constructor. + + Returns: + A tuple of the args (as a tuple) and kwargs (as a Dict[str, Any]) used to + construct `self` from its class constructor. + """ + + @OverrideToImplementCustomLogic_CallToSuperRecommended + def get_metadata(self) -> Dict: + """Returns JSON writable metadata further describing the implementing class. + + Note that this metadata is NOT part of any state and is thus NOT needed to + restore the state of a Checkpointable instance from a directory. Rather, the + metadata will be written into `self.METADATA_FILE_NAME` when calling + `self.save_to_path()` for the user's convenience. + + Returns: + A JSON-encodable dict of metadata information. + """ + return { + "class_and_ctor_args_file": self.CLASS_AND_CTOR_ARGS_FILE_NAME, + "state_file": self.STATE_FILE_NAME, + "ray_version": ray.__version__, + "ray_commit": ray.__commit__, + } + + def get_checkpointable_components(self) -> List[Tuple[str, "Checkpointable"]]: + """Returns the implementing class's own Checkpointable subcomponents. + + Returns: + A list of 2-tuples (name, subcomponent) describing the implementing class' + subcomponents, all of which have to be `Checkpointable` themselves and + whose state is therefore written into subdirectories (rather than the main + state file (self.STATE_FILE_NAME) when calling `self.save_to_path()`). + """ + return [] + + def _check_component(self, name, components, not_components) -> bool: + """Returns True if a component should be checkpointed. + + Args: + name: The checkpoint name. + components: A list of components that should be checkpointed. + non_components: A list of components that should not be checkpointed. + + Returns: + True, if the component should be checkpointed and otherwise False. + """ + comp_list = force_list(components) + not_comp_list = force_list(not_components) + if ( + components is None + or any(c.startswith(name + "/") for c in comp_list) + or name in comp_list + ) and (not_components is None or name not in not_comp_list): + return True + return False + + def _get_subcomponents(self, name, components): + if components is None: + return None + + components = force_list(components) + subcomponents = [] + for comp in components: + if comp.startswith(name + "/"): + subcomponents.append(comp[len(name) + 1 :]) + + return None if not subcomponents else subcomponents + + def _restore_all_subcomponents_from_path( + self, path, filesystem, only_comp_names=None, component=None, **kwargs + ): + for comp_name, comp in self.get_checkpointable_components(): + if only_comp_names is not None and comp_name not in only_comp_names: + continue + + # The value of the `component` argument for the upcoming + # `[subcomponent].restore_from_path(.., component=..)` call. + comp_arg = None + + if component is None: + comp_dir = path / comp_name + # If subcomponent's dir is not in path, ignore it and don't restore this + # subcomponent's state from disk. + if not _exists_at_fs_path(filesystem, comp_dir.as_posix()): + continue + else: + comp_dir = path + + # `component` is a path that starts with `comp` -> Remove the name of + # `comp` from the `component` arg in the upcoming call to `restore_..`. + if component.startswith(comp_name + "/"): + comp_arg = component[len(comp_name) + 1 :] + # `component` has nothing to do with `comp` -> Skip. + elif component != comp_name: + continue + + # If component is an ActorManager, restore all the manager's healthy + # actors' states from disk (even if they are on another node, in which case, + # we'll sync checkpoint file(s) to the respective node). + if isinstance(comp, FaultTolerantActorManager): + head_node_ip = ray.util.get_node_ip_address() + all_healthy_actors = comp.healthy_actor_ids() + + def _restore( + w, + _kwargs=MappingProxyType(kwargs), + _path=comp_dir, + _head_ip=head_node_ip, + _comp_arg=comp_arg, + ): + import ray + import tempfile + + worker_node_ip = ray.util.get_node_ip_address() + # If the worker is on the same node as the head, load the checkpoint + # directly from the path otherwise sync the checkpoint from the head + # to the worker and load it from there. + if worker_node_ip == _head_ip: + w.restore_from_path(_path, component=_comp_arg, **_kwargs) + else: + with tempfile.TemporaryDirectory() as temp_dir: + sync_dir_between_nodes( + _head_ip, _path, worker_node_ip, temp_dir + ) + w.restore_from_path( + temp_dir, component=_comp_arg, **_kwargs + ) + + comp.foreach_actor(_restore, remote_actor_ids=all_healthy_actors) + + # Call `restore_from_path()` on local subcomponent, thereby passing in the + # **kwargs. + else: + comp.restore_from_path( + comp_dir, filesystem=filesystem, component=comp_arg, **kwargs + ) + + +def _exists_at_fs_path(fs: pyarrow.fs.FileSystem, path: str) -> bool: + """Returns `True` if the path can be found in the filesystem.""" + valid = fs.get_file_info(path) + return valid.type != pyarrow.fs.FileType.NotFound + + +def _is_dir(file_info: pyarrow.fs.FileInfo) -> bool: + """Returns `True`, if the file info is from a directory.""" + return file_info.type == pyarrow.fs.FileType.Directory + + +@OldAPIStack +def get_checkpoint_info( + checkpoint: Union[str, Checkpoint_train, Checkpoint_tune], + filesystem: Optional["pyarrow.fs.FileSystem"] = None, +) -> Dict[str, Any]: + """Returns a dict with information about an Algorithm/Policy checkpoint. + + If the given checkpoint is a >=v1.0 checkpoint directory, try reading all + information from the contained `rllib_checkpoint.json` file. + + Args: + checkpoint: The checkpoint directory (str) or a Checkpoint object. + filesystem: PyArrow FileSystem to use to access data at the `checkpoint`. If not + specified, this is inferred from the URI scheme provided by `checkpoint`. + + Returns: + A dict containing the keys: + "type": One of "Policy" or "Algorithm". + "checkpoint_version": A version tuple, e.g. v1.0, indicating the checkpoint + version. This will help RLlib to remain backward compatible wrt. future + Ray and checkpoint versions. + "checkpoint_dir": The directory with all the checkpoint files in it. This might + be the same as the incoming `checkpoint` arg. + "state_file": The main file with the Algorithm/Policy's state information in it. + This is usually a pickle-encoded file. + "policy_ids": An optional set of PolicyIDs in case we are dealing with an + Algorithm checkpoint. None if `checkpoint` is a Policy checkpoint. + """ + # Default checkpoint info. + info = { + "type": "Algorithm", + "format": "cloudpickle", + "checkpoint_version": CHECKPOINT_VERSION, + "checkpoint_dir": None, + "state_file": None, + "policy_ids": None, + "module_ids": None, + } + + # `checkpoint` is a Checkpoint instance: Translate to directory and continue. + if isinstance(checkpoint, (Checkpoint_train, Checkpoint_tune)): + checkpoint = checkpoint.to_directory() + + if checkpoint and not filesystem: + # Note the path needs to be a path that is relative to the + # filesystem (e.g. `gs://tmp/...` -> `tmp/...`). + filesystem, checkpoint = pyarrow.fs.FileSystem.from_uri(checkpoint) + # Only here convert to a `Path` instance b/c otherwise + # cloud path gets broken (i.e. 'gs://' -> 'gs:/'). + checkpoint = pathlib.Path(checkpoint) + + # Checkpoint is dir. + if _exists_at_fs_path(filesystem, checkpoint.as_posix()) and _is_dir( + filesystem.get_file_info(checkpoint.as_posix()) + ): + info.update({"checkpoint_dir": str(checkpoint)}) + + # Figure out whether this is an older checkpoint format + # (with a `checkpoint-\d+` file in it). + file_info_list = filesystem.get_file_info( + pyarrow.fs.FileSelector(checkpoint.as_posix(), recursive=False) + ) + for file_info in file_info_list: + if file_info.is_file: + if re.match("checkpoint-\\d+", file_info.base_name): + info.update( + { + "checkpoint_version": version.Version("0.1"), + "state_file": str(file_info.base_name), + } + ) + return info + + # No old checkpoint file found. + + # If rllib_checkpoint.json file present, read available information from it + # and then continue with the checkpoint analysis (possibly overriding further + # information). + if _exists_at_fs_path( + filesystem, (checkpoint / "rllib_checkpoint.json").as_posix() + ): + # if (checkpoint / "rllib_checkpoint.json").is_file(): + with filesystem.open_input_stream( + (checkpoint / "rllib_checkpoint.json").as_posix() + ) as f: + # with open(checkpoint / "rllib_checkpoint.json") as f: + rllib_checkpoint_info = json.load(fp=f) + if "checkpoint_version" in rllib_checkpoint_info: + rllib_checkpoint_info["checkpoint_version"] = version.Version( + rllib_checkpoint_info["checkpoint_version"] + ) + info.update(rllib_checkpoint_info) + else: + # No rllib_checkpoint.json file present: Warn and continue trying to figure + # out checkpoint info ourselves. + if log_once("no_rllib_checkpoint_json_file"): + logger.warning( + "No `rllib_checkpoint.json` file found in checkpoint directory " + f"{checkpoint}! Trying to extract checkpoint info from other files " + f"found in that dir." + ) + + # Policy checkpoint file found. + for extension in ["pkl", "msgpck"]: + if _exists_at_fs_path( + filesystem, (checkpoint / ("policy_state." + extension)).as_posix() + ): + # if (checkpoint / ("policy_state." + extension)).is_file(): + info.update( + { + "type": "Policy", + "format": "cloudpickle" if extension == "pkl" else "msgpack", + "checkpoint_version": CHECKPOINT_VERSION, + "state_file": str(checkpoint / f"policy_state.{extension}"), + } + ) + return info + + # Valid Algorithm checkpoint >v0 file found? + format = None + for extension in ["pkl", "msgpck", "msgpack"]: + state_file = checkpoint / f"algorithm_state.{extension}" + if ( + _exists_at_fs_path(filesystem, state_file.as_posix()) + and filesystem.get_file_info(state_file.as_posix()).is_file + ): + format = "cloudpickle" if extension == "pkl" else "msgpack" + break + if format is None: + raise ValueError( + "Given checkpoint does not seem to be valid! No file with the name " + "`algorithm_state.[pkl|msgpack|msgpck]` (or `checkpoint-[0-9]+`) found." + ) + + info.update( + { + "format": format, + "state_file": str(state_file), + } + ) + + # Collect all policy IDs in the sub-dir "policies/". + policies_dir = checkpoint / "policies" + if _exists_at_fs_path(filesystem, policies_dir.as_posix()) and _is_dir( + filesystem.get_file_info(policies_dir.as_posix()) + ): + policy_ids = set() + file_info_list = filesystem.get_file_info( + pyarrow.fs.FileSelector(policies_dir.as_posix(), recursive=False) + ) + for file_info in file_info_list: + policy_ids.add(file_info.base_name) + info.update({"policy_ids": policy_ids}) + + # Collect all module IDs in the sub-dir "learner/module_state/". + modules_dir = ( + checkpoint + / COMPONENT_LEARNER_GROUP + / COMPONENT_LEARNER + / COMPONENT_RL_MODULE + ) + if _exists_at_fs_path(filesystem, checkpoint.as_posix()) and _is_dir( + filesystem.get_file_info(modules_dir.as_posix()) + ): + module_ids = set() + file_info_list = filesystem.get_file_info( + pyarrow.fs.FileSelector(modules_dir.as_posix(), recursive=False) + ) + for file_info in file_info_list: + # Only add subdirs (those are the ones where the RLModule data + # is stored, not files (could be json metadata files). + module_dir = modules_dir / file_info.base_name + if _is_dir(filesystem.get_file_info(module_dir.as_posix())): + module_ids.add(file_info.base_name) + info.update({"module_ids": module_ids}) + + # Checkpoint is a file: Use as-is (interpreting it as old Algorithm checkpoint + # version). + elif ( + _exists_at_fs_path(filesystem, checkpoint.as_posix()) + and filesystem.get_file_info(checkpoint.as_posix()).is_file + ): + info.update( + { + "checkpoint_version": version.Version("0.1"), + "checkpoint_dir": str(checkpoint.parent), + "state_file": str(checkpoint), + } + ) + + else: + raise ValueError( + f"Given checkpoint ({str(checkpoint)}) not found! Must be a " + "checkpoint directory (or a file for older checkpoint versions)." + ) + + return info + + +@OldAPIStack +def convert_to_msgpack_checkpoint( + checkpoint: Union[str, Checkpoint_train, Checkpoint_tune], + msgpack_checkpoint_dir: str, +) -> str: + """Converts an Algorithm checkpoint (pickle based) to a msgpack based one. + + Msgpack has the advantage of being python version independent. + + Args: + checkpoint: The directory, in which to find the Algorithm checkpoint (pickle + based). + msgpack_checkpoint_dir: The directory, in which to create the new msgpack + based checkpoint. + + Returns: + The directory in which the msgpack checkpoint has been created. Note that + this is the same as `msgpack_checkpoint_dir`. + """ + from ray.rllib.algorithms import Algorithm + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + from ray.rllib.core.rl_module import validate_module_id + + # Try to import msgpack and msgpack_numpy. + msgpack = try_import_msgpack(error=True) + + # Restore the Algorithm using the python version dependent checkpoint. + algo = Algorithm.from_checkpoint(checkpoint) + state = algo.__getstate__() + + # Convert all code in state into serializable data. + # Serialize the algorithm class. + state["algorithm_class"] = serialize_type(state["algorithm_class"]) + # Serialize the algorithm's config object. + if not isinstance(state["config"], dict): + state["config"] = state["config"].serialize() + else: + state["config"] = AlgorithmConfig._serialize_dict(state["config"]) + + # Extract policy states from worker state (Policies get their own + # checkpoint sub-dirs). + policy_states = {} + if "worker" in state and "policy_states" in state["worker"]: + policy_states = state["worker"].pop("policy_states", {}) + + # Policy mapping fn. + state["worker"]["policy_mapping_fn"] = NOT_SERIALIZABLE + # Is Policy to train function. + state["worker"]["is_policy_to_train"] = NOT_SERIALIZABLE + + # Add RLlib checkpoint version (as string). + state["checkpoint_version"] = str(CHECKPOINT_VERSION) + + # Write state (w/o policies) to disk. + state_file = os.path.join(msgpack_checkpoint_dir, "algorithm_state.msgpck") + with open(state_file, "wb") as f: + msgpack.dump(state, f) + + # Write rllib_checkpoint.json. + with open(os.path.join(msgpack_checkpoint_dir, "rllib_checkpoint.json"), "w") as f: + json.dump( + { + "type": "Algorithm", + "checkpoint_version": state["checkpoint_version"], + "format": "msgpack", + "state_file": state_file, + "policy_ids": list(policy_states.keys()), + "ray_version": ray.__version__, + "ray_commit": ray.__commit__, + }, + f, + ) + + # Write individual policies to disk, each in their own subdirectory. + for pid, policy_state in policy_states.items(): + # From here on, disallow policyIDs that would not work as directory names. + validate_module_id(pid, error=True) + policy_dir = os.path.join(msgpack_checkpoint_dir, "policies", pid) + os.makedirs(policy_dir, exist_ok=True) + policy = algo.get_policy(pid) + policy.export_checkpoint( + policy_dir, + policy_state=policy_state, + checkpoint_format="msgpack", + ) + + # Release all resources used by the Algorithm. + algo.stop() + + return msgpack_checkpoint_dir + + +@OldAPIStack +def convert_to_msgpack_policy_checkpoint( + policy_checkpoint: Union[str, Checkpoint_train, Checkpoint_tune], + msgpack_checkpoint_dir: str, +) -> str: + """Converts a Policy checkpoint (pickle based) to a msgpack based one. + + Msgpack has the advantage of being python version independent. + + Args: + policy_checkpoint: The directory, in which to find the Policy checkpoint (pickle + based). + msgpack_checkpoint_dir: The directory, in which to create the new msgpack + based checkpoint. + + Returns: + The directory in which the msgpack checkpoint has been created. Note that + this is the same as `msgpack_checkpoint_dir`. + """ + from ray.rllib.policy.policy import Policy + + policy = Policy.from_checkpoint(policy_checkpoint) + + os.makedirs(msgpack_checkpoint_dir, exist_ok=True) + policy.export_checkpoint( + msgpack_checkpoint_dir, + policy_state=policy.get_state(), + checkpoint_format="msgpack", + ) + + # Release all resources used by the Policy. + del policy + + return msgpack_checkpoint_dir + + +@PublicAPI +def try_import_msgpack(error: bool = False): + """Tries importing msgpack and msgpack_numpy and returns the patched msgpack module. + + Returns None if error is False and msgpack or msgpack_numpy is not installed. + Raises an error, if error is True and the modules could not be imported. + + Args: + error: Whether to raise an error if msgpack/msgpack_numpy cannot be imported. + + Returns: + The `msgpack` module, with the msgpack_numpy module already patched in. This + means you can already encde and decode numpy arrays with the returned module. + + Raises: + ImportError: If error=True and msgpack/msgpack_numpy is not installed. + """ + try: + import msgpack + import msgpack_numpy + + # Make msgpack_numpy look like msgpack. + msgpack_numpy.patch() + + return msgpack + + except Exception: + if error: + raise ImportError( + "Could not import or setup msgpack and msgpack_numpy! " + "Try running `pip install msgpack msgpack_numpy` first." + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/compression.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/compression.py new file mode 100644 index 0000000000000000000000000000000000000000..cd5e3e6975b4535b6a10a713d85d03ba2093c180 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/compression.py @@ -0,0 +1,90 @@ +from ray.rllib.utils.annotations import DeveloperAPI + +import logging +import time +import base64 +import numpy as np +from ray import cloudpickle as pickle + +logger = logging.getLogger(__name__) + +try: + import lz4.frame + + LZ4_ENABLED = True +except ImportError: + logger.warning( + "lz4 not available, disabling sample compression. " + "This will significantly impact RLlib performance. " + "To install lz4, run `pip install lz4`." + ) + LZ4_ENABLED = False + + +@DeveloperAPI +def compression_supported(): + return LZ4_ENABLED + + +@DeveloperAPI +def pack(data): + if LZ4_ENABLED: + data = pickle.dumps(data) + data = lz4.frame.compress(data) + # TODO(ekl) we shouldn't need to base64 encode this data, but this + # seems to not survive a transfer through the object store if we don't. + data = base64.b64encode(data).decode("ascii") + return data + + +@DeveloperAPI +def pack_if_needed(data): + if isinstance(data, np.ndarray): + data = pack(data) + return data + + +@DeveloperAPI +def unpack(data): + if LZ4_ENABLED: + data = base64.b64decode(data) + data = lz4.frame.decompress(data) + data = pickle.loads(data) + return data + + +@DeveloperAPI +def unpack_if_needed(data): + if is_compressed(data): + data = unpack(data) + return data + + +@DeveloperAPI +def is_compressed(data): + return isinstance(data, bytes) or isinstance(data, str) + + +# Intel(R) Core(TM) i7-4600U CPU @ 2.10GHz +# Compression speed: 753.664 MB/s +# Compression ratio: 87.4839812046 +# Decompression speed: 910.9504 MB/s +if __name__ == "__main__": + size = 32 * 80 * 80 * 4 + data = np.ones(size).reshape((32, 80, 80, 4)) + + count = 0 + start = time.time() + while time.time() - start < 1: + pack(data) + count += 1 + compressed = pack(data) + print("Compression speed: {} MB/s".format(count * size * 4 / 1e6)) + print("Compression ratio: {}".format(round(size * 4 / len(compressed), 2))) + + count = 0 + start = time.time() + while time.time() - start < 1: + unpack(compressed) + count += 1 + print("Decompression speed: {} MB/s".format(count * size * 4 / 1e6)) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/deprecation.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/deprecation.py new file mode 100644 index 0000000000000000000000000000000000000000..7f5dd0e78b8baa7a3df81cebacaeb25a25a035ae --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/deprecation.py @@ -0,0 +1,134 @@ +import inspect +import logging +from typing import Optional, Union + +from ray.util import log_once +from ray.util.annotations import _mark_annotated + +logger = logging.getLogger(__name__) + +# A constant to use for any configuration that should be deprecated +# (to check, whether this config has actually been assigned a proper value or +# not). +DEPRECATED_VALUE = -1 + + +def deprecation_warning( + old: str, + new: Optional[str] = None, + *, + help: Optional[str] = None, + error: Optional[Union[bool, Exception]] = None, +) -> None: + """Warns (via the `logger` object) or throws a deprecation warning/error. + + Args: + old: A description of the "thing" that is to be deprecated. + new: A description of the new "thing" that replaces it. + help: An optional help text to tell the user, what to + do instead of using `old`. + error: Whether or which exception to raise. If True, raise ValueError. + If False, just warn. If `error` is-a subclass of Exception, + raise that Exception. + + Raises: + ValueError: If `error=True`. + Exception: Of type `error`, iff `error` is a sub-class of `Exception`. + """ + msg = "`{}` has been deprecated.{}".format( + old, (" Use `{}` instead.".format(new) if new else f" {help}" if help else "") + ) + + if error: + if not isinstance(error, bool) and issubclass(error, Exception): + # error is an Exception + raise error(msg) + else: + # error is a boolean, construct ValueError ourselves + raise ValueError(msg) + else: + logger.warning( + "DeprecationWarning: " + msg + " This will raise an error in the future!" + ) + + +def Deprecated(old=None, *, new=None, help=None, error): + """Decorator for documenting a deprecated class, method, or function. + + Automatically adds a `deprecation.deprecation_warning(old=..., + error=False)` to not break existing code at this point to the decorated + class' constructor, method, or function. + + In a next major release, this warning should then be made an error + (by setting error=True), which means at this point that the + class/method/function is no longer supported, but will still inform + the user about the deprecation event. + + In a further major release, the class, method, function should be erased + entirely from the codebase. + + + .. testcode:: + :skipif: True + + from ray.rllib.utils.deprecation import Deprecated + # Deprecated class: Patches the constructor to warn if the class is + # used. + @Deprecated(new="NewAndMuchCoolerClass", error=False) + class OldAndUncoolClass: + ... + + # Deprecated class method: Patches the method to warn if called. + class StillCoolClass: + ... + @Deprecated(new="StillCoolClass.new_and_much_cooler_method()", + error=False) + def old_and_uncool_method(self, uncool_arg): + ... + + # Deprecated function: Patches the function to warn if called. + @Deprecated(new="new_and_much_cooler_function", error=False) + def old_and_uncool_function(*uncool_args): + ... + """ + + def _inner(obj): + # A deprecated class. + if inspect.isclass(obj): + # Patch the class' init method to raise the warning/error. + obj_init = obj.__init__ + + def patched_init(*args, **kwargs): + if log_once(old or obj.__name__): + deprecation_warning( + old=old or obj.__name__, + new=new, + help=help, + error=error, + ) + return obj_init(*args, **kwargs) + + obj.__init__ = patched_init + _mark_annotated(obj) + # Return the patched class (with the warning/error when + # instantiated). + return obj + + # A deprecated class method or function. + # Patch with the warning/error at the beginning. + def _ctor(*args, **kwargs): + if log_once(old or obj.__name__): + deprecation_warning( + old=old or obj.__name__, + new=new, + help=help, + error=error, + ) + # Call the deprecated method/function. + return obj(*args, **kwargs) + + # Return the patched class method/function. + return _ctor + + # Return the prepared decorator. + return _inner diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/error.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/error.py new file mode 100644 index 0000000000000000000000000000000000000000..e2c1773ce3d0e8f1dffa26b7bcd288d439e13365 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/error.py @@ -0,0 +1,128 @@ +from ray.rllib.utils.annotations import PublicAPI + + +@PublicAPI +class UnsupportedSpaceException(Exception): + """Error for an unsupported action or observation space.""" + + pass + + +@PublicAPI +class EnvError(Exception): + """Error if we encounter an error during RL environment validation.""" + + pass + + +@PublicAPI +class MultiAgentEnvError(Exception): + """Error if we encounter an error during MultiAgentEnv stepping/validation.""" + + pass + + +@PublicAPI +class NotSerializable(Exception): + """Error if we encounter objects that can't be serialized by ray.""" + + pass + + +# ------- +# Error messages +# ------- + +# Message explaining there are no GPUs available for the +# num_gpus=n or num_gpus_per_env_runner=m settings. +ERR_MSG_NO_GPUS = """Found {} GPUs on your machine (GPU devices found: {})! If your + machine does not have any GPUs, you should set the config keys + `num_gpus_per_learner` and `num_gpus_per_env_runner` to 0. They may be set to + 1 by default for your particular RL algorithm.""" + +ERR_MSG_INVALID_ENV_DESCRIPTOR = """The env string you provided ('{}') is: +a) Not a supported or -installed environment. +b) Not a tune-registered environment creator. +c) Not a valid env class string. + +Try one of the following: +a) For Atari support: `pip install gym[atari] autorom[accept-rom-license]`. + For PyBullet support: `pip install pybullet`. +b) To register your custom env, do `from ray import tune; + tune.register_env('[name]', lambda cfg: [return env obj from here using cfg])`. + Then in your config, do `config.environment(env='[name]'). +c) Make sure you provide a fully qualified classpath, e.g.: + `ray.rllib.examples.envs.classes.repeat_after_me_env.RepeatAfterMeEnv` +""" + + +ERR_MSG_OLD_GYM_API = """Your environment ({}) does not abide to the new gymnasium-style API! +From Ray 2.3 on, RLlib only supports the new (gym>=0.26 or gymnasium) Env APIs. +{} +Learn more about the most important changes here: +https://github.com/openai/gym and here: https://github.com/Farama-Foundation/Gymnasium + +In order to fix this problem, do the following: + +1) Run `pip install gymnasium` on your command line. +2) Change all your import statements in your code from + `import gym` -> `import gymnasium as gym` OR + `from gym.spaces import Discrete` -> `from gymnasium.spaces import Discrete` + +For your custom (single agent) gym.Env classes: +3.1) Either wrap your old Env class via the provided `from gymnasium.wrappers import + EnvCompatibility` wrapper class. +3.2) Alternatively to 3.1: + - Change your `reset()` method to have the call signature 'def reset(self, *, + seed=None, options=None)' + - Return an additional info dict (empty dict should be fine) from your `reset()` + method. + - Return an additional `truncated` flag from your `step()` method (between `done` and + `info`). This flag should indicate, whether the episode was terminated prematurely + due to some time constraint or other kind of horizon setting. + +For your custom RLlib `MultiAgentEnv` classes: +4.1) Either wrap your old MultiAgentEnv via the provided + `from ray.rllib.env.wrappers.multi_agent_env_compatibility import + MultiAgentEnvCompatibility` wrapper class. +4.2) Alternatively to 4.1: + - Change your `reset()` method to have the call signature + 'def reset(self, *, seed=None, options=None)' + - Return an additional per-agent info dict (empty dict should be fine) from your + `reset()` method. + - Rename `dones` into `terminateds` and only set this to True, if the episode is really + done (as opposed to has been terminated prematurely due to some horizon/time-limit + setting). + - Return an additional `truncateds` per-agent dictionary flag from your `step()` + method, including the `__all__` key (100% analogous to your `dones/terminateds` + per-agent dict). + Return this new `truncateds` dict between `dones/terminateds` and `infos`. This + flag should indicate, whether the episode (for some agent or all agents) was + terminated prematurely due to some time constraint or other kind of horizon setting. +""" # noqa + + +ERR_MSG_TF_POLICY_CANNOT_SAVE_KERAS_MODEL = """Could not save keras model under self[TfPolicy].model.base_model! + This is either due to .. + a) .. this Policy's ModelV2 not having any `base_model` (tf.keras.Model) property + b) .. the ModelV2's `base_model` not being used by the Algorithm and thus its + variables not being properly initialized. +""" # noqa + +ERR_MSG_TORCH_POLICY_CANNOT_SAVE_MODEL = """Could not save torch model under self[TorchPolicy].model! + This is most likely due to the fact that you are using an Algorithm that + uses a Catalog-generated TorchModelV2 subclass, which is torch.save() cannot pickle. +""" # noqa + +# ------- +# HOWTO_ strings can be added to any error/warning/into message +# to eplain to the user, how to actually fix the encountered problem. +# ------- + +# HOWTO change the RLlib config, depending on how user runs the job. +HOWTO_CHANGE_CONFIG = """ +To change the config for `tune.Tuner().fit()` in a script: Modify the python dict + passed to `tune.Tuner(param_space=[...]).fit()`. +To change the config for an RLlib Algorithm instance: Modify the python dict + passed to the Algorithm's constructor, e.g. `PPO(config=[...])`. +""" diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/filter.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/filter.py new file mode 100644 index 0000000000000000000000000000000000000000..5f1418cfd2d1773c9dcd3dd017d03bf3e6273d6c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/filter.py @@ -0,0 +1,507 @@ +import logging +import threading + +import numpy as np +import tree # pip install dm_tree + +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.deprecation import Deprecated +from ray.rllib.utils.numpy import ( + SMALL_NUMBER, +) # Assuming SMALL_NUMBER is a small float like 1e-8 +from ray.rllib.utils.typing import TensorStructType +from ray.rllib.utils.serialization import _serialize_ndarray, _deserialize_ndarray +from ray.rllib.utils.deprecation import deprecation_warning + +logger = logging.getLogger(__name__) + + +@OldAPIStack +class Filter: + """Processes input, possibly statefully.""" + + def apply_changes(self, other: "Filter", *args, **kwargs) -> None: + """Updates self with "new state" from other filter.""" + raise NotImplementedError + + def copy(self) -> "Filter": + """Creates a new object with same state as self. + + Returns: + A copy of self. + """ + raise NotImplementedError + + def sync(self, other: "Filter") -> None: + """Copies all state from other filter to self.""" + raise NotImplementedError + + def reset_buffer(self) -> None: + """Creates copy of current state and resets accumulated state""" + raise NotImplementedError + + def as_serializable(self) -> "Filter": + raise NotImplementedError + + @Deprecated(new="Filter.reset_buffer()", error=True) + def clear_buffer(self): + pass + + +@OldAPIStack +class NoFilter(Filter): + is_concurrent = True + + def __call__(self, x: TensorStructType, update=True): + # Process no further if already np.ndarray, dict, or tuple. + if isinstance(x, (np.ndarray, dict, tuple)): + return x + + try: + return np.asarray(x) + except Exception: + raise ValueError("Failed to convert to array", x) + + def apply_changes(self, other: "NoFilter", *args, **kwargs) -> None: + pass + + def copy(self) -> "NoFilter": + return self + + def sync(self, other: "NoFilter") -> None: + pass + + def reset_buffer(self) -> None: + pass + + def as_serializable(self) -> "NoFilter": + return self + + +# Based on Welford's algorithm for numerical stability +# http://www.johndcook.com/blog/standard_deviation/ [4] +@OldAPIStack +class RunningStat: + def __init__(self, shape=()): + """Initializes a `RunningStat` instance.""" + # Keep always a state and a delta from all attributes. Note, + # we use the state for filtering and the delta for updates. + # All deltas will be zero(s) after a state synchronization + # across different actors. + self.num_pushes = 0 + self.num_pushes_delta = 0 + # Stores the mean. + self.mean_array = np.zeros(shape) + self.mean_delta_array = np.zeros(shape) + # Stores the sum of squared demeaned observations. Note, this + # follows Wellington's algorithm. + self.sum_sq_diff_array = np.zeros(shape) + self.sum_sq_diff_delta_array = np.zeros(shape) + + def copy(self): + """Copies a `RunningStat`.""" + # Copy all attributes by creating a new `RunningStat` instance. + other = RunningStat(self.shape) + other.num_pushes = self.num_pushes + other.num_pushes_delta = self.num_pushes_delta + other.mean_array = np.copy(self.mean_array) + other.mean_delta_array = np.copy(self.mean_delta_array) + other.sum_sq_diff_array = np.copy(self.sum_sq_diff_array) + other.sum_sq_diff_delta_array = np.copy(self.sum_sq_diff_delta_array) + return other + + def push(self, x): + """Updates a `RunningStat` instance by a new value. + + Args: + x: A new value to update mean and sum of squares by. Must have the + same shape like the mean. + + Raises: + `ValueError` in case of a shape mismatch. + """ + x = np.asarray(x) + if x.shape != self.mean_array.shape: + raise ValueError( + "Unexpected input shape {}, expected {}, value = {}".format( + x.shape, self.mean_array.shape, x + ) + ) + + # Store old mean for Welford's sum of squares update. + old_mean = np.copy(self.mean_array) + self.num_pushes += 1 + # Also increase the delta counter since the last merge. + self.num_pushes_delta += 1 + + if self.num_pushes == 1: + self.mean_array[...] = x + self.mean_delta_array[...] = x + # sum_sq_diff_array remains 0 for the first element + else: + # Welford's update for mean + delta = x - old_mean + self.mean_array[...] += delta / self.num_pushes + # Update the mean delta. + self.mean_delta_array[...] += delta / self.num_pushes + + # Welford's update for sum of squared differences (S) + # S_k = S_{k-1} + (x_k - M_k)(x_k - M_{k-1}). + self.sum_sq_diff_array[...] += delta * (x - self.mean_array) + # Update the mean sum of squares. + self.sum_sq_diff_delta_array[...] += delta * (x - self.mean_array) + + def update(self, other): + """Update this `RunningStat` instance by another one. + + Args: + other: Another `RunningStat` instance whose state should me + merged with `self`. + """ + # Make this explicitly for future changes to avoid ever turning `num_pushes` into + # a float (this was a problem in earlier versions). + n1_int = self.num_pushes + # Note, we use only the delta for the updates, this reduces the risk of numerical + # instabilities significantly. + n2_int = other.num_pushes_delta + # For higher precision use float versions of the counters. + n1_flt = float(self.num_pushes) + n2_flt = float(other.num_pushes_delta) + n_flt = n1_flt + n2_flt + + # If none of the two `RunningStat`s has seen values, yet, return. + if n1_int + n2_int == 0: + # Avoid divide by zero, which creates nans + return + + # Numerically stable formula for combining means + # M_combined = (n1*M1 + n2*M2) / (n1+n2) + # This is equivalent to M1 + delta * n2 / n + delta_mean = other.mean_delta_array - self.mean_array + self.mean_array += delta_mean * n2_flt / n_flt + + # Numerically stable formula for combining sums of squared differences (S) + # S_combined = S1 + S2 + (n1*n2 / (n1+n2)) * (M1 - M2)^2 [6] + delta_mean_sq = delta_mean * delta_mean + self.sum_sq_diff_array += other.sum_sq_diff_delta_array + delta_mean_sq * ( + n1_flt * n2_flt / n_flt + ) + + # Update the counter with the interger versions of the two counters. + self.num_pushes = n1_int + n2_int + + def __repr__(self): + """Represents a `RunningStat` instance. + + Note, a `RunningStat` is represented by its mean, its standard deviation + and the number `n` of values used to compute the two statistics. + """ + return "(n={}, mean_mean={}, mean_std={})".format( + self.n, np.mean(self.mean), np.mean(self.std) + ) + + @property + def n(self): + """Returns the number of values seen by a `RunningStat` instance.""" + return self.num_pushes + + @property + def mean(self): + """Returns the (vector) mean estimate of a `RunningStat` instance.""" + return self.mean_array + + @property + def var(self): + """Returns the (unbiased vector) variance estimate of a `RunningStat` instance.""" + # For n=0 or n=1, variance is typically undefined or 0. + # Returning 0 for n <= 1 is a common convention for running variance. + if self.num_pushes <= 1: + return np.zeros_like(self.mean_array).astype(np.float32) + # Variance = S / (n-1) for sample variance + return (self.sum_sq_diff_array / (float(self.num_pushes) - 1)).astype( + np.float32 + ) + + @property + def std(self): + """Returns the (unbiased vector) std estimate of a `RunningStat` instance.ance.""" + # Ensure variance is non-negative before sqrt + return np.sqrt(np.maximum(0, self.var)) + + @property + def shape(self): + """Returns the shape of the `RunningStat` instance.""" + return self.mean_array.shape + + def to_state(self): + """Returns the pickable state of a `RunningStat` instance.""" + return { + "num_pushes": self.num_pushes, + "num_pushes_delta": self.num_pushes_delta, + "mean_array": _serialize_ndarray(self.mean_array), + "mean_delta_array": _serialize_ndarray(self.mean_delta_array), + "sum_sq_diff_array": _serialize_ndarray(self.sum_sq_diff_array), + "sum_sq_diff_delta_array": _serialize_ndarray(self.sum_sq_diff_delta_array), + } + + @staticmethod + def from_state(state): + """Builds a `RunningStat` instance from a pickable state.""" + # Need to pass shape to constructor for proper initialization + # Assuming shape can be inferred from mean_array in state + shape = _deserialize_ndarray(state["mean_array"]).shape + running_stats = RunningStat(shape) + running_stats.num_pushes = state["num_pushes"] + running_stats.num_pushes_delta = state["num_pushes_delta"] + running_stats.mean_array = _deserialize_ndarray(state["mean_array"]) + running_stats.mean_delta_array = _deserialize_ndarray(state["mean_delta_array"]) + running_stats.sum_sq_diff_array = _deserialize_ndarray( + state["sum_sq_diff_array"] + ) + running_stats.sum_sq_diff_delta_array = _deserialize_ndarray( + state["sum_sq_diff_delta_array"] + ) + return running_stats + + +@OldAPIStack +class MeanStdFilter(Filter): + """Keeps track of a running mean for seen states""" + + is_concurrent = False + + def __init__(self, shape, demean=True, destd=True, clip=10.0): + self.shape = shape + # We don't have a preprocessor, if shape is None (Discrete) or + # flat_shape is Tuple[np.ndarray] or Dict[str, np.ndarray] + # (complex inputs). + flat_shape = tree.flatten(self.shape) + self.no_preprocessor = shape is None or ( + isinstance(self.shape, (dict, tuple)) + and len(flat_shape) > 0 + and isinstance(flat_shape, np.ndarray) + ) + # If preprocessing (flattening dicts/tuples), make sure shape + # is an np.ndarray, so we don't confuse it with a complex Tuple + # space's shape structure (which is a Tuple[np.ndarray]). + if not self.no_preprocessor: + self.shape = np.array(self.shape) + self.demean = demean + self.destd = destd + self.clip = clip + # Running stats. + self.running_stats = tree.map_structure(lambda s: RunningStat(s), self.shape) + + # In distributed rollouts, each worker sees different states. + # The buffer is used to keep track of deltas amongst all the + # observation filters. + self.buffer = None + self.reset_buffer() + + def reset_buffer(self) -> None: + self.buffer = tree.map_structure(lambda s: RunningStat(s), self.shape) + + def apply_changes( + self, other: "MeanStdFilter", with_buffer: bool = False, *args, **kwargs + ) -> None: + """Applies updates from the buffer of another filter. + + Args: + other: Other filter to apply info from + with_buffer: Flag for specifying if the buffer should be + copied from other. + + .. testcode:: + :skipif: True + + a = MeanStdFilter(()) + a(1) + a(2) + print([a.running_stats.n, a.running_stats.mean, a.buffer.n]) + + .. testoutput:: + + [2, 1.5, 2] + + .. testcode:: + :skipif: True + + b = MeanStdFilter(()) + b(10) + a.apply_changes(b, with_buffer=False) + print([a.running_stats.n, a.running_stats.mean, a.buffer.n]) + + .. testoutput:: + + [3, 4.333333333333333, 2] + + .. testcode:: + :skipif: True + + a.apply_changes(b, with_buffer=True) + print([a.running_stats.n, a.running_stats.mean, a.buffer.n]) + + .. testoutput:: + + [4, 5.75, 1] + """ + tree.map_structure( + lambda rs, other_rs: rs.update(other_rs), self.running_stats, other.buffer + ) + if with_buffer: + self.buffer = tree.map_structure(lambda b: b.copy(), other.buffer) + + def copy(self) -> "MeanStdFilter": + """Returns a copy of `self`.""" + other = MeanStdFilter(self.shape) + other.sync(self) + return other + + def as_serializable(self) -> "MeanStdFilter": + return self.copy() + + def sync(self, other: "MeanStdFilter") -> None: + """Syncs all fields together from other filter. + + .. testcode:: + :skipif: True + + a = MeanStdFilter(()) + a(1) + a(2) + print([a.running_stats.n, a.running_stats.mean, a.buffer.n]) + + .. testoutput:: + + [2, array(1.5), 2] + + .. testcode:: + :skipif: True + + b = MeanStdFilter(()) + b(10) + print([b.running_stats.n, b.running_stats.mean, b.buffer.n]) + + .. testoutput:: + + [1, array(10.0), 1] + + .. testcode:: + :skipif: True + + a.sync(b) + print([a.running_stats.n, a.running_stats.mean, a.buffer.n]) + + .. testoutput:: + + [1, array(10.0), 1] + """ + self.demean = other.demean + self.destd = other.destd + self.clip = other.clip + self.running_stats = tree.map_structure( + lambda rs: rs.copy(), other.running_stats + ) + self.buffer = tree.map_structure(lambda b: b.copy(), other.buffer) + + def __call__(self, x: TensorStructType, update: bool = True) -> TensorStructType: + if self.no_preprocessor: + x = tree.map_structure(lambda x_: np.asarray(x_), x) + else: + x = np.asarray(x) + + def _helper(x, rs, buffer, shape): + # Discrete|MultiDiscrete spaces -> No normalization. + if shape is None: + return x + + # Keep dtype as is througout this filter. + orig_dtype = x.dtype + + if update: + if len(x.shape) == len(rs.shape) + 1: + # The vectorized case. + for i in range(x.shape): + rs.push(x[i]) + buffer.push(x[i]) + else: + # The unvectorized case. + rs.push(x) + buffer.push(x) + if self.demean: + x = x - rs.mean + if self.destd: + x = x / (rs.std + SMALL_NUMBER) + if self.clip: + x = np.clip(x, -self.clip, self.clip) + return x.astype(orig_dtype) + + if self.no_preprocessor: + return tree.map_structure_up_to( + x, _helper, x, self.running_stats, self.buffer, self.shape + ) + else: + return _helper(x, self.running_stats, self.buffer, self.shape) + + +@OldAPIStack +class ConcurrentMeanStdFilter(MeanStdFilter): + is_concurrent = True + + def __init__(self, *args, **kwargs): + super(ConcurrentMeanStdFilter, self).__init__(*args, **kwargs) + deprecation_warning( + old="ConcurrentMeanStdFilter", + error=False, + help="ConcurrentMeanStd filters are only used for testing and will " + "therefore be deprecated in the course of moving to the " + "Connetors API, where testing of filters will be done by other " + "means.", + ) + + self._lock = threading.RLock() + + def lock_wrap(func): + def wrapper(*args, **kwargs): + with self._lock: + return func(*args, **kwargs) + + return wrapper + + self.__getattribute__ = lock_wrap(self.__getattribute__) + + def as_serializable(self) -> "MeanStdFilter": + """Returns non-concurrent version of current class""" + other = MeanStdFilter(self.shape) + other.sync(self) + return other + + def copy(self) -> "ConcurrentMeanStdFilter": + """Returns a copy of Filter.""" + other = ConcurrentMeanStdFilter(self.shape) + other.sync(self) + return other + + def __repr__(self) -> str: + return "ConcurrentMeanStdFilter({}, {}, {}, {}, {}, {})".format( + self.shape, + self.demean, + self.destd, + self.clip, + self.running_stats, + self.buffer, + ) + + +@OldAPIStack +def get_filter(filter_config, shape): + if filter_config == "MeanStdFilter": + return MeanStdFilter(shape, clip=None) + elif filter_config == "ConcurrentMeanStdFilter": + return ConcurrentMeanStdFilter(shape, clip=None) + elif filter_config == "NoFilter": + return NoFilter() + elif callable(filter_config): + return filter_config(shape) + else: + raise Exception("Unknown observation_filter: " + str(filter_config)) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/filter_manager.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/filter_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..b814ee163b84b0c1b61976a053d1e3f833a2376d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/filter_manager.py @@ -0,0 +1,82 @@ +import logging +from typing import Optional + +import ray +from ray.rllib.utils.annotations import OldAPIStack + +logger = logging.getLogger(__name__) + + +@OldAPIStack +class FilterManager: + """Manages filters and coordination across remote evaluators that expose + `get_filters` and `sync_filters`. + """ + + @staticmethod + def synchronize( + local_filters, + worker_set, + update_remote=True, + timeout_seconds: Optional[float] = None, + use_remote_data_for_update: bool = True, + ): + """Aggregates filters from remote workers (if use_remote_data_for_update=True). + + Local copy is updated and then broadcasted to all remote evaluators + (if `update_remote` is True). + + Args: + local_filters: Filters to be synchronized. + worker_set: EnvRunnerGroup with remote EnvRunners with filters. + update_remote: Whether to push updates from the local filters to the remote + workers' filters. + timeout_seconds: How long to wait for filter to get or set filters + use_remote_data_for_update: Whether to use the `worker_set`'s remote workers + to update the local filters. If False, stats from the remote workers + will not be used and discarded. + """ + # No sync/update required in either direction -> Early out. + if not (update_remote or use_remote_data_for_update): + return + + logger.debug(f"Synchronizing filters: {local_filters}") + + # Get the filters from the remote workers. + remote_filters = worker_set.foreach_env_runner( + func=lambda worker: worker.get_filters(flush_after=True), + local_env_runner=False, + timeout_seconds=timeout_seconds, + ) + if len(remote_filters) != worker_set.num_healthy_remote_workers(): + logger.error( + "Failed to get remote filters from a rollout worker in " + "FilterManager! " + "Filtered metrics may be computed, but filtered wrong." + ) + + # Should we utilize the remote workers' filter stats to update the local + # filters? + if use_remote_data_for_update: + for rf in remote_filters: + for k in local_filters: + local_filters[k].apply_changes(rf[k], with_buffer=False) + + # Should we update the remote workers' filters from the (now possibly synched) + # local filters? + if update_remote: + copies = {k: v.as_serializable() for k, v in local_filters.items()} + remote_copy = ray.put(copies) + + logger.debug("Updating remote filters ...") + results = worker_set.foreach_env_runner( + func=lambda worker: worker.sync_filters(ray.get(remote_copy)), + local_env_runner=False, + timeout_seconds=timeout_seconds, + ) + if len(results) != worker_set.num_healthy_remote_workers(): + logger.error( + "Failed to set remote filters to a rollout worker in " + "FilterManager. " + "Filtered metrics may be computed, but filtered wrong." + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/framework.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/framework.py new file mode 100644 index 0000000000000000000000000000000000000000..c0b9a28fa47268138fb9229a5856a47641363579 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/framework.py @@ -0,0 +1,408 @@ +import logging +import numpy as np +import os +import sys +from typing import Any, Optional, TYPE_CHECKING + +import tree # pip install dm_tree + +import ray +from ray.rllib.utils.annotations import DeveloperAPI, PublicAPI +from ray.rllib.utils.deprecation import Deprecated +from ray.rllib.utils.typing import ( + TensorShape, + TensorStructType, + TensorType, +) + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + +logger = logging.getLogger(__name__) + + +@PublicAPI +def convert_to_tensor( + data: TensorStructType, + framework: str, + device: Optional[str] = None, +): + """Converts any nested numpy struct into framework-specific tensors. + + Args: + data: The input data (numpy) to convert to framework-specific tensors. + framework: The framework to convert to. Only "torch" and "tf2" allowed. + device: An optional device name (for torch only). + + Returns: + The converted tensor struct matching the input data. + """ + if framework == "torch": + from ray.rllib.utils.torch_utils import convert_to_torch_tensor + + return convert_to_torch_tensor(data, device=device) + elif framework == "tf2": + _, tf, _ = try_import_tf() + + return tree.map_structure(lambda s: tf.convert_to_tensor(s), data) + raise NotImplementedError( + f"framework={framework} not supported in `convert_to_tensor()`!" + ) + + +@PublicAPI +def get_device(config: "AlgorithmConfig", num_gpus_requested: int = 1): + """Returns a single device (CPU or some GPU) depending on a config. + + Args: + config: An AlgorithmConfig to extract information from about the device to use. + num_gpus_requested: The number of GPUs actually requested. This may be the value + of `config.num_gpus_per_env_runner` when for example calling this function + from an EnvRunner. + + Returns: + A single device (or name) given `config` and `num_gpus_requested`. + """ + if config.framework_str == "torch": + torch, _ = try_import_torch() + + # TODO (Kourosh): How do we handle model parallelism? + # TODO (Kourosh): Instead of using _TorchAccelerator, we should use the public + # API in ray.train but allow for session to be None without any errors raised. + if num_gpus_requested > 0: + from ray.air._internal.torch_utils import get_devices + + # `get_devices()` returns a list that contains the 0th device if + # it is called from outside a Ray Train session. It's necessary to give + # the user the option to run on the gpu of their choice, so we enable that + # option here through `config.local_gpu_idx`. + devices = get_devices() + # Note, if we have a single learner and we do not run on Ray Tune, the local + # learner is not an Ray actor and Ray does not manage devices for it. + if ( + len(devices) == 1 + and ray._private.worker._mode() == ray._private.worker.WORKER_MODE + ): + return devices[0] + else: + assert config.local_gpu_idx < torch.cuda.device_count(), ( + f"local_gpu_idx {config.local_gpu_idx} is not a valid GPU ID " + "or is not available." + ) + # This is an index into the available CUDA devices. For example, if + # `os.environ["CUDA_VISIBLE_DEVICES"] = "1"` then + # `torch.cuda.device_count() = 1` and torch.device(0) maps to that GPU + # with ID=1 on the node. + return torch.device(config.local_gpu_idx) + else: + return torch.device("cpu") + else: + raise NotImplementedError( + f"`framework_str` {config.framework_str} not supported!" + ) + + +@PublicAPI +def try_import_jax(error: bool = False): + """Tries importing JAX and FLAX and returns both modules (or Nones). + + Args: + error: Whether to raise an error if JAX/FLAX cannot be imported. + + Returns: + Tuple containing the jax- and the flax modules. + + Raises: + ImportError: If error=True and JAX is not installed. + """ + if "RLLIB_TEST_NO_JAX_IMPORT" in os.environ: + logger.warning("Not importing JAX for test purposes.") + return None, None + + try: + import jax + import flax + except ImportError: + if error: + raise ImportError( + "Could not import JAX! RLlib requires you to " + "install at least one deep-learning framework: " + "`pip install [torch|tensorflow|jax]`." + ) + return None, None + + return jax, flax + + +@PublicAPI +def try_import_tf(error: bool = False): + """Tries importing tf and returns the module (or None). + + Args: + error: Whether to raise an error if tf cannot be imported. + + Returns: + Tuple containing + 1) tf1.x module (either from tf2.x.compat.v1 OR as tf1.x). + 2) tf module (resulting from `import tensorflow`). Either tf1.x or + 2.x. 3) The actually installed tf version as int: 1 or 2. + + Raises: + ImportError: If error=True and tf is not installed. + """ + tf_stub = _TFStub() + # Make sure, these are reset after each test case + # that uses them: del os.environ["RLLIB_TEST_NO_TF_IMPORT"] + if "RLLIB_TEST_NO_TF_IMPORT" in os.environ: + logger.warning("Not importing TensorFlow for test purposes") + return None, tf_stub, None + + if "TF_CPP_MIN_LOG_LEVEL" not in os.environ: + os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" + + # Try to reuse already imported tf module. This will avoid going through + # the initial import steps below and thereby switching off v2_behavior + # (switching off v2 behavior twice breaks all-framework tests for eager). + was_imported = False + if "tensorflow" in sys.modules: + tf_module = sys.modules["tensorflow"] + was_imported = True + + else: + try: + import tensorflow as tf_module + except ImportError: + if error: + raise ImportError( + "Could not import TensorFlow! RLlib requires you to " + "install at least one deep-learning framework: " + "`pip install [torch|tensorflow|jax]`." + ) + return None, tf_stub, None + + # Try "reducing" tf to tf.compat.v1. + try: + tf1_module = tf_module.compat.v1 + tf1_module.logging.set_verbosity(tf1_module.logging.ERROR) + if not was_imported: + tf1_module.disable_v2_behavior() + tf1_module.enable_resource_variables() + tf1_module.logging.set_verbosity(tf1_module.logging.WARN) + # No compat.v1 -> return tf as is. + except AttributeError: + tf1_module = tf_module + + if not hasattr(tf_module, "__version__"): + version = 1 # sphinx doc gen + else: + version = 2 if "2." in tf_module.__version__[:2] else 1 + + return tf1_module, tf_module, version + + +# Fake module for tf. +class _TFStub: + def __init__(self) -> None: + self.keras = _KerasStub() + + def __bool__(self): + # if tf should return False + return False + + +# Fake module for tf.keras. +class _KerasStub: + def __init__(self) -> None: + self.Model = _FakeTfClassStub + + +# Fake classes under keras (e.g for tf.keras.Model) +class _FakeTfClassStub: + def __init__(self, *a, **kw): + raise ImportError("Could not import `tensorflow`. Try pip install tensorflow.") + + +@DeveloperAPI +def tf_function(tf_module): + """Conditional decorator for @tf.function. + + Use @tf_function(tf) instead to avoid errors if tf is not installed.""" + + # The actual decorator to use (pass in `tf` (which could be None)). + def decorator(func): + # If tf not installed -> return function as is (won't be used anyways). + if tf_module is None or tf_module.executing_eagerly(): + return func + # If tf installed, return @tf.function-decorated function. + return tf_module.function(func) + + return decorator + + +@PublicAPI +def try_import_tfp(error: bool = False): + """Tries importing tfp and returns the module (or None). + + Args: + error: Whether to raise an error if tfp cannot be imported. + + Returns: + The tfp module. + + Raises: + ImportError: If error=True and tfp is not installed. + """ + if "RLLIB_TEST_NO_TF_IMPORT" in os.environ: + logger.warning("Not importing TensorFlow Probability for test purposes.") + return None + + try: + import tensorflow_probability as tfp + + return tfp + except ImportError as e: + if error: + raise e + return None + + +# Fake module for torch.nn. +class _NNStub: + def __init__(self, *a, **kw): + # Fake nn.functional module within torch.nn. + self.functional = None + self.Module = _FakeTorchClassStub + self.parallel = _ParallelStub() + + +# Fake class for e.g. torch.nn.Module to allow it to be inherited from. +class _FakeTorchClassStub: + def __init__(self, *a, **kw): + raise ImportError("Could not import `torch`. Try pip install torch.") + + +class _ParallelStub: + def __init__(self, *a, **kw): + self.DataParallel = _FakeTorchClassStub + self.DistributedDataParallel = _FakeTorchClassStub + + +@PublicAPI +def try_import_torch(error: bool = False): + """Tries importing torch and returns the module (or None). + + Args: + error: Whether to raise an error if torch cannot be imported. + + Returns: + Tuple consisting of the torch- AND torch.nn modules. + + Raises: + ImportError: If error=True and PyTorch is not installed. + """ + if "RLLIB_TEST_NO_TORCH_IMPORT" in os.environ: + logger.warning("Not importing PyTorch for test purposes.") + return _torch_stubs() + + try: + import torch + import torch.nn as nn + + return torch, nn + except ImportError: + if error: + raise ImportError( + "Could not import PyTorch! RLlib requires you to " + "install at least one deep-learning framework: " + "`pip install [torch|tensorflow|jax]`." + ) + return _torch_stubs() + + +def _torch_stubs(): + nn = _NNStub() + return None, nn + + +@DeveloperAPI +def get_variable( + value: Any, + framework: str = "tf", + trainable: bool = False, + tf_name: str = "unnamed-variable", + torch_tensor: bool = False, + device: Optional[str] = None, + shape: Optional[TensorShape] = None, + dtype: Optional[TensorType] = None, +) -> Any: + """Creates a tf variable, a torch tensor, or a python primitive. + + Args: + value: The initial value to use. In the non-tf case, this will + be returned as is. In the tf case, this could be a tf-Initializer + object. + framework: One of "tf", "torch", or None. + trainable: Whether the generated variable should be + trainable (tf)/require_grad (torch) or not (default: False). + tf_name: For framework="tf": An optional name for the + tf.Variable. + torch_tensor: For framework="torch": Whether to actually create + a torch.tensor, or just a python value (default). + device: An optional torch device to use for + the created torch tensor. + shape: An optional shape to use iff `value` + does not have any (e.g. if it's an initializer w/o explicit value). + dtype: An optional dtype to use iff `value` does + not have any (e.g. if it's an initializer w/o explicit value). + This should always be a numpy dtype (e.g. np.float32, np.int64). + + Returns: + A framework-specific variable (tf.Variable, torch.tensor, or + python primitive). + """ + if framework in ["tf2", "tf"]: + import tensorflow as tf + + dtype = dtype or getattr( + value, + "dtype", + tf.float32 + if isinstance(value, float) + else tf.int32 + if isinstance(value, int) + else None, + ) + return tf.compat.v1.get_variable( + tf_name, + initializer=value, + dtype=dtype, + trainable=trainable, + **({} if shape is None else {"shape": shape}), + ) + elif framework == "torch" and torch_tensor is True: + torch, _ = try_import_torch() + if not isinstance(value, np.ndarray): + value = np.array(value) + var_ = torch.from_numpy(value) + if dtype in [torch.float32, np.float32]: + var_ = var_.float() + elif dtype in [torch.int32, np.int32]: + var_ = var_.int() + elif dtype in [torch.float64, np.float64]: + var_ = var_.double() + + if device: + var_ = var_.to(device) + var_.requires_grad = trainable + return var_ + # torch or None: Return python primitive. + return value + + +@Deprecated( + old="rllib/utils/framework.py::get_activation_fn", + new="rllib/models/utils.py::get_activation_fn", + error=True, +) +def get_activation_fn(name: Optional[str] = None, framework: str = "tf"): + pass diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/from_config.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/from_config.py new file mode 100644 index 0000000000000000000000000000000000000000..522ba8dd28783f93d41cf257507808f38259c5a4 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/from_config.py @@ -0,0 +1,325 @@ +from copy import deepcopy +from functools import partial +import importlib +import json +import os +import re +import yaml + +from ray.rllib.utils.annotations import DeveloperAPI +from ray.rllib.utils import force_list, merge_dicts + + +@DeveloperAPI +def from_config(cls, config=None, **kwargs): + """Uses the given config to create an object. + + If `config` is a dict, an optional "type" key can be used as a + "constructor hint" to specify a certain class of the object. + If `config` is not a dict, `config`'s value is used directly as this + "constructor hint". + + The rest of `config` (if it's a dict) will be used as kwargs for the + constructor. Additional keys in **kwargs will always have precedence + (overwrite keys in `config` (if a dict)). + Also, if the config-dict or **kwargs contains the special key "_args", + it will be popped from the dict and used as *args list to be passed + separately to the constructor. + + The following constructor hints are valid: + - None: Use `cls` as constructor. + - An already instantiated object: Will be returned as is; no + constructor call. + - A string or an object that is a key in `cls`'s `__type_registry__` + dict: The value in `__type_registry__` for that key will be used + as the constructor. + - A python callable: Use that very callable as constructor. + - A string: Either a json/yaml filename or the name of a python + module+class (e.g. "ray.rllib. [...] .[some class name]") + + Args: + cls: The class to build an instance for (from `config`). + config (Optional[dict, str]): The config dict or type-string or + filename. + + Keyword Args: + kwargs: Optional possibility to pass the constructor arguments in + here and use `config` as the type-only info. Then we can call + this like: from_config([type]?, [**kwargs for constructor]) + If `config` is already a dict, then `kwargs` will be merged + with `config` (overwriting keys in `config`) after "type" has + been popped out of `config`. + If a constructor of a Configurable needs *args, the special + key `_args` can be passed inside `kwargs` with a list value + (e.g. kwargs={"_args": [arg1, arg2, arg3]}). + + Returns: + any: The object generated from the config. + """ + # `cls` is the config (config is None). + if config is None and isinstance(cls, (dict, str)): + config = cls + cls = None + # `config` is already a created object of this class -> + # Take it as is. + elif isinstance(cls, type) and isinstance(config, cls): + return config + + # `type_`: Indicator for the Configurable's constructor. + # `ctor_args`: *args arguments for the constructor. + # `ctor_kwargs`: **kwargs arguments for the constructor. + # Try to copy, so caller can reuse safely. + try: + config = deepcopy(config) + except Exception: + pass + if isinstance(config, dict): + type_ = config.pop("type", None) + if type_ is None and isinstance(cls, str): + type_ = cls + ctor_kwargs = config + # Give kwargs priority over things defined in config dict. + # This way, one can pass a generic `spec` and then override single + # constructor parameters via the kwargs in the call to `from_config`. + ctor_kwargs.update(kwargs) + else: + type_ = config + if type_ is None and "type" in kwargs: + type_ = kwargs.pop("type") + ctor_kwargs = kwargs + # Special `_args` field in kwargs for *args-utilizing constructors. + ctor_args = force_list(ctor_kwargs.pop("_args", [])) + + # Figure out the actual constructor (class) from `type_`. + # None: Try __default__object (if no args/kwargs), only then + # constructor of cls (using args/kwargs). + if type_ is None: + # We have a default constructor that was defined directly by cls + # (not by its children). + if ( + cls is not None + and hasattr(cls, "__default_constructor__") + and cls.__default_constructor__ is not None + and ctor_args == [] + and ( + not hasattr(cls.__bases__[0], "__default_constructor__") + or cls.__bases__[0].__default_constructor__ is None + or cls.__bases__[0].__default_constructor__ + is not cls.__default_constructor__ + ) + ): + constructor = cls.__default_constructor__ + # Default constructor's keywords into ctor_kwargs. + if isinstance(constructor, partial): + kwargs = merge_dicts(ctor_kwargs, constructor.keywords) + constructor = partial(constructor.func, **kwargs) + ctor_kwargs = {} # erase to avoid duplicate kwarg error + # No default constructor -> Try cls itself as constructor. + else: + constructor = cls + # Try the __type_registry__ of this class. + else: + constructor = _lookup_type(cls, type_) + + # Found in cls.__type_registry__. + if constructor is not None: + pass + # type_ is False or None (and this value is not registered) -> + # return value of type_. + elif type_ is False or type_ is None: + return type_ + # Python callable. + elif callable(type_): + constructor = type_ + # A string: Filename or a python module+class or a json/yaml str. + elif isinstance(type_, str): + if re.search("\\.(yaml|yml|json)$", type_): + return from_file(cls, type_, *ctor_args, **ctor_kwargs) + # Try un-json/un-yaml'ing the string into a dict. + obj = yaml.safe_load(type_) + if isinstance(obj, dict): + return from_config(cls, obj) + try: + obj = from_config(cls, json.loads(type_)) + except json.JSONDecodeError: + pass + else: + return obj + + # Test for absolute module.class path specifier. + if type_.find(".") != -1: + module_name, function_name = type_.rsplit(".", 1) + try: + module = importlib.import_module(module_name) + constructor = getattr(module, function_name) + # Module not found. + except (ModuleNotFoundError, ImportError, AttributeError): + pass + + # If constructor still not found, try attaching cls' module, + # then look for type_ in there. + if constructor is None: + if isinstance(cls, str): + # Module found, but doesn't have the specified + # c'tor/function. + raise ValueError( + f"Full classpath specifier ({type_}) must be a valid " + "full [module].[class] string! E.g.: " + "`my.cool.module.MyCoolClass`." + ) + + try: + module = importlib.import_module(cls.__module__) + constructor = getattr(module, type_) + except (ModuleNotFoundError, ImportError, AttributeError): + # Try the package as well. + try: + package_name = importlib.import_module( + cls.__module__ + ).__package__ + module = __import__(package_name, fromlist=[type_]) + constructor = getattr(module, type_) + except (ModuleNotFoundError, ImportError, AttributeError): + pass + + if constructor is None: + raise ValueError( + f"String specifier ({type_}) must be a valid filename, " + f"a [module].[class], a class within '{cls.__module__}', " + f"or a key into {cls.__name__}.__type_registry__!" + ) + + if not constructor: + raise TypeError("Invalid type '{}'. Cannot create `from_config`.".format(type_)) + + # Create object with inferred constructor. + try: + object_ = constructor(*ctor_args, **ctor_kwargs) + # Catch attempts to construct from an abstract class and return None. + except TypeError as e: + if re.match("Can't instantiate abstract class", e.args[0]): + return None + raise e # Re-raise + # No sanity check for fake (lambda)-"constructors". + if type(constructor).__name__ != "function": + assert isinstance( + object_, + constructor.func if isinstance(constructor, partial) else constructor, + ) + + return object_ + + +@DeveloperAPI +def from_file(cls, filename, *args, **kwargs): + """ + Create object from config saved in filename. Expects json or yaml file. + + Args: + filename: File containing the config (json or yaml). + + Returns: + any: The object generated from the file. + """ + path = os.path.join(os.getcwd(), filename) + if not os.path.isfile(path): + raise FileNotFoundError("File '{}' not found!".format(filename)) + + with open(path, "rt") as fp: + if path.endswith(".yaml") or path.endswith(".yml"): + config = yaml.safe_load(fp) + else: + config = json.load(fp) + + # Add possible *args. + config["_args"] = args + return from_config(cls, config=config, **kwargs) + + +def _lookup_type(cls, type_): + if ( + cls is not None + and hasattr(cls, "__type_registry__") + and isinstance(cls.__type_registry__, dict) + and ( + type_ in cls.__type_registry__ + or ( + isinstance(type_, str) + and re.sub("[\\W_]", "", type_.lower()) in cls.__type_registry__ + ) + ) + ): + available_class_for_type = cls.__type_registry__.get(type_) + if available_class_for_type is None: + available_class_for_type = cls.__type_registry__[ + re.sub("[\\W_]", "", type_.lower()) + ] + return available_class_for_type + return None + + +class _NotProvided: + """Singleton class to provide a "not provided" value for AlgorithmConfig signatures. + + Using the only instance of this class indicates that the user does NOT wish to + change the value of some property. + + .. testcode:: + :skipif: True + + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + config = AlgorithmConfig() + # Print out the default learning rate. + print(config.lr) + + .. testoutput:: + + 0.001 + + .. testcode:: + :skipif: True + + # Print out the default `preprocessor_pref`. + print(config.preprocessor_pref) + + .. testoutput:: + + "deepmind" + + .. testcode:: + :skipif: True + + # Will only set the `preprocessor_pref` property (to None) and leave + # all other properties at their default values. + config.training(preprocessor_pref=None) + config.preprocessor_pref is None + + .. testoutput:: + + True + + .. testcode:: + :skipif: True + + # Still the same value (didn't touch it in the call to `.training()`. + print(config.lr) + + .. testoutput:: + + 0.001 + """ + + class __NotProvided: + pass + + instance = None + + def __init__(self): + if _NotProvided.instance is None: + _NotProvided.instance = _NotProvided.__NotProvided() + + +# Use this object as default values in all method signatures of +# AlgorithmConfig, indicating that the respective property should NOT be touched +# in the call. +NotProvided = _NotProvided() diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/images.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/images.py new file mode 100644 index 0000000000000000000000000000000000000000..7b0f1601d574a5e34805b30cfed7ca9c391c1f0c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/images.py @@ -0,0 +1,60 @@ +import logging +import importlib + +import numpy as np + +from ray.rllib.utils.annotations import DeveloperAPI + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +def is_package_installed(package_name): + try: + importlib.metadata.version(package_name) + return True + except importlib.metadata.PackageNotFoundError: + return False + + +try: + import cv2 + + cv2.ocl.setUseOpenCL(False) + + logger.debug("CV2 found for image processing.") +except ImportError as e: + if is_package_installed("opencv-python"): + raise ImportError( + f"OpenCV is installed, but we failed to import it. This may be because " + f"you need to install `opencv-python-headless` instead of " + f"`opencv-python`. Error message: {e}", + ) + cv2 = None + + +@DeveloperAPI +def resize(img: np.ndarray, height: int, width: int) -> np.ndarray: + if not cv2: + raise ModuleNotFoundError( + "`opencv` not installed! Do `pip install opencv-python`" + ) + return cv2.resize(img, (width, height), interpolation=cv2.INTER_AREA) + + +@DeveloperAPI +def rgb2gray(img: np.ndarray) -> np.ndarray: + if not cv2: + raise ModuleNotFoundError( + "`opencv` not installed! Do `pip install opencv-python`" + ) + return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) + + +@DeveloperAPI +def imread(img_file: str) -> np.ndarray: + if not cv2: + raise ModuleNotFoundError( + "`opencv` not installed! Do `pip install opencv-python`" + ) + return cv2.imread(img_file).astype(np.float32) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/lambda_defaultdict.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/lambda_defaultdict.py new file mode 100644 index 0000000000000000000000000000000000000000..ce4653961c565304570da87eea9066dc366643e0 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/lambda_defaultdict.py @@ -0,0 +1,52 @@ +from collections import defaultdict +from typing import Any, Callable + + +class LambdaDefaultDict(defaultdict): + """A defaultdict that creates default values based on the associated key. + + Note that the standard defaultdict can only produce default values (via its factory) + that are independent of the key under which they are stored. + As opposed to that, the lambda functions used as factories for this + `LambdaDefaultDict` class do accept a single argument: The missing key. + If a missing key is accessed by the user, the provided lambda function is called + with this missing key as its argument. The returned value is stored in the + dictionary under that key and returned. + + Example: + + In this example, if you try to access a key that doesn't exist, it will call + the lambda function, passing it the missing key. The function will return a + string, which will be stored in the dictionary under that key. + + .. testcode:: + + from ray.rllib.utils.lambda_defaultdict import LambdaDefaultDict + + default_dict = LambdaDefaultDict(lambda missing_key: f"Value for {missing_key}") + print(default_dict["a"]) + + .. testoutput:: + + Value for a + """ # noqa: E501 + + def __init__(self, default_factory: Callable[[str], Any], *args, **kwargs): + """Initializes a LambdaDefaultDict instance. + + Args: + default_factory: The default factory callable, taking a string (key) + and returning the default value to use for that key. + """ + if not callable(default_factory): + raise TypeError("First argument must be a Callable!") + + # We will handle the factory in __missing__ method. + super().__init__(None, *args, **kwargs) + + self.default_factory = default_factory + + def __missing__(self, key): + # Call default factory with the key as argument. + self[key] = value = self.default_factory(key) + return value diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/memory.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/memory.py new file mode 100644 index 0000000000000000000000000000000000000000..fe739cc0f99b8f23f68f31021b446cbf06f64d17 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/memory.py @@ -0,0 +1,8 @@ +from ray.rllib.utils.deprecation import deprecation_warning +from ray.rllib.utils.numpy import aligned_array, concat_aligned # noqa + +deprecation_warning( + old="ray.rllib.utils.memory.[...]", + new="ray.rllib.utils.numpy.[...]", + error=True, +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/minibatch_utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/minibatch_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1f2cf3d044bafd6ffa01b5a12854fdfc95df12f7 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/minibatch_utils.py @@ -0,0 +1,392 @@ +import math +from typing import List, Optional + +from ray.data import DataIterator +from ray.rllib.policy.sample_batch import MultiAgentBatch, concat_samples +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils import unflatten_dict +from ray.rllib.utils.annotations import DeveloperAPI +from ray.rllib.utils.typing import DeviceType, EpisodeType + + +@DeveloperAPI +class MiniBatchIteratorBase: + """The base class for all minibatch iterators.""" + + def __init__( + self, + batch: MultiAgentBatch, + *, + num_epochs: int = 1, + shuffle_batch_per_epoch: bool = True, + minibatch_size: int, + num_total_minibatches: int = 0, + ) -> None: + """Initializes a MiniBatchIteratorBase instance. + + Args: + batch: The input multi-agent batch. + num_epochs: The number of complete passes over the entire train batch. Each + pass might be further split into n minibatches (if `minibatch_size` + provided). The train batch is generated from the given `episodes` + through the Learner connector pipeline. + minibatch_size: The size of minibatches to use to further split the train + batch into per epoch. The train batch is generated from the given + `episodes` through the Learner connector pipeline. + num_total_minibatches: The total number of minibatches to loop through + (over all `num_epochs` epochs). It's only required to set this to != 0 + in multi-agent + multi-GPU situations, in which the MultiAgentEpisodes + themselves are roughly sharded equally, however, they might contain + SingleAgentEpisodes with very lopsided length distributions. Thus, + without this fixed, pre-computed value, one Learner might go through a + different number of minibatche passes than others causing a deadlock. + """ + pass + + +@DeveloperAPI +class MiniBatchCyclicIterator(MiniBatchIteratorBase): + """This implements a simple multi-agent minibatch iterator. + + This iterator will split the input multi-agent batch into minibatches where the + size of batch for each module_id (aka policy_id) is equal to minibatch_size. If the + input batch is smaller than minibatch_size, then the iterator will cycle through + the batch until it has covered `num_epochs` epochs. + """ + + def __init__( + self, + batch: MultiAgentBatch, + *, + num_epochs: int = 1, + minibatch_size: int, + shuffle_batch_per_epoch: bool = True, + num_total_minibatches: int = 0, + ) -> None: + """Initializes a MiniBatchCyclicIterator instance.""" + super().__init__( + batch, + num_epochs=num_epochs, + minibatch_size=minibatch_size, + shuffle_batch_per_epoch=shuffle_batch_per_epoch, + ) + + self._batch = batch + self._minibatch_size = minibatch_size + self._num_epochs = num_epochs + self._shuffle_batch_per_epoch = shuffle_batch_per_epoch + + # mapping from module_id to the start index of the batch + self._start = {mid: 0 for mid in batch.policy_batches.keys()} + # mapping from module_id to the number of epochs covered for each module_id + self._num_covered_epochs = {mid: 0 for mid in batch.policy_batches.keys()} + + self._minibatch_count = 0 + self._num_total_minibatches = num_total_minibatches + + def __iter__(self): + while ( + # Make sure each item in the total batch gets at least iterated over + # `self._num_epochs` times. + ( + self._num_total_minibatches == 0 + and min(self._num_covered_epochs.values()) < self._num_epochs + ) + # Make sure we reach at least the given minimum number of mini-batches. + or ( + self._num_total_minibatches > 0 + and self._minibatch_count < self._num_total_minibatches + ) + ): + minibatch = {} + for module_id, module_batch in self._batch.policy_batches.items(): + + if len(module_batch) == 0: + raise ValueError( + f"The batch for module_id {module_id} is empty! " + "This will create an infinite loop because we need to cover " + "the same number of samples for each module_id." + ) + s = self._start[module_id] # start + + # TODO (sven): Fix this bug for LSTMs: + # In an RNN-setting, the Learner connector already has zero-padded + # and added a timerank to the batch. Thus, n_step would still be based + # on the BxT dimension, rather than the new B dimension (excluding T), + # which then leads to minibatches way too large. + # However, changing this already would break APPO/IMPALA w/o LSTMs as + # these setups require sequencing, BUT their batches are not yet time- + # ranked (this is done only in their loss functions via the + # `make_time_major` utility). + n_steps = self._minibatch_size + + samples_to_concat = [] + + # get_len is a function that returns the length of a batch + # if we are not slicing the batch in the batch dimension B, then + # the length of the batch is simply the length of the batch + # o.w the length of the batch is the length list of seq_lens. + if module_batch._slice_seq_lens_in_B: + assert module_batch.get(SampleBatch.SEQ_LENS) is not None, ( + "MiniBatchCyclicIterator requires SampleBatch.SEQ_LENS" + "to be present in the batch for slicing a batch in the batch " + "dimension B." + ) + + def get_len(b): + return len(b[SampleBatch.SEQ_LENS]) + + n_steps = int( + get_len(module_batch) + * (self._minibatch_size / len(module_batch)) + ) + + else: + + def get_len(b): + return len(b) + + # Cycle through the batch until we have enough samples. + while s + n_steps >= get_len(module_batch): + sample = module_batch[s:] + samples_to_concat.append(sample) + len_sample = get_len(sample) + assert len_sample > 0, "Length of a sample must be > 0!" + n_steps -= len_sample + s = 0 + self._num_covered_epochs[module_id] += 1 + # Shuffle the individual single-agent batch, if required. + # This should happen once per minibatch iteration in order to make + # each iteration go through a different set of minibatches. + if self._shuffle_batch_per_epoch: + module_batch.shuffle() + + e = s + n_steps # end + if e > s: + samples_to_concat.append(module_batch[s:e]) + + # concatenate all the samples, we should have minibatch_size of sample + # after this step + minibatch[module_id] = concat_samples(samples_to_concat) + # roll minibatch to zero when we reach the end of the batch + self._start[module_id] = e + + # Note (Kourosh): env_steps is the total number of env_steps that this + # multi-agent batch is covering. It should be simply inherited from the + # original multi-agent batch. + minibatch = MultiAgentBatch(minibatch, len(self._batch)) + yield minibatch + + self._minibatch_count += 1 + + +class MiniBatchDummyIterator(MiniBatchIteratorBase): + def __init__(self, batch: MultiAgentBatch, **kwargs): + super().__init__(batch, **kwargs) + self._batch = batch + + def __iter__(self): + yield self._batch + + +@DeveloperAPI +class MiniBatchRayDataIterator: + def __init__( + self, + *, + iterator: DataIterator, + device: DeviceType, + minibatch_size: int, + num_iters: Optional[int], + **kwargs, + ): + # A `ray.data.DataIterator` that can iterate in different ways over the data. + self._iterator = iterator + # Note, in multi-learner settings the `return_state` is in `kwargs`. + self._kwargs = {k: v for k, v in kwargs.items() if k != "return_state"} + + # Holds a batched_iterable over the dataset. + self._batched_iterable = self._iterator.iter_torch_batches( + batch_size=minibatch_size, + device=device, + **self._kwargs, + ) + # Create an iterator that can be stopped and resumed during an epoch. + self._epoch_iterator = iter(self._batched_iterable) + self._num_iters = num_iters + + def __iter__(self) -> MultiAgentBatch: + iteration = 0 + while self._num_iters is None or iteration < self._num_iters: + for batch in self._epoch_iterator: + # Update the iteration counter. + iteration += 1 + + batch = unflatten_dict(batch) + batch = MultiAgentBatch( + { + module_id: SampleBatch(module_data) + for module_id, module_data in batch.items() + }, + env_steps=sum( + len(next(iter(module_data.values()))) + for module_data in batch.values() + ), + ) + + yield (batch) + + # If `num_iters` is reached break and return. + if self._num_iters and iteration == self._num_iters: + break + else: + # Reinstantiate a new epoch iterator. + self._epoch_iterator = iter(self._batched_iterable) + # If a full epoch on the data should be run, stop. + if not self._num_iters: + # Exit the loop. + break + + +@DeveloperAPI +class ShardBatchIterator: + """Iterator for sharding batch into num_shards batches. + + Args: + batch: The input multi-agent batch. + num_shards: The number of shards to split the batch into. + + Yields: + A MultiAgentBatch of size len(batch) / num_shards. + """ + + def __init__(self, batch: MultiAgentBatch, num_shards: int): + self._batch = batch + self._num_shards = num_shards + + def __iter__(self): + for i in range(self._num_shards): + # TODO (sven): The following way of sharding a multi-agent batch destroys + # the relationship of the different agents' timesteps to each other. + # Thus, in case the algorithm requires agent-synchronized data (aka. + # "lockstep"), the `ShardBatchIterator` cannot be used. + batch_to_send = {} + for pid, sub_batch in self._batch.policy_batches.items(): + batch_size = math.ceil(len(sub_batch) / self._num_shards) + start = batch_size * i + end = min(start + batch_size, len(sub_batch)) + batch_to_send[pid] = sub_batch[int(start) : int(end)] + # TODO (Avnish): int(batch_size) ? How should we shard MA batches really? + new_batch = MultiAgentBatch(batch_to_send, int(batch_size)) + yield new_batch + + +@DeveloperAPI +class ShardEpisodesIterator: + """Iterator for sharding a list of Episodes into `num_shards` lists of Episodes.""" + + def __init__( + self, + episodes: List[EpisodeType], + num_shards: int, + len_lookback_buffer: Optional[int] = None, + ): + """Initializes a ShardEpisodesIterator instance. + + Args: + episodes: The input list of Episodes. + num_shards: The number of shards to split the episodes into. + len_lookback_buffer: An optional length of a lookback buffer to enforce + on the returned shards. When spitting an episode, the second piece + might need a lookback buffer (into the first piece) depending on the + user's settings. + """ + self._episodes = sorted(episodes, key=len, reverse=True) + self._num_shards = num_shards + self._len_lookback_buffer = len_lookback_buffer + self._total_length = sum(len(e) for e in episodes) + self._target_lengths = [0 for _ in range(self._num_shards)] + remaining_length = self._total_length + for s in range(self._num_shards): + len_ = remaining_length // (num_shards - s) + self._target_lengths[s] = len_ + remaining_length -= len_ + + def __iter__(self) -> List[EpisodeType]: + """Runs one iteration through this sharder. + + Yields: + A sub-list of Episodes of size roughly `len(episodes) / num_shards`. The + yielded sublists might have slightly different total sums of episode + lengths, in order to not have to drop even a single timestep. + """ + sublists = [[] for _ in range(self._num_shards)] + lengths = [0 for _ in range(self._num_shards)] + episode_index = 0 + + while episode_index < len(self._episodes): + episode = self._episodes[episode_index] + min_index = lengths.index(min(lengths)) + + # Add the whole episode if it fits within the target length + if lengths[min_index] + len(episode) <= self._target_lengths[min_index]: + sublists[min_index].append(episode) + lengths[min_index] += len(episode) + episode_index += 1 + # Otherwise, slice the episode + else: + remaining_length = self._target_lengths[min_index] - lengths[min_index] + if remaining_length > 0: + slice_part, remaining_part = ( + # Note that the first slice will automatically "inherit" the + # lookback buffer size of the episode. + episode[:remaining_length], + # However, the second slice might need a user defined lookback + # buffer (into the first slice). + episode.slice( + slice(remaining_length, None), + len_lookback_buffer=self._len_lookback_buffer, + ), + ) + sublists[min_index].append(slice_part) + lengths[min_index] += len(slice_part) + self._episodes[episode_index] = remaining_part + else: + assert remaining_length == 0 + sublists[min_index].append(episode) + episode_index += 1 + + for sublist in sublists: + yield sublist + + +@DeveloperAPI +class ShardObjectRefIterator: + """Iterator for sharding a list of ray ObjectRefs into num_shards sub-lists. + + Args: + object_refs: The input list of ray ObjectRefs. + num_shards: The number of shards to split the references into. + + Yields: + A sub-list of ray ObjectRefs with lengths as equal as possible. + """ + + def __init__(self, object_refs, num_shards: int): + self._object_refs = object_refs + self._num_shards = num_shards + + def __iter__(self): + # Calculate the size of each sublist + n = len(self._object_refs) + sublist_size = n // self._num_shards + remaining_elements = n % self._num_shards + + start = 0 + for i in range(self._num_shards): + # Determine the end index for the current sublist + end = start + sublist_size + (1 if i < remaining_elements else 0) + # Append the sublist to the result + yield self._object_refs[start:end] + # Update the start index for the next sublist + start = end diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/numpy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/numpy.py new file mode 100644 index 0000000000000000000000000000000000000000..b0970ad51427a8ae84aff3273bd4c57798b15959 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/numpy.py @@ -0,0 +1,605 @@ +from collections import OrderedDict +from gymnasium.spaces import Discrete, MultiDiscrete +import numpy as np +import tree # pip install dm_tree +from types import MappingProxyType +from typing import List, Optional + + +from ray.rllib.utils.annotations import PublicAPI +from ray.rllib.utils.deprecation import Deprecated +from ray.rllib.utils.framework import try_import_tf, try_import_torch +from ray.rllib.utils.typing import SpaceStruct, TensorType, TensorStructType, Union + +tf1, tf, tfv = try_import_tf() +torch, _ = try_import_torch() + +SMALL_NUMBER = 1e-6 +# Some large int number. May be increased here, if needed. +LARGE_INTEGER = 100000000 +# Min and Max outputs (clipped) from an NN-output layer interpreted as the +# log(x) of some x (e.g. a stddev of a normal +# distribution). +MIN_LOG_NN_OUTPUT = -5 +MAX_LOG_NN_OUTPUT = 2 + + +@PublicAPI +@Deprecated( + help="RLlib itself has no use for this anymore.", + error=False, +) +def aligned_array(size: int, dtype, align: int = 64) -> np.ndarray: + """Returns an array of a given size that is 64-byte aligned. + + The returned array can be efficiently copied into GPU memory by TensorFlow. + + Args: + size: The size (total number of items) of the array. For example, + array([[0.0, 1.0], [2.0, 3.0]]) would have size=4. + dtype: The numpy dtype of the array. + align: The alignment to use. + + Returns: + A np.ndarray with the given specifications. + """ + n = size * dtype.itemsize + empty = np.empty(n + (align - 1), dtype=np.uint8) + data_align = empty.ctypes.data % align + offset = 0 if data_align == 0 else (align - data_align) + if n == 0: + # stop np from optimising out empty slice reference + output = empty[offset : offset + 1][0:0].view(dtype) + else: + output = empty[offset : offset + n].view(dtype) + + assert len(output) == size, len(output) + assert output.ctypes.data % align == 0, output.ctypes.data + return output + + +@PublicAPI +@Deprecated( + help="RLlib itself has no use for this anymore.", + error=False, +) +def concat_aligned( + items: List[np.ndarray], time_major: Optional[bool] = None +) -> np.ndarray: + """Concatenate arrays, ensuring the output is 64-byte aligned. + + We only align float arrays; other arrays are concatenated as normal. + + This should be used instead of np.concatenate() to improve performance + when the output array is likely to be fed into TensorFlow. + + Args: + items: The list of items to concatenate and align. + time_major: Whether the data in items is time-major, in which + case, we will concatenate along axis=1. + + Returns: + The concat'd and aligned array. + """ + + if len(items) == 0: + return [] + elif len(items) == 1: + # we assume the input is aligned. In any case, it doesn't help + # performance to force align it since that incurs a needless copy. + return items[0] + elif isinstance(items[0], np.ndarray) and items[0].dtype in [ + np.float32, + np.float64, + np.uint8, + ]: + dtype = items[0].dtype + flat = aligned_array(sum(s.size for s in items), dtype) + if time_major is not None: + if time_major is True: + batch_dim = sum(s.shape[1] for s in items) + new_shape = (items[0].shape[0], batch_dim,) + items[ + 0 + ].shape[2:] + else: + batch_dim = sum(s.shape[0] for s in items) + new_shape = (batch_dim, items[0].shape[1],) + items[ + 0 + ].shape[2:] + else: + batch_dim = sum(s.shape[0] for s in items) + new_shape = (batch_dim,) + items[0].shape[1:] + output = flat.reshape(new_shape) + assert output.ctypes.data % 64 == 0, output.ctypes.data + np.concatenate(items, out=output, axis=1 if time_major else 0) + return output + else: + return np.concatenate(items, axis=1 if time_major else 0) + + +@PublicAPI +def convert_to_numpy(x: TensorStructType, reduce_type: bool = True) -> TensorStructType: + """Converts values in `stats` to non-Tensor numpy or python types. + + Args: + x: Any (possibly nested) struct, the values in which will be + converted and returned as a new struct with all torch/tf tensors + being converted to numpy types. + reduce_type: Whether to automatically reduce all float64 and int64 data + into float32 and int32 data, respectively. + + Returns: + A new struct with the same structure as `x`, but with all + values converted to numpy arrays (on CPU). + """ + + # The mapping function used to numpyize torch/tf Tensors (and move them + # to the CPU beforehand). + def mapping(item): + if torch and isinstance(item, torch.Tensor): + ret = ( + item.cpu().item() + if len(item.size()) == 0 + else item.detach().cpu().numpy() + ) + elif ( + tf and isinstance(item, (tf.Tensor, tf.Variable)) and hasattr(item, "numpy") + ): + assert tf.executing_eagerly() + ret = item.numpy() + else: + ret = item + if reduce_type and isinstance(ret, np.ndarray): + if np.issubdtype(ret.dtype, np.floating): + ret = ret.astype(np.float32) + elif np.issubdtype(ret.dtype, int): + ret = ret.astype(np.int32) + return ret + + return tree.map_structure(mapping, x) + + +@PublicAPI +def fc( + x: np.ndarray, + weights: np.ndarray, + biases: Optional[np.ndarray] = None, + framework: Optional[str] = None, +) -> np.ndarray: + """Calculates FC (dense) layer outputs given weights/biases and input. + + Args: + x: The input to the dense layer. + weights: The weights matrix. + biases: The biases vector. All 0s if None. + framework: An optional framework hint (to figure out, + e.g. whether to transpose torch weight matrices). + + Returns: + The dense layer's output. + """ + + def map_(data, transpose=False): + if torch: + if isinstance(data, torch.Tensor): + data = data.cpu().detach().numpy() + if tf and tf.executing_eagerly(): + if isinstance(data, tf.Variable): + data = data.numpy() + if transpose: + data = np.transpose(data) + return data + + x = map_(x) + # Torch stores matrices in transpose (faster for backprop). + transpose = framework == "torch" and ( + x.shape[1] != weights.shape[0] and x.shape[1] == weights.shape[1] + ) + weights = map_(weights, transpose=transpose) + biases = map_(biases) + + return np.matmul(x, weights) + (0.0 if biases is None else biases) + + +@PublicAPI +def flatten_inputs_to_1d_tensor( + inputs: TensorStructType, + spaces_struct: Optional[SpaceStruct] = None, + time_axis: bool = False, + batch_axis: bool = True, +) -> TensorType: + """Flattens arbitrary input structs according to the given spaces struct. + + Returns a single 1D tensor resulting from the different input + components' values. + + Thereby: + - Boxes (any shape) get flattened to (B, [T]?, -1). Note that image boxes + are not treated differently from other types of Boxes and get + flattened as well. + - Discrete (int) values are one-hot'd, e.g. a batch of [1, 0, 3] (B=3 with + Discrete(4) space) results in [[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1]]. + - MultiDiscrete values are multi-one-hot'd, e.g. a batch of + [[0, 2], [1, 4]] (B=2 with MultiDiscrete([2, 5]) space) results in + [[1, 0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 0, 1]]. + + Args: + inputs: The inputs to be flattened. + spaces_struct: The (possibly nested) structure of the spaces that `inputs` + belongs to. + time_axis: Whether all inputs have a time-axis (after the batch axis). + If True, will keep not only the batch axis (0th), but the time axis + (1st) as-is and flatten everything from the 2nd axis up. + batch_axis: Whether all inputs have a batch axis. + If True, will keep that batch axis as-is and flatten everything from the + other dims up. + + Returns: + A single 1D tensor resulting from concatenating all + flattened/one-hot'd input components. Depending on the time_axis flag, + the shape is (B, n) or (B, T, n). + + .. testcode:: + :skipif: True + + # B=2 + from ray.rllib.utils.tf_utils import flatten_inputs_to_1d_tensor + from gymnasium.spaces import Discrete, Box + out = flatten_inputs_to_1d_tensor( + {"a": [1, 0], "b": [[[0.0], [0.1]], [1.0], [1.1]]}, + spaces_struct=dict(a=Discrete(2), b=Box(shape=(2, 1))) + ) + print(out) + + # B=2; T=2 + out = flatten_inputs_to_1d_tensor( + ([[1, 0], [0, 1]], + [[[0.0, 0.1], [1.0, 1.1]], [[2.0, 2.1], [3.0, 3.1]]]), + spaces_struct=tuple([Discrete(2), Box(shape=(2, ))]), + time_axis=True + ) + print(out) + + .. testoutput:: + + [[0.0, 1.0, 0.0, 0.1], [1.0, 0.0, 1.0, 1.1]] # B=2 n=4 + [[[0.0, 1.0, 0.0, 0.1], [1.0, 0.0, 1.0, 1.1]], + [[1.0, 0.0, 2.0, 2.1], [0.0, 1.0, 3.0, 3.1]]] # B=2 T=2 n=4 + """ + # `time_axis` must not be True if `batch_axis` is False. + assert not (time_axis and not batch_axis) + + flat_inputs = tree.flatten(inputs) + flat_spaces = ( + tree.flatten(spaces_struct) + if spaces_struct is not None + else [None] * len(flat_inputs) + ) + + B = None + T = None + out = [] + for input_, space in zip(flat_inputs, flat_spaces): + # Store batch and (if applicable) time dimension. + if B is None and batch_axis: + B = input_.shape[0] + if time_axis: + T = input_.shape[1] + + # One-hot encoding. + if isinstance(space, Discrete): + if time_axis: + input_ = np.reshape(input_, [B * T]) + out.append(one_hot(input_, depth=space.n).astype(np.float32)) + # Multi one-hot encoding. + elif isinstance(space, MultiDiscrete): + if time_axis: + input_ = np.reshape(input_, [B * T, -1]) + if batch_axis: + out.append( + np.concatenate( + [ + one_hot(input_[:, i], depth=n).astype(np.float32) + for i, n in enumerate(space.nvec) + ], + axis=-1, + ) + ) + else: + out.append( + np.concatenate( + [ + one_hot(input_[i], depth=n).astype(np.float32) + for i, n in enumerate(space.nvec) + ], + axis=-1, + ) + ) + # Box: Flatten. + else: + # Special case for spaces: Box(.., shape=(), ..) + if isinstance(input_, float): + input_ = np.array([input_]) + + if time_axis: + input_ = np.reshape(input_, [B * T, -1]) + elif batch_axis: + input_ = np.reshape(input_, [B, -1]) + else: + input_ = np.reshape(input_, [-1]) + out.append(input_.astype(np.float32)) + + merged = np.concatenate(out, axis=-1) + # Restore the time-dimension, if applicable. + if time_axis: + merged = np.reshape(merged, [B, T, -1]) + return merged + + +@PublicAPI +def make_action_immutable(obj): + """Flags actions immutable to notify users when trying to change them. + + Can also be used with any tree-like structure containing either + dictionaries, numpy arrays or already immutable objects per se. + Note, however that `tree.map_structure()` will in general not + include the shallow object containing all others and therefore + immutability will hold only for all objects contained in it. + Use `tree.traverse(fun, action, top_down=False)` to include + also the containing object. + + Args: + obj: The object to be made immutable. + + Returns: + The immutable object. + + .. testcode:: + :skipif: True + + import tree + import numpy as np + from ray.rllib.utils.numpy import make_action_immutable + arr = np.arange(1,10) + d = dict(a = 1, b = (arr, arr)) + tree.traverse(make_action_immutable, d, top_down=False) + """ + if isinstance(obj, np.ndarray): + obj.setflags(write=False) + return obj + elif isinstance(obj, OrderedDict): + return MappingProxyType(dict(obj)) + elif isinstance(obj, dict): + return MappingProxyType(obj) + else: + return obj + + +@PublicAPI +def huber_loss(x: np.ndarray, delta: float = 1.0) -> np.ndarray: + """Reference: https://en.wikipedia.org/wiki/Huber_loss.""" + return np.where( + np.abs(x) < delta, np.power(x, 2.0) * 0.5, delta * (np.abs(x) - 0.5 * delta) + ) + + +@PublicAPI +def l2_loss(x: np.ndarray) -> np.ndarray: + """Computes half the L2 norm of a tensor (w/o the sqrt): sum(x**2) / 2. + + Args: + x: The input tensor. + + Returns: + The l2-loss output according to the above formula given `x`. + """ + return np.sum(np.square(x)) / 2.0 + + +@PublicAPI +def lstm( + x, + weights: np.ndarray, + biases: Optional[np.ndarray] = None, + initial_internal_states: Optional[np.ndarray] = None, + time_major: bool = False, + forget_bias: float = 1.0, +): + """Calculates LSTM layer output given weights/biases, states, and input. + + Args: + x: The inputs to the LSTM layer including time-rank + (0th if time-major, else 1st) and the batch-rank + (1st if time-major, else 0th). + weights: The weights matrix. + biases: The biases vector. All 0s if None. + initial_internal_states: The initial internal + states to pass into the layer. All 0s if None. + time_major: Whether to use time-major or not. Default: False. + forget_bias: Gets added to first sigmoid (forget gate) output. + Default: 1.0. + + Returns: + Tuple consisting of 1) The LSTM layer's output and + 2) Tuple: Last (c-state, h-state). + """ + sequence_length = x.shape[0 if time_major else 1] + batch_size = x.shape[1 if time_major else 0] + units = weights.shape[1] // 4 # 4 internal layers (3x sigmoid, 1x tanh) + + if initial_internal_states is None: + c_states = np.zeros(shape=(batch_size, units)) + h_states = np.zeros(shape=(batch_size, units)) + else: + c_states = initial_internal_states[0] + h_states = initial_internal_states[1] + + # Create a placeholder for all n-time step outputs. + if time_major: + unrolled_outputs = np.zeros(shape=(sequence_length, batch_size, units)) + else: + unrolled_outputs = np.zeros(shape=(batch_size, sequence_length, units)) + + # Push the batch 4 times through the LSTM cell and capture the outputs plus + # the final h- and c-states. + for t in range(sequence_length): + input_matrix = x[t, :, :] if time_major else x[:, t, :] + input_matrix = np.concatenate((input_matrix, h_states), axis=1) + input_matmul_matrix = np.matmul(input_matrix, weights) + biases + # Forget gate (3rd slot in tf output matrix). Add static forget bias. + sigmoid_1 = sigmoid(input_matmul_matrix[:, units * 2 : units * 3] + forget_bias) + c_states = np.multiply(c_states, sigmoid_1) + # Add gate (1st and 2nd slots in tf output matrix). + sigmoid_2 = sigmoid(input_matmul_matrix[:, 0:units]) + tanh_3 = np.tanh(input_matmul_matrix[:, units : units * 2]) + c_states = np.add(c_states, np.multiply(sigmoid_2, tanh_3)) + # Output gate (last slot in tf output matrix). + sigmoid_4 = sigmoid(input_matmul_matrix[:, units * 3 : units * 4]) + h_states = np.multiply(sigmoid_4, np.tanh(c_states)) + + # Store this output time-slice. + if time_major: + unrolled_outputs[t, :, :] = h_states + else: + unrolled_outputs[:, t, :] = h_states + + return unrolled_outputs, (c_states, h_states) + + +@PublicAPI +def one_hot( + x: Union[TensorType, int], + depth: int = 0, + on_value: float = 1.0, + off_value: float = 0.0, + dtype: type = np.float32, +) -> np.ndarray: + """One-hot utility function for numpy. + + Thanks to qianyizhang: + https://gist.github.com/qianyizhang/07ee1c15cad08afb03f5de69349efc30. + + Args: + x: The input to be one-hot encoded. + depth: The max. number to be one-hot encoded (size of last rank). + on_value: The value to use for on. Default: 1.0. + off_value: The value to use for off. Default: 0.0. + + Returns: + The one-hot encoded equivalent of the input array. + """ + + # Handle simple ints properly. + if isinstance(x, int): + x = np.array(x, dtype=np.int32) + # Handle torch arrays properly. + elif torch and isinstance(x, torch.Tensor): + x = x.numpy() + + # Handle bool arrays correctly. + if x.dtype == np.bool_: + x = x.astype(np.int_) + depth = 2 + + # If depth is not given, try to infer it from the values in the array. + if depth == 0: + depth = np.max(x) + 1 + assert ( + np.max(x) < depth + ), "ERROR: The max. index of `x` ({}) is larger than depth ({})!".format( + np.max(x), depth + ) + shape = x.shape + + out = np.ones(shape=(*shape, depth)) * off_value + indices = [] + for i in range(x.ndim): + tiles = [1] * x.ndim + s = [1] * x.ndim + s[i] = -1 + r = np.arange(shape[i]).reshape(s) + if i > 0: + tiles[i - 1] = shape[i - 1] + r = np.tile(r, tiles) + indices.append(r) + indices.append(x) + out[tuple(indices)] = on_value + return out.astype(dtype) + + +@PublicAPI +def one_hot_multidiscrete(x, depths=List[int]): + # Handle torch arrays properly. + if torch and isinstance(x, torch.Tensor): + x = x.numpy() + + shape = x.shape + return np.concatenate( + [ + one_hot(x[i] if len(shape) == 1 else x[:, i], depth=n).astype(np.float32) + for i, n in enumerate(depths) + ], + axis=-1, + ) + + +@PublicAPI +def relu(x: np.ndarray, alpha: float = 0.0) -> np.ndarray: + """Implementation of the leaky ReLU function. + + y = x * alpha if x < 0 else x + + Args: + x: The input values. + alpha: A scaling ("leak") factor to use for negative x. + + Returns: + The leaky ReLU output for x. + """ + return np.maximum(x, x * alpha, x) + + +@PublicAPI +def sigmoid(x: np.ndarray, derivative: bool = False) -> np.ndarray: + """ + Returns the sigmoid function applied to x. + Alternatively, can return the derivative or the sigmoid function. + + Args: + x: The input to the sigmoid function. + derivative: Whether to return the derivative or not. + Default: False. + + Returns: + The sigmoid function (or its derivative) applied to x. + """ + if derivative: + return x * (1 - x) + else: + return 1 / (1 + np.exp(-x)) + + +@PublicAPI +def softmax( + x: Union[np.ndarray, list], axis: int = -1, epsilon: Optional[float] = None +) -> np.ndarray: + """Returns the softmax values for x. + + The exact formula used is: + S(xi) = e^xi / SUMj(e^xj), where j goes over all elements in x. + + Args: + x: The input to the softmax function. + axis: The axis along which to softmax. + epsilon: Optional epsilon as a minimum value. If None, use + `SMALL_NUMBER`. + + Returns: + The softmax over x. + """ + epsilon = epsilon or SMALL_NUMBER + # x_exp = np.maximum(np.exp(x), SMALL_NUMBER) + x_exp = np.exp(x) + # return x_exp / + # np.maximum(np.sum(x_exp, axis, keepdims=True), SMALL_NUMBER) + return np.maximum(x_exp / np.sum(x_exp, axis, keepdims=True), epsilon) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/policy.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..a5b6b2ccfda6512fbbd5e148304cecd1859cced6 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/policy.py @@ -0,0 +1,303 @@ +import gymnasium as gym +import logging +import numpy as np +from typing import ( + Callable, + Dict, + List, + Optional, + Tuple, + Type, + Union, + TYPE_CHECKING, +) +import tree # pip install dm_tree + + +import ray.cloudpickle as pickle +from ray.rllib.core.rl_module import validate_module_id +from ray.rllib.models.preprocessors import ATARI_OBS_SHAPE +from ray.rllib.policy.policy import PolicySpec +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.deprecation import Deprecated +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.typing import ( + ActionConnectorDataType, + AgentConnectorDataType, + AgentConnectorsOutput, + PartialAlgorithmConfigDict, + PolicyState, + TensorStructType, + TensorType, +) +from ray.util import log_once + +if TYPE_CHECKING: + from ray.rllib.policy.policy import Policy + +logger = logging.getLogger(__name__) + +tf1, tf, tfv = try_import_tf() + + +@OldAPIStack +def create_policy_for_framework( + policy_id: str, + policy_class: Type["Policy"], + merged_config: PartialAlgorithmConfigDict, + observation_space: gym.Space, + action_space: gym.Space, + worker_index: int = 0, + session_creator: Optional[Callable[[], "tf1.Session"]] = None, + seed: Optional[int] = None, +): + """Framework-specific policy creation logics. + + Args: + policy_id: Policy ID. + policy_class: Policy class type. + merged_config: Complete policy config. + observation_space: Observation space of env. + action_space: Action space of env. + worker_index: Index of worker holding this policy. Default is 0. + session_creator: An optional tf1.Session creation callable. + seed: Optional random seed. + """ + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + + if isinstance(merged_config, AlgorithmConfig): + merged_config = merged_config.to_dict() + + # add policy_id to merged_config + merged_config["__policy_id"] = policy_id + + framework = merged_config.get("framework", "tf") + # Tf. + if framework in ["tf2", "tf"]: + var_scope = policy_id + (f"_wk{worker_index}" if worker_index else "") + # For tf static graph, build every policy in its own graph + # and create a new session for it. + if framework == "tf": + with tf1.Graph().as_default(): + # Session creator function provided manually -> Use this one to + # create the tf1 session. + if session_creator: + sess = session_creator() + # Use a default session creator, based only on our `tf_session_args` in + # the config. + else: + sess = tf1.Session( + config=tf1.ConfigProto(**merged_config["tf_session_args"]) + ) + + with sess.as_default(): + # Set graph-level seed. + if seed is not None: + tf1.set_random_seed(seed) + with tf1.variable_scope(var_scope): + return policy_class( + observation_space, action_space, merged_config + ) + # For tf-eager: no graph, no session. + else: + with tf1.variable_scope(var_scope): + return policy_class(observation_space, action_space, merged_config) + # Non-tf: No graph, no session. + else: + return policy_class(observation_space, action_space, merged_config) + + +@OldAPIStack +def parse_policy_specs_from_checkpoint( + path: str, +) -> Tuple[PartialAlgorithmConfigDict, Dict[str, PolicySpec], Dict[str, PolicyState]]: + """Read and parse policy specifications from a checkpoint file. + + Args: + path: Path to a policy checkpoint. + + Returns: + A tuple of: base policy config, dictionary of policy specs, and + dictionary of policy states. + """ + with open(path, "rb") as f: + checkpoint_dict = pickle.load(f) + # Policy data is contained as a serialized binary blob under their + # ID keys. + w = pickle.loads(checkpoint_dict["worker"]) + + policy_config = w["policy_config"] + policy_states = w.get("policy_states", w["state"]) + serialized_policy_specs = w["policy_specs"] + policy_specs = { + id: PolicySpec.deserialize(spec) for id, spec in serialized_policy_specs.items() + } + + return policy_config, policy_specs, policy_states + + +@OldAPIStack +def local_policy_inference( + policy: "Policy", + env_id: str, + agent_id: str, + obs: TensorStructType, + reward: Optional[float] = None, + terminated: Optional[bool] = None, + truncated: Optional[bool] = None, + info: Optional[Dict] = None, + explore: bool = None, + timestep: Optional[int] = None, +) -> TensorStructType: + """Run a connector enabled policy using environment observation. + + policy_inference manages policy and agent/action connectors, + so the user does not have to care about RNN state buffering or + extra fetch dictionaries. + Note that connectors are intentionally run separately from + compute_actions_from_input_dict(), so we can have the option + of running per-user connectors on the client side in a + server-client deployment. + + Args: + policy: Policy object used in inference. + env_id: Environment ID. RLlib builds environments' trajectories internally with + connectors based on this, i.e. one trajectory per (env_id, agent_id) tuple. + agent_id: Agent ID. RLlib builds agents' trajectories internally with connectors + based on this, i.e. one trajectory per (env_id, agent_id) tuple. + obs: Environment observation to base the action on. + reward: Reward that is potentially used during inference. If not required, + may be left empty. Some policies have ViewRequirements that require this. + This can be set to zero at the first inference step - for example after + calling gmy.Env.reset. + terminated: `Terminated` flag that is potentially used during inference. If not + required, may be left None. Some policies have ViewRequirements that + require this extra information. + truncated: `Truncated` flag that is potentially used during inference. If not + required, may be left None. Some policies have ViewRequirements that + require this extra information. + info: Info that is potentially used durin inference. If not required, + may be left empty. Some policies have ViewRequirements that require this. + explore: Whether to pick an exploitation or exploration action + (default: None -> use self.config["explore"]). + timestep: The current (sampling) time step. + + Returns: + List of outputs from policy forward pass. + """ + assert ( + policy.agent_connectors + ), "policy_inference only works with connector enabled policies." + + __check_atari_obs_space(obs) + + # Put policy in inference mode, so we don't spend time on training + # only transformations. + policy.agent_connectors.in_eval() + policy.action_connectors.in_eval() + + # TODO(jungong) : support multiple env, multiple agent inference. + input_dict = {SampleBatch.NEXT_OBS: obs} + if reward is not None: + input_dict[SampleBatch.REWARDS] = reward + if terminated is not None: + input_dict[SampleBatch.TERMINATEDS] = terminated + if truncated is not None: + input_dict[SampleBatch.TRUNCATEDS] = truncated + if info is not None: + input_dict[SampleBatch.INFOS] = info + + acd_list: List[AgentConnectorDataType] = [ + AgentConnectorDataType(env_id, agent_id, input_dict) + ] + ac_outputs: List[AgentConnectorsOutput] = policy.agent_connectors(acd_list) + outputs = [] + for ac in ac_outputs: + policy_output = policy.compute_actions_from_input_dict( + ac.data.sample_batch, + explore=explore, + timestep=timestep, + ) + + # Note (Kourosh): policy output is batched, the AgentConnectorDataType should + # not be batched during inference. This is the assumption made in AgentCollector + policy_output = tree.map_structure(lambda x: x[0], policy_output) + + action_connector_data = ActionConnectorDataType( + env_id, agent_id, ac.data.raw_dict, policy_output + ) + + if policy.action_connectors: + acd = policy.action_connectors(action_connector_data) + actions = acd.output + else: + actions = policy_output[0] + + outputs.append(actions) + + # Notify agent connectors with this new policy output. + # Necessary for state buffering agent connectors, for example. + policy.agent_connectors.on_policy_output(action_connector_data) + return outputs + + +@OldAPIStack +def compute_log_likelihoods_from_input_dict( + policy: "Policy", batch: Union[SampleBatch, Dict[str, TensorStructType]] +): + """Returns log likelihood for actions in given batch for policy. + + Computes likelihoods by passing the observations through the current + policy's `compute_log_likelihoods()` method + + Args: + batch: The SampleBatch or MultiAgentBatch to calculate action + log likelihoods from. This batch/batches must contain OBS + and ACTIONS keys. + + Returns: + The probabilities of the actions in the batch, given the + observations and the policy. + """ + num_state_inputs = 0 + for k in batch.keys(): + if k.startswith("state_in_"): + num_state_inputs += 1 + state_keys = ["state_in_{}".format(i) for i in range(num_state_inputs)] + log_likelihoods: TensorType = policy.compute_log_likelihoods( + actions=batch[SampleBatch.ACTIONS], + obs_batch=batch[SampleBatch.OBS], + state_batches=[batch[k] for k in state_keys], + prev_action_batch=batch.get(SampleBatch.PREV_ACTIONS), + prev_reward_batch=batch.get(SampleBatch.PREV_REWARDS), + actions_normalized=policy.config.get("actions_in_input_normalized", False), + ) + return log_likelihoods + + +@Deprecated(new="Policy.from_checkpoint([checkpoint path], [policy IDs]?)", error=True) +def load_policies_from_checkpoint(path, policy_ids=None): + pass + + +def __check_atari_obs_space(obs): + # TODO(Artur): Remove this after we have migrated deepmind style preprocessing into + # connectors (and don't auto-wrap in RW anymore) + if any( + o.shape == ATARI_OBS_SHAPE if isinstance(o, np.ndarray) else False + for o in tree.flatten(obs) + ): + if log_once("warn_about_possibly_non_wrapped_atari_env"): + logger.warning( + "The observation you fed into local_policy_inference() has " + "dimensions (210, 160, 3), which is the standard for atari " + "environments. If RLlib raises an error including a related " + "dimensionality mismatch, you may need to use " + "ray.rllib.env.wrappers.atari_wrappers.wrap_deepmind to wrap " + "you environment." + ) + + +# @OldAPIStack +validate_policy_id = validate_module_id diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/serialization.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..30eb1aacc5d466f623d8efbeaaac64dec5787f9a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/serialization.py @@ -0,0 +1,418 @@ +import base64 +from collections import OrderedDict +import importlib +import io +import zlib +from typing import Any, Dict, Optional, Sequence, Type, Union + +import gymnasium as gym +import numpy as np + +import ray +from ray.rllib.utils.annotations import DeveloperAPI +from ray.rllib.utils.error import NotSerializable +from ray.rllib.utils.spaces.flexdict import FlexDict +from ray.rllib.utils.spaces.repeated import Repeated +from ray.rllib.utils.spaces.simplex import Simplex + +NOT_SERIALIZABLE = "__not_serializable__" + + +@DeveloperAPI +def convert_numpy_to_python_primitives(obj: Any): + """Convert an object that is a numpy type to a python type. + + If the object is not a numpy type, it is returned unchanged. + + Args: + obj: The object to convert. + """ + if isinstance(obj, np.integer): + return int(obj) + elif isinstance(obj, np.floating): + return float(obj) + elif isinstance(obj, np.bool_): + return bool(obj) + elif isinstance(obj, np.str_): + return str(obj) + elif isinstance(obj, np.ndarray): + ret = obj.tolist() + for i, v in enumerate(ret): + ret[i] = convert_numpy_to_python_primitives(v) + return ret + else: + return obj + + +def _serialize_ndarray(array: np.ndarray) -> str: + """Pack numpy ndarray into Base64 encoded strings for serialization. + + This function uses numpy.save() instead of pickling to ensure + compatibility. + + Args: + array: numpy ndarray. + + Returns: + b64 escaped string. + """ + buf = io.BytesIO() + np.save(buf, array) + return base64.b64encode(zlib.compress(buf.getvalue())).decode("ascii") + + +def _deserialize_ndarray(b64_string: str) -> np.ndarray: + """Unpack b64 escaped string into numpy ndarray. + + This function assumes the unescaped bytes are of npy format. + + Args: + b64_string: Base64 escaped string. + + Returns: + numpy ndarray. + """ + return np.load( + io.BytesIO(zlib.decompress(base64.b64decode(b64_string))), allow_pickle=True + ) + + +@DeveloperAPI +def gym_space_to_dict(space: gym.spaces.Space) -> Dict: + """Serialize a gym Space into a JSON-serializable dict. + + Args: + space: gym.spaces.Space + + Returns: + Serialized JSON string. + """ + if space is None: + return None + + def _box(sp: gym.spaces.Box) -> Dict: + return { + "space": "box", + "low": _serialize_ndarray(sp.low), + "high": _serialize_ndarray(sp.high), + "shape": sp._shape, # shape is a tuple. + "dtype": sp.dtype.str, + } + + def _discrete(sp: gym.spaces.Discrete) -> Dict: + d = { + "space": "discrete", + "n": int(sp.n), + } + # Offset is a relatively new Discrete space feature. + if hasattr(sp, "start"): + d["start"] = int(sp.start) + return d + + def _multi_binary(sp: gym.spaces.MultiBinary) -> Dict: + return { + "space": "multi-binary", + "n": sp.n, + } + + def _multi_discrete(sp: gym.spaces.MultiDiscrete) -> Dict: + return { + "space": "multi-discrete", + "nvec": _serialize_ndarray(sp.nvec), + "dtype": sp.dtype.str, + } + + def _tuple(sp: gym.spaces.Tuple) -> Dict: + return { + "space": "tuple", + "spaces": [gym_space_to_dict(sp) for sp in sp.spaces], + } + + def _dict(sp: gym.spaces.Dict) -> Dict: + return { + "space": "dict", + "spaces": {k: gym_space_to_dict(sp) for k, sp in sp.spaces.items()}, + } + + def _simplex(sp: Simplex) -> Dict: + return { + "space": "simplex", + "shape": sp._shape, # shape is a tuple. + "concentration": sp.concentration, + "dtype": sp.dtype.str, + } + + def _repeated(sp: Repeated) -> Dict: + return { + "space": "repeated", + "child_space": gym_space_to_dict(sp.child_space), + "max_len": sp.max_len, + } + + def _flex_dict(sp: FlexDict) -> Dict: + d = { + "space": "flex_dict", + } + for k, s in sp.spaces: + d[k] = gym_space_to_dict(s) + return d + + def _text(sp: "gym.spaces.Text") -> Dict: + # Note (Kourosh): This only works in gym >= 0.25.0 + charset = getattr(sp, "character_set", None) + if charset is None: + charset = getattr(sp, "charset", None) + if charset is None: + raise ValueError( + "Text space must have a character_set or charset attribute" + ) + return { + "space": "text", + "min_length": sp.min_length, + "max_length": sp.max_length, + "charset": charset, + } + + if isinstance(space, gym.spaces.Box): + return _box(space) + elif isinstance(space, gym.spaces.Discrete): + return _discrete(space) + elif isinstance(space, gym.spaces.MultiBinary): + return _multi_binary(space) + elif isinstance(space, gym.spaces.MultiDiscrete): + return _multi_discrete(space) + elif isinstance(space, gym.spaces.Tuple): + return _tuple(space) + elif isinstance(space, gym.spaces.Dict): + return _dict(space) + elif isinstance(space, gym.spaces.Text): + return _text(space) + elif isinstance(space, Simplex): + return _simplex(space) + elif isinstance(space, Repeated): + return _repeated(space) + elif isinstance(space, FlexDict): + return _flex_dict(space) + else: + raise ValueError("Unknown space type for serialization, ", type(space)) + + +@DeveloperAPI +def space_to_dict(space: gym.spaces.Space) -> Dict: + d = {"space": gym_space_to_dict(space)} + if "original_space" in space.__dict__: + d["original_space"] = space_to_dict(space.original_space) + return d + + +@DeveloperAPI +def gym_space_from_dict(d: Dict) -> gym.spaces.Space: + """De-serialize a dict into gym Space. + + Args: + str: serialized JSON str. + + Returns: + De-serialized gym space. + """ + if d is None: + return None + + def __common(d: Dict): + """Common updates to the dict before we use it to construct spaces""" + ret = d.copy() + del ret["space"] + if "dtype" in ret: + ret["dtype"] = np.dtype(ret["dtype"]) + return ret + + def _box(d: Dict) -> gym.spaces.Box: + ret = d.copy() + ret.update( + { + "low": _deserialize_ndarray(d["low"]), + "high": _deserialize_ndarray(d["high"]), + } + ) + return gym.spaces.Box(**__common(ret)) + + def _discrete(d: Dict) -> gym.spaces.Discrete: + return gym.spaces.Discrete(**__common(d)) + + def _multi_binary(d: Dict) -> gym.spaces.MultiBinary: + return gym.spaces.MultiBinary(**__common(d)) + + def _multi_discrete(d: Dict) -> gym.spaces.MultiDiscrete: + ret = d.copy() + ret.update( + { + "nvec": _deserialize_ndarray(ret["nvec"]), + } + ) + return gym.spaces.MultiDiscrete(**__common(ret)) + + def _tuple(d: Dict) -> gym.spaces.Discrete: + spaces = [gym_space_from_dict(sp) for sp in d["spaces"]] + return gym.spaces.Tuple(spaces=spaces) + + def _dict(d: Dict) -> gym.spaces.Discrete: + # We need to always use an OrderedDict here to cover the following two ways, by + # which a user might construct a Dict space originally. We need to restore this + # original Dict space with the exact order of keys the user intended to. + # - User provides an OrderedDict inside the gym.spaces.Dict constructor -> + # gymnasium should NOT further sort the keys. The same (user-provided) order + # must be restored. + # - User provides a simple dict inside the gym.spaces.Dict constructor -> + # By its API definition, gymnasium automatically sorts all keys alphabetically. + # The same (alphabetical) order must thus be restored. + spaces = OrderedDict( + {k: gym_space_from_dict(sp) for k, sp in d["spaces"].items()} + ) + return gym.spaces.Dict(spaces=spaces) + + def _simplex(d: Dict) -> Simplex: + return Simplex(**__common(d)) + + def _repeated(d: Dict) -> Repeated: + child_space = gym_space_from_dict(d["child_space"]) + return Repeated(child_space=child_space, max_len=d["max_len"]) + + def _flex_dict(d: Dict) -> FlexDict: + spaces = {k: gym_space_from_dict(s) for k, s in d.items() if k != "space"} + return FlexDict(spaces=spaces) + + def _text(d: Dict) -> "gym.spaces.Text": + return gym.spaces.Text(**__common(d)) + + space_map = { + "box": _box, + "discrete": _discrete, + "multi-binary": _multi_binary, + "multi-discrete": _multi_discrete, + "tuple": _tuple, + "dict": _dict, + "simplex": _simplex, + "repeated": _repeated, + "flex_dict": _flex_dict, + "text": _text, + } + + space_type = d["space"] + if space_type not in space_map: + raise ValueError("Unknown space type for de-serialization, ", space_type) + + return space_map[space_type](d) + + +@DeveloperAPI +def space_from_dict(d: Dict) -> gym.spaces.Space: + space = gym_space_from_dict(d["space"]) + if "original_space" in d: + assert "space" in d["original_space"] + if isinstance(d["original_space"]["space"], str): + # For backward compatibility reasons, if d["original_space"]["space"] + # is a string, this original space was serialized by gym_space_to_dict. + space.original_space = gym_space_from_dict(d["original_space"]) + else: + # Otherwise, this original space was serialized by space_to_dict. + space.original_space = space_from_dict(d["original_space"]) + return space + + +@DeveloperAPI +def check_if_args_kwargs_serializable(args: Sequence[Any], kwargs: Dict[str, Any]): + """Check if parameters to a function are serializable by ray. + + Args: + args: arguments to be checked. + kwargs: keyword arguments to be checked. + + Raises: + NoteSerializable if either args are kwargs are not serializable + by ray. + """ + for arg in args: + try: + # if the object is truly serializable we should be able to + # ray.put and ray.get it. + ray.get(ray.put(arg)) + except TypeError as e: + raise NotSerializable( + "RLModule constructor arguments must be serializable. " + f"Found non-serializable argument: {arg}.\n" + f"Original serialization error: {e}" + ) + for k, v in kwargs.items(): + try: + # if the object is truly serializable we should be able to + # ray.put and ray.get it. + ray.get(ray.put(v)) + except TypeError as e: + raise NotSerializable( + "RLModule constructor arguments must be serializable. " + f"Found non-serializable keyword argument: {k} = {v}.\n" + f"Original serialization error: {e}" + ) + + +@DeveloperAPI +def serialize_type(type_: Union[Type, str]) -> str: + """Converts a type into its full classpath ([module file] + "." + [class name]). + + Args: + type_: The type to convert. + + Returns: + The full classpath of the given type, e.g. "ray.rllib.algorithms.ppo.PPOConfig". + """ + # TODO (avnishn): find a way to incorporate the tune registry here. + # Already serialized. + if isinstance(type_, str): + return type_ + + return type_.__module__ + "." + type_.__qualname__ + + +@DeveloperAPI +def deserialize_type( + module: Union[str, Type], error: bool = False +) -> Optional[Union[str, Type]]: + """Resolves a class path to a class. + If the given module is already a class, it is returned as is. + If the given module is a string, it is imported and the class is returned. + + Args: + module: The classpath (str) or type to resolve. + error: Whether to throw a ValueError if `module` could not be resolved into + a class. If False and `module` is not resolvable, returns None. + + Returns: + The resolved class or `module` (if `error` is False and no resolution possible). + + Raises: + ValueError: If `error` is True and `module` cannot be resolved. + """ + # Already a class, return as-is. + if isinstance(module, type): + return module + # A string. + elif isinstance(module, str): + # Try interpreting (as classpath) and importing the given module. + try: + module_path, class_name = module.rsplit(".", 1) + module = importlib.import_module(module_path) + return getattr(module, class_name) + # Module not found OR not a module (but a registered string?). + except (ModuleNotFoundError, ImportError, AttributeError, ValueError) as e: + # Ignore if error=False. + if error: + raise ValueError( + f"Could not deserialize the given classpath `module={module}` into " + "a valid python class! Make sure you have all necessary pip " + "packages installed and all custom modules are in your " + "`PYTHONPATH` env variable." + ) from e + else: + raise ValueError(f"`module` ({module} must be type or string (classpath)!") + + return module diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/sgd.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/sgd.py new file mode 100644 index 0000000000000000000000000000000000000000..3e126c0a2f450147d9d3f9653ae0b320da778ac7 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/sgd.py @@ -0,0 +1,136 @@ +"""Utils for minibatch SGD across multiple RLlib policies.""" + +import logging +import numpy as np +import random + +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.policy.sample_batch import SampleBatch, MultiAgentBatch +from ray.rllib.utils.metrics.learner_info import LearnerInfoBuilder + +logger = logging.getLogger(__name__) + + +@OldAPIStack +def standardized(array: np.ndarray): + """Normalize the values in an array. + + Args: + array (np.ndarray): Array of values to normalize. + + Returns: + array with zero mean and unit standard deviation. + """ + return (array - array.mean()) / max(1e-4, array.std()) + + +@OldAPIStack +def minibatches(samples: SampleBatch, sgd_minibatch_size: int, shuffle: bool = True): + """Return a generator yielding minibatches from a sample batch. + + Args: + samples: SampleBatch to split up. + sgd_minibatch_size: Size of minibatches to return. + shuffle: Whether to shuffle the order of the generated minibatches. + Note that in case of a non-recurrent policy, the incoming batch + is globally shuffled first regardless of this setting, before + the minibatches are generated from it! + + Yields: + SampleBatch: Each of size `sgd_minibatch_size`. + """ + if not sgd_minibatch_size: + yield samples + return + + if isinstance(samples, MultiAgentBatch): + raise NotImplementedError( + "Minibatching not implemented for multi-agent in simple mode" + ) + + if "state_in_0" not in samples and "state_out_0" not in samples: + samples.shuffle() + + all_slices = samples._get_slice_indices(sgd_minibatch_size) + data_slices, state_slices = all_slices + + if len(state_slices) == 0: + if shuffle: + random.shuffle(data_slices) + for i, j in data_slices: + yield samples[i:j] + else: + all_slices = list(zip(data_slices, state_slices)) + if shuffle: + # Make sure to shuffle data and states while linked together. + random.shuffle(all_slices) + for (i, j), (si, sj) in all_slices: + yield samples.slice(i, j, si, sj) + + +@OldAPIStack +def do_minibatch_sgd( + samples, + policies, + local_worker, + num_sgd_iter, + sgd_minibatch_size, + standardize_fields, +): + """Execute minibatch SGD. + + Args: + samples: Batch of samples to optimize. + policies: Dictionary of policies to optimize. + local_worker: Master rollout worker instance. + num_sgd_iter: Number of epochs of optimization to take. + sgd_minibatch_size: Size of minibatches to use for optimization. + standardize_fields: List of sample field names that should be + normalized prior to optimization. + + Returns: + averaged info fetches over the last SGD epoch taken. + """ + + # Handle everything as if multi-agent. + samples = samples.as_multi_agent() + + # Use LearnerInfoBuilder as a unified way to build the final + # results dict from `learn_on_loaded_batch` call(s). + # This makes sure results dicts always have the same structure + # no matter the setup (multi-GPU, multi-agent, minibatch SGD, + # tf vs torch). + learner_info_builder = LearnerInfoBuilder(num_devices=1) + for policy_id, policy in policies.items(): + if policy_id not in samples.policy_batches: + continue + + batch = samples.policy_batches[policy_id] + for field in standardize_fields: + batch[field] = standardized(batch[field]) + + # Check to make sure that the sgd_minibatch_size is not smaller + # than max_seq_len otherwise this will cause indexing errors while + # performing sgd when using a RNN or Attention model + if ( + policy.is_recurrent() + and policy.config["model"]["max_seq_len"] > sgd_minibatch_size + ): + raise ValueError( + "`sgd_minibatch_size` ({}) cannot be smaller than" + "`max_seq_len` ({}).".format( + sgd_minibatch_size, policy.config["model"]["max_seq_len"] + ) + ) + + for i in range(num_sgd_iter): + for minibatch in minibatches(batch, sgd_minibatch_size): + results = ( + local_worker.learn_on_batch( + MultiAgentBatch({policy_id: minibatch}, minibatch.count) + ) + )[policy_id] + learner_info_builder.add_learn_on_batch_results(results, policy_id) + + learner_info = learner_info_builder.finalize() + return learner_info diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/tensor_dtype.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/tensor_dtype.py new file mode 100644 index 0000000000000000000000000000000000000000..83677d80a46a8048011863f65cf8b851d12dbd9e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/tensor_dtype.py @@ -0,0 +1,65 @@ +import numpy as np + +from ray.rllib.utils.typing import TensorType +from ray.rllib.utils.framework import try_import_torch, try_import_tf +from ray.util.annotations import DeveloperAPI + +torch, _ = try_import_torch() +_, tf, _ = try_import_tf() + + +# Dict of NumPy dtype -> torch dtype +if torch: + numpy_to_torch_dtype_dict = { + np.bool_: torch.bool, + np.uint8: torch.uint8, + np.int8: torch.int8, + np.int16: torch.int16, + np.int32: torch.int32, + np.int64: torch.int64, + np.float16: torch.float16, + np.float32: torch.float32, + np.float64: torch.float64, + np.complex64: torch.complex64, + np.complex128: torch.complex128, + } +else: + numpy_to_torch_dtype_dict = {} + +# Dict of NumPy dtype -> tf dtype +if tf: + numpy_to_tf_dtype_dict = { + np.bool_: tf.bool, + np.uint8: tf.uint8, + np.int8: tf.int8, + np.int16: tf.int16, + np.int32: tf.int32, + np.int64: tf.int64, + np.float16: tf.float16, + np.float32: tf.float32, + np.float64: tf.float64, + np.complex64: tf.complex64, + np.complex128: tf.complex128, + } +else: + numpy_to_tf_dtype_dict = {} + +# Dict of torch dtype -> NumPy dtype +torch_to_numpy_dtype_dict = { + value: key for (key, value) in numpy_to_torch_dtype_dict.items() +} +# Dict of tf dtype -> NumPy dtype +tf_to_numpy_dtype_dict = {value: key for (key, value) in numpy_to_tf_dtype_dict.items()} + + +@DeveloperAPI +def get_np_dtype(x: TensorType) -> np.dtype: + """Returns the NumPy dtype of the given tensor or array.""" + if torch and isinstance(x, torch.Tensor): + return torch_to_numpy_dtype_dict[x.dtype] + if tf and isinstance(x, tf.Tensor): + return tf_to_numpy_dtype_dict[x.dtype] + elif isinstance(x, np.ndarray): + return x.dtype + else: + raise TypeError("Unsupported type: {}".format(type(x))) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/test_utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2ca0547d73ee36872428d197dbd1d755bb0a6b9c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/test_utils.py @@ -0,0 +1,1917 @@ +import argparse +import json +import logging +import os +import pprint +import random +import re +import time +from typing import ( + TYPE_CHECKING, + Any, + Dict, + List, + Optional, + Tuple, + Type, + Union, +) + +import gymnasium as gym +from gymnasium.spaces import Box, Discrete, MultiDiscrete, MultiBinary +from gymnasium.spaces import Dict as GymDict +from gymnasium.spaces import Tuple as GymTuple +import numpy as np +import tree # pip install dm_tree + +import ray +from ray import tune +from ray.air.integrations.wandb import WandbLoggerCallback, WANDB_ENV_VAR +from ray.rllib.core import DEFAULT_MODULE_ID, Columns +from ray.rllib.env.wrappers.atari_wrappers import is_atari, wrap_deepmind +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.framework import try_import_jax, try_import_tf, try_import_torch +from ray.rllib.utils.metrics import ( + DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY, + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + EVALUATION_RESULTS, + NUM_ENV_STEPS_TRAINED, + NUM_ENV_STEPS_SAMPLED_LIFETIME, +) +from ray.rllib.utils.typing import ResultDict +from ray.rllib.utils.error import UnsupportedSpaceException +from ray.tune import CLIReporter +from ray.tune.result import TRAINING_ITERATION + +if TYPE_CHECKING: + from ray.rllib.algorithms import Algorithm, AlgorithmConfig + from ray.rllib.offline.dataset_reader import DatasetReader + +jax, _ = try_import_jax() +tf1, tf, tfv = try_import_tf() +torch, _ = try_import_torch() + +logger = logging.getLogger(__name__) + + +def add_rllib_example_script_args( + parser: Optional[argparse.ArgumentParser] = None, + default_reward: float = 100.0, + default_iters: int = 200, + default_timesteps: int = 100000, +) -> argparse.ArgumentParser: + """Adds RLlib-typical (and common) examples scripts command line args to a parser. + + TODO (sven): This function should be used by most of our examples scripts, which + already mostly have this logic in them (but written out). + + Args: + parser: The parser to add the arguments to. If None, create a new one. + default_reward: The default value for the --stop-reward option. + default_iters: The default value for the --stop-iters option. + default_timesteps: The default value for the --stop-timesteps option. + + Returns: + The altered (or newly created) parser object. + """ + if parser is None: + parser = argparse.ArgumentParser() + + # Algo and Algo config options. + parser.add_argument( + "--algo", type=str, default="PPO", help="The RLlib-registered algorithm to use." + ) + parser.add_argument( + "--framework", + choices=["tf", "tf2", "torch"], + default="torch", + help="The DL framework specifier.", + ) + parser.add_argument( + "--env", + type=str, + default=None, + help="The gym.Env identifier to run the experiment with.", + ) + parser.add_argument( + "--num-env-runners", + type=int, + default=None, + help="The number of (remote) EnvRunners to use for the experiment.", + ) + parser.add_argument( + "--num-envs-per-env-runner", + type=int, + default=None, + help="The number of (vectorized) environments per EnvRunner. Note that " + "this is identical to the batch size for (inference) action computations.", + ) + parser.add_argument( + "--num-agents", + type=int, + default=0, + help="If 0 (default), will run as single-agent. If > 0, will run as " + "multi-agent with the environment simply cloned n times and each agent acting " + "independently at every single timestep. The overall reward for this " + "experiment is then the sum over all individual agents' rewards.", + ) + + # Evaluation options. + parser.add_argument( + "--evaluation-num-env-runners", + type=int, + default=0, + help="The number of evaluation (remote) EnvRunners to use for the experiment.", + ) + parser.add_argument( + "--evaluation-interval", + type=int, + default=0, + help="Every how many iterations to run one round of evaluation. " + "Use 0 (default) to disable evaluation.", + ) + parser.add_argument( + "--evaluation-duration", + type=lambda v: v if v == "auto" else int(v), + default=10, + help="The number of evaluation units to run each evaluation round. " + "Use `--evaluation-duration-unit` to count either in 'episodes' " + "or 'timesteps'. If 'auto', will run as many as possible during train pass (" + "`--evaluation-parallel-to-training` must be set then).", + ) + parser.add_argument( + "--evaluation-duration-unit", + type=str, + default="episodes", + choices=["episodes", "timesteps"], + help="The evaluation duration unit to count by. One of 'episodes' or " + "'timesteps'. This unit will be run `--evaluation-duration` times in each " + "evaluation round. If `--evaluation-duration=auto`, this setting does not " + "matter.", + ) + parser.add_argument( + "--evaluation-parallel-to-training", + action="store_true", + help="Whether to run evaluation parallel to training. This might help speed up " + "your overall iteration time. Be aware that when using this option, your " + "reported evaluation results are referring to one iteration before the current " + "one.", + ) + + # RLlib logging options. + parser.add_argument( + "--output", + type=str, + default=None, + help="The output directory to write trajectories to, which are collected by " + "the algo's EnvRunners.", + ) + parser.add_argument( + "--log-level", + type=str, + default=None, # None -> use default + choices=["INFO", "DEBUG", "WARN", "ERROR"], + help="The log-level to be used by the RLlib logger.", + ) + + # tune.Tuner options. + parser.add_argument( + "--no-tune", + action="store_true", + help="Whether to NOT use tune.Tuner(), but rather a simple for-loop calling " + "`algo.train()` repeatedly until one of the stop criteria is met.", + ) + parser.add_argument( + "--num-samples", + type=int, + default=1, + help="How many (tune.Tuner.fit()) experiments to execute - if possible in " + "parallel.", + ) + parser.add_argument( + "--max-concurrent-trials", + type=int, + default=None, + help="How many (tune.Tuner) trials to run concurrently.", + ) + parser.add_argument( + "--verbose", + type=int, + default=2, + help="The verbosity level for the `tune.Tuner()` running the experiment.", + ) + parser.add_argument( + "--checkpoint-freq", + type=int, + default=0, + help=( + "The frequency (in training iterations) with which to create checkpoints. " + "Note that if --wandb-key is provided, all checkpoints will " + "automatically be uploaded to WandB." + ), + ) + parser.add_argument( + "--checkpoint-at-end", + action="store_true", + help=( + "Whether to create a checkpoint at the very end of the experiment. " + "Note that if --wandb-key is provided, all checkpoints will " + "automatically be uploaded to WandB." + ), + ) + + # WandB logging options. + parser.add_argument( + "--wandb-key", + type=str, + default=None, + help="The WandB API key to use for uploading results.", + ) + parser.add_argument( + "--wandb-project", + type=str, + default=None, + help="The WandB project name to use.", + ) + parser.add_argument( + "--wandb-run-name", + type=str, + default=None, + help="The WandB run name to use.", + ) + + # Experiment stopping and testing criteria. + parser.add_argument( + "--stop-reward", + type=float, + default=default_reward, + help="Reward at which the script should stop training.", + ) + parser.add_argument( + "--stop-iters", + type=int, + default=default_iters, + help="The number of iterations to train.", + ) + parser.add_argument( + "--stop-timesteps", + type=int, + default=default_timesteps, + help="The number of (environment sampling) timesteps to train.", + ) + parser.add_argument( + "--as-test", + action="store_true", + help="Whether this script should be run as a test. If set, --stop-reward must " + "be achieved within --stop-timesteps AND --stop-iters, otherwise this " + "script will throw an exception at the end.", + ) + parser.add_argument( + "--as-release-test", + action="store_true", + help="Whether this script should be run as a release test. If set, " + "all that applies to the --as-test option is true, plus, a short JSON summary " + "will be written into a results file whose location is given by the ENV " + "variable `TEST_OUTPUT_JSON`.", + ) + + # Learner scaling options. + parser.add_argument( + "--num-learners", + type=int, + default=None, + help="The number of Learners to use. If `None`, use the algorithm's default " + "value.", + ) + parser.add_argument( + "--num-cpus-per-learner", + type=float, + default=None, + help="The number of CPUs per Learner to use. If `None`, use the algorithm's " + "default value.", + ) + parser.add_argument( + "--num-gpus-per-learner", + type=float, + default=None, + help="The number of GPUs per Learner to use. If `None` and there are enough " + "GPUs for all required Learners (--num-learners), use a value of 1, " + "otherwise 0.", + ) + parser.add_argument( + "--num-aggregator-actors-per-learner", + type=int, + default=None, + help="The number of Aggregator actors to use per Learner. If `None`, use the " + "algorithm's default value.", + ) + + # Ray init options. + parser.add_argument("--num-cpus", type=int, default=0) + parser.add_argument( + "--local-mode", + action="store_true", + help="Init Ray in local mode for easier debugging.", + ) + + # Old API stack: config.num_gpus. + parser.add_argument( + "--num-gpus", + type=int, + default=None, + help="The number of GPUs to use (only on the old API stack).", + ) + parser.add_argument( + "--old-api-stack", + action="store_true", + help="Run this script on the old API stack of RLlib.", + ) + + # Deprecated options. Throws error when still used. Use `--old-api-stack` for + # disabling the new API stack. + parser.add_argument( + "--enable-new-api-stack", + action="store_true", + ) + + return parser + + +def check(x, y, decimals=5, atol=None, rtol=None, false=False): + """ + Checks two structures (dict, tuple, list, + np.array, float, int, etc..) for (almost) numeric identity. + All numbers in the two structures have to match up to `decimal` digits + after the floating point. Uses assertions. + + Args: + x: The value to be compared (to the expectation: `y`). This + may be a Tensor. + y: The expected value to be compared to `x`. This must not + be a tf-Tensor, but may be a tf/torch-Tensor. + decimals: The number of digits after the floating point up to + which all numeric values have to match. + atol: Absolute tolerance of the difference between x and y + (overrides `decimals` if given). + rtol: Relative tolerance of the difference between x and y + (overrides `decimals` if given). + false: Whether to check that x and y are NOT the same. + """ + # A dict type. + if isinstance(x, dict): + assert isinstance(y, dict), "ERROR: If x is dict, y needs to be a dict as well!" + y_keys = set(x.keys()) + for key, value in x.items(): + assert key in y, f"ERROR: y does not have x's key='{key}'! y={y}" + check(value, y[key], decimals=decimals, atol=atol, rtol=rtol, false=false) + y_keys.remove(key) + assert not y_keys, "ERROR: y contains keys ({}) that are not in x! y={}".format( + list(y_keys), y + ) + # A tuple type. + elif isinstance(x, (tuple, list)): + assert isinstance( + y, (tuple, list) + ), "ERROR: If x is tuple/list, y needs to be a tuple/list as well!" + assert len(y) == len( + x + ), "ERROR: y does not have the same length as x ({} vs {})!".format( + len(y), len(x) + ) + for i, value in enumerate(x): + check(value, y[i], decimals=decimals, atol=atol, rtol=rtol, false=false) + # Boolean comparison. + elif isinstance(x, (np.bool_, bool)): + if false is True: + assert bool(x) is not bool(y), f"ERROR: x ({x}) is y ({y})!" + else: + assert bool(x) is bool(y), f"ERROR: x ({x}) is not y ({y})!" + # Nones or primitives (excluding int vs float, which should be compared with + # tolerance/decimals as well). + elif ( + x is None + or y is None + or isinstance(x, str) + or (isinstance(x, int) and isinstance(y, int)) + ): + if false is True: + assert x != y, f"ERROR: x ({x}) is the same as y ({y})!" + else: + assert x == y, f"ERROR: x ({x}) is not the same as y ({y})!" + # String/byte comparisons. + elif ( + hasattr(x, "dtype") and (x.dtype == object or str(x.dtype).startswith(" raise error (not expected to be equal). + if false is True: + assert False, f"ERROR: x ({x}) is the same as y ({y})!" + + # Using atol/rtol. + else: + # Provide defaults for either one of atol/rtol. + if atol is None: + atol = 0 + if rtol is None: + rtol = 1e-7 + try: + np.testing.assert_allclose(x, y, atol=atol, rtol=rtol) + except AssertionError as e: + if false is False: + raise e + else: + if false is True: + assert False, f"ERROR: x ({x}) is the same as y ({y})!" + + +def check_compute_single_action( + algorithm, include_state=False, include_prev_action_reward=False +): + """Tests different combinations of args for algorithm.compute_single_action. + + Args: + algorithm: The Algorithm object to test. + include_state: Whether to include the initial state of the Policy's + Model in the `compute_single_action` call. + include_prev_action_reward: Whether to include the prev-action and + -reward in the `compute_single_action` call. + + Raises: + ValueError: If anything unexpected happens. + """ + # Have to import this here to avoid circular dependency. + from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID, SampleBatch + + # Some Algorithms may not abide to the standard API. + pid = DEFAULT_POLICY_ID + try: + # Multi-agent: Pick any learnable policy (or DEFAULT_POLICY if it's the only + # one). + pid = next(iter(algorithm.env_runner.get_policies_to_train())) + pol = algorithm.get_policy(pid) + except AttributeError: + pol = algorithm.policy + # Get the policy's model. + model = pol.model + + action_space = pol.action_space + + def _test( + what, method_to_test, obs_space, full_fetch, explore, timestep, unsquash, clip + ): + call_kwargs = {} + if what is algorithm: + call_kwargs["full_fetch"] = full_fetch + call_kwargs["policy_id"] = pid + + obs = obs_space.sample() + if isinstance(obs_space, Box): + obs = np.clip(obs, -1.0, 1.0) + state_in = None + if include_state: + state_in = model.get_initial_state() + if not state_in: + state_in = [] + i = 0 + while f"state_in_{i}" in model.view_requirements: + state_in.append( + model.view_requirements[f"state_in_{i}"].space.sample() + ) + i += 1 + action_in = action_space.sample() if include_prev_action_reward else None + reward_in = 1.0 if include_prev_action_reward else None + + if method_to_test == "input_dict": + assert what is pol + + input_dict = {SampleBatch.OBS: obs} + if include_prev_action_reward: + input_dict[SampleBatch.PREV_ACTIONS] = action_in + input_dict[SampleBatch.PREV_REWARDS] = reward_in + if state_in: + if what.config.get("enable_rl_module_and_learner", False): + input_dict["state_in"] = state_in + else: + for i, s in enumerate(state_in): + input_dict[f"state_in_{i}"] = s + input_dict_batched = SampleBatch( + tree.map_structure(lambda s: np.expand_dims(s, 0), input_dict) + ) + action = pol.compute_actions_from_input_dict( + input_dict=input_dict_batched, + explore=explore, + timestep=timestep, + **call_kwargs, + ) + # Unbatch everything to be able to compare against single + # action below. + # ARS and ES return action batches as lists. + if isinstance(action[0], list): + action = (np.array(action[0]), action[1], action[2]) + action = tree.map_structure(lambda s: s[0], action) + + try: + action2 = pol.compute_single_action( + input_dict=input_dict, + explore=explore, + timestep=timestep, + **call_kwargs, + ) + # Make sure these are the same, unless we have exploration + # switched on (or noisy layers). + if not explore and not pol.config.get("noisy"): + check(action, action2) + except TypeError: + pass + else: + action = what.compute_single_action( + obs, + state_in, + prev_action=action_in, + prev_reward=reward_in, + explore=explore, + timestep=timestep, + unsquash_action=unsquash, + clip_action=clip, + **call_kwargs, + ) + + state_out = None + if state_in or full_fetch or what is pol: + action, state_out, _ = action + if state_out: + for si, so in zip(tree.flatten(state_in), tree.flatten(state_out)): + if tf.is_tensor(si): + # If si is a tensor of Dimensions, we need to convert it + # We expect this to be the case for TF RLModules who's initial + # states are Tf Tensors. + si_shape = si.shape.as_list() + else: + si_shape = list(si.shape) + check(si_shape, so.shape) + + if unsquash is None: + unsquash = what.config["normalize_actions"] + if clip is None: + clip = what.config["clip_actions"] + + # Test whether unsquash/clipping works on the Algorithm's + # compute_single_action method: Both flags should force the action + # to be within the space's bounds. + if method_to_test == "single" and what == algorithm: + if not action_space.contains(action) and ( + clip or unsquash or not isinstance(action_space, Box) + ): + raise ValueError( + f"Returned action ({action}) of algorithm/policy {what} " + f"not in Env's action_space {action_space}" + ) + # We are operating in normalized space: Expect only smaller action + # values. + if ( + isinstance(action_space, Box) + and not unsquash + and what.config.get("normalize_actions") + and np.any(np.abs(action) > 15.0) + ): + raise ValueError( + f"Returned action ({action}) of algorithm/policy {what} " + "should be in normalized space, but seems too large/small " + "for that!" + ) + + # Loop through: Policy vs Algorithm; Different API methods to calculate + # actions; unsquash option; clip option; full fetch or not. + for what in [pol, algorithm]: + if what is algorithm: + # Get the obs-space from Workers.env (not Policy) due to possible + # pre-processor up front. + worker_set = getattr(algorithm, "env_runner_group", None) + assert worker_set + if not worker_set.local_env_runner: + obs_space = algorithm.get_policy(pid).observation_space + else: + obs_space = worker_set.local_env_runner.for_policy( + lambda p: p.observation_space, policy_id=pid + ) + obs_space = getattr(obs_space, "original_space", obs_space) + else: + obs_space = pol.observation_space + + for method_to_test in ["single"] + (["input_dict"] if what is pol else []): + for explore in [True, False]: + for full_fetch in [False, True] if what is algorithm else [False]: + timestep = random.randint(0, 100000) + for unsquash in [True, False, None]: + for clip in [False] if unsquash else [True, False, None]: + print("-" * 80) + print(f"what={what}") + print(f"method_to_test={method_to_test}") + print(f"explore={explore}") + print(f"full_fetch={full_fetch}") + print(f"unsquash={unsquash}") + print(f"clip={clip}") + _test( + what, + method_to_test, + obs_space, + full_fetch, + explore, + timestep, + unsquash, + clip, + ) + + +def check_inference_w_connectors(policy, env_name, max_steps: int = 100): + """Checks whether the given policy can infer actions from an env with connectors. + + Args: + policy: The policy to check. + env_name: Name of the environment to check + max_steps: The maximum number of steps to run the environment for. + + Raises: + ValueError: If the policy cannot infer actions from the environment. + """ + # Avoids circular import + from ray.rllib.utils.policy import local_policy_inference + + env = gym.make(env_name) + + # Potentially wrap the env like we do in RolloutWorker + if is_atari(env): + env = wrap_deepmind( + env, + dim=policy.config["model"]["dim"], + framestack=policy.config["model"].get("framestack"), + ) + + obs, info = env.reset() + reward, terminated, truncated = 0.0, False, False + ts = 0 + while not terminated and not truncated and ts < max_steps: + action_out = local_policy_inference( + policy, + env_id=0, + agent_id=0, + obs=obs, + reward=reward, + terminated=terminated, + truncated=truncated, + info=info, + ) + obs, reward, terminated, truncated, info = env.step(action_out[0][0]) + + ts += 1 + + +def check_learning_achieved( + tune_results: "tune.ResultGrid", + min_value: float, + evaluation: Optional[bool] = None, + metric: str = f"{ENV_RUNNER_RESULTS}/episode_return_mean", +): + """Throws an error if `min_reward` is not reached within tune_results. + + Checks the last iteration found in tune_results for its + "episode_return_mean" value and compares it to `min_reward`. + + Args: + tune_results: The tune.Tuner().fit() returned results object. + min_reward: The min reward that must be reached. + evaluation: If True, use `evaluation/env_runners/[metric]`, if False, use + `env_runners/[metric]`, if None, use evaluation sampler results if + available otherwise, use train sampler results. + + Raises: + ValueError: If `min_reward` not reached. + """ + # Get maximum value of `metrics` over all trials + # (check if at least one trial achieved some learning, not just the final one). + recorded_values = [] + for _, row in tune_results.get_dataframe().iterrows(): + if evaluation or ( + evaluation is None and f"{EVALUATION_RESULTS}/{metric}" in row + ): + recorded_values.append(row[f"{EVALUATION_RESULTS}/{metric}"]) + else: + recorded_values.append(row[metric]) + best_value = max(recorded_values) + if best_value < min_value: + raise ValueError(f"`{metric}` of {min_value} not reached!") + print(f"`{metric}` of {min_value} reached! ok") + + +def check_off_policyness( + results: ResultDict, + upper_limit: float, + lower_limit: float = 0.0, +) -> Optional[float]: + """Verifies that the off-policy'ness of some update is within some range. + + Off-policy'ness is defined as the average (across n workers) diff + between the number of gradient updates performed on the policy used + for sampling vs the number of gradient updates that have been performed + on the trained policy (usually the one on the local worker). + + Uses the published DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY metric inside + a training results dict and compares to the given bounds. + + Note: Only works with single-agent results thus far. + + Args: + results: The training results dict. + upper_limit: The upper limit to for the off_policy_ness value. + lower_limit: The lower limit to for the off_policy_ness value. + + Returns: + The off-policy'ness value (described above). + + Raises: + AssertionError: If the value is out of bounds. + """ + + # Have to import this here to avoid circular dependency. + from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID + from ray.rllib.utils.metrics.learner_info import LEARNER_INFO + + # Assert that the off-policy'ness is within the given bounds. + learner_info = results["info"][LEARNER_INFO] + if DEFAULT_POLICY_ID not in learner_info: + return None + off_policy_ness = learner_info[DEFAULT_POLICY_ID][ + DIFF_NUM_GRAD_UPDATES_VS_SAMPLER_POLICY + ] + # Roughly: Reaches up to 0.4 for 2 rollout workers and up to 0.2 for + # 1 rollout worker. + if not (lower_limit <= off_policy_ness <= upper_limit): + raise AssertionError( + f"`off_policy_ness` ({off_policy_ness}) is outside the given bounds " + f"({lower_limit} - {upper_limit})!" + ) + + return off_policy_ness + + +def check_train_results_new_api_stack(train_results: ResultDict) -> None: + """Checks proper structure of a Algorithm.train() returned dict. + + Args: + train_results: The train results dict to check. + + Raises: + AssertionError: If `train_results` doesn't have the proper structure or + data in it. + """ + # Import these here to avoid circular dependencies. + from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + FAULT_TOLERANCE_STATS, + LEARNER_RESULTS, + TIMERS, + ) + + # Assert that some keys are where we would expect them. + for key in [ + ENV_RUNNER_RESULTS, + FAULT_TOLERANCE_STATS, + LEARNER_RESULTS, + TIMERS, + TRAINING_ITERATION, + "config", + ]: + assert ( + key in train_results + ), f"'{key}' not found in `train_results` ({train_results})!" + + # Make sure, `config` is an actual dict, not an AlgorithmConfig object. + assert isinstance( + train_results["config"], dict + ), "`config` in results not a python dict!" + + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + + is_multi_agent = ( + AlgorithmConfig() + .update_from_dict({"policies": train_results["config"]["policies"]}) + .is_multi_agent + ) + + # Check in particular the "info" dict. + learner_results = train_results[LEARNER_RESULTS] + + # Make sure we have a `DEFAULT_MODULE_ID key if we are not in a + # multi-agent setup. + if not is_multi_agent: + assert len(learner_results) == 0 or DEFAULT_MODULE_ID in learner_results, ( + f"'{DEFAULT_MODULE_ID}' not found in " + f"train_results['{LEARNER_RESULTS}']!" + ) + + for module_id, module_metrics in learner_results.items(): + # The ModuleID can be __all_modules__ in multi-agent case when the new learner + # stack is enabled. + if module_id == "__all_modules__": + continue + + # On the new API stack, policy has no LEARNER_STATS_KEY under it anymore. + for key, value in module_metrics.items(): + # Min- and max-stats should be single values. + if key.endswith("_min") or key.endswith("_max"): + assert np.isscalar(value), f"'key' value not a scalar ({value})!" + + return train_results + + +@OldAPIStack +def check_train_results(train_results: ResultDict): + """Checks proper structure of a Algorithm.train() returned dict. + + Args: + train_results: The train results dict to check. + + Raises: + AssertionError: If `train_results` doesn't have the proper structure or + data in it. + """ + # Import these here to avoid circular dependencies. + from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID + from ray.rllib.utils.metrics.learner_info import LEARNER_INFO, LEARNER_STATS_KEY + + # Assert that some keys are where we would expect them. + for key in [ + "config", + "custom_metrics", + ENV_RUNNER_RESULTS, + "info", + "iterations_since_restore", + "num_healthy_workers", + "perf", + "time_since_restore", + "time_this_iter_s", + "timers", + "time_total_s", + TRAINING_ITERATION, + ]: + assert ( + key in train_results + ), f"'{key}' not found in `train_results` ({train_results})!" + + for key in [ + "episode_len_mean", + "episode_reward_max", + "episode_reward_mean", + "episode_reward_min", + "hist_stats", + "policy_reward_max", + "policy_reward_mean", + "policy_reward_min", + "sampler_perf", + ]: + assert key in train_results[ENV_RUNNER_RESULTS], ( + f"'{key}' not found in `train_results[ENV_RUNNER_RESULTS]` " + f"({train_results[ENV_RUNNER_RESULTS]})!" + ) + + # Make sure, `config` is an actual dict, not an AlgorithmConfig object. + assert isinstance( + train_results["config"], dict + ), "`config` in results not a python dict!" + + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + + is_multi_agent = ( + AlgorithmConfig() + .update_from_dict({"policies": train_results["config"]["policies"]}) + .is_multi_agent + ) + + # Check in particular the "info" dict. + info = train_results["info"] + assert LEARNER_INFO in info, f"'learner' not in train_results['infos'] ({info})!" + assert ( + "num_steps_trained" in info or NUM_ENV_STEPS_TRAINED in info + ), f"'num_(env_)?steps_trained' not in train_results['infos'] ({info})!" + + learner_info = info[LEARNER_INFO] + + # Make sure we have a default_policy key if we are not in a + # multi-agent setup. + if not is_multi_agent: + # APEX algos sometimes have an empty learner info dict (no metrics + # collected yet). + assert len(learner_info) == 0 or DEFAULT_POLICY_ID in learner_info, ( + f"'{DEFAULT_POLICY_ID}' not found in " + f"train_results['infos']['learner'] ({learner_info})!" + ) + + for pid, policy_stats in learner_info.items(): + if pid == "batch_count": + continue + + # the pid can be __all__ in multi-agent case when the new learner stack is + # enabled. + if pid == "__all__": + continue + + # On the new API stack, policy has no LEARNER_STATS_KEY under it anymore. + if LEARNER_STATS_KEY in policy_stats: + learner_stats = policy_stats[LEARNER_STATS_KEY] + else: + learner_stats = policy_stats + for key, value in learner_stats.items(): + # Min- and max-stats should be single values. + if key.startswith("min_") or key.startswith("max_"): + assert np.isscalar(value), f"'key' value not a scalar ({value})!" + + return train_results + + +# TODO (simon): Use this function in the `run_rllib_example_experiment` when +# `no_tune` is `True`. +def should_stop( + stop: Dict[str, Any], results: ResultDict, keep_ray_up: bool = False +) -> bool: + """Checks stopping criteria on `ResultDict` + + Args: + stop: Dictionary of stopping criteria. Each criterium is a mapping of + a metric in the `ResultDict` of the algorithm to a certain criterium. + results: An RLlib `ResultDict` containing all results from a training step. + keep_ray_up: Optionally shutting down the runnin Ray instance. + + Returns: True, if any stopping criterium is fulfilled. Otherwise, False. + """ + for key, threshold in stop.items(): + val = results + for k in key.split("/"): + k = k.strip() + # If k exists in the current level, continue down; + # otherwise, set val to None and break out of this inner loop. + if isinstance(val, dict) and k in val: + val = val[k] + else: + val = None + break + + # If the key was not found, simply skip to the next criterion. + if val is None: + continue + + try: + # Check that val is numeric and meets the threshold. + if not np.isnan(val) and val >= threshold: + print(f"Stop criterion ({key}={threshold}) fulfilled!") + if not keep_ray_up: + ray.shutdown() + return True + except TypeError: + # If val isn't numeric, skip this criterion. + continue + + # If none of the criteria are fulfilled, return False. + return False + + +# TODO (sven): Make this the de-facto, well documented, and unified utility for most of +# our tests: +# - CI (label: "learning_tests") +# - release tests (benchmarks) +# - example scripts +def run_rllib_example_script_experiment( + base_config: "AlgorithmConfig", + args: Optional[argparse.Namespace] = None, + *, + stop: Optional[Dict] = None, + success_metric: Optional[Dict] = None, + trainable: Optional[Type] = None, + tune_callbacks: Optional[List] = None, + keep_config: bool = False, + keep_ray_up: bool = False, + scheduler=None, + progress_reporter=None, +) -> Union[ResultDict, tune.result_grid.ResultGrid]: + """Given an algorithm config and some command line args, runs an experiment. + + There are some constraints on what properties must be defined in `args`. + It should ideally be generated via calling + `args = add_rllib_example_script_args()`, which can be found in this very module + here. + + The function sets up an Algorithm object from the given config (altered by the + contents of `args`), then runs the Algorithm via Tune (or manually, if + `args.no_tune` is set to True) using the stopping criteria in `stop`. + + At the end of the experiment, if `args.as_test` is True, checks, whether the + Algorithm reached the `success_metric` (if None, use `env_runners/ + episode_return_mean` with a minimum value of `args.stop_reward`). + + See https://github.com/ray-project/ray/tree/master/rllib/examples for an overview + of all supported command line options. + + Args: + base_config: The AlgorithmConfig object to use for this experiment. This base + config will be automatically "extended" based on some of the provided + `args`. For example, `args.num_env_runners` is used to set + `config.num_env_runners`, etc.. + args: A argparse.Namespace object, ideally returned by calling + `args = add_rllib_example_script_args()`. It must have the following + properties defined: `stop_iters`, `stop_reward`, `stop_timesteps`, + `no_tune`, `verbose`, `checkpoint_freq`, `as_test`. Optionally, for WandB + logging: `wandb_key`, `wandb_project`, `wandb_run_name`. + stop: An optional dict mapping ResultDict key strings (using "/" in case of + nesting, e.g. "env_runners/episode_return_mean" for referring to + `result_dict['env_runners']['episode_return_mean']` to minimum + values, reaching of which will stop the experiment). Default is: + { + "env_runners/episode_return_mean": args.stop_reward, + "training_iteration": args.stop_iters, + "num_env_steps_sampled_lifetime": args.stop_timesteps, + } + success_metric: Only relevant if `args.as_test` is True. + A dict mapping a single(!) ResultDict key string (using "/" in + case of nesting, e.g. "env_runners/episode_return_mean" for referring + to `result_dict['env_runners']['episode_return_mean']` to a single(!) + minimum value to be reached in order for the experiment to count as + successful. If `args.as_test` is True AND this `success_metric` is not + reached with the bounds defined by `stop`, will raise an Exception. + trainable: The Trainable sub-class to run in the tune.Tuner. If None (default), + use the registered RLlib Algorithm class specified by args.algo. + tune_callbacks: A list of Tune callbacks to configure with the tune.Tuner. + In case `args.wandb_key` is provided, appends a WandB logger to this + list. + keep_config: Set this to True, if you don't want this utility to change the + given `base_config` in any way and leave it as-is. This is helpful + for those example scripts which demonstrate how to set config settings + that are otherwise taken care of automatically in this function (e.g. + `num_env_runners`). + + Returns: + The last ResultDict from a --no-tune run OR the tune.Tuner.fit() + results. + """ + if args is None: + parser = add_rllib_example_script_args() + args = parser.parse_args() + + # Deprecated args. + if args.enable_new_api_stack: + raise ValueError( + "`--enable-new-api-stack` flag no longer supported (it's the default " + "behavior now)! To switch back to the old API stack on your scripts, use " + "the `--old-api-stack` flag." + ) + + # If run --as-release-test, --as-test must also be set. + if args.as_release_test: + args.as_test = True + + # Initialize Ray. + ray.init( + num_cpus=args.num_cpus or None, + local_mode=args.local_mode, + ignore_reinit_error=True, + ) + + # Define one or more stopping criteria. + if stop is None: + stop = { + f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": args.stop_reward, + f"{ENV_RUNNER_RESULTS}/{NUM_ENV_STEPS_SAMPLED_LIFETIME}": ( + args.stop_timesteps + ), + TRAINING_ITERATION: args.stop_iters, + } + + config = base_config + + # Enhance the `base_config`, based on provided `args`. + if not keep_config: + # Set the framework. + config.framework(args.framework) + + # Add an env specifier (only if not already set in config)? + if args.env is not None and config.env is None: + config.environment(args.env) + + # Disable the new API stack? + if args.old_api_stack: + config.api_stack( + enable_rl_module_and_learner=False, + enable_env_runner_and_connector_v2=False, + ) + + # Define EnvRunner scaling and behavior. + if args.num_env_runners is not None: + config.env_runners(num_env_runners=args.num_env_runners) + if args.num_envs_per_env_runner is not None: + config.env_runners(num_envs_per_env_runner=args.num_envs_per_env_runner) + + # Define compute resources used automatically (only using the --num-learners + # and --num-gpus-per-learner args). + # New stack. + if config.enable_rl_module_and_learner: + if args.num_gpus is not None and args.num_gpus > 0: + raise ValueError( + "--num-gpus is not supported on the new API stack! To train on " + "GPUs, use the command line options `--num-gpus-per-learner=1` and " + "`--num-learners=[your number of available GPUs]`, instead." + ) + + # Do we have GPUs available in the cluster? + num_gpus_available = ray.cluster_resources().get("GPU", 0) + # Number of actual Learner instances (including the local Learner if + # `num_learners=0`). + num_actual_learners = ( + args.num_learners + if args.num_learners is not None + else config.num_learners + ) or 1 # 1: There is always a local Learner, if num_learners=0. + # How many were hard-requested by the user + # (through explicit `--num-gpus-per-learner >= 1`). + num_gpus_requested = (args.num_gpus_per_learner or 0) * num_actual_learners + # Number of GPUs needed, if `num_gpus_per_learner=None` (auto). + num_gpus_needed_if_available = ( + args.num_gpus_per_learner + if args.num_gpus_per_learner is not None + else 1 + ) * num_actual_learners + # Define compute resources used. + config.resources(num_gpus=0) # old API stack setting + if args.num_learners is not None: + config.learners(num_learners=args.num_learners) + + # User wants to use aggregator actors per Learner. + if args.num_aggregator_actors_per_learner is not None: + config.learners( + num_aggregator_actors_per_learner=( + args.num_aggregator_actors_per_learner + ) + ) + + # User wants to use GPUs if available, but doesn't hard-require them. + if args.num_gpus_per_learner is None: + if num_gpus_available >= num_gpus_needed_if_available: + config.learners(num_gpus_per_learner=1) + else: + config.learners(num_gpus_per_learner=0) + # User hard-requires n GPUs, but they are not available -> Error. + elif num_gpus_available < num_gpus_requested: + raise ValueError( + "You are running your script with --num-learners=" + f"{args.num_learners} and --num-gpus-per-learner=" + f"{args.num_gpus_per_learner}, but your cluster only has " + f"{num_gpus_available} GPUs!" + ) + + # All required GPUs are available -> Use them. + else: + config.learners(num_gpus_per_learner=args.num_gpus_per_learner) + + # Set CPUs per Learner. + if args.num_cpus_per_learner is not None: + config.learners(num_cpus_per_learner=args.num_cpus_per_learner) + + # Old stack (override only if arg was provided by user). + elif args.num_gpus is not None: + config.resources(num_gpus=args.num_gpus) + + # Evaluation setup. + if args.evaluation_interval > 0: + config.evaluation( + evaluation_num_env_runners=args.evaluation_num_env_runners, + evaluation_interval=args.evaluation_interval, + evaluation_duration=args.evaluation_duration, + evaluation_duration_unit=args.evaluation_duration_unit, + evaluation_parallel_to_training=args.evaluation_parallel_to_training, + ) + + # Set the log-level (if applicable). + if args.log_level is not None: + config.debugging(log_level=args.log_level) + + # Set the output dir (if applicable). + if args.output is not None: + config.offline_data(output=args.output) + + # Run the experiment w/o Tune (directly operate on the RLlib Algorithm object). + if args.no_tune: + assert not args.as_test and not args.as_release_test + algo = config.build() + for i in range(stop.get(TRAINING_ITERATION, args.stop_iters)): + results = algo.train() + if ENV_RUNNER_RESULTS in results: + mean_return = results[ENV_RUNNER_RESULTS].get( + EPISODE_RETURN_MEAN, np.nan + ) + print(f"iter={i} R={mean_return}", end="") + if ( + EVALUATION_RESULTS in results + and ENV_RUNNER_RESULTS in results[EVALUATION_RESULTS] + ): + Reval = results[EVALUATION_RESULTS][ENV_RUNNER_RESULTS][ + EPISODE_RETURN_MEAN + ] + print(f" R(eval)={Reval}", end="") + print() + for key, threshold in stop.items(): + val = results + for k in key.split("/"): + try: + val = val[k] + except KeyError: + val = None + break + if val is not None and not np.isnan(val) and val >= threshold: + print(f"Stop criterium ({key}={threshold}) fulfilled!") + if not keep_ray_up: + ray.shutdown() + return results + + if not keep_ray_up: + ray.shutdown() + return results + + # Run the experiment using Ray Tune. + + # Log results using WandB. + tune_callbacks = tune_callbacks or [] + if hasattr(args, "wandb_key") and ( + args.wandb_key is not None or WANDB_ENV_VAR in os.environ + ): + wandb_key = args.wandb_key or os.environ[WANDB_ENV_VAR] + project = args.wandb_project or ( + args.algo.lower() + "-" + re.sub("\\W+", "-", str(config.env).lower()) + ) + tune_callbacks.append( + WandbLoggerCallback( + api_key=wandb_key, + project=project, + upload_checkpoints=True, + **({"name": args.wandb_run_name} if args.wandb_run_name else {}), + ) + ) + # Auto-configure a CLIReporter (to log the results to the console). + # Use better ProgressReporter for multi-agent cases: List individual policy rewards. + if progress_reporter is None and args.num_agents > 0: + progress_reporter = CLIReporter( + metric_columns={ + **{ + TRAINING_ITERATION: "iter", + "time_total_s": "total time (s)", + NUM_ENV_STEPS_SAMPLED_LIFETIME: "ts", + f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": "combined return", + }, + **{ + ( + f"{ENV_RUNNER_RESULTS}/module_episode_returns_mean/" f"{pid}" + ): f"return {pid}" + for pid in config.policies + }, + }, + ) + + # Force Tuner to use old progress output as the new one silently ignores our custom + # `CLIReporter`. + os.environ["RAY_AIR_NEW_OUTPUT"] = "0" + + # Run the actual experiment (using Tune). + start_time = time.time() + results = tune.Tuner( + trainable or config.algo_class, + param_space=config, + run_config=tune.RunConfig( + stop=stop, + verbose=args.verbose, + callbacks=tune_callbacks, + checkpoint_config=tune.CheckpointConfig( + checkpoint_frequency=args.checkpoint_freq, + checkpoint_at_end=args.checkpoint_at_end, + ), + progress_reporter=progress_reporter, + ), + tune_config=tune.TuneConfig( + num_samples=args.num_samples, + max_concurrent_trials=args.max_concurrent_trials, + scheduler=scheduler, + ), + ).fit() + time_taken = time.time() - start_time + + if not keep_ray_up: + ray.shutdown() + + # Error out, if Tuner.fit() failed to run. Otherwise, erroneous examples might pass + # the CI tests w/o us knowing that they are broken (b/c some examples do not have + # a --as-test flag and/or any passing criteris). + if results.errors: + raise RuntimeError( + "Running the example script resulted in one or more errors! " + f"{[e.args[0].args[2] for e in results.errors]}" + ) + + # If run as a test, check whether we reached the specified success criteria. + test_passed = False + if args.as_test: + # Success metric not provided, try extracting it from `stop`. + if success_metric is None: + for try_it in [ + f"{EVALUATION_RESULTS}/{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}", + f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}", + ]: + if try_it in stop: + success_metric = {try_it: stop[try_it]} + break + if success_metric is None: + success_metric = { + f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": args.stop_reward, + } + # TODO (sven): Make this work for more than one metric (AND-logic?). + # Get maximum value of `metric` over all trials + # (check if at least one trial achieved some learning, not just the final one). + success_metric_key, success_metric_value = next(iter(success_metric.items())) + best_value = max( + row[success_metric_key] for _, row in results.get_dataframe().iterrows() + ) + if best_value >= success_metric_value: + test_passed = True + print(f"`{success_metric_key}` of {success_metric_value} reached! ok") + + if args.as_release_test: + trial = results._experiment_analysis.trials[0] + stats = trial.last_result + stats.pop("config", None) + json_summary = { + "time_taken": float(time_taken), + "trial_states": [trial.status], + "last_update": float(time.time()), + "stats": stats, + "passed": [test_passed], + "not_passed": [not test_passed], + "failures": {str(trial): 1} if not test_passed else {}, + } + with open( + os.environ.get("TEST_OUTPUT_JSON", "/tmp/learning_test.json"), + "wt", + ) as f: + try: + json.dump(json_summary, f) + # Something went wrong writing json. Try again w/ simplified stats. + except Exception: + from ray.rllib.algorithms.algorithm import Algorithm + + simplified_stats = { + k: stats[k] for k in Algorithm._progress_metrics if k in stats + } + json_summary["stats"] = simplified_stats + json.dump(json_summary, f) + + if not test_passed: + raise ValueError( + f"`{success_metric_key}` of {success_metric_value} not reached!" + ) + + return results + + +def check_same_batch(batch1, batch2) -> None: + """Check if both batches are (almost) identical. + + For MultiAgentBatches, the step count and individual policy's + SampleBatches are checked for identity. For SampleBatches, identity is + checked as the almost numerical key-value-pair identity between batches + with ray.rllib.utils.test_utils.check(). unroll_id is compared only if + both batches have an unroll_id. + + Args: + batch1: Batch to compare against batch2 + batch2: Batch to compare against batch1 + """ + # Avoids circular import + from ray.rllib.policy.sample_batch import MultiAgentBatch, SampleBatch + + assert type(batch1) is type( + batch2 + ), "Input batches are of different types {} and {}".format( + str(type(batch1)), str(type(batch2)) + ) + + def check_sample_batches(_batch1, _batch2, _policy_id=None): + unroll_id_1 = _batch1.get("unroll_id", None) + unroll_id_2 = _batch2.get("unroll_id", None) + # unroll IDs only have to fit if both batches have them + if unroll_id_1 is not None and unroll_id_2 is not None: + assert unroll_id_1 == unroll_id_2 + + batch1_keys = set() + for k, v in _batch1.items(): + # unroll_id is compared above already + if k == "unroll_id": + continue + check(v, _batch2[k]) + batch1_keys.add(k) + + batch2_keys = set(_batch2.keys()) + # unroll_id is compared above already + batch2_keys.discard("unroll_id") + _difference = batch1_keys.symmetric_difference(batch2_keys) + + # Cases where one batch has info and the other has not + if _policy_id: + assert not _difference, ( + "SampleBatches for policy with ID {} " + "don't share information on the " + "following information: \n{}" + "".format(_policy_id, _difference) + ) + else: + assert not _difference, ( + "SampleBatches don't share information " + "on the following information: \n{}" + "".format(_difference) + ) + + if type(batch1) is SampleBatch: + check_sample_batches(batch1, batch2) + elif type(batch1) is MultiAgentBatch: + assert batch1.count == batch2.count + batch1_ids = set() + for policy_id, policy_batch in batch1.policy_batches.items(): + check_sample_batches( + policy_batch, batch2.policy_batches[policy_id], policy_id + ) + batch1_ids.add(policy_id) + + # Case where one ma batch has info on a policy the other has not + batch2_ids = set(batch2.policy_batches.keys()) + difference = batch1_ids.symmetric_difference(batch2_ids) + assert ( + not difference + ), f"MultiAgentBatches don't share the following information: \n{difference}." + else: + raise ValueError("Unsupported batch type " + str(type(batch1))) + + +def check_reproducibilty( + algo_class: Type["Algorithm"], + algo_config: "AlgorithmConfig", + *, + fw_kwargs: Dict[str, Any], + training_iteration: int = 1, +) -> None: + # TODO @kourosh: we can get rid of examples/deterministic_training.py once + # this is added to all algorithms + """Check if the algorithm is reproducible across different testing conditions: + + frameworks: all input frameworks + num_gpus: int(os.environ.get("RLLIB_NUM_GPUS", "0")) + num_workers: 0 (only local workers) or + 4 ((1) local workers + (4) remote workers) + num_envs_per_env_runner: 2 + + Args: + algo_class: Algorithm class to test. + algo_config: Base config to use for the algorithm. + fw_kwargs: Framework iterator keyword arguments. + training_iteration: Number of training iterations to run. + + Returns: + None + + Raises: + It raises an AssertionError if the algorithm is not reproducible. + """ + from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID + from ray.rllib.utils.metrics.learner_info import LEARNER_INFO + + stop_dict = {TRAINING_ITERATION: training_iteration} + # use 0 and 2 workers (for more that 4 workers we have to make sure the instance + # type in ci build has enough resources) + for num_workers in [0, 2]: + algo_config = ( + algo_config.debugging(seed=42).env_runners( + num_env_runners=num_workers, num_envs_per_env_runner=2 + ) + # new API + .learners( + num_gpus_per_learner=int(os.environ.get("RLLIB_NUM_GPUS", "0")), + ) + # old API + .resources( + num_gpus=int(os.environ.get("RLLIB_NUM_GPUS", "0")), + ) + ) + + print( + f"Testing reproducibility of {algo_class.__name__}" + f" with {num_workers} workers" + ) + print("/// config") + pprint.pprint(algo_config.to_dict()) + # test tune.Tuner().fit() reproducibility + results1 = tune.Tuner( + algo_class, + param_space=algo_config.to_dict(), + run_config=tune.RunConfig(stop=stop_dict, verbose=1), + ).fit() + results1 = results1.get_best_result().metrics + + results2 = tune.Tuner( + algo_class, + param_space=algo_config.to_dict(), + run_config=tune.RunConfig(stop=stop_dict, verbose=1), + ).fit() + results2 = results2.get_best_result().metrics + + # Test rollout behavior. + check( + results1[ENV_RUNNER_RESULTS]["hist_stats"], + results2[ENV_RUNNER_RESULTS]["hist_stats"], + ) + # As well as training behavior (minibatch sequence during SGD + # iterations). + # As well as training behavior (minibatch sequence during SGD + # iterations). + if algo_config.enable_rl_module_and_learner: + check( + results1["info"][LEARNER_INFO][DEFAULT_POLICY_ID], + results2["info"][LEARNER_INFO][DEFAULT_POLICY_ID], + ) + else: + check( + results1["info"][LEARNER_INFO][DEFAULT_POLICY_ID]["learner_stats"], + results2["info"][LEARNER_INFO][DEFAULT_POLICY_ID]["learner_stats"], + ) + + +def get_cartpole_dataset_reader(batch_size: int = 1) -> "DatasetReader": + """Returns a DatasetReader for the cartpole dataset. + Args: + batch_size: The batch size to use for the reader. + Returns: + A rllib DatasetReader for the cartpole dataset. + """ + from ray.rllib.algorithms import AlgorithmConfig + from ray.rllib.offline import IOContext + from ray.rllib.offline.dataset_reader import ( + DatasetReader, + get_dataset_and_shards, + ) + + path = "tests/data/cartpole/large.json" + input_config = {"format": "json", "paths": path} + dataset, _ = get_dataset_and_shards( + AlgorithmConfig().offline_data(input_="dataset", input_config=input_config) + ) + ioctx = IOContext( + config=( + AlgorithmConfig() + .training(train_batch_size=batch_size) + .offline_data(actions_in_input_normalized=True) + ), + worker_index=0, + ) + reader = DatasetReader(dataset, ioctx) + return reader + + +class ModelChecker: + """Helper class to compare architecturally identical Models across frameworks. + + Holds a ModelConfig, such that individual models can be added simply via their + framework string (by building them with config.build(framework=...). + A call to `check()` forces all added models to be compared in terms of their + number of trainable and non-trainable parameters, as well as, their + computation results given a common weights structure and values and identical + inputs to the models. + """ + + def __init__(self, config): + self.config = config + + # To compare number of params between frameworks. + self.param_counts = {} + # To compare computed outputs from fixed-weights-nets between frameworks. + self.output_values = {} + + # We will pass an observation filled with this one random value through + # all DL networks (after they have been set to fixed-weights) to compare + # the computed outputs. + self.random_fill_input_value = np.random.uniform(-0.01, 0.01) + + # Dict of models to check against each other. + self.models = {} + + def add(self, framework: str = "torch", obs=True, state=False) -> Any: + """Builds a new Model for the given framework.""" + model = self.models[framework] = self.config.build(framework=framework) + + # Pass a B=1 observation through the model. + inputs = np.full( + [1] + ([1] if state else []) + list(self.config.input_dims), + self.random_fill_input_value, + ) + if obs: + inputs = {Columns.OBS: inputs} + if state: + inputs[Columns.STATE_IN] = tree.map_structure( + lambda s: np.zeros(shape=[1] + list(s)), state + ) + if framework == "torch": + from ray.rllib.utils.torch_utils import convert_to_torch_tensor + + inputs = convert_to_torch_tensor(inputs) + # w/ old specs: inputs = model.input_specs.fill(self.random_fill_input_value) + + outputs = model(inputs) + + # Bring model into a reproducible, comparable state (so we can compare + # computations across frameworks). Use only a value-sequence of len=1 here + # as it could possibly be that the layers are stored in different order + # across the different frameworks. + model._set_to_dummy_weights(value_sequence=(self.random_fill_input_value,)) + + # Perform another forward pass. + comparable_outputs = model(inputs) + + # Store the number of parameters for this framework's net. + self.param_counts[framework] = model.get_num_parameters() + # Store the fixed-weights-net outputs for this framework's net. + if framework == "torch": + self.output_values[framework] = tree.map_structure( + lambda s: s.detach().numpy() if s is not None else None, + comparable_outputs, + ) + else: + self.output_values[framework] = tree.map_structure( + lambda s: s.numpy() if s is not None else None, comparable_outputs + ) + return outputs + + def check(self): + """Compares all added Models with each other and possibly raises errors.""" + + main_key = next(iter(self.models.keys())) + # Compare number of trainable and non-trainable params between all + # frameworks. + for c in self.param_counts.values(): + check(c, self.param_counts[main_key]) + + # Compare dummy outputs by exact values given that all nets received the + # same input and all nets have the same (dummy) weight values. + for v in self.output_values.values(): + check(v, self.output_values[main_key], atol=0.0005) + + +def _get_mean_action_from_algorithm(alg: "Algorithm", obs: np.ndarray) -> np.ndarray: + """Returns the mean action computed by the given algorithm. + + Note: This makes calls to `Algorithm.compute_single_action` + + Args: + alg: The constructed algorithm to run inference on. + obs: The observation to compute the action for. + + Returns: + The mean action computed by the algorithm over 5000 samples. + + """ + out = [] + for _ in range(5000): + out.append(float(alg.compute_single_action(obs))) + return np.mean(out) + + +def check_supported_spaces( + alg: str, + config: "AlgorithmConfig", + train: bool = True, + check_bounds: bool = False, + frameworks: Optional[Tuple[str]] = None, + use_gpu: bool = False, +): + """Checks whether the given algorithm supports different action and obs spaces. + + Performs the checks by constructing an rllib algorithm from the config and + checking to see that the model inside the policy is the correct one given + the action and obs spaces. For example if the action space is discrete and + the obs space is an image, then the model should be a vision network with + a categorical action distribution. + + Args: + alg: The name of the algorithm to test. + config: The config to use for the algorithm. + train: Whether to train the algorithm for a few iterations. + check_bounds: Whether to check the bounds of the action space. + frameworks: The frameworks to test the algorithm with. + use_gpu: Whether to check support for training on a gpu. + + + """ + # Do these imports here because otherwise we have circular imports. + from ray.rllib.examples.envs.classes.random_env import RandomEnv + from ray.rllib.models.torch.complex_input_net import ( + ComplexInputNetwork as TorchComplexNet, + ) + from ray.rllib.models.torch.fcnet import FullyConnectedNetwork as TorchFCNet + from ray.rllib.models.torch.visionnet import VisionNetwork as TorchVisionNet + + action_spaces_to_test = { + # Test discrete twice here until we support multi_binary action spaces + "discrete": Discrete(5), + "continuous": Box(-1.0, 1.0, (5,), dtype=np.float32), + "int_actions": Box(0, 3, (2, 3), dtype=np.int32), + "multidiscrete": MultiDiscrete([1, 2, 3, 4]), + "tuple": GymTuple( + [Discrete(2), Discrete(3), Box(-1.0, 1.0, (5,), dtype=np.float32)] + ), + "dict": GymDict( + { + "action_choice": Discrete(3), + "parameters": Box(-1.0, 1.0, (1,), dtype=np.float32), + "yet_another_nested_dict": GymDict( + {"a": GymTuple([Discrete(2), Discrete(3)])} + ), + } + ), + } + + observation_spaces_to_test = { + "multi_binary": MultiBinary([3, 10, 10]), + "discrete": Discrete(5), + "continuous": Box(-1.0, 1.0, (5,), dtype=np.float32), + "vector2d": Box(-1.0, 1.0, (5, 5), dtype=np.float32), + "image": Box(-1.0, 1.0, (84, 84, 1), dtype=np.float32), + "tuple": GymTuple([Discrete(10), Box(-1.0, 1.0, (5,), dtype=np.float32)]), + "dict": GymDict( + { + "task": Discrete(10), + "position": Box(-1.0, 1.0, (5,), dtype=np.float32), + } + ), + } + + # The observation spaces that we test RLModules with + rlmodule_supported_observation_spaces = [ + "multi_binary", + "discrete", + "continuous", + "image", + "tuple", + "dict", + ] + + # The action spaces that we test RLModules with + rlmodule_supported_action_spaces = ["discrete", "continuous"] + + default_observation_space = default_action_space = "discrete" + + config["log_level"] = "ERROR" + config["env"] = RandomEnv + + def _do_check(alg, config, a_name, o_name): + # We need to copy here so that this validation does not affect the actual + # validation method call further down the line. + config_copy = config.copy() + config_copy.validate() + # If RLModules are enabled, we need to skip a few tests for now: + if config_copy.enable_rl_module_and_learner: + # Skip PPO cases in which RLModules don't support the given spaces yet. + if o_name not in rlmodule_supported_observation_spaces: + logger.warning( + "Skipping PPO test with RLModules for obs space {}".format(o_name) + ) + return + if a_name not in rlmodule_supported_action_spaces: + logger.warning( + "Skipping PPO test with RLModules for action space {}".format( + a_name + ) + ) + return + + fw = config["framework"] + action_space = action_spaces_to_test[a_name] + obs_space = observation_spaces_to_test[o_name] + print( + "=== Testing {} (fw={}) action_space={} obs_space={} ===".format( + alg, fw, action_space, obs_space + ) + ) + t0 = time.time() + config.update_from_dict( + dict( + env_config=dict( + action_space=action_space, + observation_space=obs_space, + reward_space=Box(1.0, 1.0, shape=(), dtype=np.float32), + p_terminated=1.0, + check_action_bounds=check_bounds, + ) + ) + ) + stat = "ok" + + try: + algo = config.build() + except ray.exceptions.RayActorError as e: + if len(e.args) >= 2 and isinstance(e.args[2], UnsupportedSpaceException): + stat = "unsupported" + elif isinstance(e.args[0].args[2], UnsupportedSpaceException): + stat = "unsupported" + else: + raise + except UnsupportedSpaceException: + stat = "unsupported" + else: + if alg not in ["SAC", "PPO"]: + # 2D (image) input: Expect VisionNet. + if o_name in ["atari", "image"]: + assert isinstance(algo.get_policy().model, TorchVisionNet) + # 1D input: Expect FCNet. + elif o_name == "continuous": + assert isinstance(algo.get_policy().model, TorchFCNet) + # Could be either one: ComplexNet (if disabled Preprocessor) + # or FCNet (w/ Preprocessor). + elif o_name == "vector2d": + assert isinstance( + algo.get_policy().model, (TorchComplexNet, TorchFCNet) + ) + if train: + algo.train() + algo.stop() + print("Test: {}, ran in {}s".format(stat, time.time() - t0)) + + if not frameworks: + frameworks = ("tf2", "tf", "torch") + + _do_check_remote = ray.remote(_do_check) + _do_check_remote = _do_check_remote.options(num_gpus=1 if use_gpu else 0) + # Test all action spaces first. + for a_name in action_spaces_to_test.keys(): + o_name = default_observation_space + ray.get(_do_check_remote.remote(alg, config, a_name, o_name)) + + # Now test all observation spaces. + for o_name in observation_spaces_to_test.keys(): + a_name = default_action_space + ray.get(_do_check_remote.remote(alg, config, a_name, o_name)) diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/tf_run_builder.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/tf_run_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..1a4116f245203e7cedbc9348c893305186dd566d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/tf_run_builder.py @@ -0,0 +1,115 @@ +import logging +import os +import time + +from ray.util.debug import log_once +from ray.rllib.utils.annotations import OldAPIStack +from ray.rllib.utils.framework import try_import_tf + +tf1, tf, tfv = try_import_tf() +logger = logging.getLogger(__name__) + + +@OldAPIStack +class _TFRunBuilder: + """Used to incrementally build up a TensorFlow run. + + This is particularly useful for batching ops from multiple different + policies in the multi-agent setting. + """ + + def __init__(self, session, debug_name): + self.session = session + self.debug_name = debug_name + self.feed_dict = {} + self.fetches = [] + self._executed = None + + def add_feed_dict(self, feed_dict): + assert not self._executed + for k in feed_dict: + if k in self.feed_dict: + raise ValueError("Key added twice: {}".format(k)) + self.feed_dict.update(feed_dict) + + def add_fetches(self, fetches): + assert not self._executed + base_index = len(self.fetches) + self.fetches.extend(fetches) + return list(range(base_index, len(self.fetches))) + + def get(self, to_fetch): + if self._executed is None: + try: + self._executed = _run_timeline( + self.session, + self.fetches, + self.debug_name, + self.feed_dict, + os.environ.get("TF_TIMELINE_DIR"), + ) + except Exception as e: + logger.exception( + "Error fetching: {}, feed_dict={}".format( + self.fetches, self.feed_dict + ) + ) + raise e + if isinstance(to_fetch, int): + return self._executed[to_fetch] + elif isinstance(to_fetch, list): + return [self.get(x) for x in to_fetch] + elif isinstance(to_fetch, tuple): + return tuple(self.get(x) for x in to_fetch) + else: + raise ValueError("Unsupported fetch type: {}".format(to_fetch)) + + +_count = 0 + + +def _run_timeline(sess, ops, debug_name, feed_dict=None, timeline_dir=None): + if feed_dict is None: + feed_dict = {} + + if timeline_dir: + from tensorflow.python.client import timeline + + try: + run_options = tf1.RunOptions(trace_level=tf.RunOptions.FULL_TRACE) + except AttributeError: + run_options = None + # In local mode, tf1.RunOptions is not available, see #26511 + if log_once("tf1.RunOptions_not_available"): + logger.exception( + "Can not access tf.RunOptions.FULL_TRACE. This may be because " + "you have used `ray.init(local_mode=True)`. RLlib will use " + "timeline without `options=tf.RunOptions.FULL_TRACE`." + ) + run_metadata = tf1.RunMetadata() + start = time.time() + fetches = sess.run( + ops, options=run_options, run_metadata=run_metadata, feed_dict=feed_dict + ) + trace = timeline.Timeline(step_stats=run_metadata.step_stats) + global _count + outf = os.path.join( + timeline_dir, + "timeline-{}-{}-{}.json".format(debug_name, os.getpid(), _count % 10), + ) + _count += 1 + trace_file = open(outf, "w") + logger.info( + "Wrote tf timeline ({} s) to {}".format( + time.time() - start, os.path.abspath(outf) + ) + ) + trace_file.write(trace.generate_chrome_trace_format()) + else: + if log_once("tf_timeline"): + logger.info( + "Executing TF run without tracing. To dump TF timeline traces " + "to disk, set the TF_TIMELINE_DIR environment variable." + ) + fetches = sess.run(ops, feed_dict=feed_dict) + return fetches diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/tf_utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/tf_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2ba30fcbc81bd7c8b638aca057d1afea00d12f19 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/tf_utils.py @@ -0,0 +1,1041 @@ +import logging +from collections import OrderedDict, deque +from typing import Any, Callable, List, Optional, Type, TYPE_CHECKING, Union + +import gymnasium as gym +import numpy as np +import tree # pip install dm_tree +from gymnasium.spaces import Discrete, MultiDiscrete + +from ray.rllib.utils import force_list +from ray.rllib.utils.annotations import PublicAPI, DeveloperAPI +from ray.rllib.utils.framework import try_import_tf +from ray.rllib.utils.numpy import SMALL_NUMBER +from ray.rllib.utils.spaces.space_utils import get_base_struct_from_space +from ray.rllib.utils.typing import ( + LocalOptimizer, + ModelGradients, + NetworkType, + PartialAlgorithmConfigDict, + SpaceStruct, + TensorStructType, + TensorType, +) + +if TYPE_CHECKING: + from ray.rllib.algorithms.algorithm_config import AlgorithmConfig + from ray.rllib.core.learner.learner import ParamDict + from ray.rllib.policy.eager_tf_policy import EagerTFPolicy + from ray.rllib.policy.eager_tf_policy_v2 import EagerTFPolicyV2 + from ray.rllib.policy.tf_policy import TFPolicy + +logger = logging.getLogger(__name__) +tf1, tf, tfv = try_import_tf() + + +@PublicAPI +def clip_gradients( + gradients_dict: "ParamDict", + *, + grad_clip: Optional[float] = None, + grad_clip_by: str, +) -> Optional[float]: + """Performs gradient clipping on a grad-dict based on a clip value and clip mode. + + Changes the provided gradient dict in place. + + Args: + gradients_dict: The gradients dict, mapping str to gradient tensors. + grad_clip: The value to clip with. The way gradients are clipped is defined + by the `grad_clip_by` arg (see below). + grad_clip_by: One of 'value', 'norm', or 'global_norm'. + + Returns: + If `grad_clip_by`="global_norm" and `grad_clip` is not None, returns the global + norm of all tensors, otherwise returns None. + """ + # No clipping, return. + if grad_clip is None: + return + + # Clip by value (each gradient individually). + if grad_clip_by == "value": + for k, v in gradients_dict.copy().items(): + gradients_dict[k] = tf.clip_by_value(v, -grad_clip, grad_clip) + + # Clip by L2-norm (per gradient tensor). + elif grad_clip_by == "norm": + for k, v in gradients_dict.copy().items(): + gradients_dict[k] = tf.clip_by_norm(v, grad_clip) + + # Clip by global L2-norm (across all gradient tensors). + else: + assert grad_clip_by == "global_norm" + + clipped_grads, global_norm = tf.clip_by_global_norm( + list(gradients_dict.values()), grad_clip + ) + for k, v in zip(gradients_dict.copy().keys(), clipped_grads): + gradients_dict[k] = v + + # Return the computed global norm scalar. + return global_norm + + +@PublicAPI +def explained_variance(y: TensorType, pred: TensorType) -> TensorType: + """Computes the explained variance for a pair of labels and predictions. + + The formula used is: + max(-1.0, 1.0 - (std(y - pred)^2 / std(y)^2)) + + Args: + y: The labels. + pred: The predictions. + + Returns: + The explained variance given a pair of labels and predictions. + """ + _, y_var = tf.nn.moments(y, axes=[0]) + _, diff_var = tf.nn.moments(y - pred, axes=[0]) + return tf.maximum(-1.0, 1 - (diff_var / (y_var + SMALL_NUMBER))) + + +@PublicAPI +def flatten_inputs_to_1d_tensor( + inputs: TensorStructType, + spaces_struct: Optional[SpaceStruct] = None, + time_axis: bool = False, +) -> TensorType: + """Flattens arbitrary input structs according to the given spaces struct. + + Returns a single 1D tensor resulting from the different input + components' values. + + Thereby: + - Boxes (any shape) get flattened to (B, [T]?, -1). Note that image boxes + are not treated differently from other types of Boxes and get + flattened as well. + - Discrete (int) values are one-hot'd, e.g. a batch of [1, 0, 3] (B=3 with + Discrete(4) space) results in [[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1]]. + - MultiDiscrete values are multi-one-hot'd, e.g. a batch of + [[0, 2], [1, 4]] (B=2 with MultiDiscrete([2, 5]) space) results in + [[1, 0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 0, 1]]. + + Args: + inputs: The inputs to be flattened. + spaces_struct: The structure of the spaces that behind the input + time_axis: Whether all inputs have a time-axis (after the batch axis). + If True, will keep not only the batch axis (0th), but the time axis + (1st) as-is and flatten everything from the 2nd axis up. + + Returns: + A single 1D tensor resulting from concatenating all + flattened/one-hot'd input components. Depending on the time_axis flag, + the shape is (B, n) or (B, T, n). + + .. testcode:: + :skipif: True + + # B=2 + from ray.rllib.utils.tf_utils import flatten_inputs_to_1d_tensor + from gymnasium.spaces import Discrete, Box + out = flatten_inputs_to_1d_tensor( + {"a": [1, 0], "b": [[[0.0], [0.1]], [1.0], [1.1]]}, + spaces_struct=dict(a=Discrete(2), b=Box(shape=(2, 1))) + ) + print(out) + + # B=2; T=2 + out = flatten_inputs_to_1d_tensor( + ([[1, 0], [0, 1]], + [[[0.0, 0.1], [1.0, 1.1]], [[2.0, 2.1], [3.0, 3.1]]]), + spaces_struct=tuple([Discrete(2), Box(shape=(2, ))]), + time_axis=True + ) + print(out) + + .. testoutput:: + + [[0.0, 1.0, 0.0, 0.1], [1.0, 0.0, 1.0, 1.1]] # B=2 n=4 + [[[0.0, 1.0, 0.0, 0.1], [1.0, 0.0, 1.0, 1.1]], + [[1.0, 0.0, 2.0, 2.1], [0.0, 1.0, 3.0, 3.1]]] # B=2 T=2 n=4 + """ + + flat_inputs = tree.flatten(inputs) + flat_spaces = ( + tree.flatten(spaces_struct) + if spaces_struct is not None + else [None] * len(flat_inputs) + ) + + B = None + T = None + out = [] + for input_, space in zip(flat_inputs, flat_spaces): + input_ = tf.convert_to_tensor(input_) + shape = tf.shape(input_) + # Store batch and (if applicable) time dimension. + if B is None: + B = shape[0] + if time_axis: + T = shape[1] + + # One-hot encoding. + if isinstance(space, Discrete): + if time_axis: + input_ = tf.reshape(input_, [B * T]) + out.append(tf.cast(one_hot(input_, space), tf.float32)) + elif isinstance(space, MultiDiscrete): + if time_axis: + input_ = tf.reshape(input_, [B * T, -1]) + out.append(tf.cast(one_hot(input_, space), tf.float32)) + # Flatten. + else: + if time_axis: + input_ = tf.reshape(input_, [B * T, -1]) + else: + input_ = tf.reshape(input_, [B, -1]) + out.append(tf.cast(input_, tf.float32)) + + merged = tf.concat(out, axis=-1) + # Restore the time-dimension, if applicable. + if time_axis: + merged = tf.reshape(merged, [B, T, -1]) + + return merged + + +@PublicAPI +def get_gpu_devices() -> List[str]: + """Returns a list of GPU device names, e.g. ["/gpu:0", "/gpu:1"]. + + Supports both tf1.x and tf2.x. + + Returns: + List of GPU device names (str). + """ + if tfv == 1: + from tensorflow.python.client import device_lib + + devices = device_lib.list_local_devices() + else: + try: + devices = tf.config.list_physical_devices() + except Exception: + devices = tf.config.experimental.list_physical_devices() + + # Expect "GPU", but also stuff like: "XLA_GPU". + return [d.name for d in devices if "GPU" in d.device_type] + + +@PublicAPI +def get_placeholder( + *, + space: Optional[gym.Space] = None, + value: Optional[Any] = None, + name: Optional[str] = None, + time_axis: bool = False, + flatten: bool = True, +) -> "tf1.placeholder": + """Returns a tf1.placeholder object given optional hints, such as a space. + + Note that the returned placeholder will always have a leading batch + dimension (None). + + Args: + space: An optional gym.Space to hint the shape and dtype of the + placeholder. + value: An optional value to hint the shape and dtype of the + placeholder. + name: An optional name for the placeholder. + time_axis: Whether the placeholder should also receive a time + dimension (None). + flatten: Whether to flatten the given space into a plain Box space + and then create the placeholder from the resulting space. + + Returns: + The tf1 placeholder. + """ + from ray.rllib.models.catalog import ModelCatalog + + if space is not None: + if isinstance(space, (gym.spaces.Dict, gym.spaces.Tuple)): + if flatten: + return ModelCatalog.get_action_placeholder(space, None) + else: + return tree.map_structure_with_path( + lambda path, component: get_placeholder( + space=component, + name=name + "." + ".".join([str(p) for p in path]), + ), + get_base_struct_from_space(space), + ) + return tf1.placeholder( + shape=(None,) + ((None,) if time_axis else ()) + space.shape, + dtype=tf.float32 if space.dtype == np.float64 else space.dtype, + name=name, + ) + else: + assert value is not None + shape = value.shape[1:] + return tf1.placeholder( + shape=(None,) + + ((None,) if time_axis else ()) + + (shape if isinstance(shape, tuple) else tuple(shape.as_list())), + dtype=tf.float32 if value.dtype == np.float64 else value.dtype, + name=name, + ) + + +@PublicAPI +def get_tf_eager_cls_if_necessary( + orig_cls: Type["TFPolicy"], + config: Union["AlgorithmConfig", PartialAlgorithmConfigDict], +) -> Type[Union["TFPolicy", "EagerTFPolicy", "EagerTFPolicyV2"]]: + """Returns the corresponding tf-eager class for a given TFPolicy class. + + Args: + orig_cls: The original TFPolicy class to get the corresponding tf-eager + class for. + config: The Algorithm config dict or AlgorithmConfig object. + + Returns: + The tf eager policy class corresponding to the given TFPolicy class. + """ + cls = orig_cls + framework = config.get("framework", "tf") + + if framework in ["tf2", "tf"] and not tf1: + raise ImportError("Could not import tensorflow!") + + if framework == "tf2": + if not tf1.executing_eagerly(): + tf1.enable_eager_execution() + assert tf1.executing_eagerly() + + from ray.rllib.policy.tf_policy import TFPolicy + from ray.rllib.policy.eager_tf_policy import EagerTFPolicy + from ray.rllib.policy.eager_tf_policy_v2 import EagerTFPolicyV2 + + # Create eager-class (if not already one). + if hasattr(orig_cls, "as_eager") and not issubclass(orig_cls, EagerTFPolicy): + cls = orig_cls.as_eager() + # Could be some other type of policy or already + # eager-ized. + elif not issubclass(orig_cls, TFPolicy): + pass + else: + raise ValueError( + "This policy does not support eager execution: {}".format(orig_cls) + ) + + # Now that we know, policy is an eager one, add tracing, if necessary. + if config.get("eager_tracing") and issubclass( + cls, (EagerTFPolicy, EagerTFPolicyV2) + ): + cls = cls.with_tracing() + return cls + + +@PublicAPI +def huber_loss(x: TensorType, delta: float = 1.0) -> TensorType: + """Computes the huber loss for a given term and delta parameter. + + Reference: https://en.wikipedia.org/wiki/Huber_loss + Note that the factor of 0.5 is implicitly included in the calculation. + + Formula: + L = 0.5 * x^2 for small abs x (delta threshold) + L = delta * (abs(x) - 0.5*delta) for larger abs x (delta threshold) + + Args: + x: The input term, e.g. a TD error. + delta: The delta parmameter in the above formula. + + Returns: + The Huber loss resulting from `x` and `delta`. + """ + return tf.where( + tf.abs(x) < delta, # for small x -> apply the Huber correction + tf.math.square(x) * 0.5, + delta * (tf.abs(x) - 0.5 * delta), + ) + + +@PublicAPI +def l2_loss(x: TensorType) -> TensorType: + """Computes half the L2 norm over a tensor's values without the sqrt. + + output = 0.5 * sum(x ** 2) + + Args: + x: The input tensor. + + Returns: + 0.5 times the L2 norm over the given tensor's values (w/o sqrt). + """ + return 0.5 * tf.reduce_sum(tf.pow(x, 2.0)) + + +@PublicAPI +def make_tf_callable( + session_or_none: Optional["tf1.Session"], dynamic_shape: bool = False +) -> Callable: + """Returns a function that can be executed in either graph or eager mode. + + The function must take only positional args. + + If eager is enabled, this will act as just a function. Otherwise, it + will build a function that executes a session run with placeholders + internally. + + Args: + session_or_none: tf.Session if in graph mode, else None. + dynamic_shape: True if the placeholders should have a dynamic + batch dimension. Otherwise they will be fixed shape. + + Returns: + A function that can be called in either eager or static-graph mode. + """ + + if tf.executing_eagerly(): + assert session_or_none is None + else: + assert session_or_none is not None + + def make_wrapper(fn): + # Static-graph mode: Create placeholders and make a session call each + # time the wrapped function is called. Returns the output of this + # session call. + if session_or_none is not None: + args_placeholders = [] + kwargs_placeholders = {} + + symbolic_out = [None] + + def call(*args, **kwargs): + args_flat = [] + for a in args: + if type(a) is list: + args_flat.extend(a) + else: + args_flat.append(a) + args = args_flat + + # We have not built any placeholders yet: Do this once here, + # then reuse the same placeholders each time we call this + # function again. + if symbolic_out[0] is None: + with session_or_none.graph.as_default(): + + def _create_placeholders(path, value): + if dynamic_shape: + if len(value.shape) > 0: + shape = (None,) + value.shape[1:] + else: + shape = () + else: + shape = value.shape + return tf1.placeholder( + dtype=value.dtype, + shape=shape, + name=".".join([str(p) for p in path]), + ) + + placeholders = tree.map_structure_with_path( + _create_placeholders, args + ) + for ph in tree.flatten(placeholders): + args_placeholders.append(ph) + + placeholders = tree.map_structure_with_path( + _create_placeholders, kwargs + ) + for k, ph in placeholders.items(): + kwargs_placeholders[k] = ph + + symbolic_out[0] = fn(*args_placeholders, **kwargs_placeholders) + feed_dict = dict(zip(args_placeholders, tree.flatten(args))) + tree.map_structure( + lambda ph, v: feed_dict.__setitem__(ph, v), + kwargs_placeholders, + kwargs, + ) + ret = session_or_none.run(symbolic_out[0], feed_dict) + return ret + + return call + # Eager mode (call function as is). + else: + return fn + + return make_wrapper + + +# TODO (sven): Deprecate this function once we have moved completely to the Learner API. +# Replaced with `clip_gradients()`. +@PublicAPI +def minimize_and_clip( + optimizer: LocalOptimizer, + objective: TensorType, + var_list: List["tf.Variable"], + clip_val: float = 10.0, +) -> ModelGradients: + """Computes, then clips gradients using objective, optimizer and var list. + + Ensures the norm of the gradients for each variable is clipped to + `clip_val`. + + Args: + optimizer: Either a shim optimizer (tf eager) containing a + tf.GradientTape under `self.tape` or a tf1 local optimizer + object. + objective: The loss tensor to calculate gradients on. + var_list: The list of tf.Variables to compute gradients over. + clip_val: The global norm clip value. Will clip around -clip_val and + +clip_val. + + Returns: + The resulting model gradients (list or tuples of grads + vars) + corresponding to the input `var_list`. + """ + # Accidentally passing values < 0.0 will break all gradients. + assert clip_val is None or clip_val > 0.0, clip_val + + if tf.executing_eagerly(): + tape = optimizer.tape + grads_and_vars = list(zip(list(tape.gradient(objective, var_list)), var_list)) + else: + grads_and_vars = optimizer.compute_gradients(objective, var_list=var_list) + + return [ + (tf.clip_by_norm(g, clip_val) if clip_val is not None else g, v) + for (g, v) in grads_and_vars + if g is not None + ] + + +@PublicAPI +def one_hot(x: TensorType, space: gym.Space) -> TensorType: + """Returns a one-hot tensor, given and int tensor and a space. + + Handles the MultiDiscrete case as well. + + Args: + x: The input tensor. + space: The space to use for generating the one-hot tensor. + + Returns: + The resulting one-hot tensor. + + Raises: + ValueError: If the given space is not a discrete one. + + .. testcode:: + :skipif: True + + import gymnasium as gym + import tensorflow as tf + from ray.rllib.utils.tf_utils import one_hot + x = tf.Variable([0, 3], dtype=tf.int32) # batch-dim=2 + # Discrete space with 4 (one-hot) slots per batch item. + s = gym.spaces.Discrete(4) + one_hot(x, s) + + .. testoutput:: + + + + .. testcode:: + :skipif: True + + x = tf.Variable([[0, 1, 2, 3]], dtype=tf.int32) # batch-dim=1 + # MultiDiscrete space with 5 + 4 + 4 + 7 = 20 (one-hot) slots + # per batch item. + s = gym.spaces.MultiDiscrete([5, 4, 4, 7]) + one_hot(x, s) + + .. testoutput:: + + + """ + if isinstance(space, Discrete): + return tf.one_hot(x, space.n, dtype=tf.float32) + elif isinstance(space, MultiDiscrete): + if isinstance(space.nvec[0], np.ndarray): + nvec = np.ravel(space.nvec) + x = tf.reshape(x, (x.shape[0], -1)) + else: + nvec = space.nvec + return tf.concat( + [tf.one_hot(x[:, i], n, dtype=tf.float32) for i, n in enumerate(nvec)], + axis=-1, + ) + else: + raise ValueError("Unsupported space for `one_hot`: {}".format(space)) + + +@PublicAPI +def reduce_mean_ignore_inf(x: TensorType, axis: Optional[int] = None) -> TensorType: + """Same as tf.reduce_mean() but ignores -inf values. + + Args: + x: The input tensor to reduce mean over. + axis: The axis over which to reduce. None for all axes. + + Returns: + The mean reduced inputs, ignoring inf values. + """ + mask = tf.not_equal(x, tf.float32.min) + x_zeroed = tf.where(mask, x, tf.zeros_like(x)) + return tf.math.reduce_sum(x_zeroed, axis) / tf.math.reduce_sum( + tf.cast(mask, tf.float32), axis + ) + + +@PublicAPI +def scope_vars( + scope: Union[str, "tf1.VariableScope"], trainable_only: bool = False +) -> List["tf.Variable"]: + """Get variables inside a given scope. + + Args: + scope: Scope in which the variables reside. + trainable_only: Whether or not to return only the variables that were + marked as trainable. + + Returns: + The list of variables in the given `scope`. + """ + return tf1.get_collection( + tf1.GraphKeys.TRAINABLE_VARIABLES + if trainable_only + else tf1.GraphKeys.VARIABLES, + scope=scope if isinstance(scope, str) else scope.name, + ) + + +@PublicAPI +def symlog(x: "tf.Tensor") -> "tf.Tensor": + """The symlog function as described in [1]: + + [1] Mastering Diverse Domains through World Models - 2023 + D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap + https://arxiv.org/pdf/2301.04104v1.pdf + """ + return tf.math.sign(x) * tf.math.log(tf.math.abs(x) + 1) + + +@PublicAPI +def inverse_symlog(y: "tf.Tensor") -> "tf.Tensor": + """Inverse of the `symlog` function as desribed in [1]: + + [1] Mastering Diverse Domains through World Models - 2023 + D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap + https://arxiv.org/pdf/2301.04104v1.pdf + """ + # To get to symlog inverse, we solve the symlog equation for x: + # y = sign(x) * log(|x| + 1) + # <=> y / sign(x) = log(|x| + 1) + # <=> y = log( x + 1) V x >= 0 + # -y = log(-x + 1) V x < 0 + # <=> exp(y) = x + 1 V x >= 0 + # exp(-y) = -x + 1 V x < 0 + # <=> exp(y) - 1 = x V x >= 0 + # exp(-y) - 1 = -x V x < 0 + # <=> exp(y) - 1 = x V x >= 0 (if x >= 0, then y must also be >= 0) + # -exp(-y) - 1 = x V x < 0 (if x < 0, then y must also be < 0) + # <=> sign(y) * (exp(|y|) - 1) = x + return tf.math.sign(y) * (tf.math.exp(tf.math.abs(y)) - 1) + + +@PublicAPI +def two_hot( + value: "tf.Tensor", + num_buckets: int = 255, + lower_bound: float = -20.0, + upper_bound: float = 20.0, + dtype=None, +): + """Returns a two-hot vector of dim=num_buckets with two entries that are non-zero. + + See [1] for more details: + [1] Mastering Diverse Domains through World Models - 2023 + D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap + https://arxiv.org/pdf/2301.04104v1.pdf + + Entries in the vector represent equally sized buckets within some fixed range + (`lower_bound` to `upper_bound`). + Those entries not 0.0 at positions k and k+1 encode the actual `value` and sum + up to 1.0. They are the weights multiplied by the buckets values at k and k+1 for + retrieving `value`. + + Example: + num_buckets=11 + lower_bound=-5 + upper_bound=5 + value=2.5 + -> [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0] + -> [-5 -4 -3 -2 -1 0 1 2 3 4 5] (0.5*2 + 0.5*3=2.5) + + Example: + num_buckets=5 + lower_bound=-1 + upper_bound=1 + value=0.1 + -> [0.0, 0.0, 0.8, 0.2, 0.0] + -> [-1 -0.5 0 0.5 1] (0.2*0.5 + 0.8*0=0.1) + + Args: + value: The input tensor of shape (B,) to be two-hot encoded. + num_buckets: The number of buckets to two-hot encode into. + lower_bound: The lower bound value used for the encoding. If input values are + lower than this boundary, they will be encoded as `lower_bound`. + upper_bound: The upper bound value used for the encoding. If input values are + higher than this boundary, they will be encoded as `upper_bound`. + + Returns: + The two-hot encoded tensor of shape (B, num_buckets). + """ + # First make sure, values are clipped. + value = tf.clip_by_value(value, lower_bound, upper_bound) + # Tensor of batch indices: [0, B=batch size). + batch_indices = tf.cast( + tf.range(0, tf.shape(value)[0]), + dtype=dtype or tf.float32, + ) + # Calculate the step deltas (how much space between each bucket's central value?). + bucket_delta = (upper_bound - lower_bound) / (num_buckets - 1) + # Compute the float indices (might be non-int numbers: sitting between two buckets). + idx = (-lower_bound + value) / bucket_delta + # k + k = tf.math.floor(idx) + # k+1 + kp1 = tf.math.ceil(idx) + # In case k == kp1 (idx is exactly on the bucket boundary), move kp1 up by 1.0. + # Otherwise, this would result in a NaN in the returned two-hot tensor. + kp1 = tf.where(tf.equal(k, kp1), kp1 + 1.0, kp1) + # Iff `kp1` is one beyond our last index (because incoming value is larger than + # `upper_bound`), move it to one before k (kp1's weight is going to be 0.0 anyways, + # so it doesn't matter where it points to; we are just avoiding an index error + # with this). + kp1 = tf.where(tf.equal(kp1, num_buckets), kp1 - 2.0, kp1) + # The actual values found at k and k+1 inside the set of buckets. + values_k = lower_bound + k * bucket_delta + values_kp1 = lower_bound + kp1 * bucket_delta + # Compute the two-hot weights (adding up to 1.0) to use at index k and k+1. + weights_k = (value - values_kp1) / (values_k - values_kp1) + weights_kp1 = 1.0 - weights_k + # Compile a tensor of full paths (indices from batch index to feature index) to + # use for the scatter_nd op. + indices_k = tf.stack([batch_indices, k], -1) + indices_kp1 = tf.stack([batch_indices, kp1], -1) + indices = tf.concat([indices_k, indices_kp1], 0) + # The actual values (weights adding up to 1.0) to place at the computed indices. + updates = tf.concat([weights_k, weights_kp1], 0) + # Call the actual scatter update op, returning a zero-filled tensor, only changed + # at the given indices. + return tf.scatter_nd( + tf.cast(indices, tf.int32), + updates, + shape=(tf.shape(value)[0], num_buckets), + ) + + +@PublicAPI +def update_target_network( + main_net: NetworkType, + target_net: NetworkType, + tau: float, +) -> None: + """Updates a keras.Model target network using Polyak averaging. + + new_target_net_weight = ( + tau * main_net_weight + (1.0 - tau) * current_target_net_weight + ) + + Args: + main_net: The keras.Model to update from. + target_net: The target network to update. + tau: The tau value to use in the Polyak averaging formula. + """ + for old_var, current_var in zip(target_net.variables, main_net.variables): + updated_var = tau * current_var + (1.0 - tau) * old_var + old_var.assign(updated_var) + + +@PublicAPI +def zero_logps_from_actions(actions: TensorStructType) -> TensorType: + """Helper function useful for returning dummy logp's (0) for some actions. + + Args: + actions: The input actions. This can be any struct + of complex action components or a simple tensor of different + dimensions, e.g. [B], [B, 2], or {"a": [B, 4, 5], "b": [B]}. + + Returns: + A 1D tensor of 0.0 (dummy logp's) matching the batch + dim of `actions` (shape=[B]). + """ + # Need to flatten `actions` in case we have a complex action space. + # Take the 0th component to extract the batch dim. + action_component = tree.flatten(actions)[0] + logp_ = tf.zeros_like(action_component, dtype=tf.float32) + # Logp's should be single values (but with the same batch dim as + # `deterministic_actions` or `stochastic_actions`). In case + # actions are just [B], zeros_like works just fine here, but if + # actions are [B, ...], we have to reduce logp back to just [B]. + while len(logp_.shape) > 1: + logp_ = logp_[:, 0] + return logp_ + + +@DeveloperAPI +def warn_if_infinite_kl_divergence( + policy: Type["TFPolicy"], mean_kl: TensorType +) -> None: + def print_warning(): + logger.warning( + "KL divergence is non-finite, this will likely destabilize your model and" + " the training process. Action(s) in a specific state have near-zero" + " probability. This can happen naturally in deterministic environments" + " where the optimal policy has zero mass for a specific action. To fix this" + " issue, consider setting the coefficient for the KL loss term to zero or" + " increasing policy entropy." + ) + return tf.constant(0.0) + + if policy.loss_initialized(): + tf.cond( + tf.math.is_inf(mean_kl), + false_fn=lambda: tf.constant(0.0), + true_fn=lambda: print_warning(), + ) + + +def _unflatten(vector, shapes): + i = 0 + arrays = [] + for shape in shapes: + size = np.prod(shape, dtype=np.int_) + array = vector[i : (i + size)].reshape(shape) + arrays.append(array) + i += size + assert len(vector) == i, "Passed weight does not have the correct shape." + return arrays + + +@DeveloperAPI +class TensorFlowVariables: + """A class used to set and get weights for Tensorflow networks. + + Attributes: + sess (tf.Session): The tensorflow session used to run assignment. + variables (Dict[str, tf.Variable]): Extracted variables from the loss + or additional variables that are passed in. + placeholders (Dict[str, tf.placeholders]): Placeholders for weights. + assignment_nodes (Dict[str, tf.Tensor]): Nodes that assign weights. + """ + + def __init__(self, output, sess=None, input_variables=None): + """Creates TensorFlowVariables containing extracted variables. + + The variables are extracted by performing a BFS search on the + dependency graph with loss as the root node. After the tree is + traversed and those variables are collected, we append input_variables + to the collected variables. For each variable in the list, the + variable has a placeholder and assignment operation created for it. + + Args: + output (tf.Operation, List[tf.Operation]): The tensorflow + operation to extract all variables from. + sess (Optional[tf.Session]): Optional tf.Session used for running + the get and set methods in tf graph mode. + Use None for tf eager. + input_variables (List[tf.Variables]): Variables to include in the + list. + """ + self.sess = sess + output = force_list(output) + queue = deque(output) + variable_names = [] + explored_inputs = set(output) + + # We do a BFS on the dependency graph of the input function to find + # the variables. + while len(queue) != 0: + tf_obj = queue.popleft() + if tf_obj is None: + continue + # The object put into the queue is not necessarily an operation, + # so we want the op attribute to get the operation underlying the + # object. Only operations contain the inputs that we can explore. + if hasattr(tf_obj, "op"): + tf_obj = tf_obj.op + for input_op in tf_obj.inputs: + if input_op not in explored_inputs: + queue.append(input_op) + explored_inputs.add(input_op) + # Tensorflow control inputs can be circular, so we keep track of + # explored operations. + for control in tf_obj.control_inputs: + if control not in explored_inputs: + queue.append(control) + explored_inputs.add(control) + if "Variable" in tf_obj.node_def.op or "VarHandle" in tf_obj.node_def.op: + variable_names.append(tf_obj.node_def.name) + self.variables = OrderedDict() + variable_list = [ + v for v in tf1.global_variables() if v.op.node_def.name in variable_names + ] + if input_variables is not None: + variable_list += input_variables + + if not tf1.executing_eagerly(): + for v in variable_list: + self.variables[v.op.node_def.name] = v + + self.placeholders = {} + self.assignment_nodes = {} + + # Create new placeholders to put in custom weights. + for k, var in self.variables.items(): + self.placeholders[k] = tf1.placeholder( + var.value().dtype, + var.get_shape().as_list(), + name="Placeholder_" + k, + ) + self.assignment_nodes[k] = var.assign(self.placeholders[k]) + else: + for v in variable_list: + self.variables[v.name] = v + + def get_flat_size(self): + """Returns the total length of all of the flattened variables. + + Returns: + The length of all flattened variables concatenated. + """ + return sum(np.prod(v.get_shape().as_list()) for v in self.variables.values()) + + def get_flat(self): + """Gets the weights and returns them as a flat array. + + Returns: + 1D Array containing the flattened weights. + """ + # Eager mode. + if not self.sess: + return np.concatenate( + [v.numpy().flatten() for v in self.variables.values()] + ) + # Graph mode. + return np.concatenate( + [v.eval(session=self.sess).flatten() for v in self.variables.values()] + ) + + def set_flat(self, new_weights): + """Sets the weights to new_weights, converting from a flat array. + + Note: + You can only set all weights in the network using this function, + i.e., the length of the array must match get_flat_size. + + Args: + new_weights (np.ndarray): Flat array containing weights. + """ + shapes = [v.get_shape().as_list() for v in self.variables.values()] + arrays = _unflatten(new_weights, shapes) + if not self.sess: + for v, a in zip(self.variables.values(), arrays): + v.assign(a) + else: + placeholders = [self.placeholders[k] for k, v in self.variables.items()] + self.sess.run( + list(self.assignment_nodes.values()), + feed_dict=dict(zip(placeholders, arrays)), + ) + + def get_weights(self): + """Returns a dictionary containing the weights of the network. + + Returns: + Dictionary mapping variable names to their weights. + """ + # Eager mode. + if not self.sess: + return self.variables + # Graph mode. + return self.sess.run(self.variables) + + def set_weights(self, new_weights: dict): + """Sets the weights to new_weights. + + Note: + Can set subsets of variables as well, by only passing in the + variables you want to be set. + + Args: + new_weights: Dictionary mapping variable names to their + weights. + """ + if self.sess is None: + for name, var in self.variables.items(): + var.assign(new_weights[name]) + else: + assign_list, feed_dict = self._assign_weights(new_weights) + self.sess.run(assign_list, feed_dict=feed_dict) + + def _assign_weights(self, weights): + """Sets weigths using exact or closest assignable variable name + + Args: + weights: Dictionary mapping variable names to their + weights. + Returns: + Tuple[List, Dict]: assigned variables list, dict of + placeholders and weights + """ + + assigned = [] + feed_dict = {} + assignable = set(self.assignment_nodes.keys()) + + def nb_common_elem(l1, l2): + return len([e for e in l1 if e in l2]) + + def assign(name, value): + feed_dict[self.placeholders[name]] = value + assigned.append(name) + assignable.remove(name) + + for name, value in weights.items(): + if name in assignable: + assign(name, value) + else: + common = { + var: nb_common_elem(name.split("/"), var.split("/")) + for var in assignable + } + select = [ + close_var + for close_var, cn in sorted(common.items(), key=lambda i: -i[1]) + if cn > 0 and value.shape == self.assignment_nodes[close_var].shape + ] + if select: + assign(select[0], value) + + assert assigned, ( + "No variables in the input matched those in the network. " + "Possible cause: Two networks were defined in the same " + "TensorFlow graph. To fix this, place each network " + "definition in its own tf.Graph." + ) + + assert len(assigned) == len(weights), ( + "All weights couldn't be assigned because no variable " + "had an exact/close name or had same shape" + ) + + return [self.assignment_nodes[v] for v in assigned], feed_dict diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/threading.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/threading.py new file mode 100644 index 0000000000000000000000000000000000000000..a9a4461dadbf69afa24ed8e9007fe326640dc7de --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/threading.py @@ -0,0 +1,34 @@ +from typing import Callable + +from ray.rllib.utils.annotations import OldAPIStack + + +@OldAPIStack +def with_lock(func: Callable) -> Callable: + """Use as decorator (@withlock) around object methods that need locking. + + Note: The object must have a self._lock = threading.Lock() property. + Locking thus works on the object level (no two locked methods of the same + object can be called asynchronously). + + Args: + func: The function to decorate/wrap. + + Returns: + The wrapped (object-level locked) function. + """ + + def wrapper(self, *a, **k): + try: + with self._lock: + return func(self, *a, **k) + except AttributeError as e: + if "has no attribute '_lock'" in e.args[0]: + raise AttributeError( + "Object {} must have a `self._lock` property (assigned " + "to a threading.RLock() object in its " + "constructor)!".format(self) + ) + raise e + + return wrapper diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/torch_utils.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/torch_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c77bf9a8db4feefc6e1560d2cf225be11c1ba083 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/torch_utils.py @@ -0,0 +1,886 @@ +import logging +import os +import warnings +from typing import Dict, List, Optional, TYPE_CHECKING, Union + +import gymnasium as gym +from gymnasium.spaces import Discrete, MultiDiscrete +import numpy as np +from packaging import version +import tree # pip install dm_tree + +from ray.rllib.models.repeated_values import RepeatedValues +from ray.rllib.utils.annotations import PublicAPI, DeveloperAPI, OldAPIStack +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.numpy import SMALL_NUMBER +from ray.rllib.utils.typing import ( + LocalOptimizer, + NetworkType, + SpaceStruct, + TensorStructType, + TensorType, +) + +if TYPE_CHECKING: + from ray.rllib.core.learner.learner import ParamDict, ParamList + from ray.rllib.policy.torch_policy import TorchPolicy + from ray.rllib.policy.torch_policy_v2 import TorchPolicyV2 + +logger = logging.getLogger(__name__) +torch, nn = try_import_torch() + +# Limit values suitable for use as close to a -inf logit. These are useful +# since -inf / inf cause NaNs during backprop. +FLOAT_MIN = -3.4e38 +FLOAT_MAX = 3.4e38 + +if torch: + TORCH_COMPILE_REQUIRED_VERSION = version.parse("2.0.0") +else: + TORCH_COMPILE_REQUIRED_VERSION = ValueError( + "torch is not installed. TORCH_COMPILE_REQUIRED_VERSION is not defined." + ) + + +@OldAPIStack +def apply_grad_clipping( + policy: "TorchPolicy", optimizer: LocalOptimizer, loss: TensorType +) -> Dict[str, TensorType]: + """Applies gradient clipping to already computed grads inside `optimizer`. + + Note: This function does NOT perform an analogous operation as + tf.clip_by_global_norm. It merely clips by norm (per gradient tensor) and + then computes the global norm across all given tensors (but without clipping + by that global norm). + + Args: + policy: The TorchPolicy, which calculated `loss`. + optimizer: A local torch optimizer object. + loss: The torch loss tensor. + + Returns: + An info dict containing the "grad_norm" key and the resulting clipped + gradients. + """ + grad_gnorm = 0 + if policy.config["grad_clip"] is not None: + clip_value = policy.config["grad_clip"] + else: + clip_value = np.inf + + num_none_grads = 0 + for param_group in optimizer.param_groups: + # Make sure we only pass params with grad != None into torch + # clip_grad_norm_. Would fail otherwise. + params = list(filter(lambda p: p.grad is not None, param_group["params"])) + if params: + # PyTorch clips gradients inplace and returns the norm before clipping + # We therefore need to compute grad_gnorm further down (fixes #4965) + global_norm = nn.utils.clip_grad_norm_(params, clip_value) + + if isinstance(global_norm, torch.Tensor): + global_norm = global_norm.cpu().numpy() + + grad_gnorm += min(global_norm, clip_value) + else: + num_none_grads += 1 + + # Note (Kourosh): grads could indeed be zero. This method should still return + # grad_gnorm in that case. + if num_none_grads == len(optimizer.param_groups): + # No grads available + return {} + return {"grad_gnorm": grad_gnorm} + + +@PublicAPI +def clip_gradients( + gradients_dict: "ParamDict", + *, + grad_clip: Optional[float] = None, + grad_clip_by: str = "value", +) -> TensorType: + """Performs gradient clipping on a grad-dict based on a clip value and clip mode. + + Changes the provided gradient dict in place. + + Args: + gradients_dict: The gradients dict, mapping str to gradient tensors. + grad_clip: The value to clip with. The way gradients are clipped is defined + by the `grad_clip_by` arg (see below). + grad_clip_by: One of 'value', 'norm', or 'global_norm'. + + Returns: + If `grad_clip_by`="global_norm" and `grad_clip` is not None, returns the global + norm of all tensors, otherwise returns None. + """ + # No clipping, return. + if grad_clip is None: + return + + if grad_clip_by not in ["value", "norm", "global_norm"]: + raise ValueError( + f"`grad_clip_by` ({grad_clip_by}) must be one of [value|norm|global_norm]!" + ) + + # Clip by value (each gradient individually). + if grad_clip_by == "value": + for k, v in gradients_dict.items(): + gradients_dict[k] = ( + None if v is None else torch.clip(v, -grad_clip, grad_clip) + ) + + # Clip by L2-norm (per gradient tensor). + elif grad_clip_by == "norm": + for k, v in gradients_dict.items(): + if v is not None: + # Compute the L2-norm of the gradient tensor. + norm = v.norm(2).nan_to_num(neginf=-10e8, posinf=10e8) + # Clip all the gradients. + if norm > grad_clip: + v.mul_(grad_clip / norm) + + # Clip by global L2-norm (across all gradient tensors). + else: + gradients_list = list(gradients_dict.values()) + total_norm = compute_global_norm(gradients_list) + if len(gradients_list) == 0: + return total_norm + # We do want the coefficient to be in between 0.0 and 1.0, therefore + # if the global_norm is smaller than the clip value, we use the clip value + # as normalization constant. + clip_coeff = grad_clip / torch.clamp(total_norm + 1e-6, min=grad_clip) + # Note: multiplying by the clamped coefficient is redundant when the coefficient + # is clamped to 1, but doing so avoids a `if clip_coeff < 1:` conditional which + # can require a CPU <=> device synchronization when the gradients reside in GPU + # memory. + clip_coeff_clamped = torch.clamp(clip_coeff, max=1.0) + for g in gradients_list: + if g is not None: + g.detach().mul_(clip_coeff_clamped.to(g.device)) + return total_norm + + +@PublicAPI +def compute_global_norm(gradients_list: "ParamList") -> TensorType: + """Computes the global norm for a gradients dict. + + Args: + gradients_list: The gradients list containing parameters. + + Returns: + Returns the global norm of all tensors in `gradients_list`. + """ + # Define the norm type to be L2. + norm_type = 2.0 + # If we have no grads, return zero. + if len(gradients_list) == 0: + return torch.tensor(0.0) + + # Compute the global norm. + total_norm = torch.norm( + torch.stack( + [ + torch.norm(g.detach(), norm_type) + # Note, we want to avoid overflow in the norm computation, this does + # not affect the gradients themselves as we clamp by multiplying and + # not by overriding tensor values. + .nan_to_num(neginf=-10e8, posinf=10e8) + for g in gradients_list + if g is not None + ] + ), + norm_type, + ).nan_to_num(neginf=-10e8, posinf=10e8) + + # Return the global norm. + return total_norm + + +@OldAPIStack +def concat_multi_gpu_td_errors( + policy: Union["TorchPolicy", "TorchPolicyV2"] +) -> Dict[str, TensorType]: + """Concatenates multi-GPU (per-tower) TD error tensors given TorchPolicy. + + TD-errors are extracted from the TorchPolicy via its tower_stats property. + + Args: + policy: The TorchPolicy to extract the TD-error values from. + + Returns: + A dict mapping strings "td_error" and "mean_td_error" to the + corresponding concatenated and mean-reduced values. + """ + td_error = torch.cat( + [ + t.tower_stats.get("td_error", torch.tensor([0.0])).to(policy.device) + for t in policy.model_gpu_towers + ], + dim=0, + ) + policy.td_error = td_error + return { + "td_error": td_error, + "mean_td_error": torch.mean(td_error), + } + + +@PublicAPI +def convert_to_torch_tensor( + x, + device: Optional[str] = None, + pin_memory: bool = False, + use_stream: bool = False, + stream: Optional[Union["torch.cuda.Stream", "torch.cuda.classes.Stream"]] = None, +): + """ + Converts any (possibly nested) structure to torch.Tensors. + + Args: + x: The input structure whose leaves will be converted. + device: The device to create the tensor on (e.g. "cuda:0" or "cpu"). + pin_memory: If True, calls `pin_memory()` on the created tensors. + use_stream: If True, uses a separate CUDA stream for `Tensor.to()`. + stream: An optional CUDA stream for the host-to-device copy in `Tensor.to()`. + + Returns: + A new structure with the same layout as `x` but with all leaves converted + to torch.Tensors. Leaves that are None are left unchanged. + """ + + # Convert the provided device (if any) to a torch.device; default to CPU. + device = torch.device(device) if device is not None else torch.device("cpu") + is_cuda = (device.type == "cuda") and torch.cuda.is_available() + + # Determine the appropriate stream. + if is_cuda: + if use_stream: + if stream is not None: + # Ensure the provided stream is of an acceptable type. + assert isinstance( + stream, (torch.cuda.Stream, torch.cuda.classes.Stream) + ), f"`stream` must be a torch.cuda.Stream but got {type(stream)}." + else: + stream = torch.cuda.Stream() + else: + stream = torch.cuda.default_stream(device=device) + else: + stream = None + + def mapping(item): + # Pass through None values. + if item is None: + return item + + # Special handling for "RepeatedValues" types. + if isinstance(item, RepeatedValues): + return RepeatedValues( + tree.map_structure(mapping, item.values), + item.lengths, + item.max_len, + ) + + # Convert to a tensor if not already one. + if torch.is_tensor(item): + tensor = item + elif isinstance(item, np.ndarray): + # Leave object or string arrays as is. + if item.dtype == object or item.dtype.type is np.str_: + return item + # If the numpy array is not writable, suppress warnings. + if not item.flags.writeable: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + tensor = torch.from_numpy(item) + else: + tensor = torch.from_numpy(item) + else: + tensor = torch.from_numpy(np.asarray(item)) + + # Convert floating-point tensors from float64 to float32 (unless they are float16). + if tensor.is_floating_point() and tensor.dtype != torch.float16: + tensor = tensor.float() + + # Optionally pin memory for faster host-to-GPU copies. + if pin_memory and is_cuda: + tensor = tensor.pin_memory() + + # Move the tensor to the desired device. + # For CUDA devices, use the provided stream context if available. + if is_cuda: + if stream is not None: + with torch.cuda.stream(stream): + tensor = tensor.to(device, non_blocking=True) + else: + tensor = tensor.to(device, non_blocking=True) + else: + # For CPU (or non-CUDA), this is a no-op if already on the target device. + tensor = tensor.to(device) + + return tensor + + return tree.map_structure(mapping, x) + + +@PublicAPI +def copy_torch_tensors(x: TensorStructType, device: Optional[str] = None): + """Creates a copy of `x` and makes deep copies torch.Tensors in x. + + Also moves the copied tensors to the specified device (if not None). + + Note if an object in x is not a torch.Tensor, it will be shallow-copied. + + Args: + x : Any (possibly nested) struct possibly containing torch.Tensors. + device : The device to move the tensors to. + + Returns: + Any: A new struct with the same structure as `x`, but with all + torch.Tensors deep-copied and moved to the specified device. + + """ + + def mapping(item): + if isinstance(item, torch.Tensor): + return ( + torch.clone(item.detach()) + if device is None + else item.detach().to(device) + ) + else: + return item + + return tree.map_structure(mapping, x) + + +@PublicAPI +def explained_variance(y: TensorType, pred: TensorType) -> TensorType: + """Computes the explained variance for a pair of labels and predictions. + + The formula used is: + max(-1.0, 1.0 - (std(y - pred)^2 / std(y)^2)) + + Args: + y: The labels. + pred: The predictions. + + Returns: + The explained variance given a pair of labels and predictions. + """ + squeezed_y = y.squeeze() + y_var = torch.var(squeezed_y, dim=0) + diff_var = torch.var(squeezed_y - pred.squeeze(), dim=0) + min_ = torch.tensor([-1.0]).to(pred.device) + return torch.max(min_, 1 - (diff_var / (y_var + SMALL_NUMBER)))[0] + + +@PublicAPI +def flatten_inputs_to_1d_tensor( + inputs: TensorStructType, + spaces_struct: Optional[SpaceStruct] = None, + time_axis: bool = False, +) -> TensorType: + """Flattens arbitrary input structs according to the given spaces struct. + + Returns a single 1D tensor resulting from the different input + components' values. + + Thereby: + - Boxes (any shape) get flattened to (B, [T]?, -1). Note that image boxes + are not treated differently from other types of Boxes and get + flattened as well. + - Discrete (int) values are one-hot'd, e.g. a batch of [1, 0, 3] (B=3 with + Discrete(4) space) results in [[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1]]. + - MultiDiscrete values are multi-one-hot'd, e.g. a batch of + [[0, 2], [1, 4]] (B=2 with MultiDiscrete([2, 5]) space) results in + [[1, 0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 0, 1]]. + + Args: + inputs: The inputs to be flattened. + spaces_struct: The structure of the spaces that behind the input + time_axis: Whether all inputs have a time-axis (after the batch axis). + If True, will keep not only the batch axis (0th), but the time axis + (1st) as-is and flatten everything from the 2nd axis up. + + Returns: + A single 1D tensor resulting from concatenating all + flattened/one-hot'd input components. Depending on the time_axis flag, + the shape is (B, n) or (B, T, n). + + .. testcode:: + + from gymnasium.spaces import Discrete, Box + from ray.rllib.utils.torch_utils import flatten_inputs_to_1d_tensor + import torch + struct = { + "a": np.array([1, 3]), + "b": ( + np.array([[1.0, 2.0], [4.0, 5.0]]), + np.array( + [[[8.0], [7.0]], [[5.0], [4.0]]] + ), + ), + "c": { + "cb": np.array([1.0, 2.0]), + }, + } + struct_torch = tree.map_structure(lambda s: torch.from_numpy(s), struct) + spaces = dict( + { + "a": gym.spaces.Discrete(4), + "b": (gym.spaces.Box(-1.0, 10.0, (2,)), gym.spaces.Box(-1.0, 1.0, (2, + 1))), + "c": dict( + { + "cb": gym.spaces.Box(-1.0, 1.0, ()), + } + ), + } + ) + print(flatten_inputs_to_1d_tensor(struct_torch, spaces_struct=spaces)) + + .. testoutput:: + + tensor([[0., 1., 0., 0., 1., 2., 8., 7., 1.], + [0., 0., 0., 1., 4., 5., 5., 4., 2.]]) + + """ + + flat_inputs = tree.flatten(inputs) + flat_spaces = ( + tree.flatten(spaces_struct) + if spaces_struct is not None + else [None] * len(flat_inputs) + ) + + B = None + T = None + out = [] + for input_, space in zip(flat_inputs, flat_spaces): + # Store batch and (if applicable) time dimension. + if B is None: + B = input_.shape[0] + if time_axis: + T = input_.shape[1] + + # One-hot encoding. + if isinstance(space, Discrete): + if time_axis: + input_ = torch.reshape(input_, [B * T]) + out.append(one_hot(input_, space).float()) + # Multi one-hot encoding. + elif isinstance(space, MultiDiscrete): + if time_axis: + input_ = torch.reshape(input_, [B * T, -1]) + out.append(one_hot(input_, space).float()) + # Box: Flatten. + else: + if time_axis: + input_ = torch.reshape(input_, [B * T, -1]) + else: + input_ = torch.reshape(input_, [B, -1]) + out.append(input_.float()) + + merged = torch.cat(out, dim=-1) + # Restore the time-dimension, if applicable. + if time_axis: + merged = torch.reshape(merged, [B, T, -1]) + + return merged + + +@PublicAPI +def global_norm(tensors: List[TensorType]) -> TensorType: + """Returns the global L2 norm over a list of tensors. + + output = sqrt(SUM(t ** 2 for t in tensors)), + where SUM reduces over all tensors and over all elements in tensors. + + Args: + tensors: The list of tensors to calculate the global norm over. + + Returns: + The global L2 norm over the given tensor list. + """ + # List of single tensors' L2 norms: SQRT(SUM(xi^2)) over all xi in tensor. + single_l2s = [torch.pow(torch.sum(torch.pow(t, 2.0)), 0.5) for t in tensors] + # Compute global norm from all single tensors' L2 norms. + return torch.pow(sum(torch.pow(l2, 2.0) for l2 in single_l2s), 0.5) + + +@OldAPIStack +def huber_loss(x: TensorType, delta: float = 1.0) -> TensorType: + """Computes the huber loss for a given term and delta parameter. + + Reference: https://en.wikipedia.org/wiki/Huber_loss + Note that the factor of 0.5 is implicitly included in the calculation. + + Formula: + L = 0.5 * x^2 for small abs x (delta threshold) + L = delta * (abs(x) - 0.5*delta) for larger abs x (delta threshold) + + Args: + x: The input term, e.g. a TD error. + delta: The delta parmameter in the above formula. + + Returns: + The Huber loss resulting from `x` and `delta`. + """ + return torch.where( + torch.abs(x) < delta, + torch.pow(x, 2.0) * 0.5, + delta * (torch.abs(x) - 0.5 * delta), + ) + + +@OldAPIStack +def l2_loss(x: TensorType) -> TensorType: + """Computes half the L2 norm over a tensor's values without the sqrt. + + output = 0.5 * sum(x ** 2) + + Args: + x: The input tensor. + + Returns: + 0.5 times the L2 norm over the given tensor's values (w/o sqrt). + """ + return 0.5 * torch.sum(torch.pow(x, 2.0)) + + +@PublicAPI +def one_hot(x: TensorType, space: gym.Space) -> TensorType: + """Returns a one-hot tensor, given and int tensor and a space. + + Handles the MultiDiscrete case as well. + + Args: + x: The input tensor. + space: The space to use for generating the one-hot tensor. + + Returns: + The resulting one-hot tensor. + + Raises: + ValueError: If the given space is not a discrete one. + + .. testcode:: + + import torch + import gymnasium as gym + from ray.rllib.utils.torch_utils import one_hot + x = torch.IntTensor([0, 3]) # batch-dim=2 + # Discrete space with 4 (one-hot) slots per batch item. + s = gym.spaces.Discrete(4) + print(one_hot(x, s)) + x = torch.IntTensor([[0, 1, 2, 3]]) # batch-dim=1 + # MultiDiscrete space with 5 + 4 + 4 + 7 = 20 (one-hot) slots + # per batch item. + s = gym.spaces.MultiDiscrete([5, 4, 4, 7]) + print(one_hot(x, s)) + + .. testoutput:: + + tensor([[1, 0, 0, 0], + [0, 0, 0, 1]]) + tensor([[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0]]) + """ + if isinstance(space, Discrete): + return nn.functional.one_hot(x.long(), space.n) + elif isinstance(space, MultiDiscrete): + if isinstance(space.nvec[0], np.ndarray): + nvec = np.ravel(space.nvec) + x = x.reshape(x.shape[0], -1) + else: + nvec = space.nvec + return torch.cat( + [nn.functional.one_hot(x[:, i].long(), n) for i, n in enumerate(nvec)], + dim=-1, + ) + else: + raise ValueError("Unsupported space for `one_hot`: {}".format(space)) + + +@PublicAPI +def reduce_mean_ignore_inf(x: TensorType, axis: Optional[int] = None) -> TensorType: + """Same as torch.mean() but ignores -inf values. + + Args: + x: The input tensor to reduce mean over. + axis: The axis over which to reduce. None for all axes. + + Returns: + The mean reduced inputs, ignoring inf values. + """ + mask = torch.ne(x, float("-inf")) + x_zeroed = torch.where(mask, x, torch.zeros_like(x)) + return torch.sum(x_zeroed, axis) / torch.sum(mask.float(), axis) + + +@PublicAPI +def sequence_mask( + lengths: TensorType, + maxlen: Optional[int] = None, + dtype=None, + time_major: bool = False, +) -> TensorType: + """Offers same behavior as tf.sequence_mask for torch. + + Thanks to Dimitris Papatheodorou + (https://discuss.pytorch.org/t/pytorch-equivalent-for-tf-sequence-mask/ + 39036). + + Args: + lengths: The tensor of individual lengths to mask by. + maxlen: The maximum length to use for the time axis. If None, use + the max of `lengths`. + dtype: The torch dtype to use for the resulting mask. + time_major: Whether to return the mask as [B, T] (False; default) or + as [T, B] (True). + + Returns: + The sequence mask resulting from the given input and parameters. + """ + # If maxlen not given, use the longest lengths in the `lengths` tensor. + if maxlen is None: + maxlen = lengths.max() + + mask = torch.ones(tuple(lengths.shape) + (int(maxlen),)) + + mask = ~(mask.to(lengths.device).cumsum(dim=1).t() > lengths) + # Time major transformation. + if not time_major: + mask = mask.t() + + # By default, set the mask to be boolean. + mask.type(dtype or torch.bool) + + return mask + + +@PublicAPI +def update_target_network( + main_net: NetworkType, + target_net: NetworkType, + tau: float, +) -> None: + """Updates a torch.nn.Module target network using Polyak averaging. + + .. code-block:: text + + new_target_net_weight = ( + tau * main_net_weight + (1.0 - tau) * current_target_net_weight + ) + + Args: + main_net: The nn.Module to update from. + target_net: The target network to update. + tau: The tau value to use in the Polyak averaging formula. + """ + # Get the current parameters from the Q network. + state_dict = main_net.state_dict() + # Use here Polyak averaging. + new_state_dict = { + k: tau * state_dict[k] + (1 - tau) * v + for k, v in target_net.state_dict().items() + } + # Apply the new parameters to the target Q network. + target_net.load_state_dict(new_state_dict) + + +@DeveloperAPI +def warn_if_infinite_kl_divergence( + policy: "TorchPolicy", + kl_divergence: TensorType, +) -> None: + if policy.loss_initialized() and kl_divergence.isinf(): + logger.warning( + "KL divergence is non-finite, this will likely destabilize your model and" + " the training process. Action(s) in a specific state have near-zero" + " probability. This can happen naturally in deterministic environments" + " where the optimal policy has zero mass for a specific action. To fix this" + " issue, consider setting the coefficient for the KL loss term to zero or" + " increasing policy entropy." + ) + + +@PublicAPI +def set_torch_seed(seed: Optional[int] = None) -> None: + """Sets the torch random seed to the given value. + + Args: + seed: The seed to use or None for no seeding. + """ + if seed is not None and torch: + torch.manual_seed(seed) + # See https://github.com/pytorch/pytorch/issues/47672. + cuda_version = torch.version.cuda + if cuda_version is not None and float(torch.version.cuda) >= 10.2: + # See https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility. + os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8" + torch.cuda.manual_seed(seed) + torch.cuda.manual_seed_all(seed) # if using multi-GPU + else: + if version.Version(torch.__version__) >= version.Version("1.8.0"): + # Not all Operations support this. + torch.use_deterministic_algorithms(True) + else: + torch.set_deterministic(True) + # This is only for Convolution no problem. + torch.backends.cudnn.deterministic = True + # For benchmark=True, CuDNN may choose different algorithms depending on runtime + # conditions or slight differences in input sizes, even if the seed is fixed, + # which breaks determinism. + torch.backends.cudnn.benchmark = False + + +@PublicAPI +def softmax_cross_entropy_with_logits( + logits: TensorType, + labels: TensorType, +) -> TensorType: + """Same behavior as tf.nn.softmax_cross_entropy_with_logits. + + Args: + x: The input predictions. + labels: The labels corresponding to `x`. + + Returns: + The resulting softmax cross-entropy given predictions and labels. + """ + return torch.sum(-labels * nn.functional.log_softmax(logits, -1), -1) + + +@PublicAPI +def symlog(x: "torch.Tensor") -> "torch.Tensor": + """The symlog function as described in [1]: + + [1] Mastering Diverse Domains through World Models - 2023 + D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap + https://arxiv.org/pdf/2301.04104v1.pdf + """ + return torch.sign(x) * torch.log(torch.abs(x) + 1) + + +@PublicAPI +def inverse_symlog(y: "torch.Tensor") -> "torch.Tensor": + """Inverse of the `symlog` function as desribed in [1]: + + [1] Mastering Diverse Domains through World Models - 2023 + D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap + https://arxiv.org/pdf/2301.04104v1.pdf + """ + # To get to symlog inverse, we solve the symlog equation for x: + # y = sign(x) * log(|x| + 1) + # <=> y / sign(x) = log(|x| + 1) + # <=> y = log( x + 1) V x >= 0 + # -y = log(-x + 1) V x < 0 + # <=> exp(y) = x + 1 V x >= 0 + # exp(-y) = -x + 1 V x < 0 + # <=> exp(y) - 1 = x V x >= 0 + # exp(-y) - 1 = -x V x < 0 + # <=> exp(y) - 1 = x V x >= 0 (if x >= 0, then y must also be >= 0) + # -exp(-y) - 1 = x V x < 0 (if x < 0, then y must also be < 0) + # <=> sign(y) * (exp(|y|) - 1) = x + return torch.sign(y) * (torch.exp(torch.abs(y)) - 1) + + +@PublicAPI +def two_hot( + value: "torch.Tensor", + num_buckets: int = 255, + lower_bound: float = -20.0, + upper_bound: float = 20.0, + device: Optional[str] = None, +): + """Returns a two-hot vector of dim=num_buckets with two entries that are non-zero. + + See [1] for more details: + [1] Mastering Diverse Domains through World Models - 2023 + D. Hafner, J. Pasukonis, J. Ba, T. Lillicrap + https://arxiv.org/pdf/2301.04104v1.pdf + + Entries in the vector represent equally sized buckets within some fixed range + (`lower_bound` to `upper_bound`). + Those entries not 0.0 at positions k and k+1 encode the actual `value` and sum + up to 1.0. They are the weights multiplied by the buckets values at k and k+1 for + retrieving `value`. + + Example: + num_buckets=11 + lower_bound=-5 + upper_bound=5 + value=2.5 + -> [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0] + -> [-5 -4 -3 -2 -1 0 1 2 3 4 5] (0.5*2 + 0.5*3=2.5) + + Example: + num_buckets=5 + lower_bound=-1 + upper_bound=1 + value=0.1 + -> [0.0, 0.0, 0.8, 0.2, 0.0] + -> [-1 -0.5 0 0.5 1] (0.2*0.5 + 0.8*0=0.1) + + Args: + value: The input tensor of shape (B,) to be two-hot encoded. + num_buckets: The number of buckets to two-hot encode into. + lower_bound: The lower bound value used for the encoding. If input values are + lower than this boundary, they will be encoded as `lower_bound`. + upper_bound: The upper bound value used for the encoding. If input values are + higher than this boundary, they will be encoded as `upper_bound`. + + Returns: + The two-hot encoded tensor of shape (B, num_buckets). + """ + # First make sure, values are clipped. + value = torch.clamp(value, lower_bound, upper_bound) + # Tensor of batch indices: [0, B=batch size). + batch_indices = torch.arange(0, value.shape[0], device=device).float() + # Calculate the step deltas (how much space between each bucket's central value?). + bucket_delta = (upper_bound - lower_bound) / (num_buckets - 1) + # Compute the float indices (might be non-int numbers: sitting between two buckets). + idx = (-lower_bound + value) / bucket_delta + # k + k = torch.floor(idx) + # k+1 + kp1 = torch.ceil(idx) + # In case k == kp1 (idx is exactly on the bucket boundary), move kp1 up by 1.0. + # Otherwise, this would result in a NaN in the returned two-hot tensor. + kp1 = torch.where(k.eq(kp1), kp1 + 1.0, kp1) + # Iff `kp1` is one beyond our last index (because incoming value is larger than + # `upper_bound`), move it to one before k (kp1's weight is going to be 0.0 anyways, + # so it doesn't matter where it points to; we are just avoiding an index error + # with this). + kp1 = torch.where(kp1.eq(num_buckets), kp1 - 2.0, kp1) + # The actual values found at k and k+1 inside the set of buckets. + values_k = lower_bound + k * bucket_delta + values_kp1 = lower_bound + kp1 * bucket_delta + # Compute the two-hot weights (adding up to 1.0) to use at index k and k+1. + weights_k = (value - values_kp1) / (values_k - values_kp1) + weights_kp1 = 1.0 - weights_k + # Compile a tensor of full paths (indices from batch index to feature index) to + # use for the scatter_nd op. + indices_k = torch.stack([batch_indices, k], dim=-1) + indices_kp1 = torch.stack([batch_indices, kp1], dim=-1) + indices = torch.cat([indices_k, indices_kp1], dim=0).long() + # The actual values (weights adding up to 1.0) to place at the computed indices. + updates = torch.cat([weights_k, weights_kp1], dim=0) + # Call the actual scatter update op, returning a zero-filled tensor, only changed + # at the given indices. + output = torch.zeros(value.shape[0], num_buckets, device=device) + # Set our two-hot values at computed indices. + output[indices[:, 0], indices[:, 1]] = updates + return output + + +def _dynamo_is_available(): + # This only works if torch._dynamo is available + try: + # TODO(Artur): Remove this once torch._dynamo is available on CI + import torch._dynamo as dynamo # noqa: F401 + + return True + except ImportError: + return False diff --git a/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/typing.py b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/typing.py new file mode 100644 index 0000000000000000000000000000000000000000..3f7f559b6e2c0daa18afa39525fa5e2233c84c36 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/ray/rllib/utils/typing.py @@ -0,0 +1,314 @@ +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Hashable, + List, + Optional, + Sequence, + Tuple, + Type, + TypeVar, + Union, +) + +import numpy as np +import gymnasium as gym + +from ray.rllib.utils.annotations import OldAPIStack + +if TYPE_CHECKING: + from ray.rllib.core.rl_module.rl_module import RLModuleSpec + from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec + from ray.rllib.env.env_context import EnvContext + from ray.rllib.env.multi_agent_episode import MultiAgentEpisode + from ray.rllib.env.single_agent_episode import SingleAgentEpisode + from ray.rllib.policy.dynamic_tf_policy_v2 import DynamicTFPolicyV2 + from ray.rllib.policy.eager_tf_policy_v2 import EagerTFPolicyV2 + from ray.rllib.policy.policy import PolicySpec + from ray.rllib.policy.sample_batch import MultiAgentBatch, SampleBatch + from ray.rllib.policy.view_requirement import ViewRequirement + from ray.rllib.utils import try_import_jax, try_import_tf, try_import_torch + + _, tf, _ = try_import_tf() + torch, _ = try_import_torch() + jax, _ = try_import_jax() + jnp = None + if jax is not None: + jnp = jax.numpy + +# Represents a generic tensor type. +# This could be an np.ndarray, jnp.ndarray, tf.Tensor, or a torch.Tensor. +TensorType = Union[np.ndarray, "jnp.ndarray", "tf.Tensor", "torch.Tensor"] + +# Either a plain tensor, or a dict or tuple of tensors (or StructTensors). +TensorStructType = Union[TensorType, dict, tuple] + +# A shape of a tensor. +TensorShape = Union[Tuple[int], List[int]] + +# A neural network. +NetworkType = Union["torch.nn.Module", "tf.keras.Model"] + +# A device. +DeviceType = TypeVar("torch.cuda.device") + +# An RLModule spec (single-agent or multi-agent). +RLModuleSpecType = Union["RLModuleSpec", "MultiRLModuleSpec"] + +# A state dict of an RLlib component (e.g. EnvRunner, Learner, RLModule). +StateDict = Dict[str, Any] + +# Represents a fully filled out config of a Algorithm class. +# Note: Policy config dicts are usually the same as AlgorithmConfigDict, but +# parts of it may sometimes be altered in e.g. a multi-agent setup, +# where we have >1 Policies in the same Algorithm. +AlgorithmConfigDict = dict # @OldAPIStack + +# An algorithm config dict that only has overrides. It needs to be combined with +# the default algorithm config to be used. +PartialAlgorithmConfigDict = dict # @OldAPIStack + +# Represents the model config sub-dict of the algo config that is passed to +# the model catalog. +ModelConfigDict = dict # @OldAPIStack + +# Conv2D configuration format. +# Each entry in the outer list represents one Conv2D layer. +# Each inner list has the format: [num_output_filters, kernel, stride], where kernel +# and stride may be single ints (width and height are the same) or 2-tuples (int, int) +# for width and height (different values). +ConvFilterSpec = List[ + Tuple[int, Union[int, Tuple[int, int]], Union[int, Tuple[int, int]]] +] + +# Objects that can be created through the `from_config()` util method +# need a config dict with a "type" key, a class path (str), or a type directly. +FromConfigSpec = Union[Dict[str, Any], type, str] + +# Represents the env_config sub-dict of the algo config that is passed to +# the env constructor. +EnvConfigDict = dict + +# Represents an environment id. These could be: +# - An int index for a sub-env within a vectorized env. +# - An external env ID (str), which changes(!) each episode. +EnvID = Union[int, str] + +# Represents a BaseEnv, MultiAgentEnv, ExternalEnv, ExternalMultiAgentEnv, +# VectorEnv, gym.Env, or ActorHandle. +# TODO (sven): Specify this type more strictly (it should just be gym.Env). +EnvType = Union[Any, gym.Env] + +# A callable, taking a EnvContext object +# (config dict + properties: `worker_index`, `vector_index`, `num_workers`, +# and `remote`) and returning an env object (or None if no env is used). +EnvCreator = Callable[["EnvContext"], Optional[EnvType]] + +# Represents a generic identifier for an agent (e.g., "agent1"). +AgentID = Any + +# Represents a generic identifier for a policy (e.g., "pol1"). +PolicyID = str # @OldAPIStack +# Represents a generic identifier for a (single-agent) RLModule. +ModuleID = str + +# Type of the config.policies dict for multi-agent training. +MultiAgentPolicyConfigDict = Dict[PolicyID, "PolicySpec"] # @OldAPIStack + +# A new stack Episode type: Either single-agent or multi-agent. +EpisodeType = Union["SingleAgentEpisode", "MultiAgentEpisode"] + +# Is Policy to train callable. +# @OldAPIStack +IsPolicyToTrain = Callable[[PolicyID, Optional["MultiAgentBatch"]], bool] + +# Agent to module mapping and should-module-be-updated. +AgentToModuleMappingFn = Callable[[AgentID, EpisodeType], ModuleID] +ShouldModuleBeUpdatedFn = Union[ + Sequence[ModuleID], + Callable[[ModuleID, Optional["MultiAgentBatch"]], bool], +] + +# State dict of a Policy, mapping strings (e.g. "weights") to some state +# data (TensorStructType). +PolicyState = Dict[str, TensorStructType] # @OldAPIStack + +# Any tf Policy type (static-graph or eager Policy). +TFPolicyV2Type = Type[Union["DynamicTFPolicyV2", "EagerTFPolicyV2"]] # @OldAPIStack + +# Represents an episode id (old and new API stack). +EpisodeID = Union[int, str] + +# Represents an "unroll" (maybe across different sub-envs in a vector env). +UnrollID = int # @OldAPIStack + +# A dict keyed by agent ids, e.g. {"agent-1": value}. +MultiAgentDict = Dict[AgentID, Any] + +# A dict keyed by env ids that contain further nested dictionaries keyed by +# agent ids. e.g., {"env-1": {"agent-1": value}}. +MultiEnvDict = Dict[EnvID, MultiAgentDict] + +# Represents an observation returned from the env. +EnvObsType = Any + +# Represents an action passed to the env. +EnvActionType = Any + +# Info dictionary returned by calling `reset()` or `step()` on `gymnasium.Env` +# instances. Might be an empty dict. +EnvInfoDict = dict + +# Represents a File object +FileType = Any + +# Represents a ViewRequirements dict mapping column names (str) to +# ViewRequirement objects. +ViewRequirementsDict = Dict[str, "ViewRequirement"] # @OldAPIStack + +# Represents the result dict returned by Algorithm.train() and algorithm components, +# such as EnvRunners, LearnerGroup, etc.. Also, the MetricsLogger used by all these +# components returns this upon its `reduce()` method call, so a ResultDict can further +# be accumulated (and reduced again) by downstream components. +ResultDict = Dict + +# A tf or torch local optimizer object. +LocalOptimizer = Union["torch.optim.Optimizer", "tf.keras.optimizers.Optimizer"] +Optimizer = LocalOptimizer +Param = Union["torch.Tensor", "tf.Variable"] +ParamRef = Hashable +ParamDict = Dict[ParamRef, Param] +ParamList = List[Param] +NamedParamDict = Dict[str, Param] + +# A single learning rate or a learning rate schedule (list of sub-lists, each of +# the format: [ts (int), lr_to_reach_by_ts (float)]). +LearningRateOrSchedule = Union[ + float, + List[List[Union[int, float]]], + List[Tuple[int, Union[int, float]]], +] + +# Dict of tensors returned by compute gradients on the policy, e.g., +# {"td_error": [...], "learner_stats": {"vf_loss": ..., ...}}, for multi-agent, +# {"policy1": {"learner_stats": ..., }, "policy2": ...}. +GradInfoDict = dict + +# Dict of learner stats returned by compute gradients on the policy, e.g., +# {"vf_loss": ..., ...}. This will always be nested under the "learner_stats" +# key(s) of a GradInfoDict. In the multi-agent case, this will be keyed by +# policy id. +LearnerStatsDict = dict + +# List of grads+var tuples (tf) or list of gradient tensors (torch) +# representing model gradients and returned by compute_gradients(). +ModelGradients = Union[List[Tuple[TensorType, TensorType]], List[TensorType]] + +# Type of dict returned by get_weights() representing model weights. +ModelWeights = dict + +# An input dict used for direct ModelV2 calls. +ModelInputDict = Dict[str, TensorType] + +# Some kind of sample batch. +SampleBatchType = Union["SampleBatch", "MultiAgentBatch", Dict[str, Any]] + +# A (possibly nested) space struct: Either a gym.spaces.Space or a +# (possibly nested) dict|tuple of gym.space.Spaces. +SpaceStruct = Union[gym.spaces.Space, dict, tuple] + +# A list of batches of RNN states. +# Each item in this list has dimension [B, S] (S=state vector size) +StateBatches = List[List[Any]] # @OldAPIStack + +# Format of data output from policy forward pass. +# __sphinx_doc_begin_policy_output_type__ +PolicyOutputType = Tuple[TensorStructType, StateBatches, Dict] # @OldAPIStack +# __sphinx_doc_end_policy_output_type__ + + +# __sphinx_doc_begin_agent_connector_data_type__ +@OldAPIStack +class AgentConnectorDataType: + """Data type that is fed into and yielded from agent connectors. + + Args: + env_id: ID of the environment. + agent_id: ID to help identify the agent from which the data is received. + data: A payload (``data``). With RLlib's default sampler, the payload + is a dictionary of arbitrary data columns (obs, rewards, terminateds, + truncateds, etc). + """ + + def __init__(self, env_id: str, agent_id: str, data: Any): + self.env_id = env_id + self.agent_id = agent_id + self.data = data + + +# __sphinx_doc_end_agent_connector_data_type__ + + +# __sphinx_doc_begin_action_connector_output__ +@OldAPIStack +class ActionConnectorDataType: + """Data type that is fed into and yielded from agent connectors. + + Args: + env_id: ID of the environment. + agent_id: ID to help identify the agent from which the data is received. + input_dict: Input data that was passed into the policy. + Sometimes output must be adapted based on the input, for example + action masking. So the entire input data structure is provided here. + output: An object of PolicyOutputType. It is is composed of the + action output, the internal state output, and additional data fetches. + + """ + + def __init__( + self, + env_id: str, + agent_id: str, + input_dict: TensorStructType, + output: PolicyOutputType, + ): + self.env_id = env_id + self.agent_id = agent_id + self.input_dict = input_dict + self.output = output + + +# __sphinx_doc_end_action_connector_output__ + + +# __sphinx_doc_begin_agent_connector_output__ +@OldAPIStack +class AgentConnectorsOutput: + """Final output data type of agent connectors. + + Args are populated depending on the AgentConnector settings. + The branching happens in ViewRequirementAgentConnector. + + Args: + raw_dict: The raw input dictionary that sampler can use to + build episodes and training batches. + This raw dict also gets passed into ActionConnectors in case + it contains data useful for action adaptation (e.g. action masks). + sample_batch: The SampleBatch that can be immediately used for + querying the policy for next action. + """ + + def __init__( + self, raw_dict: Dict[str, TensorStructType], sample_batch: "SampleBatch" + ): + self.raw_dict = raw_dict + self.sample_batch = sample_batch + + +# __sphinx_doc_end_agent_connector_output__ + + +# Generic type var. +T = TypeVar("T")