DDPGLoss¶
- class torchrl.objectives.DDPGLoss(*args, **kwargs)[源代码]¶
DDPG 损失类。
- 参数::
actor_network (TensorDictModule) – 策略运算符。
value_network (TensorDictModule) – Q 值运算符。
loss_function (str) – 用于值差异的损失函数。可以是“l1”、“l2”或“smooth_l1”之一。
delay_actor (bool, 可选) – 是否将目标演员网络与用于数据收集的演员网络分开。默认为
False
。delay_value (bool, 可选) – 是否将目标值网络与用于数据收集的值网络分开。默认为
True
。separate_losses (bool, 可选) – 如果为
True
,则策略和评论家之间的共享参数将仅在策略损失上进行训练。默认为False
,即梯度传播到策略和评论家损失的共享参数。reduction (str, 可选) – 指定要应用于输出的缩减:
"none"
|"mean"
|"sum"
。"none"
:不应用任何缩减,"mean"
:输出的总和将除以输出中的元素数量,"sum"
:输出将被求和。默认:"mean"
。
示例
>>> import torch >>> from torch import nn >>> from torchrl.data import BoundedTensorSpec >>> from torchrl.modules.tensordict_module.actors import Actor, ValueOperator >>> from torchrl.objectives.ddpg import DDPGLoss >>> from tensordict import TensorDict >>> n_act, n_obs = 4, 3 >>> spec = BoundedTensorSpec(-torch.ones(n_act), torch.ones(n_act), (n_act,)) >>> actor = Actor(spec=spec, module=nn.Linear(n_obs, n_act)) >>> class ValueClass(nn.Module): ... def __init__(self): ... super().__init__() ... self.linear = nn.Linear(n_obs + n_act, 1) ... def forward(self, obs, act): ... return self.linear(torch.cat([obs, act], -1)) >>> module = ValueClass() >>> value = ValueOperator( ... module=module, ... in_keys=["observation", "action"]) >>> loss = DDPGLoss(actor, value) >>> batch = [2, ] >>> data = TensorDict({ ... "observation": torch.randn(*batch, n_obs), ... "action": spec.rand(batch), ... ("next", "done"): torch.zeros(*batch, 1, dtype=torch.bool), ... ("next", "terminated"): torch.zeros(*batch, 1, dtype=torch.bool), ... ("next", "reward"): torch.randn(*batch, 1), ... ("next", "observation"): torch.randn(*batch, n_obs), ... }, batch) >>> loss(data) TensorDict( fields={ loss_actor: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), loss_value: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), pred_value: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), pred_value_max: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), target_value: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False), target_value_max: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False)}, batch_size=torch.Size([]), device=None, is_shared=False)
此类也与非 tensordict 基于的模块兼容,并且可以在不诉诸任何与 tensordict 相关的原语的情况下使用。在这种情况下,预期的关键字参数是:
["next_reward", "next_done", "next_terminated"]
+ 演员网络和值网络的 in_keys。返回值是按以下顺序排列的张量元组:["loss_actor", "loss_value", "pred_value", "target_value", "pred_value_max", "target_value_max"]
示例
>>> import torch >>> from torch import nn >>> from torchrl.data import BoundedTensorSpec >>> from torchrl.modules.tensordict_module.actors import Actor, ValueOperator >>> from torchrl.objectives.ddpg import DDPGLoss >>> _ = torch.manual_seed(42) >>> n_act, n_obs = 4, 3 >>> spec = BoundedTensorSpec(-torch.ones(n_act), torch.ones(n_act), (n_act,)) >>> actor = Actor(spec=spec, module=nn.Linear(n_obs, n_act)) >>> class ValueClass(nn.Module): ... def __init__(self): ... super().__init__() ... self.linear = nn.Linear(n_obs + n_act, 1) ... def forward(self, obs, act): ... return self.linear(torch.cat([obs, act], -1)) >>> module = ValueClass() >>> value = ValueOperator( ... module=module, ... in_keys=["observation", "action"]) >>> loss = DDPGLoss(actor, value) >>> loss_actor, loss_value, pred_value, target_value, pred_value_max, target_value_max = loss( ... observation=torch.randn(n_obs), ... action=spec.rand(), ... next_done=torch.zeros(1, dtype=torch.bool), ... next_terminated=torch.zeros(1, dtype=torch.bool), ... next_observation=torch.randn(n_obs), ... next_reward=torch.randn(1)) >>> loss_actor.backward()
也可以使用
DDPGLoss.select_out_keys()
方法筛选输出键。示例
>>> loss.select_out_keys('loss_actor', 'loss_value') >>> loss_actor, loss_value = loss( ... observation=torch.randn(n_obs), ... action=spec.rand(), ... next_done=torch.zeros(1, dtype=torch.bool), ... next_terminated=torch.zeros(1, dtype=torch.bool), ... next_observation=torch.randn(n_obs), ... next_reward=torch.randn(1)) >>> loss_actor.backward()
- forward(tensordict: TensorDictBase) TensorDict [源代码]¶
根据从回放缓冲区采样的 tensordict 计算 DDPG 损失。
- 此函数还将写入一个“td_error”键,优先级回放缓冲区可以使用该键将
优先级分配给 tensordict 中的项目。
- 参数::
tensordict (TensorDictBase) – 包含 [“done”、“terminated”、“reward”] 键和演员和值网络的 in_keys 的 tensordict。
- 返回值::
包含 DDPG 损失的两个张量的元组。
- make_value_estimator(value_type: Optional[ValueEstimators] = None, **hyperparams)[源代码]¶
值函数构造函数。
如果需要非默认值函数,则必须使用此方法构建它。
- 参数::
value_type (ValueEstimators) – 指示要使用的值函数的
ValueEstimators
枚举类型。如果没有提供,将使用存储在default_value_estimator
属性中的默认值。生成的估值器类将在self.value_type
中注册,允许进行未来的改进。**hyperparams – 用于值函数的超参数。如果未提供,将使用
default_value_kwargs()
中指示的值。
示例
>>> from torchrl.objectives import DQNLoss >>> # initialize the DQN loss >>> actor = torch.nn.Linear(3, 4) >>> dqn_loss = DQNLoss(actor, action_space="one-hot") >>> # updating the parameters of the default value estimator >>> dqn_loss.make_value_estimator(gamma=0.9) >>> dqn_loss.make_value_estimator( ... ValueEstimators.TD1, ... gamma=0.9) >>> # if we want to change the gamma value >>> dqn_loss.make_value_estimator(dqn_loss.value_type, gamma=0.9)