news 2026/9/13 14:54:57

NeMo Experiment Manager 全解析:基于 PyTorch Lightning 的实验管理、Checkpoint 与日志配置实战

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
NeMo Experiment Manager 全解析:基于 PyTorch Lightning 的实验管理、Checkpoint 与日志配置实战

NeMo Experiment Manager 全解析:基于 PyTorch Lightning 的实验管理、Checkpoint 与日志配置实战

【免费下载链接】SpeechA scalable generative AI framework built for researchers and developers working on Large Language Models, Multimodal, and Speech AI (Automatic Speech Recognition and Text-to-Speech)项目地址: https://gitcode.com/GitHub_Trending/nem/Speech

Experiment Manager(实验管理器)是 NeMo 工具套件中负责管理训练实验生命周期的基础组件,它基于 PyTorch Lightning 封装了模型 Checkpoint 保存、TensorBoard / Weights and Biases / MLFlow / DLLogger / ClearML / Neptune 等多种日志记录、训练断点恢复、EMA 权重平均与集群容错能力,并被默认集成在 NeMo 的全部示例脚本中。本文以 NeMo 仓库中的 exp_manager.rst 文档为主体,结合 exp_manager.py 源码与真实示例配置,系统讲解如何通过 YAML(Hydra)与 Python 两层 API 配置并驾驭实验管理器的完整能力,读完即可在自己的 ASR / TTS 训练脚本中落地使用。

一、Experiment Manager 是什么

Experiment Manager 的核心职责可以用一句话概括:替你把"实验目录、日志、Checkpoint、断点续训"这些繁琐且容易出错的工程细节统一管起来。它遵循 PyTorch Lightning 的exp_dir / experiment_name / version三层目录范式来组织每一次实验,并完成以下工作:

  • 根据配置自动创建 TensorBoard、WandB、MLFlow、DLLogger、ClearML、Neptune 等 Logger 并挂载到 Trainer;
  • 自动创建并配置ModelCheckpoint回调,在训练过程中按指标保存最优、最近与最终 Checkpoint;
  • 提供resume_if_exists等一键续训能力,面向可能被中断的长训练任务;
  • 将启动命令(sys.argv)与 Git 信息(commit hash 与 diff)写入实验目录,保证实验可复现;
  • 可选启用 EMA 权重平均、Preemption 抢占回调、Straggler 检测与 Fault Tolerance 容错;
  • 返回最终日志目录log_dir,供后续代码引用。

从源码看,exp_manager 函数 的签名与行为非常清晰:

def exp_manager(trainer: 'lightning.pytorch.Trainer', cfg: Optional[Union[DictConfig, Dict]] = None) -> Optional[Path]:

它接收 PyTorch Lightning 的Trainer和一个(可选的)配置对象,返回Path类型的日志目录。所有传入配置都会先经过OmegaConf.structured(ExpManagerConfig)做模式校验(见源码 L585-L596),再与用户配置合并,因此任何拼写错误或非法参数都会在启动时被立即发现,而不是在训练中途才暴露。

基本用法:一行代码接入

所有 NeMo 示例脚本都在main中这样调用:

from nemo.utils.exp_manager import exp_manager exp_dir = exp_manager(trainer, cfg.get("exp_manager", None))

在 Hydra 配置中,Experiment Manager 使用 YAML 进行配置:

exp_manager: exp_dir: /path/to/my/experiments name: my_experiment_name create_tensorboard_logger: True create_checkpoint_callback: True
  • exp_dir:实验根目录,默认值为./nemo_experiments
  • name:实验名称,默认值为"default"(源码中通过name = name or "default"兜底);
  • create_tensorboard_logger:是否创建 TensorBoard Logger,默认True
  • create_checkpoint_callback:是否创建 Checkpoint 回调,默认True

训练结束后,可以直接在exp_dir上启动 TensorBoard 查看训练曲线:

tensorboard --bind_all --logdir nemo_experiments

目录结构约定

从 exp_manager 的 docstring 可以确认目录组织规则:

exp_dir/ └── name/ └── version/ # 默认使用 datetime 字符串,或 TensorBoard 的 version_{int} ├── checkpoints/ # .ckpt 与 .nemo 文件 ├── cmd-args.log # 启动命令行参数(sys.argv) ├── git-info.log # git commit hash 与 diff └── ...

version默认取 datetime 字符串,可通过use_datetime_version: False关闭后改用整数版本。此外还有几点工程细节值得注意(均可在 exp_manager 函数体 找到对应实现):

  • 启动命令会被写入cmd-args.log,Git 信息写入git-info.log,保证每次实验可复现;
  • 全局 rank 0 进程还会额外写入nemo_error_log.txtlightning_logs.txt两个日志文件;
  • 非 rank 0 进程会通过seconds_to_sleep(默认 5 秒)睡眠,给 rank 0 留出初始化时间;
  • 如果cfgNone或启用了trainer.fast_dev_run,exp_manager 会直接返回、不做任何事(源码 L578-L583)。

二、Checkpoint 回调配置(ModelCheckpoint)

create_checkpoint_callbackTrue时,NeMo 会使用 PyTorch Lightning 的ModelCheckpoint自动在训练过程中保存 Checkpoint。默认行为是:

  • 保存验证指标最优的前 3 个模型(基于val_loss);
  • 保存最近的*last.ckpt
  • 训练结束后保存最终*end.ckpt

所有这些行为都可以通过checkpoint_callback_params在 YAML 或命令行中覆盖。文档给出的最小示例:

exp_manager: ... # configure the PyTorch Lightning ModelCheckpoint using checkpoint_call_back_params # any ModelCheckpoint argument can be set here # save the best checkpoints based on this metric checkpoint_callback_params.monitor=val_loss # choose how many total checkpoints to save checkpoint_callback_params.save_top_k=5

注意文档中这两行是以点号展开的扁平写法(等价于命令行--exp_manager.checkpoint_callback_params.monitor=val_loss),在 YAML 中写成嵌套形式更常见,例如 NeMo 自带的 ASR 配置 conformer_ctc_bpe.yaml:

exp_manager: exp_dir: null name: ${name} create_tensorboard_logger: true create_checkpoint_callback: true checkpoint_callback_params: # in case of multiple validation sets, first one is used monitor: "val_wer" mode: "min" save_top_k: 5 always_save_nemo: True # saves the checkpoints as nemo files instead of PTL checkpoints # you need to set these two to True to continue the training resume_if_exists: false resume_ignore_no_checkpoint: false

CallbackParams 关键字段

从源码中的 CallbackParams 数据类 可以拿到完整的参数清单与默认值:

参数默认值说明
dirpath/filenameNoneCheckpoint 存放目录与文件名模板;为None时由 exp_manager 自动生成
monitor"val_loss"用于筛选最优 Checkpoint 的验证指标
mode"min"指标优化方向(min/max
verboseTrue是否打印保存信息
save_lastTrue是否额外保存最近的*last.ckpt
save_top_k3保留的最优 Checkpoint 数量;-1表示全部保留
save_weights_onlyFalse只保存权重不保存优化器状态
every_n_epochs1每 N 个 epoch 保存一次
every_n_train_stepsNone每 N 个训练步保存一次
train_time_intervalNone按时间间隔保存(timedelta
prefixNone文件名前缀
postfix".nemo"文件后缀
always_save_nemoFalse是否额外保存.nemo格式(仅模型权重)文件
save_nemo_on_train_endTrue训练结束时是否自动保存.nemo
save_on_train_epoch_endFalse在 train epoch 结束时保存而非验证后保存
async_saveFalse是否异步保存 Checkpoint
save_last_n_optim_states-1保存最近 N 个带优化器状态的 Checkpoint
model_parallel_sizeNone张量并行 × 流水线并行的大小,用于分布式 Checkpoint

需要特别注意的两点

  1. monitornull时的行为:若监控指标未设置,ModelCheckpoint将退化为"按步数保存"模式,此时save_top_k不再有意义,需改用every_n_train_stepsevery_n_epochs控制保存频率。
  2. .ckpt.nemo是两种文件.ckpt包含优化器状态(Adam 优化器下体积约为纯模型参数的三倍);.nemo只包含模型权重,体积小、可直接恢复用于推理或二次微调,具体机制在"节省磁盘空间"一节详述。

三、自动恢复训练(Resume Training)

长训练任务可能因为机器故障、抢占或超时被中断,自动恢复是生产级训练的刚需。通过配置exp_manager即可启用:

exp_manager: ... # resume training if checkpoints already exist resume_if_exists: True # to start training with no existing checkpoints resume_ignore_no_checkpoint: True # by default experiments will be versioned by datetime # we can set our own version with exp_manager.version: my_experiment_version

各参数语义(可对照源码 check_resume 函数 与 exp_manager docstring):

  • resume_if_exists(默认False):若实验目录下已存在 Checkpoint,则自动从最近的*last.ckpt恢复。自 v1.0.0 起,置为True时 exp_manager不再创建 version 子目录,方便连续作业找到统一的日志目录;
  • resume_past_end(默认False):若检测到*end.ckpt(表示上一次训练已完整跑完),exp_manager 默认会报错;置为True可强制加载该 Checkpoint 继续训练;
  • resume_ignore_no_checkpoint(默认False):若目录下没有 Checkpoint,默认报错;置为True则打印提示并从零开始训练
  • resume_from_checkpoint(默认None):显式指定要加载的 Checkpoint 路径,优先级高于自动查找;
  • version/use_datetime_version:控制实验版本命名。默认按 datetime 生成版本,也可以手工指定version: my_experiment_version

从 check_resume 实现 可以看到,恢复逻辑会依次查找*end.ckpt*last.ckpt,并过滤掉带"未完成"标记(is_checkpoint_unfinished,对应_filter_out_unfinished_checkpoints)的中间产物;同时支持本地文件系统、S3 与 Multi-Storage Client 路径。若开启 S3 存储,还会只在全局 rank 0 上执行查找以避免 S3 限流。

# 命令行覆盖示例 python examples/asr/speech_to_text_finetune.py \ --config-path=conf/asr_finetune --config-name=speech_to_text_finetune \ exp_manager.resume_if_exists=true \ exp_manager.resume_ignore_no_checkpoint=true

四、多 Logger 实验日志系统

除了默认的 TensorBoard,NeMo 还支持 Weights and Biases、MLFlow、DLLogger、ClearML 与 Neptune。统一通过exp_manager配置,且在 configure_loggers 中被一次性创建并挂载到 Trainer。

兼容性约束:如果trainer.logger已经存在(例如在pl.Trainer(logger=...)中显式传入过 Logger),同时又在 exp_manager 中开启了create_tensorboard_logger/create_wandb_logger/create_mlflow_logger,会抛出LoggerMisconfigurationError(error_checks 源码)。提示信息会建议把logger=False传给 Trainer 构造器,让 exp_manager 全权接管日志。

4.1 TensorBoard(默认开启)

exp_manager: create_tensorboard_logger: True # 默认开启 summary_writer_kwargs: # 透传给 Lightning TensorBoardLogger 的额外参数 <Any TensorBoardLogger argument>

summary_writer_kwargs可透传任意 LightningTensorBoardLogger参数;注意log_dir由 exp_manager 自动计算并传入,不能出现在该字典中。

4.2 Weights and Biases(WandB)

exp_manager: ... create_checkpoint_callback: True create_wandb_logger: True wandb_logger_kwargs: name: ${name} project: ${project} entity: ${entity} <Add any other arguments supported by WandB logger here>

源码 docstring 明确要求:create_wandb_loggerTrue时,nameproject是必填项(L534-L536)。entity与其余参数可按需补充。

4.3 MLFlow

exp_manager: ... create_checkpoint_callback: True create_mlflow_logger: True mlflow_logger_kwargs: experiment_name: ${name} tags: <Any key:value pairs> save_dir: './mlruns' prefix: '' artifact_location: None # provide run_id if resuming a previously started run run_id: Optional[str] = None

源码中有个贴心的默认行为:如果开启了 MLFlow 但未设置experiment_name,exp_manager 会自动复用与 TensorBoard 相同的实验名称并给出警告(L627-L632)。run_id用于恢复之前已开始的 run。

4.4 DLLogger

DLLogger 是 NVIDIA 的 JSON 结构化日志工具,适合在容器/集群环境下采集训练指标:

exp_manager: ... create_checkpoint_callback: True create_dllogger_logger: True dllogger_logger_kwargs: verbose: False stdout: False json_file: "./dllogger.json"

4.5 ClearML

exp_manager: ... create_checkpoint_callback: True create_clearml_logger: True clearml_logger_kwargs: project: None # name of the project task: None # optional name of task connect_pytorch: False model_name: None # optional name of model tags: None # Should be a list of str log_model: False # log model to clearml server log_cfg: False # log config to clearml server log_metrics: False # log metrics to clearml server

4.6 Neptune

exp_manager: ... create_checkpoint_callback: True create_neptune_logger: false neptune_logger_kwargs: project: ${project} name: ${name} prefix: train log_model_checkpoints: false # set to True if checkpoints need to be pushed to Neptune tags: null # can specify as an array of strings in yaml array format description: null <Add any other arguments supported by Neptune logger here>

五、EMA 指数移动平均

EMA(Exponential Moving Average)通过对模型参数维护滑动平均副本,通常能提升模型的泛化能力与训练稳定性。NeMo 通过ema配置段启用,其实现位于 nemo/collections/common/callbacks/ema.py 的 EMA 回调类,对应的参数定义见 EMAParams:

exp_manager: ... # use exponential moving average for model parameters ema: enabled: True # False by default decay: 0.999 # decay rate cpu_offload: False # If EMA parameters should be offloaded to CPU to save GPU memory every_n_steps: 1 # How often to update EMA weights validate_original_weights: False # Whether to use original weights for validation calculation or EMA weights

各字段含义与源码级细节:

  • enabled:默认False。置为True时,exp_manager 会实例化EMA回调并追加到 trainer.callbacks;
  • decay:EMA 衰减系数,必须位于 0~1 之间,否则EMA.__init__会抛出MisconfigurationException(ema.py L51-L52)。通常取值 0.99 ~ 0.9999;
  • cpu_offload:将 EMA 参数副本放到 CPU 以节省 GPU 显存,适合大模型;
  • every_n_steps:每隔 N 个训练步更新一次 EMA 权重;
  • validate_original_weights:默认False,即验证时使用 EMA 权重;置为True则验证时使用原始权重。

EMA 回调的行为特点(见 EMA docstring):训练期间维护参数的滑动平均副本;评估时默认切换到 EMA 副本进行验证;保存 Checkpoint 时额外保存一组带ema前缀的参数,供恢复后继续使用或导出。

六、集群可靠性:Preemption、Straggler 检测与 Fault Tolerance

6.1 抢占回调(PreemptionCallback)

PreemptionCallback默认启用create_preemption_callback默认值为True,见 ExpManagerConfig),适用于集群抢占场景:收到抢占信号时先保存当前训练状态(生成带*last.ckpt后缀的 Checkpoint),随后优雅退出,从而提升集群资源利用率。如需禁用:

exp_manager: create_preemption_callback: False

该回调由 nemo.utils.callbacks.PreemptionCallback 实现。

6.2 Straggler 检测(慢节点识别)

Straggler(掉队节点)会拖慢整个分布式训练。Straggler Detection 功能包含在可选的 NeMo resiliency 包中(源码通过try: from ptl_resiliency import StragglerDetectionCallback判断是否可用,见 exp_manager.py L65-L71),由StragglerDetectionCallback实现,默认关闭

核心机制:回调计算归一化的 GPU 性能分数,取值 0.0(最差)~ 1.0(最优),可理解为"当前性能 / 参考性能"的比值。分数分两种:

  • 相对 GPU 性能分数:以当前作业中性能最好的 GPU 为参考。例如某 GPU 相对分数为 0.5,表示它比最快的 GPU 慢一倍;
  • 个体 GPU 性能分数:以该 GPU 自身的历史最佳表现为参考。例如某 GPU 个体分数为 0.5,表示它比自己的最佳表现慢一倍。

当分数低于设定阈值时即判定为 straggler。启用与调参:

exp_manager: ... create_straggler_detection_callback: True straggler_detection_callback_params: report_time_interval: 300 # Interval [seconds] of the straggler check calc_relative_gpu_perf: True # Calculate relative GPU performance calc_individual_gpu_perf: True # Calculate individual GPU performance num_gpu_perf_scores_to_log: 5 # Log 5 best and 5 worst GPU performance scores, even if no stragglers are detected gpu_relative_perf_threshold: 0.7 # Threshold for relative GPU performance scores gpu_individual_perf_threshold: 0.7 # Threshold for individual GPU performance scores stop_if_detected: True # Terminate the workload if stragglers are detected

对应源码为 StragglerDetectionParams:report_time_interval默认 300 秒、两个阈值默认 0.7、stop_if_detected默认False(文档示例中写为True,请按需调整——检测到后是终止作业还是仅记录)。straggler 检测涉及跨 rank 同步,建议每隔几分钟周期性执行。注意:若开启该回调但未安装 resiliency 包,程序会直接raise ValueError(L756-L759)。

6.3 Fault Tolerance(容错与自动续跑)

Fault Tolerance(FT)同样属于可选的 NeMo resiliency 包(exp_manager.py L73-L78),用于检测分布式训练停滞并在必要时终止挂起作业、按需从最后一个 Checkpoint 重启。

关键前提:使用 FT 必须用ft_launcher启动作业ft_launcher是修改版的torchrun,它会在后台启动称为 rank monitor 的监控进程。每个训练进程(rank)在训练/验证步中向 monitor 发送心跳(heartbeat);一旦 monitor 停止收到心跳,即判定训练失败。若要为 SLURM 集群生成带 FT 支持的批处理脚本,可借助 NeMo-Framework-Launcher 生成。

启用方式与参数:

exp_manager: ... create_fault_tolerance_callback: True fault_tolerance: initial_rank_heartbeat_timeout: 600 # wait for 10 minutes for the initial heartbeat rank_heartbeat_timeout: 300 # wait for 5 minutes for subsequent heartbeats calculate_timeouts: True # estimate more accurate timeouts based on observed intervals

超时设置需要针对具体 workload 调整:

  • initial_rank_heartbeat_timeout应足够长,以覆盖工作负载的初始化时间;
  • rank_heartbeat_timeout至少应不短于两步之间可能出现的最长间隔;
  • 重要:Checkpoint 加载与保存期间不会发送心跳,因此计算超时要把 Checkpoint 相关操作耗时计入。

calculate_timeouts: True(默认)时,会基于观察到的真实心跳间隔自动估算超时,估算值优先于配置文件中的设定值;但超时估算是在观察到 Checkpoint 加载/保存的训练运行结束时完成的,因此对于从零开始的多段训练,前两次运行拿不到估算值。估算结果存放在单独的 JSON 文件中。

完整的 FT 配置项汇总(对应 FaultToleranceParams):

配置项默认值说明
workload_check_interval5.0workload monitor 的周期性检查间隔(秒)
initial_rank_heartbeat_timeout60.0 * 60.0等待某个 rank 首个心跳的超时(秒)
rank_heartbeat_timeout45.0 * 60.0等待后续心跳的超时(秒)
calculate_timeoutsTrue根据观察到的间隔自动估算两个超时
safety_factor5.0估算超时 = 最大观察间隔 × 该系数;环境稳定可调小,不稳定调大
rank_termination_signalsignal.SIGKILL检测到故障后用于终止 rank 的信号
log_level'INFO'FT 客户端与 server(rank monitor)的日志级别
max_rank_restarts0FT launcher 使用;>0 时 rank 失败会在现有节点上重启
max_subsequent_job_failures0FT launcher 使用;允许的连续作业失败次数,0表示不自动续跑
additional_ft_launcher_args''附加的 FT launcher 参数(高级用法)

其中max_subsequent_job_failures用于 SLURM 集群上的自动续跑:要求作业由 NeMo-Framework-Launcher 调度。当值>0时,会预调度续跑作业,持续工作直到连续失败次数达到上限(SLURM 作业退出码!= 0)或训练正常完成(FaultToleranceCallback会产出 "end of training" 标记文件,例如达到迭代数或时间上限)。

启用 FT 但未安装 resiliency 包同样会直接抛错(L776-L780)。

七、Hydra Multi-Run:一次配置、网格化超参搜索

训练神经网络时经常需要做超参搜索。手动准备一组实验并管理所有 Checkpoint 与指标十分繁琐,NeMo 通过集成 Hydra Multi-Run 提供统一方案:直接在配置里声明一组实验并批量执行。

使用限制(文档明确列出)

  • 所有实验假定在单 GPU上运行;单个 run 内的多 GPU / 模型并行暂不支持;
  • 目前仅支持对一组超参做网格搜索(grid search),更高级的搜索策略将在未来加入;
  • NeMo Multi-Run 必须有一张或多张 GPU 才能运行,无 GPU 设备不可用。

7.1 配置步骤一:启用 Hydra Multi-Run

在 YAML 中追加以下片段,告知 Hydra 将从该配置派生出多个实验:

# Required for Hydra launch of hyperparameter search via multirun defaults: - override hydra/launcher: nemo_launcher # Hydra arguments necessary for hyperparameter optimization hydra: # Helper arguments to ensure all hyper parameter runs are from the directory that launches the script. sweep: dir: "." subdir: "." # Define all the hyper parameters here sweeper: params: # Place all the parameters you wish to search over here (corresponding to the rest of the config) # NOTE: Make sure that there are no spaces between the commas that separate the config params ! model.optim.lr: 0.001,0.0001 model.encoder.dim: 32,64,96,128 model.decoder.dropout: 0.0,0.1,0.2 # Arguments to the process launcher launcher: num_gpus: -1 # Number of gpus to use. Each run works on a single GPU. jobs_per_gpu: 1 # If each GPU has large memory, you can run multiple jobs on the same GPU for faster results (until OOM).

要点:

  • hydra/launcher: nemo_launcher是 NeMo 自带的进程启动器,实现位于 nemo/core/utils/process_launcher/launcher.py;
  • sweep.dir: "."sweep.subdir: "."确保所有超参 run 都从启动脚本所在的目录派生,便于定位产物;
  • sweeper.params中逗号分隔的值即网格搜索的候选集合,逗号之间不能有空格
  • num_gpus: -1表示使用全部可用 GPU(每个 run 独占单卡);jobs_per_gpu: 1表示显存充裕时可在同一张卡上并行多个作业(直到 OOM)。

7.2 配置步骤二:为每个实验生成唯一"可恢复键"

超参搜索的每个 run 都可能耗时较长,如果某个 run 因 OOM 或机器超时中断,我们不希望整个搜索推倒重来。因此需要让每个实验拥有唯一标识——最简单的方式是把全部超参拼进实验名称:

exp_manager: exp_dir: null # Can be set by the user. # Add a unique name for all hyper parameter arguments to allow continued training. # NOTE: It is necessary to add all hyperparameter arguments to the name ! # This ensures successful restoration of model runs in case HP search crashes. name: ${name}-lr-${model.optim.lr}-adim-${model.adapter.dim}-sd-${model.adapter.adapter_strategy.stochastic_depth} ... checkpoint_callback_params: ... save_top_k: 1 # Dont save too many .ckpt files during HP search always_save_nemo: True # saves the checkpoints as nemo files for fast checking of results later ... # We highly recommend use of any experiment tracking took to gather all the experiments in one location create_wandb_logger: True wandb_logger_kwargs: project: "<Add some project name here>" # HP Search may crash due to various reasons, best to attempt continuation in order to # resume from where the last failure case occurred. resume_if_exists: true resume_ignore_no_checkpoint: true

文档特别强调:name 中必须包含所有参与搜索的超参数,否则某个 run 崩溃后无法精确恢复。同时建议:

  • save_top_k: 1——搜索期间不要保存太多.ckpt
  • always_save_nemo: True——同时保存.nemo便于后续快速查验结果;
  • 开启任意实验追踪工具(如 WandB)把结果汇总到一处;
  • resume_if_existsresume_ignore_no_checkpoint均置true——搜索崩溃后自动从失败点继续。

7.3 运行 Multi-Run 配置

配置就绪后,与普通 Hydra 脚本一致,只需多加一个-m标志:

python script.py --config-path=ABC --config-name=XYZ -m \ trainer.max_steps=5000 \ # Any additional arg after -m will be passed to all the runs generated from the config ! ...

-m之后追加的任何参数(如trainer.max_steps)会传递给由该配置生成的所有 run

八、实用技巧(Tips and Tricks)

8.1 大规模实验下节省磁盘空间

大模型参数众多,保存大量 Checkpoint 的存储开销不容忽视。例如使用 Adam 优化器时,每个 PyTorch Lightning.ckpt的体积约为纯模型参数的三倍(因为含优化器动量状态),多轮实验累积下来可能非常惊人。

两种手段配合使用:

  1. save_top_k: 1+always_save_nemo: True:把.ckpt数量压到最少,同时保存仅含模型权重、不含优化器状态的.nemo文件,后者体积小、可立即恢复用于继续工作;
  2. 训练结束后调用clean_exp_ckpt自动清理:适合"结果已汇总到实验追踪工具、搜索完成后只需重跑最优配置"的场景。

clean_exp_ckpt的完整用法(源码见 nemo/utils/exp_manager.py L1640-L1664):

# Import `clean_exp_ckpt` along with exp_manager from nemo.utils.exp_manager import clean_exp_ckpt, exp_manager @hydra_runner(...) def main(cfg): ... # Keep track of the experiment directory exp_log_dir = exp_manager(trainer, cfg.get("exp_manager", None)) ... add any training code here as needed ... # Add following line to end of the training script # Remove PTL ckpt file, and potentially also remove .nemo file to conserve storage space. clean_exp_ckpt(exp_log_dir, remove_ckpt=True, remove_nemo=False)

函数签名clean_exp_ckpt(exp_log_dir, remove_ckpt=True, remove_nemo=False)remove_ckpt删除checkpoints/下所有*.ckptremove_nemo删除所有*.nemo。按需把对应开关置为True即可。

8.2 Multi-Run 脚本调试

NeMo Multi-Run 中,单个 run 的崩溃不会让整个程序崩溃——框架会记录错误并继续执行下一个 job;所有 job 跑完后,再按发生顺序抛出错误,并以第一个错误的堆栈信息终止程序。

因此调试建议是:先注释掉sweep.params中的全部超参配置,用该配置单跑一个实验,配置错误会立即暴露。

8.3 实验名包含 Trainer 参数导致 Hydra 解析失败

当超参中包含 PyTorch Lightningtrainer参数(如步数、epoch 数、是否梯度累积)并试图写进实验名称时,Hydra 可能报错trainer.xyz cannot be resolved。解决办法是在调用exp_manager()之前先解析(finalize)Hydra 配置:

@hydra_runner(...) def main(cfg): # Make any changes as necessary to the config cfg.xyz.abc = uvw # Finalize the config cfg = OmegaConf.resolve(cfg) # Carry on as normal by calling trainer and exp_manager trainer = pl.Trainer(**cfg.trainer) exp_log_dir = exp_manager(trainer, cfg.get("exp_manager", None)) ...

8.4 其他隐藏但有用的能力

从 ExpManagerConfig 可以看到文档之外若干实用开关:

  • create_early_stopping_callback/early_stopping_callback_params:一键启用 EarlyStopping(默认关闭),monitor默认val_losspatience默认 10;
  • create_ipl_epoch_stopper_callback:Top-IPL 迭代伪标签训练专用的 epoch 停止回调(IPLEpochStopperParams);
  • max_time_per_run:设置单次 run 的墙钟时间上限(如"00:59:00:00"),到达后保存 Checkpoint 并退出,方便在集群上分段续跑;内部使用StatelessTimer实现(L727-L748);
  • log_step_timing/log_delta_step_timing:记录每个 train/val/test step 的耗时(TimingCallback/DeltaTimingCallback,默认开启前者);
  • log_tflops_per_sec_per_gpu:记录每 GPU 每秒 TFLOPs(默认开启,模型不支持时输出-1);
  • files_to_copy:把指定的额外文件复制进实验目录;
  • explicit_log_dir:完全绕过exp_dir/name/version三级目录,直接指定日志目录。

九、ExpManagerConfig 全参数速查

完整参数以源码中 ExpManagerConfig 为准,按功能分组:

  • 目录相关explicit_log_direxp_dir(默认./nemo_experiments)、name(默认"default")、versionuse_datetime_version(默认True);
  • 恢复相关resume_if_exists(默认False)、resume_past_end(默认False)、resume_ignore_no_checkpoint(默认False)、resume_from_checkpointdisable_validation_on_resume(默认True,恢复后跳过首轮验证);
  • 日志相关create_tensorboard_logger(默认True)、summary_writer_kwargscreate_wandb_logger(默认False)、wandb_logger_kwargscreate_mlflow_loggermlflow_logger_kwargscreate_dllogger_loggerdllogger_logger_kwargscreate_clearml_loggerclearml_logger_kwargscreate_neptune_loggerneptune_logger_kwargs
  • 回调相关create_checkpoint_callback(默认True)、checkpoint_callback_paramscreate_early_stopping_callback(默认False)、early_stopping_callback_paramscreate_ipl_epoch_stopper_callbackcreate_preemption_callback(默认True)、create_straggler_detection_callback(默认False)、straggler_detection_paramscreate_fault_tolerance_callback(默认False)、fault_tolerance
  • 其他emamax_time_per_runseconds_to_sleep(默认 5)、log_step_timing(默认True)、log_delta_step_timingstep_timing_kwargslog_tflops_per_sec_per_gpu(默认True)、files_to_copy

十、在真实示例中的落地形态

以 NeMo 自带的 ASR 示例为例,examples/asr/conf/conformer/conformer_ctc_bpe.yaml 中 Trainer 侧刻意关闭了自身能力,把控制权交给 exp_manager:

trainer: ... enable_checkpointing: False # Provided by exp_manager logger: false # Provided by exp_manager

enable_checkpointing: Falselogger: false——Checkpoint 与 Logger 全部由exp_manager统一创建。这种"单点配置、全局接管"的设计在 examples/asr/speech_to_text_finetune.py、examples/audio/audio_to_audio_train.py、examples/tts/fastpitch.py 等所有示例脚本中一致,验证了文档所述"Experiment Manager 默认包含在 NeMo 所有示例脚本中"。对应的单测覆盖见 tests/utils/test_exp_manager.py。

结语

Experiment Manager 是 NeMo 训练管线的"总开关":一段 YAML 配置即可统一解决目录组织、多路日志、Checkpoint 策略、断点续训、EMA 与集群容错等工程问题。无论你是跑单机单卡的快速实验,还是在 SLURM 集群上做大规模超参搜索,都可以直接复用本文介绍的配置模板;需要更深层定制时,可随时查阅 ExpManagerConfig 与 exp_manager 函数源码,以确认每个参数的默认值与边界行为。

【免费下载链接】SpeechA scalable generative AI framework built for researchers and developers working on Large Language Models, Multimodal, and Speech AI (Automatic Speech Recognition and Text-to-Speech)项目地址: https://gitcode.com/GitHub_Trending/nem/Speech

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/9/13 14:53:09

嵌入式低功耗设计实战:收益、风险与可落地的平衡策略

做低功耗项目这些年&#xff0c;我对“省电”这件事越来越谨慎。刚接触嵌入式低功耗设计时&#xff0c;我一度以为把芯片扔进停止模式、把外设时钟全关掉就是胜利&#xff0c;直到产品在现场因为唤醒不及时被客户投诉、因为电流倒灌把电池寿命算崩、因为调试接口被功耗策略锁死…

作者头像 李华
网站建设 2026/9/13 14:51:45

高级计算机系统结构:从乱序执行到多核并行的核心知识体系

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

作者头像 李华