|
| 1 | +# Copyright 2025 The Orbax Authors. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Benchmarks for orbax.checkpoint.PyTreeCheckpointHandler.""" |
| 16 | + |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +import dataclasses |
| 20 | +import pprint |
| 21 | +import time |
| 22 | +from typing import Any |
| 23 | + |
| 24 | +from absl import logging |
| 25 | +import jax |
| 26 | +from jax.experimental import multihost_utils |
| 27 | +import numpy as np |
| 28 | +import orbax.checkpoint as ocp_v0 # pylint: disable=unused-import |
| 29 | +from orbax.checkpoint import v1 as ocp |
| 30 | +from orbax.checkpoint._src.testing.benchmarks.core import core as benchmarks_core |
| 31 | +from orbax.checkpoint._src.testing.benchmarks.core import metric as metric_lib |
| 32 | +import requests |
| 33 | + |
| 34 | + |
| 35 | +SERVICE_URL = "http://service-dns/" |
| 36 | + |
| 37 | + |
| 38 | +def _metrics_to_measure(options: LustreBenchmarkOptions) -> list[str]: |
| 39 | + """Returns the list of metrics to measure.""" |
| 40 | + del options |
| 41 | + metrics = ["time", "rss", "io"] |
| 42 | + return metrics |
| 43 | + |
| 44 | + |
| 45 | +# ============================================================================== |
| 46 | +# 1. Define the Options Dataclass for this specific benchmark |
| 47 | +# ============================================================================== |
| 48 | +@dataclasses.dataclass(frozen=True) |
| 49 | +class LustreBenchmarkOptions(benchmarks_core.BenchmarkOptions): |
| 50 | + """Configuration options for benchmarks targeting PyTreeCheckpointHandler. |
| 51 | +
|
| 52 | + Each attribute can be a single value or a list of values to create |
| 53 | + a parameter sweep. |
| 54 | +
|
| 55 | + Attributes: |
| 56 | + use_ocdbt: Whether to use OCDBT for checkpointing. |
| 57 | + steps: Number of steps to run the benchmark for. |
| 58 | + """ |
| 59 | + |
| 60 | + use_ocdbt: bool = True |
| 61 | + steps: int = 1 |
| 62 | + |
| 63 | + def is_valid(self): |
| 64 | + return True |
| 65 | + |
| 66 | + |
| 67 | +class StorageServiceClient: |
| 68 | + """Docstring.""" |
| 69 | + |
| 70 | + def __init__(self, service_url: str | None = None): |
| 71 | + self._service_url = service_url or SERVICE_URL |
| 72 | + |
| 73 | + def resolve(self, execution_id: int, step: int) -> str: |
| 74 | + """Resolves an asset path from the service.""" |
| 75 | + start = time.time() |
| 76 | + logging.info("Resolving ID-step: %s-%s.", execution_id, step) |
| 77 | + payload = {"execution_id": execution_id, "step": step} |
| 78 | + response = requests.post(f"{self._service_url}/resolve", json=payload) |
| 79 | + logging.info("Response: %s", response.json()) |
| 80 | + response.raise_for_status() |
| 81 | + result = response.json()["path"] |
| 82 | + end = time.time() |
| 83 | + logging.info("Resolved %s in %s seconds.", result, end - start) |
| 84 | + return result |
| 85 | + |
| 86 | + def finalize(self, execution_id: int, step: int) -> None: |
| 87 | + """Finalizes an asset in the service.""" |
| 88 | + start = time.time() |
| 89 | + payload = {"execution_id": execution_id, "step": step} |
| 90 | + response = requests.post(f"{self._service_url}/finalize", json=payload) |
| 91 | + response.raise_for_status() |
| 92 | + logging.info(response) |
| 93 | + # assert response.json()["status"] == "ok" |
| 94 | + end = time.time() |
| 95 | + logging.info( |
| 96 | + "Finalized %s %s in %s seconds.", execution_id, step, end - start |
| 97 | + ) |
| 98 | + |
| 99 | + |
| 100 | +def _get_xid() -> int: |
| 101 | + """Returns the XID for this run.""" |
| 102 | + xid = multihost_utils.broadcast_one_to_all( |
| 103 | + np.asarray(int(time.time())) |
| 104 | + ).item() |
| 105 | + logging.info("XID: %s", xid) |
| 106 | + return xid |
| 107 | + |
| 108 | + |
| 109 | +# ============================================================================== |
| 110 | +# 2. Implement the Benchmark Generator |
| 111 | +# ============================================================================== |
| 112 | +@benchmarks_core.benchmark_options(LustreBenchmarkOptions) |
| 113 | +class LustreBenchmark(benchmarks_core.BenchmarksGenerator): |
| 114 | + """Docstring.""" |
| 115 | + |
| 116 | + def __init__(self, *args, **kwargs): |
| 117 | + super().__init__(*args, **kwargs) |
| 118 | + self._client = StorageServiceClient() |
| 119 | + self._xid = _get_xid() |
| 120 | + |
| 121 | + def _clear_pytree(self, pytree: Any) -> Any: |
| 122 | + """Clears the pytree to free up memory.""" |
| 123 | + return jax.tree.map( |
| 124 | + lambda x: x.delete() if isinstance(x, jax.Array) else None, pytree |
| 125 | + ) |
| 126 | + |
| 127 | + def test_fn( |
| 128 | + self, context: benchmarks_core.TestContext |
| 129 | + ) -> benchmarks_core.TestResult: |
| 130 | + """The core test logic for a single save/restore cycle. |
| 131 | +
|
| 132 | + This function is called for each combination of options generated by the |
| 133 | + framework. It uses the `context.options` to configure the handler |
| 134 | + dynamically for each run. |
| 135 | +
|
| 136 | + Args: |
| 137 | + context: The test context containing the pytree, path, and options. |
| 138 | +
|
| 139 | + Returns: |
| 140 | + The test result containing the metrics. |
| 141 | + """ |
| 142 | + logging.info( |
| 143 | + "JAX info: %s processes, %s devices, %s process index", |
| 144 | + jax.process_count(), |
| 145 | + jax.device_count(), |
| 146 | + jax.process_index(), |
| 147 | + ) |
| 148 | + metrics = metric_lib.Metrics() |
| 149 | + pytree = context.pytree |
| 150 | + options = context.options |
| 151 | + assert isinstance(options, LustreBenchmarkOptions) |
| 152 | + |
| 153 | + logging.info("Benchmark options: %s", pprint.pformat(options)) |
| 154 | + logging.info("Benchmark context: %s", pprint.pformat(context)) |
| 155 | + metrics_to_measure = _metrics_to_measure(options) |
| 156 | + |
| 157 | + for step in range(options.steps): |
| 158 | + logging.info("Benchmark step %d", step) |
| 159 | + |
| 160 | + with metrics.measure("resolve_cache", metrics_to_measure): |
| 161 | + resolved_path = self._client.resolve(self._xid, step) |
| 162 | + with metrics.measure("save_cache", metrics_to_measure): |
| 163 | + ocp.save_pytree(resolved_path, pytree) |
| 164 | + with metrics.measure("finalize_cache", metrics_to_measure): |
| 165 | + self._client.finalize(self._xid, step) |
| 166 | + with metrics.measure("restore_cache", metrics_to_measure): |
| 167 | + restored_pytree = ocp.load_pytree(resolved_path, pytree) |
| 168 | + self._clear_pytree(restored_pytree) |
| 169 | + |
| 170 | + with metrics.measure("save", metrics_to_measure): |
| 171 | + ocp.save_pytree(context.path / str(step), pytree) |
| 172 | + with metrics.measure("restore", metrics_to_measure): |
| 173 | + restored_pytree = ocp.load_pytree(context.path / str(step), pytree) |
| 174 | + self._clear_pytree(restored_pytree) |
| 175 | + |
| 176 | + return benchmarks_core.TestResult(metrics=metrics) |
0 commit comments