Skip to content
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

init #2322

Merged
merged 3 commits into from
Jul 25, 2024
Merged

init #2322

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
7 changes: 7 additions & 0 deletions test/test_modules.py
Original file line number Diff line number Diff line change
Expand Up @@ -863,6 +863,13 @@ def test_multiagent_mlp_init(
share_params=share_params,
depth=2,
)
for m in mlp.modules():
if isinstance(m, nn.Linear):
assert not isinstance(m.weight, nn.Parameter)
assert m.weight.device == torch.device("meta")
break
else:
raise RuntimeError("could not find a Linear module")
if n_agent_inputs is None:
n_agent_inputs = 6
td = self._get_mock_input_td(n_agents, n_agent_inputs, batch=batch)
Expand Down
19 changes: 17 additions & 2 deletions torchrl/modules/models/multiagent.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,23 @@ def __init__(
break
self.initialized = initialized
self._make_params(agent_networks)
# We make sure all params and buffers are on 'meta' device
# To do this, we set the device keyword arg to 'meta', we also temporarily change
# the default device. Finally, we convert all params to 'meta' tensors that are not params.
kwargs["device"] = "meta"
self.__dict__["_empty_net"] = self._build_single_net(**kwargs)
with torch.device("meta"):
try:
self._empty_net = self._build_single_net(**kwargs)
except NotImplementedError as err:
if "Cannot copy out of meta tensor" in str(err):
raise RuntimeError(
"The network was built using `factory().to(device), build the network directly "
"on device using `factory(device=device)` instead."
)
# Remove all parameters
TensorDict.from_module(self._empty_net).data.to("meta").to_module(
self._empty_net
)

@property
def vmap_randomness(self):
Expand Down Expand Up @@ -225,7 +240,7 @@ def from_stateful_net(self, stateful_net: nn.Module):
self.params.data.update_(params.data)

def __repr__(self):
empty_net = self.__dict__["_empty_net"]
empty_net = self._empty_net
with self.params.to_module(empty_net):
module_repr = indent(str(empty_net), 4 * " ")
n_agents = indent(f"n_agents={self.n_agents}", 4 * " ")
Expand Down
Loading