orthogonal.py 6.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
#   Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from ...fluid.initializer import Initializer
from ...fluid.data_feeder import check_variable_and_dtype
from ...fluid.core import VarDesc
from ...fluid import unique_name, framework
from ...tensor import diag, transpose, sign, qr, reshape

__all__ = []


class Orthogonal(Initializer):
    """The orthogonal initializer. The initialized tensor is (semi) orthogonal.

27 28 29 30 31 32
    It's only applied to Tensor whose dimension is greater than or equal to 2. 
    
    For the Tensor whose dimension is greater than 2, the 0 dimension is seen as ``rows`` , 
    and the >=1 dimension are flattened as ``cols`` .

    Which can be describe as:
33 34 35

    .. code-block:: text

36 37 38 39
        rows = shape[0]
        cols = shape[1]·shape[2]···shape[N]
        
        if rows < cols:
40
            The rows are orthogonal vectors
41
        elif rows > cols:
42
            The columns are orthogonal vectors
43
        else rows = cols:
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
            Both rows and columns are orthogonal vectors

    Args:
        gain(float, optional): The multiplication coefficient for initialized tensor. Default: 1.0.
        name(str, optional): The default value is None. Normally there is no need for user to set this
            property. For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        A parameter initialized by orthogonal initialized.

    Examples:
        .. code-block:: python

            import paddle

            weight_attr = paddle.ParamAttr(initializer=paddle.nn.initializer.Orthogonal())
            linear = paddle.nn.Linear(10, 15, weight_attr=weight_attr)
            # linear.weight: X * X' = I

            linear = paddle.nn.Linear(15, 10, weight_attr=weight_attr)
            # linear.weight: X' * X = I
    """

    def __init__(self, gain=1.0, name=None):
        assert gain is not None, 'gain should not be None'
        super(Orthogonal, self).__init__()
        self._gain = gain

    def __call__(self, var, block=None):
        """Initialize the input tensor with orthogonal initializer.

        Args:
            var(Tensor): Tensor that needs to be initialized.
            block(Block, optional): The block in which initialization ops
                   should be added. Used in static graph only, default None.

        Returns:
            The last initialization op, it contain 8 ops in orthogonal initializer.
        """
        block = self._check_block(block)
        assert isinstance(var, framework.Parameter)
        assert isinstance(block, framework.Block)
        # 'qr' op only support float32/float64 now
        check_variable_and_dtype(var, "Out", ["float32", "float64"],
                                 "Orthogonal")

        self._seed = block.program.random_seed

        shape = var.shape
        assert len(
            shape
        ) >= 2, "Only Tensor with 2 or more dimensions can be initialized by Orthogonal"

        row = shape[0]
        col = 1
        for i in shape[1:]:
            col *= i

        flatten_shape = [max(row, col), min(row, col)]

        normal_var = block.create_var(
            name=unique_name.generate('.'.join(['gaussian_random', 'tmp'])),
            dtype=var.dtype,
            persistable=False,
            stop_gradient=True)
        block.append_op(
            type='gaussian_random',
            inputs={},
            outputs={'Out': normal_var},
            attrs={
                'mean': 0.0,
                'std': 1.0,
                'shape': flatten_shape,
                'seed': self._seed,
                'dtype': var.dtype
            },
            stop_gradient=True)

        q = block.create_var(
            name=unique_name.generate('.'.join(['qr', 'q', 'tmp'])),
            dtype=normal_var.dtype,
            persistable=False,
            stop_gradient=True)
        r = block.create_var(
            name=unique_name.generate('.'.join(['qr', 'r', 'tmp'])),
            dtype=normal_var.dtype,
            persistable=False,
            stop_gradient=True)
        block.append_op(
            type='qr',
            inputs={'X': [normal_var]},
            outputs={
                'Q': q,
                'R': r,
            },
            attrs={'mode': 'reduced'},
            stop_gradient=True)

        r_diag = block.create_var(
            name=unique_name.generate('.'.join(['diag', 'tmp'])),
            dtype=r.dtype,
            persistable=False,
            stop_gradient=True)
        block.append_op(
            type='diag_v2',
            inputs={'X': r},
            outputs={'Out': r_diag},
            attrs={'offset': 0,
                   'padding_value': 0},
            stop_gradient=True)

        r_sign = r_diag
        block.append_op(
            type='sign',
            inputs={'X': [r_diag]},
            outputs={'Out': r_sign},
            stop_gradient=True)

        block.append_op(
            type='elementwise_mul',
            inputs={'X': q,
                    'Y': r_sign},
            outputs={'Out': q},
            attrs={},
            stop_gradient=True)

        x_shape = block.create_var(
            name=unique_name.generate('.'.join(['transpose', 'shape', 'tmp'])),
            dtype=q.dtype,
            persistable=False,
            stop_gradient=True)
        if row < col:
            q_transpose = block.create_var(
                name=unique_name.generate('.'.join(['transpose', 'tmp'])),
                dtype=q.dtype,
                persistable=False,
                stop_gradient=True)
            block.append_op(
                type='transpose2',
                inputs={'X': q},
                outputs={'Out': q_transpose,
                         'XShape': x_shape},
                attrs={'axis': [1, 0]},
                stop_gradient=True)
            q = q_transpose

        block.append_op(
            type='reshape2',
            inputs={'X': q},
            outputs={'Out': q,
                     "XShape": x_shape},
            attrs={'shape': var.shape},
            stop_gradient=True)

        op = block.append_op(
            type='scale',
            inputs={'X': q},
            outputs={'Out': var},
            attrs={'scale': self._gain,
                   'bias': 0.0})

        return op