RslRlOnPolicyRunnerCfg 学习
文章目录
- 1 RslRlOnPolicyRunnerCfg
- 2 G1FlatPPORunnerCfg
- 3 Actor-Critic
- 3.1 方法简介
- 3.2 Actor-Critic 的核心机制
- 3.3 Actor-Critic 结构的全连接前馈神经网络(MLP):
- 3.4 Actor-Critic 算法流程
- 4 如何设计隐藏层
1 RslRlOnPolicyRunnerCfg
强化学习(RL)训练运行器的配置类,主要用于基于策略(On-Policy)的算法:
概览
RslRlPpoActorCriticCfg:定义 Actor-Critic 网络的结构与初始化噪声。RslRlPpoAlgorithmCfg:指定 PPO 算法的核心超参数,如剪切系数、熵系数、折扣因子等。RslRlOnPolicyRunnerCfg:配置整个 on-policy 训练流程,包括环境交互步数、训练轮次、日志保存、恢复机制及所用设备。
@configclass
class RslRlPpoActorCriticCfg:"""Configuration for the PPO actor-critic networks."""class_name: str = "ActorCritic""""The policy class name. Default is ActorCritic."""init_noise_std: float = MISSING"""The initial noise standard deviation for the policy."""actor_hidden_dims: list[int] = MISSING"""The hidden dimensions of the actor network."""critic_hidden_dims: list[int] = MISSING"""The hidden dimensions of the critic network."""activation: str = MISSING"""The activation function for the actor and critic networks."""
字段解析
class_name
指定策略与价值网络的封装类名,通常不需修改,框架内会根据此字段加载相应类。init_noise_std
初始动作噪声的标准差,用于策略探索。数值越大,初期策略随机性越强;越小,则探索更集中。actor_hidden_dims
Actor(策略网络)中各隐藏层的维度列表,例如 [64, 64] 表示两层隐藏层,每层 64 个神经元。critic_hidden_dims
Critic(价值网络)中各隐藏层的维度列表,结构通常可与 Actor 对称或略有不同。activation
隐藏层用到的激活函数,如 "relu"、"tanh" 等。决定网络非线性变换方式。
@configclass
class RslRlPpoAlgorithmCfg:"""Configuration for the PPO algorithm."""class_name: str = "PPO""""The algorithm class name. Default is PPO."""value_loss_coef: float = MISSING"""The coefficient for the value loss."""use_clipped_value_loss: bool = MISSING"""Whether to use clipped value loss."""clip_param: float = MISSING"""The clipping parameter for the policy."""entropy_coef: float = MISSING"""The coefficient for the entropy loss."""num_learning_epochs: int = MISSING"""The number of learning epochs per update."""num_mini_batches: int = MISSING"""The number of mini-batches per update."""learning_rate: float = MISSING"""The learning rate for the policy."""schedule: str = MISSING"""The learning rate schedule."""gamma: float = MISSING"""The discount factor."""lam: float = MISSING"""The lambda parameter for Generalized Advantage Estimation (GAE)."""desired_kl: float = MISSING"""The desired KL divergence."""max_grad_norm: float = MISSING"""The maximum gradient norm."""
字段解析
value_loss_coef
价值损失的权重系数,用于平衡策略损失与价值损失。use_clipped_value_loss
是否对价值函数也使用 PPO 中的“剪切”技术,以提高训练稳定性。clip_param
PPO 的策略更新剪切范围(ε),常见取值如 0.1、0.2。entropy_coef
熵项系数,用于鼓励策略探索,防止过早收敛到局部最优。num_learning_epochs
每次数据收集后,用同一批数据训练的循环次数。num_mini_batches
将一轮采集到的数据分割为多少个小批进行梯度更新。learning_rate
策略与价值网络的学习率。schedule
学习率调度方式,如 "constant"、"linear" 等。gamma
折扣因子,用于计算未来累积奖励的衰减。lam
GAE(Generalized Advantage Estimation)中的 λ 参数,平衡偏差与方差。desired_kl
希望在每次策略更新时达到的目标 KL 散度,可用于早停更新。max_grad_norm
梯度裁剪的最大范数,防止梯度爆炸
@configclass
class RslRlOnPolicyRunnerCfg:"""Configuration of the runner for on-policy algorithms."""seed: int = 42"""The seed for the experiment. Default is 42."""device: str = "cuda:0""""The device for the rl-agent. Default is cuda:0."""num_steps_per_env: int = MISSING"""The number of steps per environment per update."""max_iterations: int = MISSING"""The maximum number of iterations."""empirical_normalization: bool = MISSING"""Whether to use empirical normalization."""policy: RslRlPpoActorCriticCfg = MISSING"""The policy configuration."""algorithm: RslRlPpoAlgorithmCfg = MISSING"""The algorithm configuration."""### Checkpointing parameters##save_interval: int = MISSING"""The number of iterations between saves."""experiment_name: str = MISSING"""The experiment name."""run_name: str = """""The run name. Default is empty string.The name of the run directory is typically the time-stamp at execution. If the run name is not empty,then it is appended to the run directory's name, i.e. the logging directory's name will become``{time-stamp}_{run_name}``."""### Logging parameters##logger: Literal["tensorboard", "neptune", "wandb"] = "tensorboard""""The logger to use. Default is tensorboard."""neptune_project: str = "isaaclab""""The neptune project name. Default is "isaaclab"."""wandb_project: str = "isaaclab""""The wandb project name. Default is "isaaclab"."""### Loading parameters##resume: bool = False"""Whether to resume. Default is False."""load_run: str = ".*""""The run directory to load. Default is ".*" (all).If regex expression, the latest (alphabetical order) matching run will be loaded."""load_checkpoint: str = "model_.*.pt""""The checkpoint file to load. Default is ``"model_.*.pt"`` (all).If regex expression, the latest (alphabetical order) matching file will be loaded."""
基本训练参数
seed
随机种子,确保实验可复现。device
训练所用设备,例如 "cuda:0"、"cpu"。num_steps_per_env
单个环境每次采集的步数,决定每次更新使用的数据量。max_iterations
整体训练的最大迭代次数。empirical_normalization
是否对观测和回报使用经验归一化。policy 与 algorithm
嵌套前两部分的网络及算法配置对象,必须传入对应的 RslRlPpoActorCriticCfg 与 RslRlPpoAlgorithmCfg 实例。
检查点与实验管理
save_interval
每隔多少次迭代保存一次模型与日志。experiment_name
实验大类名,用于组织不同实验项目的根目录。run_name
本次运行的子目录后缀,便于区分同一实验下的多次运行。
日志与恢复
logger
日志工具选择,可为 "tensorboard"、"neptune" 或 "wandb"。neptune_project、wandb_project
对应云端项目名,若使用这些服务需提前配置。resume
是否从已有检查点继续训练(True/False)。load_run 与 load_checkpoint
以正则表达式指定要加载的运行目录和模型文件,默认加载最新符合条件的文件。
2 G1FlatPPORunnerCfg
@configclass
class G1FlatPPORunnerCfg(G1RoughPPORunnerCfg):def __post_init__(self):super().__post_init__()self.max_iterations = 1500self.experiment_name = "g1_flat"self.policy.actor_hidden_dims = [256, 128, 128]self.policy.critic_hidden_dims = [256, 128, 128]
G1FlatPPORunnerCfg 继承自 G1RoughPPORunnerCfg,用于 G1 机器人在平坦地形(Flat Terrain)上的 PPO 训练,并在 post_init 方法中 修改了一些关键参数。
actor_hidden_dims(策略网络隐藏层)设置为 [256, 128, 128]:
三层隐藏层,第一层 256 单元,后两层各 128 单元。较深且首层较宽,能捕捉更复杂的策略表示。
critic_hidden_dims(价值网络隐藏层)同样设置为 [256, 128, 128]:
与策略网络对称,确保策略评估网络有同等的表达能力。
3 Actor-Critic
3.1 方法简介
Actor-Critic(AC)是一种强化学习(RL)方法,结合了 策略优化(Policy-based) 和 值函数优化(Value-based) 的优点。它由两个核心组件组成:
Actor(执行者):负责学习策略 𝜋 ( 𝑠 , 𝑎 ),决定在状态 𝑠 下采取的动作 𝑎。
Critic(评论者):估计状态值函数 𝑉 ( 𝑠 ) 或动作值函数 𝑄 ( 𝑠 , 𝑎 ) ,用于指导 Actor 进行更好的决策。
直观理解:Actor 类似于游戏中的玩家,它根据当前状态选择动作;Critic 类似于教练,它给玩家的选择提供反馈,告诉它哪些选择好,哪些不好。
3.2 Actor-Critic 的核心机制
(1)传统策略梯度(Policy Gradient)方法的问题
在纯 策略优化(Policy-based) 方法(如 REINFORCE)中,策略 𝜋 𝜃 通过优化目标函数:
𝐽 ( 𝜃 ) = 𝐸 𝜋 𝜃 [ 𝑅 ]
其中, 𝑅是从环境中获得的累计奖励。
但问题是:
高方差:由于奖励信号的随机性,学习信号波动大,难以收敛。
效率低下:每次更新依赖于完整的轨迹,更新速度较慢。
(2)价值基方法(Value-based)的不足
在纯 值优化(Value-based) 方法(如 DQN)中,使用 Q-learning 来估计状态值函数:
𝑄 ( 𝑠 , 𝑎 ) = 𝑟 + 𝛾 max 𝑎 ′ 𝑄 ( 𝑠 ′ , 𝑎 ′ )
问题: 无法直接学习策略,只能通过贪心策略( 𝜖 -greedy)选择动作。
(3) Actor-Critic 结合两者的优势
Actor(策略):学习如何选择动作。
Critic(值函数):评估 Actor 选择的动作质量,提供优化信号。
Critic 提供 低方差的梯度估计,减少策略梯度的方差,从而提高学习效率。
(4)优化目标:
Actor 通过策略梯度更新:
𝜃 ← 𝜃 + 𝛼 ∇ 𝜃 log 𝜋 𝜃 ( 𝑠 , 𝑎 ) 𝐴 ( 𝑠 , 𝑎 )
其中, 𝐴 ( 𝑠 , 𝑎 ) = 𝑄 ( 𝑠 , 𝑎 ) − 𝑉 ( 𝑠 ) A(s,a)=Q(s,a)−V(s) 是优势函数(Advantage Function),用于衡量动作 𝑎 a 相比平均水平的好坏。
Critic 通过 TD 误差更新:
𝛿 = 𝑟 + 𝛾 𝑉 ( 𝑠 ′ ) − 𝑉 ( 𝑠 )
𝑤 ← 𝑤 + 𝛽 𝛿 ∇ 𝑤 𝑉 ( 𝑠 )
这样,Actor 负责选择策略,Critic 负责优化策略的方向。
3.3 Actor-Critic 结构的全连接前馈神经网络(MLP):
1> 策略网络(Actor)
actor_hidden_dims=[512, 256, 128]
这表示 策略网络(Actor) 的隐藏层由三层全连接层(MLP)组成:
输入层: 接收环境的观察(state)
第一层隐藏层: 512 个神经元,使用 ELU 激活函数
第二层隐藏层: 256 个神经元,使用 ELU 激活函数
第三层隐藏层: 128 个神经元,使用 ELU 激活函数
输出层: 生成策略(policy)分布,用于决定行动(action)
数学表示(假设输入 𝑠 s 是状态向量):
ℎ 1 = ELU ( 𝑊 1 𝑠 + 𝑏 1 ) ( 512 维 )
ℎ 2 = ELU ( 𝑊 2 ℎ 1 + 𝑏 2 ) ( 256 维 )
ℎ 3 = ELU ( 𝑊 3 ℎ 2 + 𝑏 3 ) ( 128 维 )
𝜋 ( 𝑎 ∣ 𝑠 ) = Softmax ( 𝑊 4 ℎ 3 + 𝑏 4 ) ( 输出 action 维度 )
这里 pi(a | s) 是策略网络的输出,表示不同动作的概率分布。
2> 价值网络(Critic)
critic_hidden_dims=[512, 256, 128]
这表示 价值网络(Critic) 的结构,与 actor_hidden_dims 相同:
输入层: 接收环境的观察(state)
三层隐藏层: 结构同 Actor
输出层: 计算当前状态的状态值 𝑉 ( 𝑠 )(标量)
数学表示:
ℎ 1 = ELU ( 𝑊 1 𝑠 + 𝑏 1 ) ( 512 维 )
ℎ 2 = ELU ( 𝑊 2 ℎ 1 + 𝑏 2 ) ( 256 维 )
ℎ 3 = ELU ( 𝑊 3 ℎ 2 + 𝑏 3 ) ( 128 维 )
𝑉 ( 𝑠 ) = 𝑊 4 ℎ 3 + 𝑏 4 ( 标量输出 )
V(s) 表示当前状态 𝑠 s 的价值估计,用于计算优势函数(Advantage Function)。
3.4 Actor-Critic 算法流程
1> 初始化:随机初始化 Actor-Critic 网络和优化器。
2> 采样:与环境交互,Actor 选择动作,环境返回奖励和下一个状态。
3> Critic 评估:
计算 TD 误差: 𝛿 = 𝑟 + 𝛾 𝑉 ( 𝑠 ′ ) − 𝑉 ( 𝑠 )
更新 Critic 网络
4> Actor 训练:
计算 Advantage: 𝐴 ( 𝑠 , 𝑎 ) = 𝛿
更新 Actor 网络
5> 重复以上步骤,直到收敛。
4 如何设计隐藏层
1. 网络容量与任务复杂度匹配
(1) 复杂任务(如连续控制、多智能体交互)需要更深的网络或更宽的层来捕捉状态-动作的非线性关系 例如,[256, 128, 128]的三层结构适合中等复杂度的环境(如机器人步态控制),通过逐步压缩特征维度实现高效的特征提取。
(2)简单任务(如离散动作的CartPole)可能仅需单层或更窄的隐藏层(如[128])
2.梯度稳定性与训练效率的平衡
Critic网络需更精确的价值估计,通常需要比Actor更深的架构,但用户配置中两者对称,可能是为了简化调参流程
逐渐减小的维度(如256→128→128)有助于抑制过拟合,同时保持梯度传播的稳定性