Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 47 additions & 1 deletion test/test_configs.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@
ValueOperator,
)
from torchrl.modules.tensordict_module.exploration import AdditiveGaussianModule
from torchrl.objectives import DQNLoss, SoftUpdate
from torchrl.objectives.common import LossModule
from torchrl.objectives.ppo import ClipPPOLoss, KLPENPPOLoss, PPOLoss
from torchrl.record.loggers import (
Expand All @@ -87,7 +88,7 @@
from torchrl.record.loggers.trackio import TrackioLogger
from torchrl.record.loggers.wandb import WandbLogger
from torchrl.testing.mocking_classes import ContinuousActionVecMockEnv, CountingEnv
from torchrl.trainers import Trainer
from torchrl.trainers import OptimizationStepper, TargetNetUpdaterHook, Trainer
from torchrl.trainers.trainers import CountFramesLog

# Test if configs can be imported (requires hydra)
Expand Down Expand Up @@ -3705,6 +3706,51 @@ def load_state_dict(self, state_dict):
# implemented (Trainer.state_dict iterates registered modules).
hook.load_state_dict(hook.state_dict())

@pytest.mark.parametrize("name", [None, "custom_name"])
def test_target_net_updater_hook_registration(self, name):
class OneBatchCollector:
init_random_frames = 0

def __iter__(self):
yield TensorDict({}, batch_size=[1])

def shutdown(self):
pass

class NoOpStepper(OptimizationStepper):
def step(self, trainer, sub_batch):
return TensorDict({"loss": torch.zeros(())}, [])

loss = DQNLoss(
TensorDictModule(torch.nn.Linear(1, 2), ["observation"], ["action_value"]),
action_space="one-hot",
delay_value=True,
)
with torch.no_grad():
for parameter in loss.value_network_params.values(True, True):
parameter.zero_()
updater = SoftUpdate(loss, eps=0.5)
with torch.no_grad():
for parameter in loss.value_network_params.values(True, True):
parameter.fill_(1)
trainer = Trainer(
collector=OneBatchCollector(),
total_frames=1,
frame_skip=1,
optim_steps_per_batch=1,
loss_module=loss,
optimization_stepper=NoOpStepper(),
progress_bar=False,
)
hook = TargetNetUpdaterHook(updater)
if name is None:
hook.register(trainer)
else:
hook.register(trainer, name=name)
trainer.train()
for target in loss.target_value_network_params.values(True, True):
torch.testing.assert_close(target, torch.full_like(target, 0.5))

@pytest.mark.skipif(not _has_gymnasium, reason="Gymnasium is not installed")
def test_ddpg_trainer_config(self):
from torchrl.trainers.algorithms.configs.trainers import DDPGTrainerConfig
Expand Down
2 changes: 1 addition & 1 deletion torchrl/trainers/trainers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3606,7 +3606,7 @@ def __call__(self, tensordict: TensorCollection | None = None):
self.target_params_updater.step()
return tensordict

def register(self, trainer: Trainer, name: str):
def register(self, trainer: Trainer, name: str = "target_net_updater"):
trainer.register_op("post_steps", self)


Expand Down
Loading