composite_rules.py 21.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# Copyright (c) 2023 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.

# This file contains composite rules of nonbasic operations. There are some notes:
# 1. When define composite rule of some op, you can only use primitive ops defined in primitives.py.
# 2. The name and args of target op must be corresponding with standard description of op in
#    ops.yaml or legacy_ops.yaml.

Z
zqw_1997 已提交
20 21
import functools
import operator
22

23 24
from paddle.fluid import core

25 26 27 28 29 30 31 32 33 34 35 36
from .primitives import *  # noqa: F403
from .primreg import REGISTER_COMPOSITE, lookup_composite


def _composite(op, *args):
    _lowerrule = lookup_composite(op.type)
    return _lowerrule(op, *args)


@REGISTER_COMPOSITE('softmax')
def softmax_composite(x, axis):
    """define composite rule of op softmax"""
37 38 39 40
    is_amp = False
    from paddle.fluid.data_feeder import convert_dtype

    # Softmax need fp32 compute since it has sum op in
41 42
    dtype = convert_dtype(x.dtype)
    if dtype in ["float16", "uint16"]:
43 44
        is_amp = True
        x = cast(x, "float32")
C
cyber-pioneer 已提交
45 46
    if not x.shape:
        # do not return 1, to ensure gradients
47
        res = exp(x - x)
48 49
        if is_amp:
            res = cast(res, "float16")
C
cyber-pioneer 已提交
50
        return res
51 52 53 54
    max_temp = max(x, axis, keepdim=True)
    max_temp.stop_gradient = True
    molecular = exp(x - max_temp)
    denominator = sum(molecular, axis=axis, keepdim=True)
55
    res = divide(molecular, denominator)
56
    if is_amp:
57
        res = cast(res, dtype)
58
    return res
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74


@REGISTER_COMPOSITE('batch_norm')
def composite_batchnorm(
    x,
    run_mean,
    run_var,
    scale,
    bias,
    is_test,
    momentum,
    epsilon,
    data_layout,
    use_global_stats,
    trainable_statistics,
):
75 76 77 78 79
    """
    define composite rule of op batch_norm
    As the same with op kernel, the position of savedvariance indeed return inverse std.
    """

J
Jiabin Yang 已提交
80 81 82
    is_amp = False
    from paddle.fluid.data_feeder import convert_dtype

83 84
    dtype = convert_dtype(x.dtype)
    if dtype in ["float16", "uint16"]:
J
Jiabin Yang 已提交
85 86
        is_amp = True
        x = cast(x, "float32")
87 88
        scale = cast(scale, "float32") if scale else scale
        bias = cast(bias, "float32") if bias else bias
89 90 91 92 93 94 95 96 97 98 99

    feature_axis = (
        1 if data_layout in ('NC', 'NCL', 'NCHW', 'NCHWD') else len(x.shape) - 1
    )

    use_run_stat = (is_test and (not trainable_statistics)) or use_global_stats
    reduce_axes = tuple(i for i in range(len(x.shape)) if i != feature_axis)
    stats_shape = tuple(
        1 if i in reduce_axes else s for i, s in enumerate(x.shape)
    )

100
    half = full([1], -0.5, x.dtype)
J
Jiabin Yang 已提交
101

102 103 104
    if not use_run_stat:
        batch_mean = mean(x, reduce_axes)
        temp = mean(x * x, reduce_axes)
105
        batch_var = temp - batch_mean * batch_mean
106 107 108 109 110 111 112 113 114 115
        inv_std = pow((batch_var + epsilon), half)
        if data_layout == "NHWC":
            x_hat = (x - batch_mean) * inv_std
        else:
            x_hat = (x - reshape(batch_mean, stats_shape)) * reshape(
                inv_std, stats_shape
            )

        run_mean = momentum * run_mean + (1 - momentum) * batch_mean
        run_var = momentum * run_var + (1 - momentum) * batch_var
116
    else:
117 118 119 120 121 122 123 124 125 126 127 128 129
        batch_mean = zeros(run_mean.shape, run_mean.dtype)
        batch_var = zeros(run_var.shape, run_var.dtype)
        inv_std = pow((batch_var + epsilon), half)
        if data_layout == "NHWC":
            x_hat = (x - run_mean) * pow((run_var + epsilon), half)
        else:
            x_hat = (x - reshape(run_mean, stats_shape)) * pow(
                (reshape(run_var, stats_shape) + epsilon), half
            )
    if data_layout == "NHWC":
        y = scale * x_hat + bias
    else:
        y = reshape(scale, stats_shape) * x_hat + reshape(bias, stats_shape)
J
Jiabin Yang 已提交
130
    if is_amp:
131
        y = cast(y, dtype)
132 133

    # add op assign to detach tensor in void unsafe change outside the rule.
134 135
    batch_mean_ = assign(batch_mean)
    inv_std_ = assign(inv_std)
C
cyber-pioneer 已提交
136 137
    run_mean_ = assign(run_mean)
    run_var_ = assign(run_var)
138

I
iLeGend 已提交
139
    # reserve_space is not needed in composite rule, but still ruturn None to keep same as phi op definition.
C
cyber-pioneer 已提交
140
    reserve_space = None
141 142 143 144
    if not use_run_stat:
        return y, run_mean_, run_var_, batch_mean_, inv_std_, reserve_space
    else:
        return y, run_mean_, run_var_, None, None, reserve_space
G
GGBond8488 已提交
145 146


X
xiaoguoguo626807 已提交
147 148 149 150 151 152 153
@REGISTER_COMPOSITE('layer_norm')
def layernorm_composite(x, scale, bias, epsilon, begin_norm_axis):
    """
    define composite rule of op layer_norm
    out = (x - mean(x)) / sqrt(var + epsilon))
    var = mean((x-mean(x))^2)
    """
154 155 156
    is_amp = False
    from paddle.fluid.data_feeder import convert_dtype

157 158
    dtype = convert_dtype(x.dtype)
    if dtype in ["float16", "uint16"]:
159 160
        is_amp = True
        x = cast(x, "float32")
161 162
        scale = cast(scale, "float32") if scale else scale
        bias = cast(bias, "float32") if bias else bias
X
xiaoguoguo626807 已提交
163 164 165 166 167 168 169

    axis = tuple(range(begin_norm_axis, len(x.shape)))
    mean_ = mean(x, axis=axis, keepdim=True)
    difference = x - mean_
    var_tmp1 = difference * difference
    variance = mean(var_tmp1, axis=axis, keepdim=True)
    var_tmp3 = variance + epsilon
170 171
    rsqrt_var = rsqrt(var_tmp3)
    out = difference * rsqrt_var
X
xiaoguoguo626807 已提交
172 173

    if scale is not None:
174 175
        if x.shape[begin_norm_axis:] is not scale.shape:
            scale = reshape(scale, x.shape[begin_norm_axis:])
X
xiaoguoguo626807 已提交
176 177
        out = out * scale
    if bias is not None:
178 179
        if x.shape[begin_norm_axis:] is not bias.shape:
            bias = reshape(bias, x.shape[begin_norm_axis:])
X
xiaoguoguo626807 已提交
180 181 182 183
        out = out + bias

    mean_ = reshape(mean_, [-1])
    variance = reshape(variance, [-1])
184
    if is_amp:
185
        out = cast(out, dtype)
X
xiaoguoguo626807 已提交
186 187 188
    return out, mean_, variance


189 190 191 192 193 194 195 196 197 198 199 200 201 202
@REGISTER_COMPOSITE('instance_norm')
def instancenorm_composite(x, scale, bias, epsilon):
    """
    define composite rule of op instance_norm
    out = (x - mean(x)) / sqrt(var + epsilon))
    var = mean((x-mean(x))^2)
    """
    n, c, h, w = x.shape
    axis = tuple(range(2, len(x.shape)))
    mean_ = mean(x, axis=axis, keepdim=True)
    difference = x - mean_
    var_tmp1 = difference * difference
    variance = mean(var_tmp1, axis=axis, keepdim=True)
    var_tmp3 = variance + epsilon
Z
zyfncg 已提交
203
    sqrt_var = pow(var_tmp3, full([1], 0.5, dtype=var_tmp3.dtype))
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
    out = difference / sqrt_var

    if scale is not None:
        scale_tile = reshape(scale, [1, c, 1, 1])
        out = out * scale_tile
    if bias is not None:
        bias_tile = reshape(bias, [1, c, 1, 1])
        out = out + bias_tile

    mean_ = reshape(mean_, [-1])
    saved_variance = 1 / sqrt_var
    saved_variance = reshape(saved_variance, [-1])
    return out, mean_, saved_variance


G
GGBond8488 已提交
219 220 221 222 223 224 225
@REGISTER_COMPOSITE('gelu')
def gelu_composite(x, approximate):
    """define composite rule of op gelu"""
    M_SQRT1_2 = (
        0.70710678118654752440  # /* 1/sqrt(2) */ copy from gelu-kernel.cc
    )
    M_2_SQRTPI = 1.12837916709551257390  # /* 2/sqrt(pi) */
226 227 228
    full_shape = x.shape if len(x.shape) == 0 else [1]
    one = ones(full_shape, x.dtype)
    half = full(full_shape, 0.5, x.dtype)
G
GGBond8488 已提交
229 230
    if approximate:
        # gelu(x) = 0.5 * x * (1 + tanh(sqrt(2 / \pi) * (x + 0.044715 * x^{3})))
231 232
        kAlpha = full(full_shape, M_2_SQRTPI * M_SQRT1_2, x.dtype)
        GELU_CONSTANT = full(full_shape, 0.044715, x.dtype)
G
GGBond8488 已提交
233 234 235 236 237 238 239 240 241
        tanh_out = tanh(kAlpha * (x + GELU_CONSTANT * x * x * x))
        out = x * half * (one + tanh_out)
        return out

    else:
        # gelu(x) = 0.5 * x *  (1 + erf(x / sqrt(2)))
        cdf = half * (one + erf(x * full(x.shape, M_SQRT1_2, x.dtype)))
        out = x * cdf
        return out
Z
zqw_1997 已提交
242 243 244 245 246


@REGISTER_COMPOSITE('reduce_mean')
def mean_composite(x, axis, keepdim):
    """define composite rule of op mean"""
J
Jiabin Yang 已提交
247 248 249
    is_amp = False
    from paddle.fluid.data_feeder import convert_dtype

250
    dtype = convert_dtype(x.dtype)
251
    if dtype in ["float16", "uint16"]:
J
Jiabin Yang 已提交
252 253 254
        is_amp = True
        x = cast(x, "float32")

Z
zqw_1997 已提交
255 256 257
    axes = axis or list(range(0, len(x.shape)))
    axes = [axes] if isinstance(axes, int) else axes
    sum_x = sum(x, axis=axes, keepdim=keepdim)
258 259 260 261 262
    ele_nums_list = [x.shape[axis] for axis in axes]
    if ele_nums_list == []:
        value_to_fill = 1
    else:
        value_to_fill = functools.reduce(operator.mul, ele_nums_list)
Z
zqw_1997 已提交
263
    norm = fill_constant(
264
        shape=[],
Z
zqw_1997 已提交
265 266 267
        value=value_to_fill,
        dtype=sum_x.dtype,
    )
J
Jiabin Yang 已提交
268 269
    res = divide(sum_x, norm)
    if is_amp:
270
        res = cast(res, dtype)
J
Jiabin Yang 已提交
271
    return res
272 273


274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
@REGISTER_COMPOSITE('expand_v2')
def expand_v2_composite(x, shape):
    """
    define composite rule of op expnad_v2, expand_v2->expand
    repeat_times = shape / x.shape
    out = tile(x, repeat_times = repeat_times)
    """
    shape_in = x.shape
    dim_out = len(shape)
    dim_in = len(shape_in)
    assert dim_in <= dim_out and dim_out >= 0
    repeat_times = []
    for i in range(dim_out):
        offset = dim_out - i
        dim = dim_in - offset
        size_in = shape_in[dim] if dim >= 0 else 1
        size_out = shape[i]
        if size_out == -1:
            assert dim >= 0
            repeat = 1
        else:
            assert size_out % size_in == 0
            repeat = int(size_out / size_in)
        repeat_times.append(repeat)
    if dim_in < dim_out:
        shape_in_expand = []
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
        for i in range(dim_out - dim_in):
            shape_in_expand.append(1)
        shape_in_expand.extend(shape_in)
        x_reshape = reshape(x, shape_in_expand)
        return tile(x_reshape, repeat_times=repeat_times)
    return tile(x, repeat_times=repeat_times)


@REGISTER_COMPOSITE('expand_as_v2')
def expand_as_v2_composite(x, y, target_shape):
    """
    define composite rule of op expnad_as_v2, expand_as_v2->expand_as
    repeat_times = target_shape / x.shape
    out = tile(x, repeat_times = repeat_times)
    """
    shape_in = x.shape
    if y is not None:
        target_shape = y.shape
    assert target_shape is not None
    dim_out = len(target_shape)
    dim_in = len(shape_in)
    assert dim_in <= dim_out and dim_out >= 0
    repeat_times = []
    for i in range(dim_out):
        offset = dim_out - i
        dim = dim_in - offset
        size_in = shape_in[dim] if dim >= 0 else 1
        size_out = target_shape[i]
        if size_out == -1:
            assert dim >= 0
            repeat = 1
        else:
            assert size_out % size_in == 0
            repeat = int(size_out / size_in)
        repeat_times.append(repeat)
    if dim_in < dim_out:
        shape_in_expand = []
337 338 339 340 341 342 343 344
        for i in range(dim_out - dim_in):
            shape_in_expand.append(1)
        shape_in_expand.extend(shape_in)
        x_reshape = reshape(x, shape_in_expand)
        return tile(x_reshape, repeat_times=repeat_times)
    return tile(x, repeat_times=repeat_times)


C
ccrrong 已提交
345 346 347 348 349 350 351 352 353 354 355 356 357 358
@REGISTER_COMPOSITE('stack')
def stack_composite(x, axis):
    """
    define composite rule of op stack
    unsqueeze each dimension of the input (use reshape), and then concat
    """
    x_shape = x[0].shape
    if axis < 0:
        axis += len(x_shape) + 1
    out_shape = x_shape[:axis] + (1,) + x_shape[axis:]
    out = concat([reshape(item, out_shape) for item in x], axis)
    return out


359 360 361 362
@REGISTER_COMPOSITE('flatten_contiguous_range')
def flatten_contiguous_range_composite(x, start_axis, stop_axis):
    """
    define composite rule of op flatten, flatten_contiguous_range -> flatten.
363 364

    xshape is the dim with 0 added to the front of x, keep the shape information of x to calculate the grad.
365 366 367 368 369 370 371 372
    CINN doesn't need xshape for backward pass, return none instead of xshape.
    shape_out is the parameter of reshape, get from start_axis and stop_axis.
    out = reshape(x, shape=shape_out), xshape
    """
    shape_in = x.shape
    start_dim = start_axis if len(shape_in) != 0 else 0
    end_dim = stop_axis if len(shape_in) != 0 else 0
    assert start_dim <= end_dim
373 374 375
    if len(shape_in) == 0:
        return reshape(x, shape=[1]), None
    if start_dim == end_dim:
376 377 378 379 380 381 382 383 384 385 386 387 388
        return reshape(x, shape=shape_in), None
    slice_numel = 1
    for i in range(start_dim, end_dim + 1):
        slice_numel *= shape_in[i]
    shape_out = []
    for i in range(start_dim):
        shape_out.append(shape_in[i])
    shape_out.append(slice_numel)
    for i in range(end_dim + 1, len(shape_in)):
        shape_out.append(shape_in[i])
    return reshape(x, shape=shape_out), None


389 390 391 392 393 394 395 396 397 398 399 400 401
@REGISTER_COMPOSITE('dropout')
def dropout_composite(x, seed_tensor, p, is_test, mode, seed, fix_seed):
    """define composite rule of op dropout.
    upscale_in_train:
        train: out = input * mask / ( 1.0 - p )
        inference: out = input
    downscale_in_infer
        train: out = input * mask
        inference: out = input * (1.0 - p)
    """
    fix_seed = True if fix_seed is None else fix_seed
    seed = seed if fix_seed else 0
    upscale_in_train = mode == "upscale_in_train"
402

403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
    mask = bernoulli(shape=x.shape, dtype=x.dtype, p=p, seed=seed)

    if upscale_in_train:
        if not is_test:
            # Process p=1.0 for avoid devide zero error (x*mask/(1.0-p))
            if p == 1.0:
                return 0.0 * x, zeros(x.shape, core.VarDesc.VarType.UINT8)
            else:
                return x * mask / (1.0 - p), cast(
                    mask, core.VarDesc.VarType.UINT8
                )
        else:
            return assign(x), cast(mask, core.VarDesc.VarType.UINT8)
    else:
        if not is_test:
            return x * mask, cast(mask, core.VarDesc.VarType.UINT8)
        else:
            return x * (1.0 - p), cast(mask, core.VarDesc.VarType.UINT8)


def bernoulli(shape, dtype, p, seed=0):
424 425 426
    from paddle.fluid.data_feeder import convert_dtype

    # TODO(jiabin) Fix uniform doesn't support float16 error in CINN
427 428 429
    new_dtype = (
        "float32" if convert_dtype(dtype) in ["float16", "uint16"] else dtype
    )
430 431
    return cast(
        greater_equal(
432
            uniform(shape, new_dtype, min=0.0, max=1.0, seed=seed),
433
            fill_constant(shape if len(shape) == 0 else [1], new_dtype, p),
434 435 436
        ),
        dtype,
    )
Z
zxcd 已提交
437 438


R
Roc 已提交
439 440 441 442 443 444 445 446 447 448
@REGISTER_COMPOSITE('hard_swish')
def hard_swish_composite(x):
    """define composite rule of op hard_swish.
    offset=3, threshold=6, scale=6
    out = minimum(
        maxmum(x + offset, 0), threshold
    ) * x / scale
    """
    threshold = 6.0
    scale = 6.0
449
    offset = 3.0
450
    full_shape = x.shape if len(x.shape) == 0 else [1]
R
Roc 已提交
451 452 453
    res = (
        minimum(
            maximum(
454 455
                x + full(full_shape, offset, dtype=x.dtype),
                full(full_shape, 0.0, dtype=x.dtype),
R
Roc 已提交
456
            ),
457
            full(full_shape, threshold, dtype=x.dtype),
R
Roc 已提交
458 459
        )
        * x
460
        / full(full_shape, scale, dtype=x.dtype)
R
Roc 已提交
461 462 463 464
    )
    return res


R
Roc 已提交
465 466 467 468 469 470 471 472 473
@REGISTER_COMPOSITE('index_select')
def index_select_composite(x, index, axis):
    """define composite rule of op index_select."""
    if axis < 0:
        axis = len(x.shape) + axis
    res = gather(x, index, axis=axis)
    return res


Z
zxcd 已提交
474 475 476 477 478 479
@REGISTER_COMPOSITE('sigmoid')
def sigmoid_composite(x):
    """
    define composite rule of op sigmoid
    res = 1 / (1 + exp(-x))
    """
J
Jiabin Yang 已提交
480 481 482
    is_amp = False
    from paddle.fluid.data_feeder import convert_dtype

483 484
    dtype = convert_dtype(x.dtype)
    if dtype in ["float16", "uint16"]:
J
Jiabin Yang 已提交
485 486 487
        is_amp = True
        x = cast(x, "float32")

Z
zxcd 已提交
488 489
    sum_temp = 1 + exp(-x)
    res = 1 / sum_temp
490
    return res if not is_amp else cast(res, dtype)
Z
zxcd 已提交
491 492


Z
zxcd 已提交
493 494 495 496 497 498
@REGISTER_COMPOSITE('silu')
def silu_composite(x):
    """
    define composite rule of op silu
    res = x / (1 + exp(-x))
    """
J
Jiabin Yang 已提交
499 500 501
    is_amp = False
    from paddle.fluid.data_feeder import convert_dtype

502 503
    dtype = convert_dtype(x.dtype)
    if dtype in ["float16", "uint16"]:
J
Jiabin Yang 已提交
504 505 506
        is_amp = True
        x = cast(x, "float32")

Z
zxcd 已提交
507 508
    sum_temp = 1 + exp(-x)
    res = x / sum_temp
509
    return res if not is_amp else cast(res, dtype)
510 511


512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
@REGISTER_COMPOSITE('meshgrid')
def meshgrid_composite(inputs):
    """
    define composite rule of op meshgrid
    If the input has N tensors of size S_0, ... S_n-1, then the output will also have N tensors, where
    each tensor is of shape (S_0, ..., S_n-1).
    E.g. a1 is Tensor [1,2,3]
         b1 is Tensor [4,5]
         r1, r2 = paddle.meshgrid([a1, b1])
         r1 is Tensor [[1,1], [2,2], [3,3]]
         r2 is Tensor [[4,5], [4,5], [4,5]]
    """
    size = len(inputs)
    shape = [1] * size
    for i in range(size):
        dim = inputs[i].dim()
        assert dim == 0 or dim == 1
        if dim == 1:
            shape[i] = inputs[i].shape[0]
    outputs = []
    for i in range(size):
        view_shape = [1] * size
        view_shape[i] = shape[i]
        outputs.append(inputs[i].reshape(view_shape).broadcast_to(shape))
    return outputs


539 540 541 542 543 544 545
@REGISTER_COMPOSITE('fill_any_like')
def fill_any_like(x, fill_value, dtype, place=None):
    """define composite rule of op full_like."""
    """op name: full_like  op type name: fill_any_like."""
    """arg place is not used, add it here to keep same as python api."""
    val = full(x.shape, fill_value, dtype)
    return val
K
Kang Zhao 已提交
546 547


548 549 550 551 552 553 554 555 556 557 558
@REGISTER_COMPOSITE('squeeze2')
def squeeze2_composite(x, axis):
    """define composite rule of squeeze"""
    """
    canonicalize dim within range 0 to rank and
    determine new shape after squeeze op
    if axis not specified, remove all dims equal to 1
    otherwise, remove dims equal to 1 in axis
    axis can only be list, not int
    """
    rank = len(x.shape)
559 560
    if rank == 0:
        return [assign(x), None]
561 562 563
    if len(axis) == 0:
        dims = set(range(rank))
    else:
564
        dims = {ax % rank for ax in axis}
565 566 567 568 569 570 571 572
    new_shape = []
    for d, s in enumerate(x.shape):
        if not (s == 1 and (d in dims)):
            new_shape.append(s)
    out = reshape(x, new_shape)
    return [out, None]


M
mhy-666 已提交
573 574 575 576 577 578
@REGISTER_COMPOSITE('sqrt')
def sqrt_composite(x):
    """
    define composite rule of op sqrt
    res = pow(x, 0.5)
    """
J
Jiabin Yang 已提交
579 580 581
    is_amp = False
    from paddle.fluid.data_feeder import convert_dtype

582 583
    dtype = convert_dtype(x.dtype)
    if dtype in ["float16", "uint16"]:
J
Jiabin Yang 已提交
584 585 586
        is_amp = True
        x = cast(x, "float32")

587
    y = full(x.shape if len(x.shape) == 0 else [1], 0.5, x.dtype)
M
mhy-666 已提交
588
    res = pow(x, y)
589
    return res if not is_amp else cast(res, dtype)
M
mhy-666 已提交
590 591


592 593 594 595 596 597
@REGISTER_COMPOSITE('pow')
def pow_composite(x, y):
    """
    define composite rule of op pow
    res = x^y
    """
J
Jiabin Yang 已提交
598 599 600
    is_amp = False
    from paddle.fluid.data_feeder import convert_dtype

601 602
    dtype = convert_dtype(x.dtype)
    if dtype in ["float16", "uint16"]:
J
Jiabin Yang 已提交
603 604 605
        is_amp = True
        x = cast(x, "float32")

606
    if isinstance(y, (int, float)):
607
        y = full(x.shape if len(x.shape) == 0 else [1], y, x.dtype)
608
    res = pow(x, y)
J
Jiabin Yang 已提交
609
    if is_amp:
610
        res = cast(res, dtype)
611 612 613
    return res


K
Kang Zhao 已提交
614 615 616 617
@REGISTER_COMPOSITE('relu')
def relu_composite(x):
    """define composite rule of op relu."""
    # relu(x) = max(x, 0)
618 619 620 621
    if len(x.shape) == 0:
        return maximum(x, full(x.shape, 0.0, x.dtype))
    else:
        return maximum(x, full([1], 0.0, x.dtype))
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641


@REGISTER_COMPOSITE('unsqueeze2')
def unsqueeze_composite(x, axis):
    """define composite rule of op unsqueeze"""
    """using reshape to implement unsqueeze op"""
    x_shape = list(x.shape)
    axis_list = list(axis)
    for i in axis_list:
        if i < 0:
            i += len(x_shape) + 1
        x_shape = (
            x_shape[:i]
            + [
                1,
            ]
            + x_shape[i:]
        )
    out = reshape(x, x_shape)
    return [out, None]
642 643 644 645 646 647


@REGISTER_COMPOSITE('rsqrt')
def rsqrt_composite(x):
    """define composite rule of op rsqrt."""
    # rsqrt(x) = x^(-0.5)
J
Jiabin Yang 已提交
648 649 650
    is_amp = False
    from paddle.fluid.data_feeder import convert_dtype

651
    dtype = convert_dtype(x.dtype)
652
    if dtype in ["float16", "uint16"]:
J
Jiabin Yang 已提交
653 654
        is_amp = True
        x = cast(x, "float32")
655
    y = full(x.shape if len(x.shape) == 0 else [1], -0.5, x.dtype)
J
Jiabin Yang 已提交
656
    res = pow(x, y)
657
    return res if not is_amp else cast(res, dtype)
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673


@REGISTER_COMPOSITE('group_norm')
def group_norm_composite(x, scale, bias, epsilon, groups, data_layout):
    """
    define composite rule of op group_norm.
    x = ((x - mean) / sqrt(var + epsilon)) * scale + bias
    mean and var are computed from groups
    """
    # original GroupNorm op cannot support NHWC format
    assert data_layout == 'NCHW'
    N, C, H, W = x.shape

    is_amp = False
    from paddle.fluid.data_feeder import convert_dtype

674 675 676
    dtype = convert_dtype(x.dtype)
    # when inputs are float16 or bfloat16, convert to float32 in computing
    if dtype in ["float16", "uint16"]:
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
        is_amp = True
        x = cast(x, "float32")
        scale = cast(scale, "float32")
        bias = cast(bias, "float32")

    x = reshape(x, (N * groups, -1))
    mean_ = mean(x, axis=1, keepdim=True)
    var_ = mean(x * x, axis=1, keepdim=True) - mean_ * mean_
    var_ = maximum(var_, zeros_like(var_))
    var_inv = 1 / sqrt(var_ + epsilon)
    out = (x - mean_) * var_inv
    out = reshape(out, (N, C, H, W))
    if scale is not None:
        out = out * reshape(scale, (-1, 1, 1))
    if bias is not None:
        out = out + reshape(bias, (-1, 1, 1))
    ret_mean_ = reshape(mean_, (N, groups))
    ret_var_ = reshape(var_, (N, groups))
695
    # return output in float16 or bfloat16, mean and var in float32
696
    if is_amp:
697
        out = cast(out, dtype)
698
    return out, ret_mean_, ret_var_
699 700


X
xiaoguoguo626807 已提交
701 702 703 704 705 706 707 708
@REGISTER_COMPOSITE('sum')
def sum_composite(x):
    ans = 0
    for xi in x:
        ans += xi
    return ans


709 710 711 712 713 714 715
@REGISTER_COMPOSITE('leaky_relu')
def leaky_relu_composite(x, negative_slope):
    """define composite rule of op leaky_relu."""
    if negative_slope < 1.0:
        return maximum(x, negative_slope * x)
    else:
        return minimum(x, negative_slope * x)