Paddle icon indicating copy to clipboard operation
Paddle copied to clipboard

在paddle中,如何将一个网络的参数全部复制到另一个完全一样的网络中?实现思路是什么?(用于强化学习DQN算法中)

Open ydchen9 opened this issue 6 years ago • 15 comments

能否提供简要的实现思路,当然能具体点更好。感谢! 另,因为我使用的是python2.6,因此无法安装parl库。只能自己动手实现。

ydchen9 avatar Jul 22 '20 10:07 ydchen9

我看有用deepcopy操作的,拷贝出一个想要拷贝的模型类,但是我用的时候不行..

ruyijidan avatar Jul 22 '20 10:07 ruyijidan

我看有用deepcopy操作的,拷贝出一个想要拷贝的模型类,但是我用的时候不行..

好的。

ydchen9 avatar Jul 22 '20 13:07 ydchen9

请问是想实现不同网络之间的参数共享么,PaddlePaddle 的参数只要有相同的命名,且运行的时候两个模型是在同一个 scope 里面,这两个参数就是共享内存的

kuke avatar Jul 23 '20 03:07 kuke

请问是想实现不同网络之间的参数共享么,PaddlePaddle 的参数只要有相同的命名,且运行的时候两个模型是在同一个 scope 里面,这两个参数就是贡献内存的

是的,要实现参数共享。

image 这个方法似乎需要在同一个program内,通过指定param_attr相同名字。因为在同一个program内,所有无法建立两个网络,这方法试过,行不通。

ydchen9 avatar Jul 23 '20 06:07 ydchen9

deepcopy是对动态图操作的. 你要是静态图,指定name,然后你去看program.all_parameter(),你会发现只创建了一个参数

当你打算在不同program中操作的话,把你的网络封装成一个函数,在每个program调用一次就好(计算复杂度x2😂

andylida avatar Jul 24 '20 03:07 andylida

deepcopy是对动态图操作的. 你要是静态图,指定name,然后你去看program.all_parameter(),你会发现只创建了一个参数

当你打算在不同program中操作的话,把你的网络封装成一个函数,在每个program调用一次就好(计算复杂度x2

按你说的这样,会不会有两个网络结构是一样的,但是它们的参数并不能共享,而是各自计算各自的? 我前面回复的话有些问题,我需要的应该不是参数共享。参数共享的话会使得两个网络,每时每刻的参数值都相同。而我需要的是在指定时刻,把一个网络的参数值全部复制到(或,全部同步到)另一个完全一样的网络中。

ydchen9 avatar Jul 24 '20 03:07 ydchen9

难道没人用paddle实现过DQN?

ydchen9 avatar Jul 24 '20 03:07 ydchen9

这样的话,deepcopy就应该够了.我个人的理解是,静态图组网的时候是没有参数的,参数保存在program中.所以deepcopy应该只复制网络结构而不复制参数. 如果这个逻辑正确的话,你可以看下下面的源代码.他的方法是,从global_scope中,找到某个参数的名字,获取它的值.在调用.sync_weights_to以后,将其中一个模型的参数全部通过.assign方法赋值过去.

https://github.com/PaddlePaddle/PARL/blob/0a068653bd988a2dac72dd53967f30e36b6a14b6/parl/core/fluid/model.py#L69

andylida avatar Jul 24 '20 12:07 andylida

call last)<ipython-input-11-9afa840df4ad> in <module> 10 Generator = G("G") 11 Discriminator = D("D") ---> 12 g=deepcopy(Generator) 13 #Generator.load_dict(gparams_dict) 14 #Discriminator.load_dict(dparams_dict) /opt/conda/envs/python35-paddle120-env/lib/python3.7/copy.py in deepcopy(x, memo, _nil) 167 reductor = getattr(x, "__reduce_ex__", None) 168 if reductor: --> 169 rv = reductor(4) 170 else: 171 reductor = getattr(x, "__reduce__", None) TypeError: can't pickle G objects

但是实际在paddle中用deepcopy的时候报错呢,难道跟PARL中use the PyTorch backend model有关系?只能在PARL中这样用么?

在parl中的Model类是这样说的

class Model(nn.Module, ModelBase): """ | alias: parl.Model | alias: parl.core.torch.agent.Model

| ``Model`` is a base class of PARL for the neural network. A ``Model`` is
usually a policy or Q-value function, which predicts an action or an
estimate according to the environmental observation.

| To use the ``PyTorch`` backend model, user needs to call ``super(Model,
self).__init__()`` at the beginning of ``__init__`` function.

| ``Model`` supports duplicating a ``Model`` instance in a pythonic way:

| ``copied_model = copy.deepcopy(model)``

Example:

.. code-block:: python

    import parl
    import torch.nn as nn

    class Policy(parl.Model):
        def __init__(self):
            super(Policy, self).__init__()
            self.fc = nn.Linear(in_features=100, out_features=32)

        def policy(self, obs):
            out = self.fc(obs)
            return out

    policy = Policy()
    copied_policy = copy.deepcopy(model)

Attributes:
    model_id(str): each model instance has its unique model_id.

Public Functions:
    - ``sync_weights_to``: synchronize parameters of the current model to
    another model.
    - ``get_weights``: return a list containing all the parameters of the
    current model.
    - ``set_weights``: copy parameters from ``set_weights()`` to the model.
    - ``forward``: define the computations of a neural network. **Should**
    be overridden by all subclasses.

"""

def __init___(self):
    super(Model, self).__init__()

def sync_weights_to(self, target_model, decay=0.0):
    """Synchronize parameters of current model to another model.

    target_model_weights = decay * target_model_weights + (1 - decay) *
    current_model_weights

    Args:
        target_model (`parl.Model`): an instance of ``Model`` that has the
        same neural network architecture as the current model.
        decay (float):  the rate of decline in copying parameters. 0 if no
        parameters decay when synchronizing the parameters.

    Example:

    .. code-block:: python

        import copy
        # create a model that has the same neural network structures.
        target_model = copy.deepcopy(model)

        # after initializing the parameters ...
        model.sync_weights_to(target_model)

    Note:
        Before calling ``sync_weights_to``, parameters of the model must
        have been initialized.
    """

    assert not target_model is self, "cannot copy between identical model"
    assert isinstance(target_model, Model)
    assert self.__class__.__name__ == target_model.__class__.__name__, \
        "must be the same class for params syncing!"
    assert (decay >= 0 and decay <= 1)

    target_vars = dict(target_model.named_parameters())
    for name, var in self.named_parameters():
        target_vars[name].data.copy_(decay * target_vars[name].data +
                                     (1 - decay) * var.data)

ruyijidan avatar Jul 25 '20 10:07 ruyijidan

@ruyijidan, @ydchen9 我遇到了同样的问题,不过我是要将动态图的网络进行soft update, 参照pytorch的写法提示没有“data”属性。 经过摸索,目前发现在paddle的动态图下,以下方法可行,供参考:

def soft_update(target, source, decay):
	"""
	Copies the parameters from source network (x) to target network (y)
	using the below update
	y = decay * source + (1 - decay) * target_param
	:param target: Target network (PaddleDynaGraphModel)
	:param source: Source network (PaddleDynaGraphModel)
	:decay: decay ratio should be super lower than 1, in range of [0,1]
	:return:
	https://paddlepaddle.org.cn/documentation/docs/zh/api_cn/fluid_cn/Variable_cn.html#set-value
	"""
	target_model_map = dict(target.named_parameters())
	for param_name, source_param in source.named_parameters():
		target_param = target_model_map[param_name]
		target_param.set_value(decay * source_param +
							   (1.0 - decay) * target_param)

	# pytorch version
	# for target_param, param in zip(target.parameters(), source.parameters()):
	#     target_param.data.copy_(target_param.data * (1.0 - tau) +
	#                             param.data * tau)

dbsxdbsx avatar Aug 01 '20 03:08 dbsxdbsx

@ruyijidan, @ydchen9 我遇到了同样的问题,不过我是要将动态图的网络进行soft update, 参照pytorch的写法提示没有“data”属性。 经过摸索,目前发现在paddle的动态图下,以下方法可行,供参考:

def soft_update(target, source, decay):
	"""
	Copies the parameters from source network (x) to target network (y)
	using the below update
	y = decay * source + (1 - decay) * target_param
	:param target: Target network (PaddleDynaGraphModel)
	:param source: Source network (PaddleDynaGraphModel)
	:decay: decay ratio should be super lower than 1, in range of [0,1]
	:return:
	https://paddlepaddle.org.cn/documentation/docs/zh/api_cn/fluid_cn/Variable_cn.html#set-value
	"""
	target_model_map = dict(target.named_parameters())
	for param_name, source_param in source.named_parameters():
		target_param = target_model_map[param_name]
		target_param.set_value(decay * source_param +
							   (1.0 - decay) * target_param)

	# pytorch version
	# for target_param, param in zip(target.parameters(), source.parameters()):
	#     target_param.data.copy_(target_param.data * (1.0 - tau) +
	#                             param.data * tau)

最近有另外其他的重要事情,暂时没搞这事。谢谢。

ydchen9 avatar Aug 01 '20 07:08 ydchen9

@ruyijidan, @ydchen9 我遇到了同样的问题,不过我是要将动态图的网络进行soft update, 参照pytorch的写法提示没有“data”属性。 经过摸索,目前发现在paddle的动态图下,以下方法可行,供参考:

def soft_update(target, source, decay):
	"""
	Copies the parameters from source network (x) to target network (y)
	using the below update
	y = decay * source + (1 - decay) * target_param
	:param target: Target network (PaddleDynaGraphModel)
	:param source: Source network (PaddleDynaGraphModel)
	:decay: decay ratio should be super lower than 1, in range of [0,1]
	:return:
	https://paddlepaddle.org.cn/documentation/docs/zh/api_cn/fluid_cn/Variable_cn.html#set-value
	"""
	target_model_map = dict(target.named_parameters())
	for param_name, source_param in source.named_parameters():
		target_param = target_model_map[param_name]
		target_param.set_value(decay * source_param +
							   (1.0 - decay) * target_param)

	# pytorch version
	# for target_param, param in zip(target.parameters(), source.parameters()):
	#     target_param.data.copy_(target_param.data * (1.0 - tau) +
	#                             param.data * tau)

好的,我试试,我之前也想到了把模型的参数全部拿出来,再通过lerp对模型参数进行更新,但我得到是参数列表...就没办法对参数进行操作。 还有,target, source可以是同一个网络么?我的目的是要做EMA,所以之前想用deepcopy把模型的参数都拷贝一份.

ruyijidan avatar Aug 01 '20 13:08 ruyijidan

@ruyijidan ,“target, source可以是同一个网络么?”,我测试下来是可行的。而且因为是同一个网路,所以decay系数比例无论多少,最后网络参数仍然没变(若不算精度损失的话)。

dbsxdbsx avatar Aug 01 '20 16:08 dbsxdbsx

@ruyijidan ,“target, source可以是同一个网络么?”,我测试下来是可行的。而且因为是同一个网路,所以decay系数比例无论多少,最后网络参数仍然没变(若不算精度损失的话)。

哦,这样,我还是需要再创建一个网络,来更新target网络的参数,我想想办法看看能不能deepcopy一下模型

ruyijidan avatar Aug 02 '20 04:08 ruyijidan

Since you haven't replied for more than a year, we have closed this issue/pr. If the problem is not solved or there is a follow-up one, please reopen it at any time and we will continue to follow up. 由于您超过一年未回复,我们将关闭这个issue/pr。 若问题未解决或有后续问题,请随时重新打开,我们会继续跟进。

paddle-bot-old avatar Sep 14 '21 09:09 paddle-bot-old