|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +"""Run-metadata exporters. |
| 16 | +
|
| 17 | +`setup_exporters` opens one exporter per configured backend during global config resolution; call |
| 18 | +sites then fan out through the module-level `export_*` helpers. |
| 19 | +
|
| 20 | +A backend's module — and with it a multi-hundred-millisecond tracking SDK import — is loaded only |
| 21 | +once its config says it is wired up. That is why the registry pairs each backend with a config |
| 22 | +model from `config_types` rather than asking the exporter class whether it is available. |
| 23 | +""" |
| 24 | + |
| 25 | +import atexit |
| 26 | +import logging |
| 27 | +from importlib import import_module |
| 28 | +from typing import Any, Optional |
| 29 | + |
| 30 | +from omegaconf import DictConfig |
| 31 | + |
| 32 | +from nemo_gym.config_types import ExporterConfig, MLFlowConfig, WANDBConfig |
| 33 | +from nemo_gym.exporters.base import BaseExporter |
| 34 | + |
| 35 | + |
| 36 | +logger = logging.getLogger(__name__) |
| 37 | + |
| 38 | +# Backend name -> (config model, "module:class"). |
| 39 | +EXPORTER_REGISTRY: dict[str, tuple[type[ExporterConfig], str]] = { |
| 40 | + "wandb": (WANDBConfig, "nemo_gym.exporters.wandb:WandbExporter"), |
| 41 | + "mlflow": (MLFlowConfig, "nemo_gym.exporters.mlflow:MLflowExporter"), |
| 42 | +} |
| 43 | + |
| 44 | +_EXPORTERS: list[BaseExporter] = [] |
| 45 | + |
| 46 | + |
| 47 | +def _load_exporter_class(class_path: str) -> type[BaseExporter]: |
| 48 | + module_name, class_name = class_path.split(":") |
| 49 | + return getattr(import_module(module_name), class_name) |
| 50 | + |
| 51 | + |
| 52 | +def get_exporters() -> list[BaseExporter]: |
| 53 | + """The exporters opened for this process. Empty when no backend is configured.""" |
| 54 | + return list(_EXPORTERS) |
| 55 | + |
| 56 | + |
| 57 | +def setup_exporters(global_config_dict: DictConfig) -> list[BaseExporter]: |
| 58 | + """Open every backend that is fully configured, and log the run config to each. |
| 59 | +
|
| 60 | + Replaces any previously opened exporters. A backend that fails to start is skipped with a |
| 61 | + warning: telemetry must not take the run down with it. |
| 62 | + """ |
| 63 | + teardown_exporters() |
| 64 | + |
| 65 | + for name, (config_model, class_path) in EXPORTER_REGISTRY.items(): |
| 66 | + if not config_model.model_validate(global_config_dict).is_available: |
| 67 | + continue |
| 68 | + try: |
| 69 | + exporter = _load_exporter_class(class_path)(global_config_dict) |
| 70 | + exporter.setup() |
| 71 | + except Exception as e: |
| 72 | + logger.warning(f"Exporter {name} failed to start; continuing without it: {e}", exc_info=True) |
| 73 | + continue |
| 74 | + |
| 75 | + exporter.export_config() |
| 76 | + _EXPORTERS.append(exporter) |
| 77 | + |
| 78 | + # Registered here rather than at import so this lands after any hook a backend installed while |
| 79 | + # opening. atexit runs LIFO, so ours goes first: the wandb SDK closes its service in its own |
| 80 | + # hook, which would leave our teardown talking to a dead socket. Re-registering is harmless |
| 81 | + # because `teardown_exporters` is idempotent. |
| 82 | + atexit.register(teardown_exporters) |
| 83 | + return get_exporters() |
| 84 | + |
| 85 | + |
| 86 | +def teardown_exporters() -> None: |
| 87 | + """Close all open exporters. Safe to call repeatedly and when none are open.""" |
| 88 | + while _EXPORTERS: |
| 89 | + exporter = _EXPORTERS.pop() |
| 90 | + try: |
| 91 | + exporter.teardown() |
| 92 | + except Exception as e: |
| 93 | + logger.warning(f"Exporter {exporter.name} failed to shut down cleanly: {e}", exc_info=True) |
| 94 | + |
| 95 | + |
| 96 | +def export_metrics(metrics: dict[str, Any], step: Optional[int] = None) -> None: |
| 97 | + for exporter in _EXPORTERS: |
| 98 | + exporter.export_metrics(metrics, step) |
| 99 | + |
| 100 | + |
| 101 | +def export_rollouts(rollouts: list[dict[str, Any]]) -> None: |
| 102 | + for exporter in _EXPORTERS: |
| 103 | + exporter.export_rollouts(rollouts) |
0 commit comments