Logging

class masa.common.metrics.BaseLogger(stdout: bool = True, tqdm: bool = True, tensorboard: bool = False, summary_writer: SummaryWriter | None = None, stats_window_size: int = 100, prefix: str = '')[source]

Bases: object

Base class for logging scalar statistics and distributions.

A logger ingests objects via add() and produces aggregated outputs via log(). Concrete subclasses define how they ingest and summarise data.

TensorBoard logging uses a tf.summary.SummaryWriter. If tensorboard is True then a writer must be provided.

Parameters:
  • stdout – If True, print logs to stdout via print() or tqdm.write().

  • tqdm – If True, use tqdm.write() for stdout printing.

  • tensorboard – If True, emit TensorBoard summaries.

  • summary_writer – TensorBoard writer. Required when tensorboard=True.

  • stats_window_size – Maximum number of recent scalar values retained per metric.

  • prefix – Optional string prefix for TensorBoard tag names and stdout display. If non-empty, a trailing "/" is ensured.

Variables:
  • stdout – Whether stdout logging is enabled.

  • tqdm – Whether tqdm-compatible printing is enabled.

  • tensorboard – Whether TensorBoard logging is enabled.

  • summary_writer – TensorBoard summary writer (may be None).

  • stats_window_size – Window size for scalar smoothing.

  • prefix – Namespace prefix ending with "/" (or empty).

  • stats – Mapping from metric key to a deque of recent values.

reset()[source]

Clear all buffered statistics.

add(new: Any)[source]

Ingest a new object into the logger.

Concrete subclasses define the supported input types.

Parameters:

new – Object to ingest.

Raises:

NotImplementedError – Always, in the base class.

log(step: int)[source]

Emit logs for a given global step.

Parameters:

step – Global step index used for TensorBoard summary steps.

Raises:

NotImplementedError – Always, in the base class.

class masa.common.metrics.StatsLogger(stdout: bool = True, tqdm: bool = True, tensorboard: bool = False, summary_writer: SummaryWriter | None = None, stats_window_size: int = 100, prefix: str = '')[source]

Bases: BaseLogger

Logger for streaming scalar stats (Stats) and distributions (Dist).

The add() method accepts a mapping whose values are one of:

  • Stats: expanded into multiple scalar keys (mean/std/min/max/mag).

  • Dist: captured for histogram logging.

  • float / int / numpy scalar: treated as a scalar time series.

Aggregation:
  • Scalars are smoothed by taking the mean of the most recent stats_window_size values.

  • Distributions are logged as histograms using the stored reservoir.

Notes

This class creates internal dictionaries stats_to_log and dists_to_log during log().

reset()[source]

Clear all buffered scalar and distribution values.

add(new: Mapping[str, Stats | Dist | float | int | floating])[source]

Add a batch of metrics to the logger.

Parameters:

new – Mapping from metric name to a supported metric object.

Raises:

NotImplementedError – If a value type is unsupported.

log(step: int)[source]

Aggregate buffered values and emit logs.

Parameters:

step – Global step index used for TensorBoard summary steps.

class masa.common.metrics.RolloutLogger(stdout: bool = True, tqdm: bool = True, tensorboard: bool = False, summary_writer: SummaryWriter | None = None, stats_window_size: int = 100, prefix: str = '')[source]

Bases: BaseLogger

Logger for episodic metrics produced during environment rollouts.

This logger is designed for per-episode summaries that arrive via an info dict (e.g., from Gymnasium environments). It looks for:

  • info["constraint"]["episode"]: constraint-related episode metrics

  • info["metrics"]["episode"]: generic episode metrics

and treats the values as scalars.

It also reports simple runtime diagnostics to stdout:

  • fps: \(\frac{\text{timesteps}}{\text{wall-clock seconds}}\)

  • time_elapsed: wall-clock seconds since the first add()

  • total_timesteps: the provided global step

Notes

The most recent value in each deque is treated as the “current episode” and excluded from the mean shown in stdout/TensorBoard (so the displayed mean reflects completed episodes only).

add(info: Mapping[str, Any], verbose: int = 0)[source]

Ingest an info dict and extract episodic scalars.

Parameters:
  • info – Rollout info mapping (typically from environment step). If present, the logger reads: info["constraint"]["episode"] and/or info["metrics"]["episode"].

  • verbose – Reserved for compatibility; currently unused.

log(step: int)[source]

Aggregate buffered episode metrics and emit logs.

Parameters:

step – Global step index used for TensorBoard summary steps.

class masa.common.metrics.TrainLogger(loggers: List[Tuple[str, Any]], stdout: bool = True, tqdm: bool = True, tensorboard: bool = False, summary_writer: SummaryWriter | None = None, stats_window_size: int | List[int] = 100, prefix: str = '')[source]

Bases: BaseLogger

Orchestrate multiple loggers for a training run.

A TrainLogger is a thin wrapper around a set of sub-loggers (e.g. StatsLogger, RolloutLogger). It forwards add() calls to the appropriate sub-logger and aggregates stdout/TensorBoard output.

Parameters:
  • loggers – A list of (name, ctor) pairs. ctor must be a BaseLogger subclass (or compatible callable) that can be constructed with the same keyword arguments as BaseLogger.

  • stdout – If True, print a combined stdout table for all sub-loggers.

  • tqdm – If True, use tqdm.write() when printing.

  • tensorboard – If True, forward TensorBoard logging to sub-loggers.

  • summary_writer – TensorBoard writer passed to each sub-logger when tensorboard=True.

  • stats_window_size – Either a single window size used for all sub-loggers, or a list of per-logger window sizes aligned with loggers.

  • prefix – Optional display prefix for stdout tables.

Variables:
  • loggers – Mapping from logger key to instantiated BaseLogger.

  • start_time – Wall-clock time at which the first add() occurred, used for runtime diagnostics.

add(key: str, obj: Any)[source]

Add an object to a named sub-logger.

Parameters:
  • key – The sub-logger key as provided in loggers during construction.

  • obj – The object to forward to self.loggers[key].add(...).

Raises:

KeyError – If key is not a configured sub-logger.

log(step: int)[source]

Emit TensorBoard logs (per sub-logger) and a combined stdout table.

Parameters:

step – Global step index used for TensorBoard summary steps.