primrules.py 35.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
# 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.
14
import functools
15
import math
16 17
import operator
import typing
18 19 20

import paddle

21
from . import primops
22 23
from .primops import (
    add,
24
    bernoulli,
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
    broadcast,
    concat,
    cos,
    div,
    eq,
    erf,
    exp,
    fill_const,
    gather,
    ge,
    gt,
    log,
    matmul,
    mul,
    ne,
    neg,
    reduce_sum,
    reshape,
43
    rsqrt,
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
    scatter_add,
    select,
    set_value,
    sin,
    slice_assign,
    slice_select,
    split,
    sqrt,
    sub,
    tanh,
    transpose,
    uniform_random,
)
from .primreg import (
    REGISTER_JVP,
    REGISTER_ORIG2PRIM,
    REGISTER_PRIM2ORIG,
    REGISTER_TRANSPOSE,
    lookup_fn,
    lookup_jvp,
    lookup_orig2prim,
    lookup_prim2orig,
    lookup_transpose,
    op_position_inputs,
    op_position_output,
)
70
from .utils import INT_DTYPE_2_STRING, get_output_var_list
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


def _orig2prim(op, *args):
    _lowerrule = lookup_orig2prim(op.type)
    return _lowerrule(op, *args)


def _prim2orig(op, *args):
    _lowerrule = lookup_prim2orig(op.type)
    return _lowerrule(op, *args)


def _jvp(op, *args):
    _jvprule = lookup_jvp(op.type)
    return _jvprule(op, *args)


def _transpose(op, dot_checker, *args):
    _transposerule = lookup_transpose(op.type)
    return _transposerule(op, dot_checker, *args)


def linear_jvp(op, *args, **kwargs):
    fn = lookup_fn(op.type)
    out_dot = fn(*args, **kwargs)
    return out_dot


99
# Register orig2prim lower rules
100 101 102 103 104 105 106 107
"""
These original ops are fully supported:

elementwise_add
elementwise_sub
elementwise_mul
tanh
fill_zeros_like
108
fill_any_like
109 110 111 112 113
sum
index_select
scale
assign
sqrt
114 115 116 117
log
select
equal
elementwise_pow
118
dropout
119
uniform_random
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134

These original ops are partially supported:

matmul_v2
reshape2
concat
slice
p_norm
"""


@REGISTER_ORIG2PRIM('elementwise_add')
def elementwise_add_orig2prim(op, x, y):
    if x.shape != y.shape:
        y = broadcast(y, shape=x.shape)
135
    return add(x, y)
136 137 138 139 140 141


@REGISTER_ORIG2PRIM('elementwise_sub')
def elementwise_sub_orig2prim(op, x, y):
    if x.shape != y.shape:
        y = broadcast(y, shape=x.shape)
142
    return sub(x, y)
143 144 145 146 147 148


@REGISTER_ORIG2PRIM('elementwise_mul')
def elementwise_mul_orig2prim(op, x, y):
    if x.shape != y.shape:
        y = broadcast(y, shape=x.shape)
149
    return mul(x, y)
150 151


152 153 154 155 156 157 158
@REGISTER_ORIG2PRIM('elementwise_div')
def elementwise_div_orig2prim(op, x, y):
    if x.shape != y.shape:
        y = broadcast(y, shape=x.shape)
    return primops.div(x, y)


159 160 161 162 163
@REGISTER_ORIG2PRIM('tanh')
def tanh_orig2prim(op, x):
    return tanh(x)


164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
@REGISTER_ORIG2PRIM('sin')
def sin_orig2prim(op, x):
    return sin(x)


@REGISTER_ORIG2PRIM('cos')
def cos_orig2prim(op, x):
    return cos(x)


@REGISTER_ORIG2PRIM('exp')
def exp_orig2prim(op, x):
    return exp(x)


179 180 181 182 183
@REGISTER_ORIG2PRIM('erf')
def erf_orig2prim(op, x):
    return erf(x)


184 185 186 187 188
@REGISTER_ORIG2PRIM('abs')
def abs_orig2prim(op, x):
    return primops.abs(x)


189 190 191 192 193
@REGISTER_ORIG2PRIM('log')
def log_orig2prim(op, x):
    return log(x)


194 195 196 197 198
@REGISTER_ORIG2PRIM('fill_zeros_like')
def fill_zeros_like_orig2prim(op, x):
    return fill_const(value=0.0, shape=x.shape, dtype=x.dtype)


199 200 201 202
@REGISTER_ORIG2PRIM('fill_any_like')
def fill_any_like_orig2prim(op, x):
    if op.attr('dtype') == -1:
        return fill_const(value=op.attr('value'), shape=x.shape, dtype=x.dtype)
203 204 205 206 207
    return fill_const(
        value=op.attr('value'),
        shape=x.shape,
        dtype=paddle.dtype(op.attr('dtype')),
    )
208 209


210
@REGISTER_ORIG2PRIM('fill_constant')
211 212 213
def fill_const_orig2prim(
    op, shape_tensor=None, shape_tensor_list=None, value_tensor=None
):
214 215 216 217
    if shape_tensor or shape_tensor_list or value_tensor:
        raise TypeError(
            'fill_const_orig2prim currently not support Tensor input of shape and value.'
        )
218 219 220 221 222
    return fill_const(
        value=op.attr('value'),
        shape=op.attr('shape'),
        dtype=paddle.dtype(op.attr('dtype')),
    )
223 224


225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
@REGISTER_ORIG2PRIM('sum')
def sum_orig2prim(op, xs):
    x0 = xs[0]
    for x in xs[1:]:
        x0 = add(x0, x)
    return x0


@REGISTER_ORIG2PRIM('index_select')
def index_select_orig2prim(op, index_t, x):
    return gather(x, indextensor=index_t, axis=op.attr('dim'))


@REGISTER_ORIG2PRIM('scale')
def scale_orig2prim(op, scale_t, x):
    if scale_t is None:
241 242 243
        scale_t = fill_const(
            shape=x.shape, dtype=x.dtype, value=op.attr('scale')
        )
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
    bias_t = fill_const(shape=x.shape, dtype=x.dtype, value=op.attr('bias'))
    if op.attr('bias_after_scale'):
        return add(mul(x, scale_t), bias_t)
    else:
        return mul(add(x, bias_t), scale_t)


@REGISTER_ORIG2PRIM('assign')
def assign_orig2prim(op, x):
    zero_t = fill_const(shape=x.shape, dtype=x.dtype, value=0.0)
    return add(x, zero_t)


@REGISTER_ORIG2PRIM('sqrt')
def sqrt_orig2prim(op, x):
    return sqrt(x)


J
Jiabin Yang 已提交
262 263 264 265 266
@REGISTER_ORIG2PRIM('rsqrt')
def rsqrt_orig2prim(op, x):
    return rsqrt(x)


267 268 269
@REGISTER_ORIG2PRIM('matmul_v2')
def matmul_v2_orig2prim(op, x, y):
    def trans(shape):
270
        ret = list(range(len(shape)))
271 272 273
        ret[-1], ret[-2] = ret[-2], ret[-1]
        return ret

274 275 276
    assert (
        len(x.shape) < 4 and len(y.shape) < 4
    ), 'Do not support multi batchsize dimensions currently.'
277 278 279 280 281 282 283 284 285 286 287 288

    if len(x.shape) == 1:
        x = broadcast(x, shape=[1, x.shape[0]])
    if len(y.shape) == 1:
        y = broadcast(y, shape=[y.shape[0], 1])
    if op.attr('trans_x'):
        x = transpose(x, axis=trans(x.shape))
    if op.attr('trans_y'):
        y = transpose(y, axis=trans(y.shape))
    return matmul(x, y)


289
# NOTE(lml): The second output of reshape2 Xshape, which is only used in reshape2_grad, is meanlingless in new autograd mechanism, thus we use a zero tensor instead.
290 291
@REGISTER_ORIG2PRIM('reshape2')
def reshape2_orig2prim(op, shape_t, shape_tl, x):
292 293 294 295 296 297
    assert (
        shape_t is None
    ), 'Can not lower reshape2 into prim ops with shapetensor.'
    assert (
        shape_tl is None
    ), 'Can not lower reshape2 into prim ops with shapetensorlist.'
298
    y, xshape = get_output_var_list(op)
299 300 301
    return reshape(x, shape=y.shape), fill_const(
        shape=xshape.shape, dtype=xshape.dtype, value=0.0
    )
302 303 304 305 306 307 308 309 310 311


@REGISTER_ORIG2PRIM('concat')
def concat_orig2prim(op, axis_t, xs):
    assert axis_t is None, 'Can not lower concat into prim ops with axistensor.'
    return concat(xs, axis=op.attr('axis'))


@REGISTER_ORIG2PRIM('slice')
def slice_orig2prim(op, ends_t, ends_tl, x, starts_t, starts_tl):
312 313 314
    assert (
        starts_t is None
    ), 'Can not lower concat into prim ops with startstensor.'
315
    assert ends_t is None, 'Can not lower concat into prim ops with endstensor.'
316 317 318 319 320 321
    assert (
        starts_tl is None
    ), 'Can not lower concat into prim ops with startstensorlist.'
    assert (
        ends_tl is None
    ), 'Can not lower concat into prim ops with endstensorlist.'
322 323 324 325 326 327 328 329 330 331
    starts = op.attr('starts')
    ends = op.attr('ends')
    strides = [1 for _ in starts]
    axis = op.attr('axes')
    y = slice_select(x, starts=starts, ends=ends, strides=strides, axis=axis)
    if op.attr('decrease_axis'):
        y = reshape(y, shape=get_output_var_list(op)[0].shape)
    return y


332 333 334 335
@REGISTER_ORIG2PRIM('sigmoid')
def sigmoid_orig2prim(op, x):
    return div(
        fill_const(value=1.0, shape=x.shape, dtype=x.dtype),
336 337
        (add(fill_const(value=1.0, shape=x.shape, dtype=x.dtype), exp(neg(x)))),
    )
338 339


340 341 342 343 344 345 346 347 348
@REGISTER_ORIG2PRIM('p_norm')
def p_norm_orig2prim(op, x):
    def num_el(shape):
        n = 1
        for s in shape:
            n = n * s
        return n

    assert op.attr(
349 350
        'asvector'
    ), 'Only support lower pnorm when asvector=True currently'
351 352 353 354
    if len(x.shape) > 1:
        x = reshape(x, shape=[num_el(x.shape)])

    if abs(op.attr('porder') - 2.0) < 1e-5:
355
        return sqrt(reduce_sum(mul(x, x), axis=[0]))
356
    elif abs(op.attr('porder') - 1.0) < 1e-5:
357
        return reduce_sum(primops.abs(x), axis=[0])
358 359 360 361
    else:
        raise RuntimeError('Only support lower l2/l1 norm currently')


362 363 364 365 366
@REGISTER_ORIG2PRIM('cast')
def cast_orig2prim(op, x):
    return primops.cast(x, paddle.dtype(op.attr('out_dtype')))


367 368 369 370 371 372 373 374 375 376 377 378 379
# TODO: support broadcast
@REGISTER_ORIG2PRIM('where')
def select_orig2prim(op, condition, x, y):
    return select(condition, x, y)


@REGISTER_ORIG2PRIM('equal')
def equal_orig2prim(op, x, y):
    if x.shape != y.shape:
        y = broadcast(y, shape=x.shape)
    return eq(x, y)


380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
@REGISTER_ORIG2PRIM('not_equal')
def ne_orig2prim(op, x, y):
    if x.shape != y.shape:
        y = broadcast(y, shape=x.shape)
    return ne(x, y)


@REGISTER_ORIG2PRIM('greater_than')
def gt_orig2prim(op, x, y):
    if x.shape != y.shape:
        y = broadcast(y, shape=x.shape)
    return gt(x, y)


@REGISTER_ORIG2PRIM('greater_equal')
def ge_orig2prim(op, x, y):
    if x.shape != y.shape:
        y = broadcast(y, shape=x.shape)
    return ge(x, y)


401
# paddle.pow API use "elementwise_pow" operator when y is a Tensor.
402 403 404 405 406 407 408 409
@REGISTER_ORIG2PRIM('elementwise_pow')
def elementwise_pow_orig2prim(op, x, y):
    if x.shape != y.shape:
        y = broadcast(y, shape=x.shape)
    z = primops.pow(x, y)
    return z


410 411 412 413 414 415 416 417 418
# paddle.pow API use "pow" operator when y is a scalar.
@REGISTER_ORIG2PRIM('pow')
def pow_orig2prim(op, x, y):
    # x is factorTensor defined in paddle phi op. Currently it is None.
    return primops.pow(y, fill_const(op.attr('factor'), y.shape, y.dtype))


@REGISTER_ORIG2PRIM('square')
def square_orig2prim(op, x):
419
    return primops.square(x)
420 421


422 423 424 425 426 427 428
@REGISTER_ORIG2PRIM('elementwise_max')
def elementwise_max_orig2prim(op, x, y):
    if x.shape != y.shape:
        y = broadcast(y, shape=x.shape)
    return primops.max(x, y)


429 430 431 432 433 434 435 436 437 438 439 440 441 442
@REGISTER_ORIG2PRIM('gelu')
def gelu_orig2prim(op, x):
    if op.attr('approximate'):
        cdf = mul(
            fill_const(0.5, x.shape, x.dtype),
            add(
                fill_const(1.0, x.shape, x.dtype),
                tanh(
                    mul(
                        fill_const(math.sqrt(2 / math.pi), x.shape, x.dtype),
                        add(
                            x,
                            mul(
                                fill_const(0.044715, x.shape, x.dtype),
443 444 445 446 447 448 449 450 451
                                primops.pow(
                                    x, fill_const(3.0, x.shape, x.dtype)
                                ),
                            ),
                        ),
                    )
                ),
            ),
        )
452 453 454 455
        return mul(x, cdf)
    else:
        return mul(
            mul(fill_const(0.5, x.shape, x.dtype), x),
456 457 458 459 460
            add(
                fill_const(1.0, x.shape, x.dtype),
                erf(mul(x, fill_const(1 / math.sqrt(2.0), x.shape, x.dtype))),
            ),
        )
461 462


463 464
@REGISTER_ORIG2PRIM('dropout')
def dropout_orig2prim(op, seed_t, x):
465 466 467
    assert (
        seed_t is None
    ), 'Can not lower dropout into prim ops with seedtensor.'
468 469
    mask = bernoulli(shape=x.shape, dtype=x.dtype, p=op.attr('dropout_prob'))
    if op.attr('dropout_implementation') == 'upscale_in_train':
470
        if not op.attr('is_test'):
471 472
            out = div(
                mul(x, mask),
473 474
                fill_const(1.0 - op.attr('dropout_prob'), x.shape, x.dtype),
            )
475 476 477 478
            return primops.cast(mask, dtype=paddle.uint8), out
        else:
            return primops.cast(mask, dtype=paddle.uint8), x
    elif op.attr('dropout_implementation') == 'downgrade_in_infer':
479
        if not op.attr('is_test'):
480 481 482
            return primops.cast(mask, dtype=paddle.uint8), mul(x, mask)
        else:
            return primops.cast(mask, dtype=paddle.uint8), mul(
483 484
                x, fill_const(1.0 - op.attr('dropout_prob'), x.shape, x.dtype)
            )
485 486 487 488 489 490
    else:
        raise RuntimeError(
            'Unsupported dropout_implementation, only support upscale_in_train and downgrade_in_infer'
        )


491 492 493 494 495 496 497 498 499 500 501 502 503 504
@REGISTER_ORIG2PRIM('uniform_random')
def uniform_random_orig2prim(op, shape_t, shape_tl):
    if shape_t or shape_tl:
        raise TypeError(
            'uniform_random_orig2prim currently not support ShapeTensor input or ShapeTensorList input.'
        )
    min_value = op.attr('min')
    max_value = op.attr('max')
    seed = op.attr('seed')
    dtype = paddle.dtype(op.attr('dtype'))
    shape = op.attr('shape')
    return uniform_random(dtype, min_value, max_value, seed, shape=shape)


505 506
@REGISTER_ORIG2PRIM('reduce_sum')
def reduce_sum_orig2prim(op, x):
507 508 509 510 511
    axes = (
        tuple(range(0, len(x.shape)))
        if op.attr('reduce_all')
        else op.attr('dim')
    )
512 513 514 515 516
    return reduce_sum(x, axis=axes, keepdim=op.attr('keep_dim'))


@REGISTER_ORIG2PRIM('reduce_mean')
def reduce_mean_orig2prim(op, x):
517 518 519 520 521
    axes = (
        tuple(range(0, len(x.shape)))
        if op.attr('reduce_all')
        else op.attr('dim')
    )
522 523 524 525
    return primops.mean(x, axes, op.attr('keep_dim'))


@REGISTER_ORIG2PRIM('batch_norm')
526 527 528
def batch_norm_orig2prim(
    op, bias, run_mean, momentum_tensor, scale, run_var, x
):
529 530 531 532 533 534
    momentum = op.attr('momentum')
    eps = op.attr('epsilon')
    is_test = op.attr('is_test')
    data_layout = op.attr('data_layout')
    use_global_stats = op.attr('use_global_stats')
    trainable_statistics = op.attr('trainable_statistics')
535 536 537
    reserve_space = (
        None if len(op.output_names) == 5 else get_output_var_list(op)[1]
    )
538

539 540 541
    feature_axis = (
        1 if data_layout in ('NC', 'NCL', 'NCHW', 'NCHWD') else len(x.shape) - 1
    )
542 543
    use_run_stat = (is_test and (not trainable_statistics)) or use_global_stats

544 545 546 547 548 549 550 551 552 553 554 555
    return primops.batch_norm(
        x,
        feature_axis,
        scale,
        bias,
        run_mean,
        run_var,
        eps=eps,
        momentum=momentum,
        use_run_stat=use_run_stat,
        reserve_space=reserve_space,
    )
556 557


558 559
@REGISTER_ORIG2PRIM('size')
def size_orig2prim(op, x):
zhouweiwei2014's avatar
zhouweiwei2014 已提交
560
    return fill_const(functools.reduce(operator.mul, x.shape), (), paddle.int64)
561 562


563
# Register prim2orig lower rules
564 565 566 567 568 569 570 571 572 573
@REGISTER_PRIM2ORIG('add_p')
def add_prim2orig(op, x, y):
    return paddle.add(x, y)


@REGISTER_PRIM2ORIG('sub_p')
def sub_prim2orig(op, x, y):
    return paddle.subtract(x, y)


J
Jiabin Yang 已提交
574 575 576 577 578
@REGISTER_PRIM2ORIG('rsqrt_p')
def rsqrt_prim2orig(op, x):
    return paddle.rsqrt(x)


579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
@REGISTER_PRIM2ORIG('mul_p')
def mul_prim2orig(op, x, y):
    return paddle.multiply(x, y)


@REGISTER_PRIM2ORIG('div_p')
def div_prim2orig(op, x, y):
    return paddle.divide(x, y)


@REGISTER_PRIM2ORIG('sqrt_p')
def sqrt_prim2orig(op, x):
    return paddle.sqrt(x)


@REGISTER_PRIM2ORIG('tanh_p')
def tanh_prim2orig(op, x):
    return paddle.tanh(x)


599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
@REGISTER_PRIM2ORIG('sin_p')
def sin_prim2orig(op, x):
    return paddle.sin(x)


@REGISTER_PRIM2ORIG('cos_p')
def cos_prim2orig(op, x):
    return paddle.cos(x)


@REGISTER_PRIM2ORIG('exp_p')
def exp_prim2orig(op, x):
    return paddle.exp(x)


614 615 616 617 618
@REGISTER_PRIM2ORIG('erf_p')
def erf_prim2orig(op, x):
    return paddle.erf(x)


619 620 621 622 623
@REGISTER_PRIM2ORIG('abs_p')
def abs_prim2orig(op, x):
    return paddle.abs(x)


624 625 626 627 628
@REGISTER_PRIM2ORIG('log_p')
def log_prim2orig(op, x):
    return paddle.log(x)


629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
@REGISTER_PRIM2ORIG('reshape_p')
def reshape_prim2orig(op, x):
    return paddle.reshape(x, shape=op.attr('shape'))


@REGISTER_PRIM2ORIG('broadcast_p')
def broadcast_prim2orig(op, x):
    return paddle.broadcast_to(x, shape=op.attr('shape'))


@REGISTER_PRIM2ORIG('transpose_p')
def transpose_prim2orig(op, x):
    return paddle.transpose(x, perm=op.attr('axis'))


@REGISTER_PRIM2ORIG('split_p')
def split_prim2orig(op, x):
    num_or_sections = op.attr('num_or_sections')
    if len(num_or_sections) == 1:
        num_or_sections = num_or_sections[0]
649 650 651
    return paddle.split(
        x, num_or_sections=num_or_sections, axis=op.attr('axis')
    )
652 653 654 655 656 657 658


@REGISTER_PRIM2ORIG('concat_p')
def concat_prim2orig(op, xs):
    return paddle.concat(xs, axis=op.attr('axis'))


659
@REGISTER_PRIM2ORIG('reduce_sum_p')
660 661 662 663 664 665 666 667 668 669 670
def reduce_prim2orig(op, x):
    return paddle.sum(x, axis=op.attr('axis'), keepdim=op.attr('keepdim'))


@REGISTER_PRIM2ORIG('matmul_p')
def matmul_prim2orig(op, x, y):
    return paddle.matmul(x, y)


@REGISTER_PRIM2ORIG('slice_select_p')
def slice_select_prim2orig(op, x):
671 672 673 674 675 676 677
    return paddle.strided_slice(
        x,
        axes=op.attr('axis'),
        starts=op.attr('starts'),
        ends=op.attr('ends'),
        strides=op.attr('strides'),
    )
678 679 680 681 682


@REGISTER_PRIM2ORIG('slice_assign_p')
def slice_assign_prim2orig(op, x, y):
    x_copy = paddle.assign(x)
683 684 685 686 687 688 689 690 691
    return set_value(
        x_copy,
        y,
        axis=op.attr('axis'),
        starts=op.attr('starts'),
        ends=op.attr('ends'),
        strides=op.attr('strides'),
        out=x_copy,
    )
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708


@REGISTER_PRIM2ORIG('gather_p')
def gather_prim2orig(op, index_t, x):
    return paddle.gather(x, index_t, axis=op.attr('axis'))


@REGISTER_PRIM2ORIG('scatter_add_p')
def scatter_add_prim2orig(op, index_t, x, y):
    assert op.attr('axis') == 0, 'Only support axis==0 currently'
    zeros = paddle.zeros_like(x=x, dtype=x.dtype)
    tmp = paddle.scatter(x=zeros, index=index_t, updates=y, overwrite=False)
    return paddle.add(x, tmp)


@REGISTER_PRIM2ORIG('fill_constant_p')
def fill_constant_prim2orig(op):
709 710 711 712 713
    return paddle.full(
        shape=op.attr('shape'),
        fill_value=op.attr('value'),
        dtype=INT_DTYPE_2_STRING[op.attr('dtype')],
    )
714 715


716 717
@REGISTER_PRIM2ORIG('bernoulli_p')
def bernoulli_prim2orig(op):
718 719 720 721 722
    t = paddle.full(
        shape=op.attr('shape'),
        fill_value=op.attr('p'),
        dtype=INT_DTYPE_2_STRING[op.attr('dtype')],
    )
723 724 725
    return paddle.bernoulli(t)


726 727
@REGISTER_PRIM2ORIG('uniform_random_p')
def uniform_random_prim2orig(op):
728 729 730 731 732 733 734
    return paddle.uniform(
        shape=op.attr('shape'),
        dtype=INT_DTYPE_2_STRING[op.attr('dtype')],
        min=op.attr('min'),
        max=op.attr('max'),
        seed=op.attr('seed'),
    )
735 736


737 738 739 740 741 742 743 744 745 746
@REGISTER_PRIM2ORIG('select_p')
def select_prim2orig(op, condition, x, y):
    return paddle.where(condition, x, y)


@REGISTER_PRIM2ORIG('eq_p')
def eq_prim2orig(op, x, y):
    return paddle.equal(x, y)


747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
@REGISTER_PRIM2ORIG('gt_p')
def gt_prim2orig(op, x, y):
    return paddle.greater_than(x, y)


@REGISTER_PRIM2ORIG('ge_p')
def ge_prim2orig(op, x, y):
    return paddle.greater_equal(x, y)


@REGISTER_PRIM2ORIG('ne_p')
def ne_prim2orig(op, x, y):
    return paddle.not_equal(x, y)


762 763 764 765 766
@REGISTER_PRIM2ORIG('pow_p')
def pow_prim2orig(op, x, y):
    return paddle.pow(x, y)


767 768 769 770 771
@REGISTER_PRIM2ORIG('max_p')
def max_prim2orig(op, x, y):
    return paddle.maximum(x, y)


772 773 774 775 776
@REGISTER_PRIM2ORIG('cast_p')
def cast_prim2orig(op, x):
    return paddle.cast(x, paddle.dtype(op.attr('dtype')))


777
# Register linearize rules
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
@REGISTER_JVP('add_p')
def add_jvp(op, x_dot, y_dot):
    if x_dot is None:
        return y_dot
    elif y_dot is None:
        return x_dot
    else:
        return linear_jvp(op, x_dot, y_dot)


@REGISTER_JVP('sub_p')
def sub_jvp(op, x_dot, y_dot):
    if x_dot is None:
        return neg(y_dot)
    elif y_dot is None:
        return x_dot
    else:
        return linear_jvp(op, x_dot, y_dot)


@REGISTER_JVP('mul_p')
def mul_jvp(op, x_dot, y_dot):
    if x_dot is None and y_dot is None:
        return None
    x, y = op_position_inputs(op)
    if x_dot is None:
        return mul(x, y_dot)
    elif y_dot is None:
        return mul(x_dot, y)
    else:
        t1, t2 = mul(x_dot, y), mul(x, y_dot)
        z_dot = add(t1, t2)
        return z_dot


@REGISTER_JVP('div_p')
def div_jvp(op, x_dot, y_dot):
    if x_dot is None and y_dot is None:
        return None
    x, y = op_position_inputs(op)
    if y_dot is None:
        return div(x_dot, y)
    elif x_dot is None:
        return neg(div(mul(x, y_dot), mul(y, y)))
    else:
        t1 = div(x_dot, y)
        t2 = div(mul(x, y_dot), mul(y, y))
        return sub(t1, t2)


@REGISTER_JVP('sqrt_p')
def sqrt_jvp(op, x_dot):
    if x_dot is None:
        return None
    y = op_position_output(op)
    c2 = fill_const(value=2.0, shape=y.shape, dtype=y.dtype)
    y_dot = div(x_dot, mul(c2, y))
    return y_dot


@REGISTER_JVP('tanh_p')
def tanh_jvp(op, x_dot):
    if x_dot is None:
        return None
    y = op_position_output(op)
    c1 = fill_const(value=1.0, shape=y.shape, dtype=y.dtype)
    y_dot = mul(x_dot, sub(c1, mul(y, y)))
    return y_dot


848 849 850 851
@REGISTER_JVP('sin_p')
def sin_jvp(op, x_dot):
    if x_dot is None:
        return None
852
    (x,) = op_position_inputs(op)
853 854 855 856 857 858 859
    return mul(x_dot, cos(x))


@REGISTER_JVP('cos_p')
def cos_jvp(op, x_dot):
    if x_dot is None:
        return None
860
    (x,) = op_position_inputs(op)
861 862 863 864 865 866 867 868 869 870 871
    return mul(x_dot, neg(sin(x)))


@REGISTER_JVP('exp_p')
def exp_jvp(op, x_dot):
    if x_dot is None:
        return None
    y = op_position_output(op)
    return mul(x_dot, y)


872 873 874 875
@REGISTER_JVP('erf_p')
def erf_jvp(op, x_dot):
    if x_dot is None:
        return None
876
    (x,) = op_position_inputs(op)
877
    return mul(
878 879 880
        fill_const(2.0 / math.sqrt(math.pi), x.shape, x.dtype),
        mul(x_dot, exp(neg(primops.pow(x, fill_const(2.0, x.shape, x.dtype))))),
    )
881 882


883 884 885 886
@REGISTER_JVP('abs_p')
def abs_jvp(op, x_dot):
    if x_dot is None:
        return None
887 888
    (x,) = op_position_inputs(op)
    return select(ge(x, fill_const(0.0, x.shape, x.dtype)), x_dot, neg(x_dot))
889 890


891 892 893 894
@REGISTER_JVP('log_p')
def log_jvp(op, x_dot):
    if x_dot is None:
        return None
895
    (x,) = op_position_inputs(op)
896 897 898
    return div(x_dot, x)


899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
@REGISTER_JVP('reshape_p')
def reshape_jvp(op, x_dot):
    if x_dot is None:
        return None
    shape = op.attr('shape')
    return linear_jvp(op, x_dot, shape=shape)


@REGISTER_JVP('broadcast_p')
def broadcast_jvp(op, x_dot):
    if x_dot is None:
        return None
    shape = op.attr('shape')
    return linear_jvp(op, x_dot, shape=shape)


@REGISTER_JVP('transpose_p')
def transpose_jvp(op, x_dot):
    if x_dot is None:
        return None
    axis = op.attr('axis')
    return linear_jvp(op, x_dot, axis=axis)


@REGISTER_JVP('split_p')
def split_jvp(op, x_dot):
    if x_dot is None:
        return None
    num_or_sections = op.attr('num_or_sections')
    axis = op.attr('axis')
    return linear_jvp(op, x_dot, num_or_sections=num_or_sections, axis=axis)


@REGISTER_JVP('concat_p')
def concat_jvp(op, xs_dot):
    if xs_dot is None:
        return None
    axis = op.attr('axis')
    return linear_jvp(op, xs_dot, axis=axis)


940 941
@REGISTER_JVP('reduce_sum_p')
def reduce_sum_jvp(op, x_dot):
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
    if x_dot is None:
        return None
    axis = op.attr('axis')
    keepdim = op.attr('keepdim')
    return linear_jvp(op, x_dot, axis=axis, keepdim=keepdim)


@REGISTER_JVP('matmul_p')
def matmul_jvp(op, x_dot, y_dot):
    if x_dot is None and y_dot is None:
        return None
    x, y = op_position_inputs(op)
    if x_dot is None:
        return matmul(x, y_dot)
    elif y_dot is None:
        return matmul(x_dot, y)
    else:
        t1 = matmul(x, y_dot)
        t2 = matmul(x_dot, y)
        return add(t1, t2)


@REGISTER_JVP('slice_select_p')
def slice_select_jvp(op, x_dot):
    if x_dot is None:
        return x_dot
    axis = op.attr('axis')
    starts = op.attr('starts')
    ends = op.attr('ends')
    strides = op.attr('strides')
972 973 974
    return linear_jvp(
        op, x_dot, axis=axis, starts=starts, ends=ends, strides=strides
    )
975 976 977 978


@REGISTER_JVP('slice_assign_p')
def slice_assign_jvp(op, x_dot, y_dot):
C
Charles-hit 已提交
979 980 981 982
    x, y = op_position_inputs(op)
    assert (
        x_dot is not None or y_dot is not None
    ), "x_dot and y_dot can't be None at the same time. "
983 984 985 986
    axis = op.attr('axis')
    starts = op.attr('starts')
    ends = op.attr('ends')
    strides = op.attr('strides')
C
Charles-hit 已提交
987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
    if x_dot is None:
        return linear_jvp(
            op,
            fill_const(value=0.0, shape=x.shape, dtype=x.dtype),
            y_dot,
            axis=axis,
            starts=starts,
            ends=ends,
            strides=strides,
        )
    elif y_dot is None:
        return linear_jvp(
            op,
            x_dot,
            fill_const(value=0.0, shape=y.shape, dtype=y.dtype),
            axis=axis,
            starts=starts,
            ends=ends,
            strides=strides,
        )
    return add(
        linear_jvp(
            op,
            fill_const(value=0.0, shape=x.shape, dtype=x.dtype),
            y_dot,
            axis=axis,
            starts=starts,
            ends=ends,
            strides=strides,
        ),
        linear_jvp(
            op,
            x_dot,
            fill_const(value=0.0, shape=y.shape, dtype=y.dtype),
            axis=axis,
            starts=starts,
            ends=ends,
            strides=strides,
        ),
1026
    )
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046


@REGISTER_JVP('gather_p')
def gather_jvp(op, x_dot, indextensor):
    if x_dot is None:
        return None
    _, indextensor = op_position_inputs(op)
    axis = op.attr('axis')
    return linear_jvp(op, x_dot, indextensor, axis=axis)


@REGISTER_JVP('scatter_add_p')
def scatter_add_jvp(op, x_dot, y_dot):
    if x_dot is None:
        return None
    _, _, indextensor = op_position_inputs(op)
    axis = op.attr('axis')
    return linear_jvp(op, x_dot, y_dot, indextensor, axis=axis)


1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
@REGISTER_JVP('select_p')
def select_jvp(op, cond_dot, x_dot, y_dot):
    if x_dot is None and y_dot is None:
        return None

    cond, x, y = op_position_inputs(op)
    if x_dot is None:
        x_dot = fill_const(value=0.0, shape=y.shape, dtype=y.dtype)
    if y_dot is None:
        y_dot = fill_const(value=0.0, shape=y.shape, dtype=y.dtype)
    return select(cond, x_dot, y_dot)


@REGISTER_JVP('eq_p')
def eq_jvp(op, x_dot, y_dot):
    if x_dot is None and y_dot is None:
        return None
    x, _ = op_position_inputs(op)
1065
    z_dot = fill_const(value=0.0, shape=x.shape, dtype=x.dtype)
1066 1067 1068
    return z_dot


1069 1070 1071 1072 1073
@REGISTER_JVP('gt_p')
def gt_jvp(op, x_dot, y_dot):
    if x_dot is None and y_dot is None:
        return None
    x, _ = op_position_inputs(op)
1074
    z_dot = fill_const(value=0.0, shape=x.shape, dtype=x.dtype)
1075 1076 1077 1078 1079 1080 1081 1082
    return z_dot


@REGISTER_JVP('ge_p')
def ge_jvp(op, x_dot, y_dot):
    if x_dot is None and y_dot is None:
        return None
    x, _ = op_position_inputs(op)
1083
    z_dot = fill_const(value=0.0, shape=x.shape, dtype=x.dtype)
1084 1085 1086 1087 1088 1089 1090 1091
    return z_dot


@REGISTER_JVP('ne_p')
def ne_jvp(op, x_dot, y_dot):
    if x_dot is None and y_dot is None:
        return None
    x, _ = op_position_inputs(op)
1092
    z_dot = fill_const(value=0.0, shape=x.shape, dtype=x.dtype)
1093 1094 1095
    return z_dot


1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
@REGISTER_JVP('pow_p')
def pow_jvp(op, x_dot, y_dot):
    def _compute_t1(x, y):
        zero_y = fill_const(value=0.0, shape=y.shape, dtype=y.dtype)
        one_y = fill_const(value=1.0, shape=y.shape, dtype=y.dtype)

        cond = eq(y, zero_y)
        new_y = select(cond, one_y, sub(y, one_y))
        t1 = mul(x_dot, mul(y, primops.pow(x, new_y)))
        return t1

    if x_dot is None and y_dot is None:
        return None
    x, y = op_position_inputs(op)
    z = op_position_output(op)

    if y_dot is None:
        return _compute_t1(x, y)
    elif x_dot is None:
        return mul(y_dot, mul(log(x), z))
    else:
        t1, t2 = _compute_t1(x, y), mul(y_dot, mul(log(x), z))
        z_dot = add(t1, t2)
        return z_dot


1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
@REGISTER_JVP('max_p')
def max_jvp(op, x_dot, y_dot):
    if x_dot is None and y_dot is None:
        return None

    x, y = op_position_inputs(op)
    z = op_position_output(op)
    z_zeros = fill_const(value=0.0, shape=z.shape, dtype=z.dtype)

    # To make the grad of max_p consistent with paddle.maximum when x==y,
    # we just let z_dot = y_dot when compute z_dot to y and x==y,
    # instead of using balance_eq like Jax.
    if y_dot is None:
        return select(eq(y, z), z_zeros, x_dot)
    elif x_dot is None:
        return select(eq(y, z), y_dot, z_zeros)
    else:
        return select(eq(y, z), y_dot, x_dot)


1142 1143 1144 1145 1146 1147
@REGISTER_JVP('cast_p')
def cast_jvp(op, x_dot):
    y = op_position_output(op)
    return primops.cast(x_dot, y.dtype)


J
Jiabin Yang 已提交
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
@REGISTER_JVP('rsqrt_p')
def rsqrt_jvp(op, x_dot):
    if x_dot is None:
        return None
    y = op_position_output(op)
    x = op_position_inputs(op)
    c2 = fill_const(value=-2.0, shape=y.shape, dtype=y.dtype)
    y_dot = mul(x_dot, div(div(y, x), c2))
    return y_dot


1159
# Register transpose rules
1160 1161 1162 1163 1164 1165 1166


@REGISTER_TRANSPOSE('add_p')
def add_transpose(op, check_dot, z_bar):
    x, y = op_position_inputs(op)
    assert check_dot(x) or check_dot(y), (
        f'(check_dot(x) or check_dot(y)) must be True, '
1167 1168
        f'but check_dot(x)={check_dot(x)} and check_dot(y)={check_dot(y)}.'
    )
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
    x_bar = z_bar if check_dot(x) else None
    y_bar = z_bar if check_dot(y) else None
    return x_bar, y_bar


@REGISTER_TRANSPOSE('sub_p')
def sub_transpose(op, check_dot, z_bar):
    x, y = op_position_inputs(op)
    assert check_dot(x) or check_dot(y), (
        f'(check_dot(x) or check_dot(y)) must be True, '
1179 1180
        f'but check_dot(x)={check_dot(x)} and check_dot(y)={check_dot(y)}.'
    )
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
    x_bar = z_bar if check_dot(x) else None
    y_bar = neg(z_bar) if check_dot(y) else None
    return x_bar, y_bar


@REGISTER_TRANSPOSE('mul_p')
def mul_transpose(op, check_dot, z_bar):
    x, y = op_position_inputs(op)
    assert check_dot(x) ^ check_dot(y), (
        f'(check_dot(x) ^ check_dot(y)) must be True, '
1191 1192
        f'but check_dot(x)={check_dot(x)} and check_dot(y)={check_dot(y)}.'
    )
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
    if check_dot(x):
        return mul(z_bar, y), None
    else:
        return None, mul(x, z_bar)


@REGISTER_TRANSPOSE('div_p')
def div_transpose(op, check_dot, z_bar):
    x, y = op_position_inputs(op)
    assert not check_dot(y), 'check_dot(y) must be False'
    x_bar = div(z_bar, y) if check_dot(x) else None
    return x_bar, None


@REGISTER_TRANSPOSE('reshape_p')
def reshape_transpose(op, check_dot, y_bar):
1209
    (x,) = op_position_inputs(op)
1210 1211 1212 1213 1214 1215
    assert check_dot(x), 'check_dot(x) must be True'
    return reshape(y_bar, shape=x.shape)


@REGISTER_TRANSPOSE('broadcast_p')
def broadcast_transpose(op, check_dot, y_bar):
1216
    (x,) = op_position_inputs(op)
1217 1218 1219 1220 1221 1222
    assert check_dot(x), 'check_dot(x) must be True'
    bat = len(y_bar.shape) - len(x.shape)
    axis = list(range(bat))
    keepdim = [(bat + i) for i, s in enumerate(x.shape) if s == 1]
    axis += keepdim
    # TODO: Change it. keepdim boolean
1223
    out = reduce_sum(y_bar, axis=axis, keepdim=False)
1224 1225 1226 1227 1228
    return reshape(out, x.shape)


@REGISTER_TRANSPOSE('transpose_p')
def transpose_transpose(op, check_dot, y_bar):
1229
    (x,) = op_position_inputs(op)
1230 1231 1232 1233 1234 1235 1236 1237 1238
    assert check_dot(x), 'check_dot(x) must be True'
    axis = op.attr('axis')
    reordered = sorted((k, i) for i, k in enumerate(axis))
    axis = [i for k, i in reordered]
    return transpose(y_bar, axis=axis)


@REGISTER_TRANSPOSE('split_p')
def split_transpose(op, check_dot, ys_bar):
1239
    (x,) = op_position_inputs(op)
1240 1241 1242 1243 1244 1245
    assert check_dot(x), 'check_dot(x) must be True'
    return concat(ys_bar, axis=op.attr('axis'))


@REGISTER_TRANSPOSE('concat_p')
def concat_transpose(op, check_dot, y_bar):
1246
    (xs,) = op_position_inputs(op)
1247 1248
    if not isinstance(xs, typing.Sequence):
        xs = [xs]
1249 1250 1251 1252
    for x in xs:
        assert check_dot(x), 'check_dot(x) must be True'
    axis = op.attr('axis')
    sections = [x.shape[axis] for x in xs]
1253 1254
    if len(sections) == 1:
        return y_bar
1255 1256 1257
    return split(y_bar, num_or_sections=sections, axis=axis)


1258 1259
@REGISTER_TRANSPOSE('reduce_sum_p')
def reduce_sum_transpose(op, check_dot, y_bar):
1260
    (x,) = op_position_inputs(op)
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
    assert check_dot(x), 'check_dot(x) must be True'
    axes = op.attr('axis')
    shape = tuple(1 if i in axes else size for i, size in enumerate(x.shape))
    t = reshape(y_bar, shape=shape)
    return broadcast(t, shape=x.shape)


@REGISTER_TRANSPOSE('matmul_p')
def matmul_transpose(op, check_dot, z_bar):
    x, y = op_position_inputs(op)
    assert check_dot(x) ^ check_dot(y), (
        f'(check_dot(x) ^ check_dot(y)) must be True, '
1273 1274
        f'but check_dot(x)={check_dot(x)} and check_dot(y)={check_dot(y)}.'
    )
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
    # TODO: replace it. this is hacky
    axis = [1, 0] if len(x.shape) == 2 else [0, 2, 1]
    if check_dot(x):
        return matmul(z_bar, transpose(y, axis=axis)), None
    else:
        return None, matmul(transpose(x, axis=axis), z_bar)


@REGISTER_TRANSPOSE('slice_select_p')
def slice_select_transpose(op, check_dot, y_bar):
1285
    (x,) = op_position_inputs(op)
1286 1287 1288 1289 1290 1291
    assert check_dot(x), 'check_dot(x) must be True'
    zeros = fill_const(value=0.0, shape=x.shape, dtype=x.dtype)
    axis = op.attr('axis')
    starts = op.attr('starts')
    ends = op.attr('ends')
    strides = op.attr('strides')
1292 1293 1294
    return slice_assign(
        zeros, y_bar, axis=axis, starts=starts, ends=ends, strides=strides
    )
1295 1296 1297 1298 1299


@REGISTER_TRANSPOSE('slice_assign_p')
def slice_assign_transpose(op, check_dot, z_bar):
    x, y = op_position_inputs(op)
C
Charles-hit 已提交
1300 1301
    assert check_dot(x) ^ check_dot(y), (
        f'(check_dot(x) ^ check_dot(y)) must be True, '
1302 1303
        f'but check_dot(x)={check_dot(x)} and check_dot(y)={check_dot(y)}.'
    )
1304 1305 1306 1307 1308
    zeros = fill_const(value=0.0, shape=y.shape, dtype=y.dtype)
    axis = op.attr('axis')
    starts = op.attr('starts')
    ends = op.attr('ends')
    strides = op.attr('strides')
C
Charles-hit 已提交
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
    if check_dot(x):
        return (
            slice_assign(
                z_bar,
                zeros,
                axis=axis,
                starts=starts,
                ends=ends,
                strides=strides,
            ),
            None,
        )
    return None, slice_select(
1322 1323
        z_bar, axis=axis, starts=starts, ends=ends, strides=strides
    )
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341


@REGISTER_TRANSPOSE('gather_p')
def gather_transpose(op, check_dot, y_bar):
    x, indextensor = op_position_inputs(op)
    assert check_dot(x), 'check_dot(x) must be True'
    axis = op.attr('axis')
    zeros = fill_const(0.0, x.shape, x.dtype)
    x_bar = scatter_add(zeros, y_bar, indextensor, axis=axis)
    indextensor_bar = None
    return x_bar, indextensor_bar


@REGISTER_TRANSPOSE('scatter_add_p')
def scatter_add_transpose(op, check_dot, z_bar):
    x, y, indextensor = op_position_inputs(op)
    assert check_dot(x) and check_dot(y), (
        f'(check_dot(x) and check_dot(y)) must be True, '
1342 1343
        f'but check_dot(x)={check_dot(x)} and check_dot(y)={check_dot(y)}.'
    )
1344 1345 1346 1347 1348 1349
    axis = op.attr('axis')
    zeros = fill_const(value=0.0, shape=y.shape, dtype=y.dtype)
    x_bar = scatter_add(z_bar, zeros, indextensor, axis=axis)
    y_bar = gather(z_bar, indextensor, axis=axis)
    indextensor_bar = None
    return x_bar, y_bar, indextensor_bar
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362


@REGISTER_TRANSPOSE('select_p')
def select_transpose(op, check_dot, z_bar):
    cond, x, y = op_position_inputs(op)
    assert check_dot(cond) or check_dot(x) or check_dot(y), (
        f'check_dot(cond) ^ (check_dot(x) ^ check_dot(y)) must be True, '
        f'but check_dot(cond)={check_dot(cond)}, check_dot(x)={check_dot(x)} and check_dot(y)={check_dot(y)}.'
    )

    zeros_x = fill_const(value=0.0, shape=x.shape, dtype=x.dtype)
    zeros_y = fill_const(value=0.0, shape=y.shape, dtype=y.dtype)

1363 1364 1365 1366 1367
    cond_bar = (
        fill_const(value=0.0, shape=y.shape, dtype=cond.dtype)
        if check_dot(cond)
        else None
    )
1368 1369 1370 1371
    x_bar = select(cond, z_bar, zeros_x) if check_dot(x) else None
    y_bar = select(cond, zeros_y, z_bar) if check_dot(y) else None

    return cond_bar, x_bar, y_bar
1372 1373 1374 1375


@REGISTER_TRANSPOSE('cast_p')
def cast_transpose(op, check_dot, y_bar):
1376
    (x,) = op_position_inputs(op)
1377
    return primops.cast(y_bar, x.dtype)