primreg.py 9.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Copyright (c) 2022 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.


16
class Registry:
17 18
    """A general registry object."""

19 20 21 22 23 24 25
    __slots__ = ['name', 'tab']

    def __init__(self, name):
        self.name = name
        self.tab = {}

    def register(self, name, value):
26 27 28
        assert (
            name not in self.tab
        ), f'name "{name}" should not be registered before.'
29 30 31 32 33 34 35 36 37 38 39 40
        self.tab[name] = value

    def lookup(self, name):
        return self.tab.get(name)


_primop_fn = Registry('primop_fn')
_orig2prim = Registry('orig2prim')
_prim2orig = Registry('prim2orig')
_primop_jvp = Registry('primop_jvp')
_primop_transpose = Registry('primop_transpose')
_primop_position_argnames = Registry('primop_position_argnames')
41
_composite_ops = Registry('composite')
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63


def lookup_fn(optype):
    return _primop_fn.lookup(optype)


def lookup_orig2prim(optype):
    return _orig2prim.lookup(optype)


def lookup_prim2orig(optype):
    return _prim2orig.lookup(optype)


def lookup_jvp(optype):
    return _primop_jvp.lookup(optype)


def lookup_transpose(optype):
    return _primop_transpose.lookup(optype)


64 65 66 67
def lookup_composite(optype):
    return _composite_ops.lookup(optype)


68 69 70
def op_position_inputs(op):
    """
    Returns the position inputs of `op` as registered with REGISTER_FN.
71

72 73 74 75 76 77
    Args:
        op(Operator): The op that needs to get the inputs

    Returns:
        Tensor(s): Inputs of the op

78
    Examples:
79 80 81 82 83 84 85
        .. code-block:: python
            @REGISTER_FN('div_p', 'X', 'Y', 'Z')
            def div(x, y, out=None):
                return _simple_binop(LayerHelper('div_p', **locals()))

    The registered inputs are ['X', 'Y'] for div_p and accordingly this
    function will return inputs in the order of X then Y.
86

87 88
    """
    args = _primop_position_argnames.lookup(op.type)
89 90 91
    assert (
        args is not None
    ), f'args of {op.type} should not be None in op_position_inputs().'
92 93 94 95 96
    *input_names, _ = args

    inputs = []
    for name in input_names:
        vars = list(map(op.block.var, op.input(name)))
97 98 99
        assert (
            len(vars) >= 0
        ), f'len(vars) should be greater than or equal to 0, but len(vars)={len(vars)}.'
100 101 102 103 104 105 106 107 108 109 110
        if len(vars) > 1:
            inputs.append(vars)
        else:
            inputs.append(vars[0])

    return inputs


def op_position_output(op):
    """
    Returns the output of `op` as registered with REGISTER_FN.
111

112 113 114 115 116 117
    Args:
        op(Operator): The op that needs to get the output

    Returns:
        Tensor(s): Output of the op

118
    Examples:
119 120 121 122 123 124 125
        .. code-block:: python
            @REGISTER_FN('div_p', 'X', 'Y', 'Z')
            def div(x, y, out=None):
                return _simple_binop(LayerHelper('div_p', **locals()))

    The registered output is ['Z'] for div_p and accordingly this
    function will return output Z.
126

127 128 129 130 131 132
    """
    args = _primop_position_argnames.lookup(op.type)
    assert args is not None, 'args should not be None in op_position_output().'
    *_, output_name = args

    outvars = list(map(op.block.var, op.output(output_name)))
133 134 135
    assert (
        len(outvars) >= 0
    ), f'len(outvars) should be greater than or equal to 0, but len(outvars)={len(outvars)}.'
136 137 138 139 140 141 142 143 144 145
    if len(outvars) > 1:
        output = outvars
    else:
        output = outvars[0]

    return output


def REGISTER_FN(op_type, *position_argnames):
    """
146
    Decorator for registering the Python function for a primitive op.
147 148 149

    Args:
        op_type(str): The op name
S
Shuangchi He 已提交
150
        position_argnames(list[str]): Input and output names of the op
151 152 153 154

    Returns:
        wrapper: Inner wrapper function

155
    Examples:
156 157 158 159
        .. code-block:: python
        @REGISTER_FN('tanh_p', 'X', 'Y')
        def tanh(x, out=None):
            return _simple_unop(LayerHelper('tanh_p', **locals()))
160

161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
    """

    if not isinstance(op_type, str):
        raise TypeError(f'op_type must be str, but got {type(op_type)}.')

    _primop_position_argnames.register(op_type, position_argnames)

    def wrapper(f):
        _primop_fn.register(op_type, f)
        return f

    return wrapper


def REGISTER_ORIG2PRIM(op_type):
    """
    Decorator for registering the lower function for an original op into sequence of primitive ops.
178

179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
    Args:
        op_type(str): The op name

    Returns:
        wrapper: Inner wrapper function

    Examples:
        .. code-block:: python
            @REGISTER_ORIG2PRIM('tanh')
            def tanh_orig2prim(op):
                x, = get_input_var_list(op)
                return primops.tanh(x)

    """
    if not isinstance(op_type, str):
        raise TypeError(f'op_type must be str, but got {type(op_type)}.')

    def wrapper(f):
        def _lower(op, *args, **kwargs):
198 199 200
            assert (
                op.type == op_type
            ), f'op.type should be equal to op_type, but op.type is {op.type} and op_type is {op_type}'
201 202 203 204 205 206 207
            return f(op, *args, **kwargs)

        _orig2prim.register(op_type, _lower)

    return wrapper


208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
def REGISTER_COMPOSITE(op_type):
    """
    Decorator for registering the lower function for an original op into sequence of primitive ops.

    Args:
        op_type(str): The op name

    Returns:
        wrapper: Inner wrapper function

    Examples:
        .. code-block:: python
            @REGISTER_COMPOSITE('softmax')
            def softmax_composite(x, axis):
                molecular = exp(x)
                denominator = broadcast_to(sum(molecular, axis=axis, keepdim=True), x.shape)
                res = divide(molecular, denominator)
                return res

    """
    if not isinstance(op_type, str):
        raise TypeError(f'op_type must be str, but got {type(op_type)}.')

    def wrapper(f):
        def _lower(op, *args, **kwargs):
            assert (
                op.type == op_type
            ), f'op.type should be equal to op_type, but op.type is {op.type} and op_type is {op_type}'
            return f(*args, **kwargs)

        _composite_ops.register(op_type, _lower)

    return wrapper


243 244 245
def REGISTER_PRIM2ORIG(op_type):
    """
    Decorator for registering the lower function for an primitive op into sequence of original ops.
246

247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
    Args:
        op_type(str): The op name

    Returns:
        wrapper: Inner wrapper function

    Examples:
        .. code-block:: python
            @REGISTER_PRIM2ORIG('tanh_p')
            def tanh_prim2orig(op):
                x, = get_input_var_list(op)
                return paddle.tanh(x)

    """
    if not isinstance(op_type, str):
        raise TypeError(f'op_type must be str, but got {type(op_type)}.')

    def wrapper(f):
        def _lower(op, *args, **kwargs):
266 267 268
            assert (
                op.type == op_type
            ), f'op.type should be equal to op_type, but op.type is {op.type} and op_type is {op_type}'
269 270 271 272 273 274 275 276 277 278
            return f(op, *args, **kwargs)

        _prim2orig.register(op_type, _lower)

    return wrapper


def REGISTER_JVP(op_type):
    """
    Decorator for registering the JVP function for a primitive op.
279

280 281 282 283 284 285 286 287 288 289 290
    Args:
        op_type(str): The op name

    Returns:
        wrapper: Inner wrapper function

    Examples:
        .. code-block:: python
            @REGISTER_JVP('add_p')
            def add_jvp(op, x_dot, y_dot):
                return primops.add(x_dot, y_dot)
291

292 293 294 295 296 297
    """
    if not isinstance(op_type, str):
        raise TypeError(f'op_type must be str, but got {type(op_type)}.')

    def wrapper(f):
        def _jvp(op, *args, **kwargs):
298 299 300
            assert (
                op.type == op_type
            ), f'op.type should be equal to op_type, but op.type is {op.type} and op_type is {op_type}'
301 302 303 304 305 306 307 308 309 310 311 312
            return f(op, *args, **kwargs)

        _primop_jvp.register(op_type, _jvp)
        return f

    return wrapper


def REGISTER_TRANSPOSE(op_type):
    """
    Decorator for registering the transpose function for a primitive op
    that denotes a linear operation in the forward AD graph.
313

314 315 316 317 318 319 320 321 322 323 324
    Args:
        op_type(str): The op name

    Returns:
        wrapper: Inner wrapper function

    Examples:
        .. code-block:: python
            @REGISTER_TRANSPOSE('add_p')
            def add_transpose(op, z_bar):
                return z_bar, z_bar
325

326 327 328 329 330 331
    """
    if not isinstance(op_type, str):
        raise TypeError(f'op_type must be str, but got {type(op_type)}.')

    def wrapper(f):
        def _transpose(op, dot_checker, *args, **kwargs):
332 333 334
            assert (
                op.type == op_type
            ), f'op.type should be equal to op_type, but op.type is {op.type} and op_type is {op_type}'
335 336 337 338 339 340
            return f(op, dot_checker, *args, **kwargs)

        _primop_transpose.register(op_type, _transpose)
        return f

    return wrapper