[docs]@dataclassclassMetricSaverCallback(Callback):""" A callback that captures the latest metrics on rank 0 and saves to a JSON file in the trainer's ``save_folder``. """step_metrics_fname:str="metrics_step{step}.json""""The filename to save the step metrics to, with ``{step}`` as a placeholder for the step number."""final_metrics_fname:str="metrics.json""""The filename to save the final metrics to."""metrics_to_capture:Optional[List[str]]=None""" An optional list of glob patterns to filter which metrics to capture. If ``None``, all metrics are captured. """save_interval:Optional[int]=None"""An optional interval (in steps) at which to save the metrics."""fixed_steps:Optional[List[int]]=None"""An optional list of fixed steps at which to save the metrics."""enabled:bool=True_metrics:Optional[Dict[str,Any]]=dataclasses.field(default=None,repr=False)_metrics_step:int=dataclasses.field(default=0,repr=False)@propertydefmetrics(self)->Optional[Dict[str,Any]]:""" The latest metrics recorded. """returnself._metricsdeflog_metrics(self,step:int,metrics:Dict[str,float]):ifnotself.enabledorget_rank()!=0:returnifself._metricsisNone:self._metrics={}ifstep>=self._metrics_step:ifself.metrics_to_captureisnotNone:metrics={k:vfork,vinmetrics.items()ifany(fnmatch(k,pattern)forpatterninself.metrics_to_capture)}self._metrics.update(metrics)self._metrics_step=stepif(self.save_intervalisnotNoneandstep%self.save_interval==0)or(self.fixed_stepsisnotNoneandstepinself.fixed_steps):dest_path=self._write_metrics(self.step_metrics_fname.format(step=step),self._metrics)log.info(f"Metrics for step {step} saved to '{dest_path}'")defclose(self):ifnotself.enabledorget_rank()!=0:returnifself.metricsisnotNone:dest_path=self._write_metrics(self.final_metrics_fname,self.metrics)log.info(f"Final metrics from step {self._metrics_step} saved to '{dest_path}'")self._metrics=Noneself._metrics_step=0def_write_metrics(self,fname:str,metrics:Dict[str,float])->PathOrStr:returnself.trainer.write_file(fname,json.dumps(metrics))