Skip to content

Commit 9a1d7fe

Browse files
committed
add an option for deepcopy to NaiveParallelNetwork and Network.copy
1 parent d6ba6bf commit 9a1d7fe

2 files changed

Lines changed: 21 additions & 14 deletions

File tree

alf/algorithms/actor_bayes_critic_algorithm.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,8 @@
6363
],
6464
default_value=())
6565

66+
AbcRolloutInfo = namedtuple("AbcRolloutInfo", ["action"], default_value=())
67+
6668
AbcLossInfo = namedtuple(
6769
'AbcLossInfo', ['actor', 'explore', 'critic', 'alpha', 'explore_alpha'],
6870
default_value=())
@@ -379,7 +381,7 @@ def rollout_step(self, inputs: TimeStep, state: AbcState):
379381
explore=state.explore,
380382
critic=state.critic)
381383
return AlgStep(
382-
output=action, state=new_state, info=AbcInfo(action=action))
384+
output=action, state=new_state, info=AbcRolloutInfo(action=action))
383385

384386
def _consensus_q_for_actor_train(self, critics, explore, info=()):
385387
"""Get q_value for _actor_train_step.
@@ -474,8 +476,7 @@ def actor_loss_fn(dqda, action):
474476
return critics_state, actor_info
475477

476478
def _compute_critic_train_info(self, inputs: TimeStep,
477-
state: AbcCriticState,
478-
rollout_info: AbcInfo, action):
479+
state: AbcCriticState, action):
479480
target_critics_dist, target_critics_state = self._target_critic_network(
480481
(inputs.observation, action), state.target_critics)
481482

@@ -498,7 +499,7 @@ def _alpha_train_step(self, log_pi):
498499
return sum(nest.flatten(alpha_loss))
499500

500501
def train_step(self, inputs: TimeStep, state: AbcState,
501-
rollout_info: AbcInfo):
502+
rollout_info: AbcRolloutInfo):
502503

503504
self._training_started = True
504505

@@ -549,7 +550,7 @@ def train_step(self, inputs: TimeStep, state: AbcState,
549550

550551
# compute train_info for critic_module, trained in calc_loss
551552
critic_state, critic_train_info = self._compute_critic_train_info(
552-
inputs, state.critic, rollout_info, action)
553+
inputs, state.critic, action)
553554

554555
if self._deterministic_actor or self._fixed_alpha:
555556
alpha_loss = ()

alf/networks/network.py

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -143,18 +143,20 @@ def singleton(self, singleton_instance=True):
143143
self._singleton_instance = singleton_instance
144144
return self
145145

146-
def copy(self, **kwargs):
146+
def copy(self, deepcopy=False, **kwargs):
147147
"""Create a copy of this network or return the current instance.
148148
149149
If ``self._singleton_instance`` is True, calling ``copy()`` will return
150150
``self``; otherwise it will re-create and return a new ``Network``
151151
instance using the original arguments used by the constructor.
152152
153-
**NOTE** When re-creating ``Network``, Network layer weights are *never*
154-
copied. This method recreates the ``Network`` instance with the same
155-
arguments it was initialized with (excepting any new kwargs).
153+
**NOTE** When re-creating ``Network``, by default (``deepcopy=False``),
154+
Network layer weights are *never* copied, instead, this method recreates the
155+
``Network`` instance with the same arguments it was initialized with
156+
(excepting any new kwargs).
156157
157158
Args:
159+
deepcopy (bool): If True, Network layer weights are also copied.
158160
**kwargs: Args to override when recreating this network. Commonly
159161
overridden args include 'name'.
160162
@@ -171,7 +173,8 @@ def _copy(a):
171173
return a.copy()
172174
elif isinstance(a, torch.nn.Module):
173175
b = copy.deepcopy(a)
174-
alf.layers.reset_parameters(b)
176+
if not deepcopy:
177+
alf.layers.reset_parameters(b)
175178
return b
176179
else:
177180
return a
@@ -264,10 +267,9 @@ def make_parallel(self, n):
264267
class NaiveParallelNetwork(Network):
265268
"""Naive implementation of parallel network."""
266269

267-
def __init__(self, network, n, name=None):
270+
def __init__(self, network, n, deepcopy=False, name=None):
268271
"""
269-
A parallel network has ``n`` copies of network with the same structure but
270-
different indepently initialized parameters.
272+
A parallel network has ``n`` copies of network with the same structure.
271273
272274
``NaiveParallelNetwork`` created ``n`` independent networks with the same
273275
structure as ``network`` and evaluate them separately in loop during
@@ -277,6 +279,9 @@ def __init__(self, network, n, name=None):
277279
network (Network): the parallel network will have ``n`` copies of
278280
``network``.
279281
n (int): ``n`` copies of ``network``
282+
deepcopy (bool): if True, the copies of network will have same
283+
initialized parameters, otherwise, they will have different
284+
independently initialized parameters.
280285
name(str): a string that will be used as the name of the created
281286
NaiveParallelNetwork instance. If ``None``, ``naive_parallel_``
282287
followed by the ``network.name`` will be used by default.
@@ -288,7 +293,8 @@ def __init__(self, network, n, name=None):
288293
super().__init__(
289294
network.input_tensor_spec, state_spec=state_spec, name=name)
290295
self._networks = nn.ModuleList(
291-
[network.copy(name=self.name + '_%d' % i) for i in range(n)])
296+
[network.copy(
297+
deepcopy=deepcopy, name=self.name + '_%d' % i) for i in range(n)])
292298
self._n = n
293299

294300
def forward(self, inputs, state=()):

0 commit comments

Comments
 (0)