人工智能分布式训练强化学习任务调度模型推理服务【免费下载链接】rayRay is an AI compute engine. Ray consists of a core distributed runtime and a set of AI Libraries for accelerating ML workloads.项目地址https://gitcode.com/gh_mirrors/ra/ray点击查看免费下载导读本文以 Ray Tune 官方示例仓库中的 PBT 示例pbt_example.py为骨架系统讲解 Population Based TrainingPBT调度器的使用方式与底层原理。通过一个可完整运行的自适应学习率基准问题你将掌握PBT 的 exploit/explore 运行机制、PopulationBasedTraining全部核心参数扰动区间、超参变异、重采样概率、分位数等的含义与默认值、Trainable 类必须实现的生命周期方法setup/step/save_checkpoint/load_checkpoint/reset_config以及如何正确设置 checkpoint 与扰动节奏以获取可靠的 PBT 调度。读完本文你可以直接复刻该示例并迁移到自己的深度学习训练任务中。关联文档与示例的定位本文的关联文档 pbt_example.rst 本身是一个典型的 Sphinx 文档占位文件它通过literalinclude指令将 python/ray/tune/examples/pbt_example.py 的完整源码直接嵌入文档页因此示例的完整可运行代码就是这篇文档的核心内容。该文件位于 Ray Tune 示例集doc/source/tune/examples/index.rst 中归类为 Using Population-Based Training (PBT)中与同目录下的 pbt_function.py、pbt_convnet_example.py、pbt_ppo_example.py、pb2_example.py 等构成 PBT 系列示例。API 层的官方说明位于 doc/source/tune/api/schedulers.rst 的 Population Based Training 小节。PBT 是什么训练过程中的物竞天择Population Based Training 与传统的超参搜索如网格搜索、贝叶斯优化最大的不同在于超参数是在训练过程中动态进化的而不是在训练开始前一次性确定。PBT 同时训练一组一个种群模型周期性执行两个动作exploitation利用将表现较差的 trial训练任务变体的检查点与超参配置替换为种群中表现最好的 trial 的检查点与超参配置让差模型继承好模型的权重继续训练exploration探索在继承的配置上施加随机扰动如把学习率乘以 1.2 或 0.8或从分布中重新采样在好配置附近继续探索更优解。这种方式不仅能快速发现好超参还能自动发现退火式的调度曲线——比如许多真实模型的最佳学习率呈现先升后降的形态PBT 可以通过种群竞争自动逼近这条曲线。Ray Tune 对 PBT 的官方描述见 doc/source/tune/api/schedulers.rst进一步明确了三点机制周期性地对表现最好的 trial 做 checkpoint要求 Trainable 支持保存/恢复低分 trial 克隆高分 trial 的超参配置并施加扰动低分 trial 同时从高分 trial 的 checkpoint 恢复训练从而在新配置下从部分训练好的模型如复制权重继续出发。一个可视化的直觉三角形学习率波示例中的玩具问题PBTBenchmarkExample的 docstring 给出了最直观的理解方式该问题的最优学习率是精度的三角形波函数——初始为 0.001在精度到达中点 100 时峰值到 0.01之后又线性回落至 0.001。注释指出真实模型的许多学习率调度曲线也遵循这一形状在该问题上PBT 仅凭 24 个种群的规模就足以大致逼近这个调度种群越大收敛越快而不使用 PBT 则无法收敛。完整示例源码逐段解读示例的完整源码见 python/ray/tune/examples/pbt_example.py。下面按结构拆解。第一步定义 Trainable 类import argparse import random import numpy as np import ray from ray import tune from ray.tune.schedulers import PopulationBasedTraining class PBTBenchmarkExample(tune.Trainable): Toy PBT problem for benchmarking adaptive learning rate. The goal is to optimize this trainables accuracy. The accuracy increases fastest at the optimal lr, which is a function of the current accuracy. The optimal lr schedule for this problem is the triangle wave as follows. Note that many lr schedules for real models also follow this shape: best lr ^ | /\ | / \ | / \ | / \ ------------ accuracy In this problem, using PBT with a population of 2-4 is sufficient to roughly approximate this lr schedule. Higher population sizes will yield faster convergence. Training will not converge without PBT. Trainable 是 Ray Tune 的类 API一个可训练单元Tune 会为每个 trial 实例化一个 Trainable 并循环调用step()直到停止条件满足。它需要实现以下四个方法其中后三个对 PBT 是必须的。def setup(self, config): self.lr config[lr] self.accuracy 0.0 # end 1000 def step(self): midpoint 100 # lr starts decreasing after acc midpoint q_tolerance 3 # penalize exceeding lr by more than this multiple noise_level 2 # add gaussian noise to the acc increase # triangle wave: # - start at 0.001 t0, # - peak at 0.01 tmidpoint, # - end at 0.001 tmidpoint * 2, if self.accuracy midpoint: optimal_lr 0.01 * self.accuracy / midpoint else: optimal_lr 0.01 - 0.01 * (self.accuracy - midpoint) / midpoint optimal_lr min(0.01, max(0.001, optimal_lr)) # compute accuracy increase q_err max(self.lr, optimal_lr) / min(self.lr, optimal_lr) if q_err q_tolerance: self.accuracy (1.0 / q_err) * random.random() elif self.lr optimal_lr: self.accuracy - (q_err - q_tolerance) * random.random() self.accuracy noise_level * np.random.normal() self.accuracy max(0, self.accuracy) return { mean_accuracy: self.accuracy, cur_lr: self.lr, optimal_lr: optimal_lr, # for debugging q_err: q_err, # for debugging done: self.accuracy midpoint * 2, }方法职责setup(config)trial 启动时调用一次从配置中读取lr并初始化状态这里把初始 accuracy 置 0最终目标是 1000。step()每轮训练迭代被调用一次返回一个结果字典。这里模拟学习率越接近最优值精度增长越快的规律optimal_lr按三角形波计算实际self.lr与最优值的比值q_err越小accuracy 增长越快超出容差q_tolerance3倍则被惩罚还叠加了高斯噪声防止问题过于平凡。结果字典中的mean_accuracy将被用作 PBT 的优化指标done作为停止信号。save_checkpoint(checkpoint_dir)PBT 要求 trial 可持久化save_checkpoint返回需要保存的状态这里保存 accuracy 与 lr。load_checkpoint(checkpoint)从 checkpoint 恢复状态这里恢复 accuracy。PBT 在 exploit 时会用该接口让差 trial 从好 trial 的 checkpoint 处继续。reset_config(new_config)PBT 扰动后必须能原地应用新配置配合reuse_actorsTrue时尤为重要这里把lr更新为新配置并返回True表示成功。注意save_checkpoint的参数checkpoint_dir在本例中未使用返回 dict 即可但真实训练中通常用它把模型权重写入该目录。第二步配置 PBT 调度器与 Tunerif __name__ __main__: parser argparse.ArgumentParser() parser.add_argument( --smoke-test, actionstore_true, helpFinish quickly for testing ) args, _ parser.parse_known_args() if args.smoke_test: ray.init(num_cpus2) # force pausing to happen for test perturbation_interval 5 pbt PopulationBasedTraining( time_attrtraining_iteration, perturbation_intervalperturbation_interval, hyperparam_mutations{ # distribution for resampling lr: lambda: random.uniform(0.0001, 0.02), # allow perturbations within this set of categorical values some_other_factor: [1, 2], }, )关键点--smoke-test用于快速验证此时ray.init(num_cpus2)强制只有 2 个 CPU8 个 trial 必须抢占/暂停运行PBT 支持种群规模大于集群容量的时间复用以此触发完整的暂停-恢复路径便于测试。time_attrtraining_iteration以训练迭代次数作为时间轴PBT 每perturbation_interval个迭代做一次评估。源码 pbt.py 中默认是time_total_s墙钟秒此处改为迭代数使行为确定、可复现。perturbation_interval5每 5 个time_attr单位考虑一次扰动。hyperparam_mutations指定哪些超参可被变异以及变异方式——lr使用 lambda 函数作为连续分布重采样时从uniform(0.0001, 0.02)取样未重采样时乘以扰动因子some_other_factor使用列表[1, 2]作为离散分类集合重采样时随机选一个否则左/右移动到相邻值。注意some_other_factor在本例中对训练无实际影响仅用于演示离散扰动。接着是 Tuner 的完整装配tuner tune.Tuner( PBTBenchmarkExample, run_configtune.RunConfig( namepbt_class_api_example, # Stop when done True or at some # of train steps (whichever comes first) stop{ done: True, training_iteration: 10 if args.smoke_test else 1000, }, verbose0, # We recommend matching perturbation_interval and checkpoint_interval # (e.g. checkpoint every 4 steps, and perturb on those same steps) # or making perturbation_interval a multiple of checkpoint_interval # (e.g. checkpoint every 2 steps, and perturb every 4 steps). # This is to ensure that the lastest checkpoints are being used by PBT # when trials decide to exploit. If checkpointing and perturbing are not # aligned, then PBT may use a stale checkpoint to resume from. checkpoint_configtune.CheckpointConfig( checkpoint_frequencyperturbation_interval, checkpoint_score_attributemean_accuracy, num_to_keep4, ), ), tune_configtune.TuneConfig( schedulerpbt, metricmean_accuracy, modemax, reuse_actorsTrue, num_samples8, ), param_space{ lr: 0.0001, # note: this parameter is perturbed but has no effect on # the model training in this example some_other_factor: 1, }, ) results tuner.fit() print(Best hyperparameters found were: , results.get_best_result().config)RunConfig 与 CheckpointConfigstop两个条件取先到者——done为 Trueaccuracy 超过 200或迭代数达到上限冒烟测试 10正式 1000。verbose0关闭冗长输出。checkpoint_config这是 PBT 能否正确工作的关键。checkpoint_frequencyperturbation_interval让 checkpoint 与扰动节奏对齐源码注释明确警告若二者不对齐PBT exploit 时可能使用过期的 checkpoint 恢复导致利用的不是最新状态。推荐perturbation_interval等于checkpoint_frequency或前者是后者的整数倍。checkpoint_score_attributemean_accuracycheckpoint 按该指标保留最优num_to_keep4每个 trial 最多保留 4 个 checkpoint。调度器源码 pbt.py 的on_trial_add中会警告num_to_keep 2时checkpoint 可能过早被删除导致其他 trial 无法 exploit若出现恢复问题应增大该值。TuneConfigschedulerpbt启用 PBT 调度器。当种群规模超过集群容量时trial 会被时间复用暂停/恢复轮流跑保证种群整体进度均衡。metricmean_accuracy、modemax种群排名的依据指标与优化方向。调度器通过_quantiles()pbt.py 中的实现按该指标排序后取上下分位。若在TuneConfig中未指定也可在PopulationBasedTraining(metric..., mode...)中直接传入。reuse_actorsTrue允许 trial 暂停后复用已有 actor配合reset_config可大幅降低重启开销——PBT 的 exploit 本质上是暂停-改配置-从 checkpoint 恢复因此该开关对效率至关重要。num_samples8种群规模。8 个 trial 共享参数空间param_space其中lr初始值 0.0001some_other_factor初始值 1。第三步运行示例# 快速验证约 10 个迭代即停止强制 2 CPU 触发暂停路径 python python/ray/tune/examples/pbt_example.py --smoke-test # 完整运行1000 个迭代8 个 trial python python/ray/tune/examples/pbt_example.py运行结束后控制台会打印最优结果对应的超参配置Best hyperparameters found were: {lr: ..., some_other_factor: ...}结果目录默认位于~/ray_results/pbt_class_api_example/其中每个 trial 一个子目录。从源码看 PBT 的完整执行流程阅读 python/ray/tune/schedulers/pbt.py 可以还原 PBT 在每个训练迭代的内部调用链这也是官方 API 文档所描述机制的源码级印证on_trial_addtrial 加入种群为每个 trial 创建_PBTTrialState跟踪状态若 trial 的 config 缺少hyperparam_mutations中的某个 key会通过_fill_config从变异分布中采样补全见 pbt.py同时拒绝与搜索算法SearchGenerator共用——PBT 与 tune 搜索算法不兼容。on_trial_result每轮结果回调检查结果中是否包含time_attr与metricrequire_attrsTrue时缺失即报错可设False降级为警告未过burn_in_period或未到perturbation_interval则直接CONTINUE避免 checkpoint 开销到达扰动点时按synch选择异步或同步路径见 pbt.py。_quantiles分位划分对存活且得分非 NaN 的 trial 按last_score排序取上下各quantile_fraction默认 0.25的 trial少于 2 个 trial 时返回空列表不执行 exploit见 pbt.py。_checkpoint_or_exploit利用与保存上分位的 trial 安排保存 checkpoint下分位的 trial 随机挑选一个上分位 trial 作为克隆源若有可用 checkpoint 则执行_exploit见 pbt.py。_explore探索/变异对克隆源的配置按hyperparam_mutations逐个变异见 pbt.pydict 值递归处理嵌套超参list/tuple 值以resample_probability概率从集合中重采样否则向左/右移动到相邻值边界处可能 noop函数或 tune 搜索空间Domain以resample_probability概率调用函数/分布重新采样否则乘以perturbation_factors中的随机一个因子默认(1.2, 0.8)布尔值保持布尔整数值会四舍五入取整如batch_size。若提供了custom_explore_fn在内置变异后以f(config)形式调用并断言返回新配置。_exploit执行替换暂停被 exploit 的 trial不重复保存 checkpoint设置新的实验标签原标签perturbed[...]set_config(new_config)写入新配置并从克隆源最新 checkpoint 的浅拷贝恢复训练见 pbt.py。choose_trial_to_run公平调度所有 PENDING/PAUSED 的 trial 按last_train_time升序选择下一个运行的 trial从而保证种群中每个成员获得公平的训练时间支撑种群大于集群容量的场景见 pbt.py。其中_explore的变异语义与官方 API 文档doc/source/tune/api/schedulers.rst中给出的配置示例完全一致列表值表示允许的离散集合函数或tune.uniform等表示连续分布tune.choice列表则被当作连续超参处理与裸列表语义不同。相关的行为断言与边界情况如quantile_fraction必须位于 00.5、perturbation_interval必须为正、hyperparam_mutations与custom_explore_fn至少提供一个等均由 python/ray/tune/tests/test_trial_scheduler_pbt.py 中的单元测试覆盖。PopulationBasedTraining 参数速查表下表汇总PopulationBasedTraining构造函数的全部参数与默认值来源pbt.py便于配置时对照参数默认值说明time_attrtime_total_s作为时间轴的结果字段需单调递增。training_iteration、time_total_s恒可用也可用 trainable 报告的任意数值单调字段如timesteps_total。缺失时调度器会跳过该步决策metricNone优化指标字段名仅在 TuneConfig 传入mode时可用DEFAULT_METRIC兜底modeNonemin或max决定指标最小化还是最大化perturbation_interval60.0每隔多少个time_attr单位评估一次扰动过小会增加 checkpoint 开销不应设得太频繁burn_in_period0.0在此时间之前不参与扰动保证模型先训练够一定步数hyperparam_mutationsNone可变异超参定义值为 list/tuple离散集合、函数或 tune 搜索空间连续分布或 dict嵌套与custom_explore_fn至少提供其一quantile_fraction0.25参数从排名前quantile_fraction转移到排名后quantile_fraction的 trial取值必须在 00.5 之间取 0 等价于不做 exploitresample_probability0.25变异时从原分布重采样的概率否则连续参数乘扰动因子、离散参数移到相邻值perturbation_factors(1.2, 0.8)连续超参的缩放因子集合变异时随机选一个custom_explore_fnNone内置变异后执行的定制探索函数f(config) - new_configlog_configTrue每次 exploit 时把每个模型的 config 记入本地目录用于重建配置调度曲线require_attrsTrue是否强制每个结果都包含time_attr与metric缺失时报错设False降级为警告synchFalseFalse为异步 PBT各 trial 独立按间隔扰动True为同步 PBT所有 trial 对齐到同一时刻才扰动官方 API 文档schedulers.rst还给出一个更贴近真实训练的写法展示了lr用离散列表、alpha用tune.uniform的混合配置from ray import tune from ray.tune.schedulers import PopulationBasedTraining pbt_scheduler PopulationBasedTraining( time_attrtraining_iteration, metricloss, modemin, perturbation_interval1, hyperparam_mutations{ lr: [1e-3, 5e-4, 1e-4, 5e-5, 1e-5], alpha: tune.uniform(0.0, 1.0), } ) tuner tune.Tuner( train_fn, tune_configtune.TuneConfig( num_samples4, schedulerpbt_scheduler, ), ) tuner.fit()注意perturbation_interval1表示每轮迭代都评估仅适用于小规模演示。结果日志pbt_global.txt 与 pbt_policy 文件PBT 与普通超参搜索的另一个重要区别是它产出的不是单一配置而是一条配置调度曲线。默认log_configTrue时每次 exploit 都会把变异过程写入日志见 pbt.py 的_log_config_on_step实验目录下的pbt_global.txt全局记录每次扰动每行 JSON 为[目标 trial 标签, 克隆源 trial 标签, 目标迭代, 克隆源迭代, 旧配置, 新配置]每个 trial 的pbt_policy_{trial_id}.txt该 trial 专属的配置变更轨迹。借助这些日志可以重建完整的学习率退火调度。Ray Tune 还提供了PopulationBasedTrainingReplay调度器传入某个 policy 文件即可用单 trial原样重放该条配置调度曲线见 pbt.py 与 schedulers.rst 中 Population Based Training Replay 小节from ray import tune from ray.tune.schedulers import PopulationBasedTrainingReplay replay PopulationBasedTrainingReplay( ~/ray_results/pbt_class_api_example/pbt_policy_XXXXX_00001.txt ) tuner tune.Tuner( train_fn, run_configtune.RunConfig(stop{training_iteration: 100}), tune_configtune.TuneConfig(schedulerreplay), ) tuner.fit()进阶路线与注意事项函数式 API如果不想用类 API可以看 pbt_function.py对应文档页 pbt_function.rst用tune.with_parameters checkpoint 管理实现同样的 PBT 逻辑。真实模型案例pbt_convnet_example.py 演示 MNIST ConvNet 上的 PBTpbt_ppo_example.py 演示 RL 场景PPO下的 PBTpbt_convnet_function_example.py 是函数式版本。完整的交互式讲解可参考 pbt_guide.ipynb。PB2 变体若不想用随机扰动Ray Tune 还实现了基于高斯过程选择新配置的 PB2Population Based Bandits见 pb2_example.py 与 schedulers.rst 中 Population Based Bandits (PB2) 小节。Checkpoint 节奏必须对齐checkpoint_frequency与perturbation_interval需匹配相等或成整数倍否则 exploit 会使用陈旧 checkpoint不要与搜索算法混用PopulationBasedTraining与 tune 搜索算法SearchGenerator不兼容实例化时会直接报错种群规模num_samples决定种群大小示例注释指出 24 个即可逼近玩具问题的最优调度更大种群收敛更快但受集群容量限制时会触发时间复用保留足够 checkpointnum_to_keep过小≤2可能导致 checkpoints 被过早清理而无法被 exploit出现恢复问题时调大该值。小结通过 pbt_example.py 这个麻雀虽小五脏俱全的基准示例本文完整覆盖了 Ray Tune PBT 的三层知识Trainable 生命周期方法setup/step/save_checkpoint/load_checkpoint/reset_config、PopulationBasedTraining的全部参数语义与默认值、以及调度器内部 exploit/explore 的执行链路pbt.py。以此为基础你可以把同样的模式迁移到真实的神经网络训练与强化学习任务中让超参在训练过程中自我进化并利用pbt_global.txt日志与PopulationBasedTrainingReplay复现、分析得到的调度曲线。赞分享人工智能分布式训练强化学习任务调度模型推理服务【免费下载链接】rayRay is an AI compute engine. Ray consists of a core distributed runtime and a set of AI Libraries for accelerating ML workloads.项目地址https://gitcode.com/gh_mirrors/ra/ray点击查看免费下载相关推荐IsaacLab 群体训练实战指南基于 rl_games 的 Population Based Training (PBT) 实现与配置解析IsaacLab 群体训练实战指南基于 rl_games 的 Population Based Training PBT 实现与配置解析 本篇围绕 Isaac人工智能强化学习机器人具身智能深度学习Ray Tune Trial Schedulers 全面指南ASHA、HyperBand、Median Stopping、PBT/PB2 与 BOHB 的调度器选型与原理剖析Ray Tune Trial Schedulers 全面指南ASHA、HyperBand、Median Stopping、PBT/PB2 与 BOHB 的调度人工智能分布式训练强化学习任务调度模型推理服务Ray Tune HyperBand 示例实战用 HyperBandScheduler 实现超参数搜索的早停调度Ray Tune HyperBand 示例实战用 HyperBandScheduler 实现超参数搜索的早停调度 本文围绕 Ray 仓库中的 HyperBan人工智能分布式训练强化学习任务调度模型推理服务创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考