Skip to content

easy parameter sharing problem #3830

@Superjomn

Description

@Superjomn

PaddlePaddle uses the class Scope to store Variables, Scope can be viewed as a key-value map from Variable's name to the corresponding Variable.

There might be many variables in a scope, so users should make sure all the variables in the same scope have unique names, with a light wrapper as follows:

class Variable(object):
    counter = 0
    def __init__(self, name=None):
        if not name:
            name = "var-%d" % Variable.counter
        self.name = name

it is easy to make the work done automatically.

But it is often for users to have some parameter variables shared between multiple sub-models, let's take a simple model for example:

import paddle as pd

a1 = pd.NewVar(shape=[20, 20], initializer=pd.gaussian_random_initializer())
a2 = pd.NewVar(shape=[20, 20], initializer=pd.gaussian_random_initializer())
a3 = pd.NewVar(shape=[20, 20], initializer=pd.gaussian_random_initializer())
b = pd.NewVar(shape=[20, 20],  initializer=pd.gaussian_random_initializer())

fc_out1 = pd.fc(a1, params=["W1", "b1"])
fc_out11 = pd.fc(fc_out1, params=["W11", "b11"])
out1 = fc_out12 + b

fc_out2 = pd.fc(a2, params=["W1", "b1"])
fc_out21 = pd.fc(fc_out2, params=["W11", "b11"])
out2 = fc_out21 + b

fc_out3 = pd.fc(a3, params=["W1", "b1"])
fc_out31 = pd.fc(fc_out3, params=["W11", "b11"])
out3 = fc_out31 + b

# different parameter names with previous 
fc_out4 = pd.fc(a3, params=["W2", "b2"])
fc_out41 = pd.fc(fc_out4, params=["W21", "b21"])
out4 = fc_out41 + b

both fc_out11, fc_out21, fc_out31 take the same FC with shared parameter variables, fc_out41 have similar network structure but parameters are not shared.

It is better to have some help functions to make such code cleaner.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions