Skip to content

Add reference to policy with state dict #3043

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
16 changes: 13 additions & 3 deletions torchrl/collectors/collectors.py
Original file line number Diff line number Diff line change
Expand Up @@ -689,6 +689,10 @@ def __init__(
policy = RandomPolicy(env.full_action_spec)
elif policy_factory is not None:
raise TypeError("policy_factory cannot be used with policy argument.")
# If the underlying policy has a state_dict, we keep a reference to the policy and
# do all policy weight saving/loading through it
if hasattr(policy, "state_dict"):
self._policy_w_state_dict = policy

if trust_policy is None:
trust_policy = isinstance(policy, (RandomPolicy, CudaGraphModule))
Expand Down Expand Up @@ -1681,8 +1685,8 @@ def state_dict(self) -> OrderedDict:
else:
env_state_dict = OrderedDict()

if hasattr(self.policy, "state_dict"):
policy_state_dict = self.policy.state_dict()
if hasattr(self, "_policy_w_state_dict"):
policy_state_dict = self._policy_w_state_dict.state_dict()
state_dict = OrderedDict(
policy_state_dict=policy_state_dict,
env_state_dict=env_state_dict,
Expand All @@ -1706,7 +1710,13 @@ def load_state_dict(self, state_dict: OrderedDict, **kwargs) -> None:
if strict or "env_state_dict" in state_dict:
self.env.load_state_dict(state_dict["env_state_dict"], **kwargs)
if strict or "policy_state_dict" in state_dict:
self.policy.load_state_dict(state_dict["policy_state_dict"], **kwargs)
if not hasattr(self, "_policy_w_state_dict"):
raise ValueError(
"Underlying policy does not have state_dict to load policy_state_dict into."
)
self._policy_w_state_dict.load_state_dict(
state_dict["policy_state_dict"], **kwargs
)
self._frames = state_dict["frames"]
self._iter = state_dict["iter"]

Expand Down