Repository navigation
Expand file tree
/
Copy pathtracking.py
More file actions
939 lines (760 loc) · 33.2 KB
/
Copy pathtracking.py
File metadata and controls
939 lines (760 loc) · 33.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
# Copyright 2024 Bytedance Ltd. and/or its affiliates
#
# 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
#
# http://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.
"""
A unified tracking interface that supports logging data to different backend
"""
import dataclasses
import inspect
import json
import logging
import os
from contextlib import contextmanager
from enum import Enum
from functools import partial, wraps
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Callable
import orjson
from packaging.version import Version
logger = logging.getLogger(__name__)
MLFLOW_MAX_ATTEMPTS = 3
MLFLOW_SLEEP_SECONDS = 5
class Tracking:
"""A unified tracking interface for logging experiment data to multiple backends.
This class provides a centralized way to log experiment metrics, parameters, and artifacts
to various tracking backends including WandB, MLflow, SwanLab, TensorBoard, and console.
Attributes:
supported_backend: List of supported tracking backends.
logger: Dictionary of initialized logger instances for each backend.
"""
supported_backend = [
"wandb",
"mlflow",
"swanlab",
"vemlp_wandb",
"tensorboard",
"console",
"clearml",
"trackio",
"file",
"rl_insight",
]
def __init__(self, project_name, experiment_name, default_backend: str | list[str] = "console", config=None):
if isinstance(default_backend, str):
default_backend = [default_backend]
for backend in default_backend:
if backend == "tracking":
import warnings
warnings.warn("`tracking` logger is deprecated. use `wandb` instead.", DeprecationWarning, stacklevel=2)
else:
assert backend in self.supported_backend, f"{backend} is not supported"
self.logger = {}
self._finished = False
if "tracking" in default_backend or "wandb" in default_backend:
import os
import wandb
settings = None
if config and config["trainer"].get("wandb_proxy", None):
settings = wandb.Settings(https_proxy=config["trainer"]["wandb_proxy"])
entity = os.environ.get("WANDB_ENTITY", None)
wandb.init(project=project_name, name=experiment_name, entity=entity, config=config, settings=settings)
self.logger["wandb"] = wandb
if "trackio" in default_backend:
import trackio
from trackio import context_vars
if context_vars.current_run.get() is None:
trackio.init(project=project_name, name=experiment_name, config=config)
self.logger["trackio"] = _TrackioLoggingAdapter(trackio)
if "mlflow" in default_backend:
import os
import time
import mlflow
for _mlflow_attempt in range(1, MLFLOW_MAX_ATTEMPTS + 1):
try:
MLFLOW_TRACKING_URI = os.environ.get("MLFLOW_TRACKING_URI", "sqlite:////tmp/mlruns.db")
logger.info("Using MLFlow tracking URI: %s", MLFLOW_TRACKING_URI)
mlflow.set_tracking_uri(MLFLOW_TRACKING_URI)
# Some cloud providers like Azure ML or Databricks automatically set MLFLOW_RUN_ID
# If set, attach to the existing run instead of creating a new one
run_id = os.environ.get("MLFLOW_RUN_ID")
if run_id:
mlflow.start_run(run_id=run_id)
else:
# Project_name is actually experiment_name in MLFlow
# If experiment does not exist, will create a new experiment
experiment = mlflow.set_experiment(project_name)
mlflow.start_run(experiment_id=experiment.experiment_id, run_name=experiment_name)
mlflow.log_params(_compute_mlflow_params_from_objects(config))
self.logger["mlflow"] = _MlflowLoggingAdapter()
break # Success
except Exception as e:
logger.warning(
"MLflow initialization attempt %d/%d failed: %s", _mlflow_attempt, MLFLOW_MAX_ATTEMPTS, e
)
if _mlflow_attempt < MLFLOW_MAX_ATTEMPTS:
time.sleep(MLFLOW_SLEEP_SECONDS)
else:
logger.warning("All MLflow initialization attempts failed. Proceeding without MLflow tracking.")
if "swanlab" in default_backend:
import os
import swanlab
SWANLAB_API_KEY = os.environ.get("SWANLAB_API_KEY", None)
SWANLAB_LOG_DIR = os.environ.get("SWANLAB_LOG_DIR", "swanlog")
SWANLAB_MODE = os.environ.get("SWANLAB_MODE", "cloud")
if SWANLAB_API_KEY:
swanlab.login(SWANLAB_API_KEY) # NOTE: previous login information will be overwritten
if config is None:
config = {} # make sure config is not None, otherwise **config will raise error
swanlab.init(
project=project_name,
experiment_name=experiment_name,
config={"FRAMEWORK": "verl", **config},
logdir=SWANLAB_LOG_DIR,
mode=SWANLAB_MODE,
)
self.logger["swanlab"] = swanlab
if "vemlp_wandb" in default_backend:
import os
import volcengine_ml_platform
from volcengine_ml_platform import wandb as vemlp_wandb
volcengine_ml_platform.init(
ak=os.environ["VOLC_ACCESS_KEY_ID"],
sk=os.environ["VOLC_SECRET_ACCESS_KEY"],
region=os.environ["MLP_TRACKING_REGION"],
)
vemlp_wandb.init(
project=project_name,
name=experiment_name,
config=config,
sync_tensorboard=True,
)
self.logger["vemlp_wandb"] = vemlp_wandb
if "tensorboard" in default_backend:
self.logger["tensorboard"] = _TensorboardAdapter(project_name, experiment_name)
if "console" in default_backend:
from verl.utils.logger import LocalLogger
self.console_logger = LocalLogger(print_to_console=True)
self.logger["console"] = self.console_logger
if "clearml" in default_backend:
self.logger["clearml"] = ClearMLLogger(project_name, experiment_name, config)
if "file" in default_backend:
self.logger["file"] = FileLogger(project_name, experiment_name)
if "rl_insight" in default_backend:
self.logger["rl_insight"] = RLInsightLogger(project_name, experiment_name, config)
def log(self, data, step, backend=None):
for default_backend, logger_instance in self.logger.items():
if backend is None or default_backend in backend:
logger_instance.log(data=data, step=step)
def finish(self, exit_code: int = 0):
"""Flush and finalize every configured backend exactly once."""
if getattr(self, "_finished", False):
return
self._finished = True
loggers = getattr(self, "logger", {})
if "wandb" in loggers:
loggers["wandb"].finish(exit_code=exit_code)
if "swanlab" in loggers:
loggers["swanlab"].finish()
if "vemlp_wandb" in loggers:
loggers["vemlp_wandb"].finish(exit_code=exit_code)
if "tensorboard" in loggers:
loggers["tensorboard"].finish()
if "clearml" in loggers:
loggers["clearml"].finish()
if "mlflow" in loggers:
loggers["mlflow"].finish()
if "trackio" in loggers:
loggers["trackio"].finish()
if "file" in loggers:
loggers["file"].finish()
if "rl_insight" in loggers:
loggers["rl_insight"].finish()
def __del__(self):
self.finish()
class RLInsightLogger:
"""Logger backend that exports scalar metrics and rl-insight runtime signals."""
ENABLE_ENV = "VERL_RL_INSIGHT_ENABLE"
MINIMUM_RL_INSIGHT_VERSION = Version("0.3.0")
_init_done = False
_rl_insight_module = None
_registered_metrics: set[tuple[str | None, tuple[str, ...], str | None]] = set()
_warned_unsupported_features: set[str] = set()
def __init__(self, project_name, experiment_name, config=None):
self.init(project_name=project_name, experiment_name=experiment_name, config=config)
@classmethod
def _get_rl_insight(cls):
if cls._rl_insight_module is None:
import rl_insight
cls._rl_insight_module = rl_insight
return cls._rl_insight_module
@classmethod
def enabled(cls) -> bool:
"""Return whether rl-insight is globally enabled in this process."""
return os.getenv(cls.ENABLE_ENV) == "1"
@classmethod
def _warn_unsupported_rl_insight(cls, feature: str) -> None:
"""Warn once when an optional RL-Insight feature is unavailable."""
if feature in cls._warned_unsupported_features:
return
cls._warned_unsupported_features.add(feature)
logger.warning(
"RL-Insight does not support %s (requires >= %s); monitoring is disabled for this feature",
feature,
cls.MINIMUM_RL_INSIGHT_VERSION,
)
@classmethod
def _rl_insight_version(cls) -> Version:
module = cls._get_rl_insight()
return Version(getattr(module, "__version__", "0"))
@classmethod
def init(cls, project_name=None, experiment_name=None, config=None):
if not cls.enabled() or cls._init_done:
return
rl_insight_config = {}
if config is not None:
try:
rl_insight_config = config.get("trainer", {}).get("rl_insight", {}) or {}
except (AttributeError, KeyError, TypeError):
pass
cls._get_rl_insight().init(project=project_name, experiment_name=experiment_name, config=rl_insight_config)
cls._init_done = True
if config is not None:
cls.register_transfer_queue_metrics(config)
@classmethod
def log(cls, data, step):
if not cls.enabled():
return
cls._ensure_rl_insight_init()
module = cls._get_rl_insight()
# Present on current main, but not in the released 0.3.0 package.
metric_log = getattr(module, "metric_log", None)
if not callable(metric_log):
metric_log = None
for key, value in data.items():
try:
scalar = float(value)
except (TypeError, ValueError):
continue
if metric_log is not None:
metric_log(str(key), scalar, step=int(step))
else:
module.metric_gauge(str(key).replace("/", "_"), scalar)
@classmethod
def finish(cls):
if not cls._init_done:
return
cls._get_rl_insight().finish()
cls._init_done = False
cls._registered_metrics.clear()
@classmethod
@contextmanager
def trace_state(
cls,
state_name: str,
*,
state_lane_id: str | int | None = None,
**labels: Any,
):
if not cls.enabled():
yield
return
cls._ensure_rl_insight_init()
with cls._get_rl_insight().trace_state(state_name, state_lane_id=state_lane_id, **labels):
yield
@classmethod
def trace_state_decorator(
cls,
state_name: str,
*,
state_lane_id: str | int | Callable[[Any], str | int | None] | None = None,
):
"""Decorate an async instance method with an RL-Insight state trace."""
def decorator(method):
if not inspect.iscoroutinefunction(method):
raise TypeError("trace_state_decorator can only decorate async methods")
@wraps(method)
async def wrapped(self, *args, **kwargs):
if not cls.enabled():
return await method(self, *args, **kwargs)
lane_id = state_lane_id(self) if callable(state_lane_id) else state_lane_id
with cls.trace_state(state_name, state_lane_id=lane_id):
return await method(self, *args, **kwargs)
return wrapped
return decorator
@classmethod
def trace_span(
cls,
name: str,
*,
start_time_ns: int,
end_time_ns: int,
attributes: dict[str, Any] | None = None,
) -> None:
"""Report one completed span through rl-insight's direct trace API."""
if not cls.enabled():
return
module = cls._get_rl_insight()
if cls._rl_insight_version() < cls.MINIMUM_RL_INSIGHT_VERSION or not callable(
getattr(module, "trace_span", None)
):
cls._warn_unsupported_rl_insight("trace_span")
return
cls._ensure_rl_insight_init()
cls._get_rl_insight().trace_span(
name=name,
start_time_ns=start_time_ns,
end_time_ns=end_time_ns,
attributes=dict(attributes or {}),
)
@classmethod
def _ensure_rl_insight_init(cls) -> None:
if not cls._init_done:
cls._get_rl_insight().init()
cls._init_done = True
@classmethod
def agent_loop_session(
cls,
*,
experiment_name: Any | None = None,
sample: Any,
session: Any,
traj: Any = 0,
uid: Any = None,
global_steps: Any = None,
session_id: Any = None,
):
"""Return the shared agent-loop session trace state."""
from verl.utils.rollout_trace import RolloutTraceConfig
rollout_config = RolloutTraceConfig.get_instance()
project_name = rollout_config.project_name
if experiment_name is None:
experiment_name = rollout_config.experiment_name or "default"
def fallback_session():
return SimpleNamespace(
identity={
"project": project_name or "default",
"experiment_name": experiment_name,
"sample": str(sample),
"session": str(session),
"traj": str(traj),
"state_lane_id": f"experiment={experiment_name}/sample={sample}/session={session}/traj={traj}",
"uid": uid or "",
"global_steps": global_steps if global_steps is not None else "",
"session_id": session_id or "",
},
finish=lambda **kwargs: None,
)
if cls.enabled() and cls._rl_insight_version() < cls.MINIMUM_RL_INSIGHT_VERSION:
cls._warn_unsupported_rl_insight("agent_loop_session")
return fallback_session()
if cls.enabled() and not cls._init_done:
cls.init(project_name=project_name, experiment_name=experiment_name)
try:
from rl_insight.agent_loop import agent_loop_session
except ImportError:
cls._warn_unsupported_rl_insight("agent_loop_session")
return fallback_session()
return agent_loop_session(
project=project_name,
experiment_name=experiment_name,
sample=sample,
session=session,
traj=traj,
uid=uid,
global_steps=global_steps,
session_id=session_id,
)
@classmethod
def register_rollout_metrics(
cls,
server_addresses: list[str],
rollout_name: str | None,
labels: list[dict[str, Any] | None] | None = None,
) -> None:
cls.register_metrics(server_addresses, rollout_name, labels)
@classmethod
def register_transfer_queue_metrics(cls, config) -> None:
if not (config or {}).get("transfer_queue", {}).get("metrics", {}).get("enabled", False):
return
try:
import transfer_queue as tq
endpoint = tq.get_metrics_endpoint()
except Exception:
logger.exception("[rl-insight] Failed to get transfer_queue metrics endpoint")
return
if endpoint:
cls.register_metrics([endpoint], "transfer_queue", None)
@classmethod
def register_metrics(
cls,
server_addresses: list[str],
job_name: str | None = None,
labels: list[dict[str, Any] | None] | None = None,
) -> None:
if not cls.enabled():
return
metric_key = (job_name, tuple(server_addresses), repr(labels))
if metric_key in cls._registered_metrics:
return
try:
cls._get_rl_insight().update_prometheus_config(server_addresses, job_name, labels)
cls._registered_metrics.add(metric_key)
except Exception:
logger.exception("[rl-insight] Failed to register metrics endpoint")
class ClearMLLogger:
def __init__(self, project_name: str, experiment_name: str, config):
self.project_name = project_name
self.experiment_name = experiment_name
import clearml
self._task: clearml.Task = clearml.Task.init(
task_name=experiment_name,
project_name=project_name,
continue_last_task=True,
output_uri=False,
)
self._task.connect_configuration(config, name="Hyperparameters")
def _get_logger(self):
return self._task.get_logger()
def log(self, data, step):
import numpy as np
import pandas as pd
# logs = self._rewrite_logs(data)
logger = self._get_logger()
for k, v in data.items():
title, series = k.split("/", 1)
if isinstance(v, int | float | np.floating | np.integer):
logger.report_scalar(
title=title,
series=series,
value=v,
iteration=step,
)
elif isinstance(v, pd.DataFrame):
logger.report_table(
title=title,
series=series,
table_plot=v,
iteration=step,
)
else:
logger.warning(
f'Trainer is attempting to log a value of "{v}" of type {type(v)} for key "{k}". This '
f"invocation of ClearML logger's function is incorrect so this attribute was dropped. "
)
def finish(self):
self._task.close()
class _TrackioLoggingAdapter:
def __init__(self, trackio):
self.trackio = trackio
def log(self, data, step):
self.trackio.log(data, step=step)
def finish(self):
from trackio import context_vars
if context_vars.current_run.get() is not None:
self.trackio.finish()
class FileLogger:
def __init__(self, project_name: str, experiment_name: str):
self.project_name = project_name
self.experiment_name = experiment_name
self.filepath = os.getenv("VERL_FILE_LOGGER_PATH", None)
if self.filepath is None:
root_path = os.path.expanduser(os.getenv("VERL_FILE_LOGGER_ROOT", "."))
directory = os.path.join(root_path, self.project_name)
os.makedirs(directory, exist_ok=True)
self.filepath = os.path.join(directory, f"{self.experiment_name}.jsonl")
print(f"Creating file logger at {os.path.abspath(self.filepath)}")
self.fp = open(self.filepath, "wb", buffering=0)
def log(self, data, step):
data = {"step": step, "data": data}
self.fp.write(orjson.dumps(data, option=orjson.OPT_SERIALIZE_NUMPY) + b"\n")
def finish(self):
self.fp.close()
class _TensorboardAdapter:
def __init__(self, project_name, experiment_name):
import os
from torch.utils.tensorboard import SummaryWriter
tensorboard_dir = os.environ.get("TENSORBOARD_DIR", f"tensorboard_log/{project_name}/{experiment_name}")
os.makedirs(tensorboard_dir, exist_ok=True)
print(f"Saving tensorboard log to {tensorboard_dir}.")
self.writer = SummaryWriter(tensorboard_dir)
def log(self, data, step):
for key in data:
self.writer.add_scalar(key, data[key], step)
def finish(self):
self.writer.close()
class _MlflowLoggingAdapter:
def __init__(self):
import logging
import re
self.logger = logging.getLogger(__name__)
# Suppress noisy "Found credentials from IAM Role" on every MLflow request
logging.getLogger("botocore.credentials").setLevel(logging.WARNING)
# MLflow metric key validation logic:
# https://github.com/mlflow/mlflow/blob/master/mlflow/utils/validation.py#L157C12-L157C44
# Only characters allowed: slashes, alphanumerics, underscores, periods, dashes, colons,
# and spaces.
self._invalid_chars_pattern = re.compile(
r"[^/\w.\- :]"
) # Allowed: slashes, alphanumerics, underscores, periods, dashes, colons, and spaces.
self._consecutive_slashes_pattern = re.compile(r"/+")
self._sanitized_key_cache = {}
def _sanitize_key(self, key):
if key in self._sanitized_key_cache:
return self._sanitized_key_cache[key] or key
# First replace @ with _at_ for backward compatibility
sanitized = key.replace("@", "_at_")
# Replace consecutive slashes with a single slash (MLflow treats them as file paths)
sanitized = self._consecutive_slashes_pattern.sub("/", sanitized)
# Then replace any other invalid characters with _
sanitized = self._invalid_chars_pattern.sub("_", sanitized)
if sanitized == key:
self._sanitized_key_cache[key] = None
else:
self.logger.warning("[MLflow] Metric key '%s' sanitized to '%s' due to invalid characters.", key, sanitized)
self._sanitized_key_cache[key] = sanitized
return sanitized
def log(self, data, step):
import mlflow
results = {self._sanitize_key(k): v for k, v in data.items()}
for _attempt in range(MLFLOW_MAX_ATTEMPTS):
try:
mlflow.log_metrics(metrics=results, step=step)
return
except Exception as error:
# No sleep between retries — this runs per training step, so we avoid blocking.
msg = "mlflow.log_metrics failed (attempt %d/%d): %s"
args = (_attempt + 1, MLFLOW_MAX_ATTEMPTS, error)
if _attempt < MLFLOW_MAX_ATTEMPTS - 1:
self.logger.info(msg, *args)
else:
self.logger.warning(msg, *args)
def finish(self):
import mlflow
if mlflow.active_run() is not None:
mlflow.end_run()
def _compute_mlflow_params_from_objects(params) -> dict[str, Any]:
if params is None:
return {}
return _flatten_dict(_transform_params_to_json_serializable(params, convert_list_to_dict=True), sep="/")
def _transform_params_to_json_serializable(x, convert_list_to_dict: bool):
_transform = partial(_transform_params_to_json_serializable, convert_list_to_dict=convert_list_to_dict)
if dataclasses.is_dataclass(x):
return _transform(dataclasses.asdict(x))
if isinstance(x, dict):
return {k: _transform(v) for k, v in x.items()}
if isinstance(x, list):
if convert_list_to_dict:
return {"list_len": len(x)} | {f"{i}": _transform(v) for i, v in enumerate(x)}
else:
return [_transform(v) for v in x]
if isinstance(x, Path):
return str(x)
if isinstance(x, Enum):
return x.value
return x
def _flatten_dict(raw: dict[str, Any], *, sep: str) -> dict[str, Any]:
import pandas as pd
ans = pd.json_normalize(raw, sep=sep).to_dict(orient="records")[0]
assert isinstance(ans, dict)
return ans
@dataclasses.dataclass
class ValidationGenerationsLogger:
project_name: str = None
experiment_name: str = None
def log(self, loggers, samples, step):
if "wandb" in loggers:
self.log_generations_to_wandb(samples, step)
if "swanlab" in loggers:
self.log_generations_to_swanlab(samples, step)
if "mlflow" in loggers:
self.log_generations_to_mlflow(samples, step)
if "trackio" in loggers:
self.log_generations_to_trackio(samples, step)
if "clearml" in loggers:
self.log_generations_to_clearml(samples, step)
if "tensorboard" in loggers:
self.log_generations_to_tensorboard(samples, step)
if "vemlp_wandb" in loggers:
self.log_generations_to_vemlp_wandb(samples, step)
def log_generations_to_vemlp_wandb(self, samples, step):
from volcengine_ml_platform import wandb as vemlp_wandb
self._log_generations_to_wandb(samples, step, vemlp_wandb)
def log_generations_to_wandb(self, samples, step):
import wandb
self._log_generations_to_wandb(samples, step, wandb)
def _log_generations_to_wandb(self, samples, step, wandb):
"""Log samples to wandb as a table"""
# Create column names for all samples
columns = ["step"] + sum(
[[f"input_{i + 1}", f"output_{i + 1}", f"score_{i + 1}"] for i in range(len(samples))], []
)
if not hasattr(self, "validation_table"):
# Initialize the table on first call
self.validation_table = wandb.Table(columns=columns)
# Create a new table with same columns and existing data
# Workaround for https://github.com/wandb/wandb/issues/2981#issuecomment-1997445737
new_table = wandb.Table(columns=columns, data=self.validation_table.data)
# Add new row with all data
row_data = []
row_data.append(step)
for sample in samples:
row_data.extend(sample)
new_table.add_data(*row_data)
# Update reference and log
if wandb.run is not None:
wandb.log({"val/generations": new_table}, step=step)
self.validation_table = new_table
def log_generations_to_swanlab(self, samples, step):
"""Log samples to swanlab as text"""
import swanlab
swanlab_table = swanlab.echarts.Table()
# Create column names
headers = ["step", "input", "output", "score"]
swanlab_row_list = [[step, *sample] for sample in samples]
swanlab_table.add(headers=headers, rows=swanlab_row_list)
# Log to swanlab
swanlab.log({"val/generations": swanlab_table}, step=step)
def log_generations_to_mlflow(self, samples, step):
"""Log validation generation to mlflow as artifacts"""
# https://mlflow.org/docs/latest/api_reference/python_api/mlflow.html?highlight=log_artifact#mlflow.log_artifact
import tempfile
import mlflow
try:
with tempfile.TemporaryDirectory() as tmp_dir:
validation_gen_step_file = Path(tmp_dir, f"val_step{step}.json")
row_data = []
for sample in samples:
data = {"input": sample[0], "output": sample[1], "score": sample[2]}
row_data.append(data)
with open(validation_gen_step_file, "w") as file:
json.dump(row_data, file)
mlflow.log_artifact(validation_gen_step_file)
except Exception as e:
print(f"WARNING: save validation generation file to mlflow failed with error {e}")
def log_generations_to_trackio(self, samples, step):
"""Log validation generations to trackio as traces."""
import trackio
traces = []
for sample_index, sample in enumerate(samples):
if len(sample) >= 3:
input_text, output_text, score = sample[0], sample[1], sample[2]
else:
input_text, output_text, score = sample, "", None
traces.append(
trackio.Trace(
messages=[
{"role": "user", "content": str(input_text)},
{"role": "assistant", "content": str(output_text)},
],
metadata={
"source": "validation_generations",
"sample_index": sample_index,
"score": score,
},
)
)
if traces:
trackio.log({"val/generations": traces}, step=step)
def log_generations_to_clearml(self, samples, step):
"""Log validation generation to clearml as table"""
import clearml
import pandas as pd
task: clearml.Task | None = clearml.Task.current_task()
if task is None:
return
table = [
{
"step": step,
"input": sample[0],
"output": sample[1],
"score": sample[2],
}
for sample in samples
]
logger = task.get_logger()
logger.report_table(
series="Validation generations",
title="Validation",
table_plot=pd.DataFrame.from_records(table),
iteration=step,
)
def log_generations_to_tensorboard(self, samples, step):
"""Log samples to tensorboard as text"""
# Initialize tensorboard writer if not exists
if not hasattr(self, "writer"):
from torch.utils.tensorboard import SummaryWriter
# Use the same directory structure as _TensorboardAdapter
if self.project_name and self.experiment_name:
default_dir = os.path.join("tensorboard_log", self.project_name, self.experiment_name)
else:
default_dir = "tensorboard_log"
tensorboard_dir = os.environ.get("TENSORBOARD_DIR", default_dir)
os.makedirs(tensorboard_dir, exist_ok=True)
self.writer = SummaryWriter(log_dir=tensorboard_dir)
# Format the samples data into readable text
text_content = f"**Generation Results - Step {step}**\n\n"
for i, sample in enumerate(samples):
text_content += f"### Sample {i + 1}\n"
# Assuming sample contains [input, output, score]
if len(sample) >= 3:
input_text, output_text, score = sample[0], sample[1], sample[2]
text_content += f"**Input:** {input_text}\n\n"
text_content += f"**Output:** {output_text}\n\n"
text_content += f"**Score:** {score}\n\n"
else:
# Handle cases where sample format might be different
text_content += f"**Data:** {sample}\n\n"
text_content += "---\n\n"
# Log to tensorboard as text
self.writer.add_text("val/generations", text_content, step)
# Flush to ensure data is written
self.writer.flush()
@dataclasses.dataclass
class DapoFilteredRewardTableLogger:
"""Wandb table of DAPO-filtered (no-signal) group counts per reward value.
Each training step adds one row containing compact ``reward:count`` pairs. Wandb 0.20+
uploads rows incrementally; older versions rebuild the full table for compatibility.
Intentionally wandb-only: this "value distribution over time" view is a table, which other
tracking backends do not render usefully. Non-wandb backends are silently skipped.
"""
project_name: str = None
experiment_name: str = None
def log(self, loggers, reward_counts: dict, step: int):
"""reward_counts maps metric value -> count for this step (already merged across mini-batches)."""
if "wandb" in loggers:
self._log_to_wandb(reward_counts, step)
def _log_to_wandb(self, reward_counts: dict, step: int):
import wandb
if wandb.run is None:
return
row = {float(value): int(count) for value, count in reward_counts.items()}
counts_text = ", ".join(f"{value:g}:{row[value]}" for value in sorted(row))
columns = ["step", "reward_counts"]
if not hasattr(self, "_use_incremental_table"):
self._use_incremental_table = Version(wandb.__version__) >= Version("0.20.0")
if self._use_incremental_table:
self._table = wandb.Table(columns=columns, log_mode="INCREMENTAL")
else:
self._rows = []
logger.warning(
"wandb<0.20.0 does not support incremental tables; "
"the DAPO filtered-reward table will re-upload its full history each step."
)
if self._use_incremental_table:
self._table.add_data(step, counts_text)
table = self._table
else:
self._rows.append([step, counts_text])
table = wandb.Table(columns=columns, data=list(self._rows))
wandb.log({"training/filter_groups/filtered_reward_counts": table}, step=step)