variable_index.py 29.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#   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.

import sys
import numpy as np
from . import unique_name
from . import core
W
WeiXin 已提交
19
import paddle
20
import warnings
21 22 23 24

MAX_INTEGER = 2**31 - 1


W
WeiXin 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
def is_list_tuple(index, contain_type):
    def _is_list_tuple(item):
        if not (isinstance(item, (list, tuple)) or type(item) == contain_type):
            return False
        if isinstance(item, (tuple, list)):
            for s in item:
                if not _is_list_tuple(s):
                    return False
        return True

    if not isinstance(index, (tuple, list)):
        return False
    for s in index:
        if not _is_list_tuple(s):
            return False
    return True


def is_one_dim_list(index, contain_type):
    if isinstance(index, list):
        for i in index:
            if not isinstance(i, contain_type):
                return False
    else:
        return False
    return True


def get_list_index_shape(var_dims, index_dims):
    var_dims_size = len(var_dims)
    index_dims_size = len(index_dims)

    out_dims_size = var_dims_size - index_dims[0] + index_dims_size - 1

    out_dims_shape = [1] * out_dims_size

61
    out_dims_shape[: index_dims_size - 1] = index_dims[1:]
W
WeiXin 已提交
62

63
    out_dims_shape[index_dims_size - 1 :] = var_dims[index_dims[0] :]
W
WeiXin 已提交
64 65 66 67 68 69 70
    return out_dims_shape


class SliceInfo:
    def __init__(self):
        self.pre_shape = None
        self.indexes = []
W
WeiXin 已提交
71
        self.dtype = None
W
WeiXin 已提交
72 73

    def update(self, index):
74
        if is_list_tuple(index, int) or isinstance(
75 76
            index, (paddle.fluid.Variable, np.ndarray)
        ):
W
WeiXin 已提交
77 78 79 80
            # convert index to Tensor
            if not isinstance(index, paddle.fluid.Variable):
                index = paddle.assign(index)

W
WeiXin 已提交
81 82 83 84 85
            if self.dtype is None:
                self.dtype = index.dtype
            else:
                if index.dtype != self.dtype:
                    raise IndexError(
86 87 88 89
                        "Data type of Tensor/List index should be same. The current data type is {}, but the previous data type is {}.".format(
                            index.dtype, self.dtype
                        )
                    )
W
WeiXin 已提交
90

W
WeiXin 已提交
91 92 93 94 95 96
            self.indexes.append(index)

            if self.pre_shape is None:
                self.pre_shape = index.shape
            else:
                if self.pre_shape != index.shape:
97
                    # broadcast
98 99 100
                    cur_shape = paddle.broadcast_shape(
                        self.pre_shape, index.shape
                    )
W
WeiXin 已提交
101
                    for i in range(len(self.indexes)):
102
                        self.indexes[i] = paddle.broadcast_to(
103 104
                            self.indexes[i], cur_shape
                        )
W
WeiXin 已提交
105 106 107
                self.pre_shape = self.indexes[-1].shape
        else:
            raise ValueError(
108 109 110 111
                "Index should be list/tuple of int or Tensor, but received {}.".format(
                    index
                )
            )
W
WeiXin 已提交
112 113 114 115 116 117 118 119 120

    def shape_stride(self, shape):
        s = [1] * len(shape)
        for i in range(len(shape) - 2, -1, -1):
            s[i] = shape[i + 1] * s[i + 1]

        return s

    def numel(self, shape):
121
        return reduce(lambda x, y: x * y, shape, 1)
W
WeiXin 已提交
122 123 124 125 126 127

    def get_offset_stride(self, tensor_shape):
        for index in self.indexes:
            if not isinstance(index, paddle.fluid.Variable):
                raise ValueError(
                    "only support list/tensor index, but received {}.".format(
128 129 130
                        type(index)
                    )
                )
W
WeiXin 已提交
131 132 133

        if len(self.indexes) <= len(tensor_shape) or len(self.indexes) == 1:
            shape = paddle.stack(self.indexes)
134 135 136
            axes = list(range(1, len(self.pre_shape) + 1)) + [
                0,
            ]
W
WeiXin 已提交
137 138 139

        else:
            raise ValueError(
140 141 142 143
                "too many indices for tensor: tensor is {}-dimensional, but {} were indexed".format(
                    len(tensor_shape), self.pre_shape[0]
                )
            )
W
WeiXin 已提交
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158

        shape_transpose = paddle.transpose(shape, axes)
        return shape_transpose

    def get_item(self, tensor):
        shape_transpose = self.get_offset_stride(tensor.shape)
        index = paddle.assign(shape_transpose)
        return paddle.gather_nd(tensor, index)

    def set_item(self, tensor_origin, value):
        if not isinstance(value, paddle.fluid.Variable):
            value = paddle.assign(value)
        tensor_type = None

        if tensor_origin.dtype in [
159 160
            core.VarDesc.VarType.FP32,
            core.VarDesc.VarType.FP64,
W
WeiXin 已提交
161 162 163 164 165 166 167 168 169 170 171 172
        ]:
            tensor = tensor_origin
        else:
            tensor_type = tensor_origin.dtype
            tensor = tensor_origin.astype(core.VarDesc.VarType.FP32)

        if value.dtype != tensor.dtype:
            value = value.astype(tensor.dtype)

        shape_transpose = self.get_offset_stride(tensor_origin.shape)
        index = paddle.assign(shape_transpose)

173 174 175 176 177 178 179
        gather_tensor_shape = get_list_index_shape(
            tensor.shape,
            [
                len(self.indexes),
            ]
            + list(self.indexes[-1].shape),
        )
W
WeiXin 已提交
180

181 182 183
        value_dims_bd = [
            1,
        ] * len(gather_tensor_shape)
184
        value_dims_bd[-len(value.shape) :] = list(value.shape)
W
WeiXin 已提交
185 186

        for i in range(len(gather_tensor_shape)):
187
            if not (
188 189
                len(value_dims_bd) == 0
                or value_dims_bd[i] == gather_tensor_shape[i]
190 191 192 193 194 195 196
                or value_dims_bd[i] == 1
            ):
                raise ValueError(
                    "{} can not broadcast into {}".format(
                        value.shape, gather_tensor_shape
                    )
                )
W
WeiXin 已提交
197 198 199

        value_broadcast = paddle.broadcast_to(value, gather_tensor_shape)

200
        value_1d = value_broadcast.reshape(
201 202
            [-1] + gather_tensor_shape[len(index.shape) - 1 :]
        )
W
WeiXin 已提交
203 204 205 206

        index_1d = index.reshape([-1, index.shape[-1]])

        tensor_stride = paddle.assign(
207 208
            self.shape_stride(tensor.shape[: index.shape[-1]])
        )
W
WeiXin 已提交
209 210 211 212 213
        inds = []
        for i in range(index_1d.shape[0]):
            temp = (index_1d[i] * tensor_stride).sum()
            inds.append(temp)
        index_1d = paddle.stack(inds).reshape([-1])
214
        t_reshape = tensor.reshape([-1] + list(tensor.shape[index.shape[-1] :]))
W
WeiXin 已提交
215 216 217
        out = paddle.scatter(t_reshape, index_1d, value_1d)
        if tensor_type is not None:
            out = out.astype(tensor_type)
218 219 220
        tensor_origin = _setitem_impl_(
            tensor_origin, ..., out.reshape(tensor_origin.shape)
        )
W
WeiXin 已提交
221 222 223 224

        return tensor_origin


225 226
def replace_ellipsis(var, item):
    from .framework import Variable
227

228 229 230 231 232 233 234 235 236 237
    # Use slice(None) to replace Ellipsis.
    # For var, var.shape = [3,4,5,6]
    #
    #   var[..., 1:2] -> var[:, :, :, 1:2]
    #   var[0, ...] -> var[0]
    #   var[0, ..., 1:2] -> var[0, :, :, 1:2]

    item = list(item)

    # Remove Variable to skip bug when counting Ellipsis
W
WeiXin 已提交
238
    item_remove_var = [
239 240
        ele
        for ele in item
241
        if not isinstance(ele, (Variable, np.ndarray)) and ele is not None
W
WeiXin 已提交
242
    ]
243 244 245 246 247 248 249 250 251 252 253
    ell_count = item_remove_var.count(Ellipsis)
    if ell_count == 0:
        return item
    elif ell_count > 1:
        raise IndexError("An index can only have a single ellipsis ('...')")

    ell_idx = item.index(Ellipsis)

    if ell_idx == len(item) - 1:
        return item[:-1]
    else:
254 255 256
        item[ell_idx : ell_idx + 1] = [slice(None)] * (
            len(var.shape) - len(item) + item.count(None) + 1
        )
257 258 259 260

    return item


W
WeiXin 已提交
261 262 263 264 265 266 267 268 269 270
def replace_ndarray(item):
    new_item = []
    for slice_item in item:
        if isinstance(slice_item, np.ndarray):
            new_item.append(paddle.assign(slice_item))
        else:
            new_item.append(slice_item)
    return new_item


271 272 273 274 275 276 277 278 279 280 281
def replace_none(item):
    new_item = []
    none_axes = []
    for i, slice_item in enumerate(item):
        if slice_item is None:
            none_axes.append(i)
        else:
            new_item.append(slice_item)
    return new_item, none_axes


282 283
def is_integer_or_scalar_tensor(ele):
    from .framework import Variable
284

285 286 287
    if isinstance(ele, int):
        return True
    elif isinstance(ele, Variable):
J
JYChen 已提交
288 289 290 291 292 293 294 295 296
        # NOTE(zoooo0820): For compatibility, if FLAGS_set_to_1d is set to True,
        # 1-D tensor is still treated as a scalar, which means basic indexing.
        # This will be removed in future.
        if paddle.get_flags('FLAGS_set_to_1d')['FLAGS_set_to_1d']:
            if len(ele.shape) == 1 and ele.shape[0] == 1:
                warnings.warn(
                    "1-D Tensor will be treat as advanced indexing in future version. Currently, 1-D Tensor means a scalar, not vector, and please modify it to 0-D Tensor. If advanced indexing is needed, please use `export FLAGS_set_to_1d=False` to set the flag."
                )
                return True
297
        if len(ele.shape) == 0:
298 299 300 301
            return True
    return False


302 303
def is_bool_tensor(ele):
    from .framework import Variable
304

305 306 307 308 309
    if isinstance(ele, Variable) and ele.dtype == paddle.bool:
        return True
    return False


310 311 312
def deal_attrs(attrs, attr, attr_name, tensor_attr_name, inputs, infer_flags):
    from .framework import Variable

313 314
    if paddle.utils._contain_var(attr):
        inputs[tensor_attr_name] = paddle.utils._convert_to_tensor_list(
315 316
            attr, dtype="int64"
        )
317 318 319 320 321 322 323 324 325 326
        for i, dim in enumerate(attr):
            if isinstance(dim, Variable):
                attrs[attr_name].append(-1)
                infer_flags[i] = -1
            else:
                attrs[attr_name].append(dim)
    else:
        attrs[attr_name] = attr


327
# the item is a tensor of bool
328 329
def get_value_for_bool_tensor(var, item):
    if len(item.shape) > len(var.shape):
330 331 332 333 334
        raise IndexError(
            "The dims of bool index doesn't match indexed array, "
            "the dims of bool index except to be equal or less "
            "than {}, but received {}.".format(len(var.shape), len(item.shape))
        )
335 336 337 338 339
    i = 0
    item_shape = item.shape
    while i < len(item.shape):
        dim_len = item_shape[i]
        if dim_len != -1 and var.shape[i] != -1 and dim_len != var.shape[i]:
340
            raise IndexError(
341 342 343 344 345
                "The dimension of bool index doesn't match indexed array along "
                "dimension {}, the target dimension is {}, but received {}.".format(
                    i, var.shape[i], dim_len
                )
            )
346 347
        i += 1
    empty_shape = [0] + list(var.shape[i:])
348 349 350 351

    def idx_not_empty(var, item):
        from ..tensor import gather_nd

352
        bool_2_idx = paddle.nonzero(item == True)
353 354
        return gather_nd(var, bool_2_idx)

355
    from paddle.static.nn import cond
356 357

    return cond(
358 359 360
        item.any(),
        lambda: idx_not_empty(var, item),
        lambda: paddle.empty(empty_shape, var.dtype),
361
    )
362 363


364 365 366 367 368 369 370 371 372 373
def _getitem_impl_(var, item):
    """
    Slice the variable.

    Args:
        item(int/slice/tuple) : the index.

    Returns:
        Sliced variable
    """
374
    from .framework import default_main_program, Variable
W
wanghuancoder 已提交
375 376 377 378
    from .dygraph.base import in_declarative_mode

    if in_declarative_mode() and hasattr(var, "is_view_var"):
        var.is_view_var = True
379

W
WeiXin 已提交
380 381 382
    if isinstance(item, list):
        if not is_one_dim_list(item, int):
            item = tuple(item)
383 384

    if not isinstance(item, tuple):
385
        item = (item,)
386 387 388 389 390 391

    decrease_axes = []
    axes = []
    starts = []
    ends = []
    steps = []
392
    reverse_axes = []
393 394

    use_strided_slice = False
W
WeiXin 已提交
395
    item = replace_ndarray(item)
396
    item = replace_ellipsis(var, item)
397
    item, none_axes = replace_none(item)
W
WeiXin 已提交
398
    slice_info = SliceInfo()
399 400 401 402
    is_tensor_array = (
        hasattr(var, "desc")
        and var.desc.type() == core.VarDesc.VarType.LOD_TENSOR_ARRAY
    )
403 404

    for dim, slice_item in enumerate(item):
405 406 407 408
        if is_integer_or_scalar_tensor(slice_item) and not is_bool_tensor(
            slice_item
        ):
            if (
409 410
                not is_tensor_array
                and isinstance(slice_item, int)
411 412 413 414
                and var.shape[dim] is not None
                and var.shape[dim] >= 0
                and slice_item >= var.shape[dim]
            ):
415 416 417 418 419 420 421 422
                # For python, if users write a, b = var, the __getitem__
                # method will iterate through 0, 1, 2 ... until __getitem__
                # throws an IndexError, then stop. The var[0], var[1] will
                # be given to a, b respectively. If more values are given,
                # the unpack size would cause error.
                # We raises IndexError here to support grammar like `a, b = var`
                raise IndexError(
                    "slice_item %d at dim %d should be >= 0 and < var.shape[%d]: %d"
423 424
                    % (slice_item, dim, dim, var.shape[dim])
                )
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
            decrease_axes.append(dim)
            start = slice_item
            step = 1
            end = slice_item + 1 if slice_item != -1 else MAX_INTEGER

        elif isinstance(slice_item, slice):
            start = slice_item.start
            end = slice_item.stop
            step = slice_item.step

            if start is None and end is None and step is None:
                continue

            step = 1 if step is None else step

440 441 442
            if start is None:
                start = 0 if step > 0 else MAX_INTEGER
            if end is None:
443
                if (
444
                    paddle.in_dynamic_mode() or not is_tensor_array
445
                ) and var.shape[dim] != -1:
446 447 448
                    end = var.shape[dim] if step > 0 else -1
                else:
                    end = MAX_INTEGER if step > 0 else -1
449

450
        elif isinstance(slice_item, list):
Z
zyfncg 已提交
451
            all_bool = True
W
WeiXin 已提交
452 453 454 455 456

            if is_list_tuple(slice_item, int):
                slice_info.update(slice_item)
                continue

457
            for i in slice_item:
Z
zyfncg 已提交
458 459 460
                if type(i) is int:
                    all_bool = False
                elif not isinstance(i, bool):
461 462
                    raise TypeError("Only support int or bool in index list.")

463 464
            if len(item) != 1:
                raise IndexError(
465 466 467 468
                    "When index contains a list, its length must be 1, but received {}.".format(
                        len(item)
                    )
                )
Z
zyfncg 已提交
469 470 471 472
            new_slice_item = []
            if all_bool:
                if len(slice_item) != var.shape[0]:
                    raise IndexError(
473 474 475 476 477
                        "The dimension of bool index doesn't match indexed array along "
                        "dimension 0, the target dimension is {}, but received {}.".format(
                            var.shape[0], len(slice_item)
                        )
                    )
478 479 480 481
                for idx, ele in enumerate(slice_item):
                    if ele is True:
                        new_slice_item.append(idx)
                slice_item = new_slice_item
Z
zyfncg 已提交
482 483 484 485 486 487 488 489 490
            else:
                for idx, ele in enumerate(slice_item):
                    if type(ele) is int:
                        new_slice_item.append(ele)
                    elif ele is True:
                        new_slice_item.append(1)
                    else:
                        new_slice_item.append(0)
                slice_item = new_slice_item
491

492 493
            from ..tensor import index_select

494
            idx = paddle.assign(np.array(slice_item).astype("int32"))
495 496
            return index_select(var, index=idx, axis=0)

W
wanghuancoder 已提交
497
        elif isinstance(slice_item, (Variable, core.eager.Tensor)):
W
WeiXin 已提交
498
            if len(item) == 1:
499
                from ..tensor import index_select
Z
zyfncg 已提交
500

W
WeiXin 已提交
501
                if slice_item.dtype == paddle.bool:
W
wanghuancoder 已提交
502 503 504 505 506 507 508
                    if in_declarative_mode():
                        tmp = get_value_for_bool_tensor(var, slice_item)
                        if hasattr(tmp, "is_view_var"):
                            tmp.is_view_var = True
                        return tmp
                    else:
                        return get_value_for_bool_tensor(var, slice_item)
W
WeiXin 已提交
509 510 511 512 513 514 515 516 517
                else:
                    if len(slice_item.shape) == 1:
                        return index_select(var, index=slice_item, axis=0)
                    else:
                        slice_info.update(slice_item)
                        continue
            else:
                slice_info.update(slice_item)
                continue
518

519 520
        else:
            raise IndexError(
521 522 523 524
                "Valid index accept int or slice or ellipsis or list, but received {}.".format(
                    slice_item
                )
            )
525 526 527 528 529 530 531

        axes.append(dim)
        starts.append(start)
        ends.append(end)
        steps.append(step)
        use_strided_slice = True if step != 1 else use_strided_slice

W
WeiXin 已提交
532 533 534
    if slice_info.indexes:
        if len(slice_info.indexes) != len(item):
            raise IndexError(
535 536 537 538
                "Valid index accept int or slice or ellipsis or list, but received {}.".format(
                    item
                )
            )
W
wanghuancoder 已提交
539 540 541 542 543 544 545
        if in_declarative_mode():
            tmp = slice_info.get_item(var)
            if hasattr(tmp, "is_view_var"):
                tmp.is_view_var = True
            return tmp
        else:
            return slice_info.get_item(var)
W
WeiXin 已提交
546

547 548 549 550 551
    inputs = {'Input': [var]}
    attrs = {
        'axes': axes,
        'starts': [],
        'ends': [],
552
        'decrease_axis': decrease_axes,
553 554 555 556 557 558 559
    }
    if use_strided_slice:
        attrs['strides'] = []

    infer_flags = [1] * len(axes)
    deal_attrs(attrs, starts, "starts", "StartsTensorList", inputs, infer_flags)
    deal_attrs(attrs, ends, "ends", "EndsTensorList", inputs, infer_flags)
560 561 562
    deal_attrs(
        attrs, steps, "strides", "StridesTensorList", inputs, infer_flags
    )
563 564 565 566 567
    attrs['infer_flags'] = infer_flags

    out = var
    if len(axes) > 0:
        op_type = "strided_slice" if use_strided_slice else "slice"
568
        if paddle.in_dynamic_mode() and op_type == "slice":
569 570 571 572 573 574 575 576
            if "StartsTensorList" in inputs.keys():
                st = inputs['StartsTensorList']
            else:
                st = attrs['starts']
            if "EndsTensorList" in inputs.keys():
                end = inputs['EndsTensorList']
            else:
                end = attrs['ends']
577 578 579
            out = paddle._C_ops.slice(
                var, axes, st, end, attrs['infer_flags'], attrs['decrease_axis']
            )
580 581 582 583
        else:
            target_block = default_main_program().current_block()

            slice_out_var = target_block.create_var(
584 585 586 587 588 589 590 591 592 593 594
                name=unique_name.generate_with_ignorable_key(
                    var.name + "_" + op_type
                ),
                dtype=var.dtype,
            )
            target_block.append_op(
                type=op_type,
                inputs=inputs,
                outputs={'Out': [slice_out_var]},
                attrs=attrs,
            )
595
            out = slice_out_var
596

597
    if len(reverse_axes) > 0:
598
        from .layers.tensor import reverse
599

600 601
        out = reverse(out, axis=reverse_axes)

602 603 604 605 606
    # NOTE(zoooo0820): When all axes are decreased, the output will be 1-D
    # with FLAGS_set_to_1d=True. In this case, one `None` should be pop out,
    # otherwise the output shape will be not correct.
    set_to_1d = paddle.get_flags('FLAGS_set_to_1d')['FLAGS_set_to_1d']
    if set_to_1d and len(decrease_axes) == len(var.shape):
607 608 609
        warnings.warn(
            "Warning: In Tensor '__getitem__', if the number of scalar elements in the index is equal to the rank of the Tensor, the output should be 0-D. In order to be consistent with the behavior of previous versions, it will be processed to 1-D. But it is not correct and will be removed in release 2.6. If 1-D is still wanted, please modify the index element from scalar to slice (e.g. 'x[i]' => 'x[i:i+1]')."
        )
610 611
        none_axes = none_axes[1:]

612 613 614 615 616 617 618 619 620 621 622
    if len(none_axes) > 0:
        # Deal with cases that decrease_axes is not empty
        # For example:
        # # x.shape: (2,3,4)
        # out = x[0, 0:2, None] # out.shape : (2, 1, 4)
        for idx, axis in enumerate(none_axes):
            l = len([i for i in decrease_axes if i < axis])
            new_axis = axis - l
            none_axes[idx] = new_axis

        from ..tensor import unsqueeze
623

624
        out = unsqueeze(out, axis=none_axes)
625

W
wanghuancoder 已提交
626 627
    if in_declarative_mode() and hasattr(out, "is_view_var"):
        out.is_view_var = True
628 629 630
    return out


631
def _setitem_for_tensor_array(var, item, value):
632 633 634 635 636 637 638
    """branches for tensor array setitem operation.
    A item can be a:
    (1) int/Variable, which is a simple number/variable such as [1], [-2]
    (2) Slice, which is represented by bounds such as [2:-1]
    (3) Tuple, which includes the above two cases such as [2:-1, 1]
    If item is case (1), we perform paddle.tensor.array_write,
    in other cases, we raise a NotImplementedError.
639
    """
640

641
    from .framework import Variable
642 643

    assert (
644
        not paddle.in_dynamic_mode()
645 646
    ), "setitem for tensor_array must be called in static graph mode."
    if isinstance(item, (Variable, int)):
647
        from paddle.jit.dy2static.variable_trans_func import (
648 649
            to_static_variable,
        )
650 651
        from paddle import cast
        from paddle.tensor import array_write
652

653 654
        item = paddle.cast(to_static_variable(item), dtype='int64')
        value = to_static_variable(value)
655
        return array_write(x=value, i=item, array=var)
656 657
    else:
        raise NotImplementedError(
658 659 660 661
            "Only support __setitem__ by Int/Variable in tensor_array, but gets {}".format(
                type(item)
            )
        )
662 663


664 665
def _setitem_impl_(var, item, value):
    from .framework import default_main_program, Variable
666
    from paddle.fluid import core
667

668 669
    if var.type == core.VarDesc.VarType.LOD_TENSOR_ARRAY:
        return _setitem_for_tensor_array(var, item, value)
670 671

    inputs = {'Input': var}
W
WeiXin 已提交
672 673 674
    if isinstance(item, list):
        if not is_one_dim_list(item, int):
            item = tuple(item)
675 676
    # 1. Parse item
    if not isinstance(item, tuple):
677
        item = (item,)
678 679 680 681 682 683 684

    decrease_axes = []
    axes = []
    starts = []
    ends = []
    steps = []

W
WeiXin 已提交
685
    item = replace_ndarray(item)
686
    item = replace_ellipsis(var, item)
687
    item, none_axes = replace_none(item)
W
WeiXin 已提交
688
    slice_info = SliceInfo()
Z
zyfncg 已提交
689 690
    dim = 0
    for _, slice_item in enumerate(item):
691 692 693
        if is_integer_or_scalar_tensor(slice_item) and not is_bool_tensor(
            slice_item
        ):
694 695 696 697 698 699 700 701 702 703 704
            decrease_axes.append(dim)
            start = slice_item
            end = slice_item + 1 if slice_item != -1 else MAX_INTEGER
            step = 1

        elif isinstance(slice_item, slice):
            start = slice_item.start
            end = slice_item.stop
            step = slice_item.step

            if start is None and end is None and step is None:
Z
zyfncg 已提交
705
                dim += 1
706 707 708 709 710 711 712
                continue

            step = 1 if step is None else step

            if not isinstance(step, Variable) and step == 0:
                raise ValueError(
                    "When assign a value to a paddle.Tensor, step can not be 0, "
713 714
                    "but received step is {}.".format(step)
                )
715 716 717 718 719 720 721 722 723 724 725 726

            if isinstance(step, Variable) and (start is None or end is None):
                raise ValueError(
                    "When assign a value to a paddle.Tensor, it's not supported that "
                    "the start or end is None when the type of step is paddle.Tensor."
                )

            if start is None:
                start = 0 if step > 0 else MAX_INTEGER

            if end is None:
                end = MAX_INTEGER if step > 0 else (0 - MAX_INTEGER)
Z
zyfncg 已提交
727 728 729 730 731 732 733
        elif isinstance(slice_item, list):
            if is_list_tuple(slice_item, int):
                slice_info.update(slice_item)
                continue

            for i in slice_item:
                if not isinstance(i, bool):
734 735 736
                    raise TypeError(
                        "Doesn't support {} in index list.".format(type(i))
                    )
Z
zyfncg 已提交
737 738 739

            if len(item) != 1:
                raise IndexError(
740 741 742 743
                    "When index contains a bool list, its length must be 1, but received {}.".format(
                        len(item)
                    )
                )
Z
zyfncg 已提交
744

745
            idx_tensor = paddle.assign(slice_item)
Z
zyfncg 已提交
746 747 748 749 750 751
            return set_value_for_bool_tensor(var, idx_tensor, value)

        elif isinstance(slice_item, Variable):
            if slice_item.dtype == core.VarDesc.VarType.BOOL:
                if len(item) != 1:
                    raise IndexError(
752 753 754 755
                        "When index contains a bool tensor, its length must be 1, but received {}.".format(
                            len(item)
                        )
                    )
Z
zyfncg 已提交
756 757 758 759
                return set_value_for_bool_tensor(var, slice_item, value)
            else:
                slice_info.update(slice_item)
                continue
760 761
        else:
            raise IndexError(
Z
zyfncg 已提交
762
                "Valid index accept int, slice, ellipsis, None, list of bool, Variable, "
763 764
                "but received {}.".format(slice_item)
            )
765 766 767 768 769 770

        axes.append(dim)
        starts.append(start)
        ends.append(end)
        steps.append(step)

Z
zyfncg 已提交
771
        dim += 1
W
WeiXin 已提交
772 773 774
    if slice_info.indexes:
        if len(slice_info.indexes) != len(item):
            raise IndexError(
775 776 777 778
                "Valid index accept int or slice or ellipsis or list, but received {}.".format(
                    item
                )
            )
W
WeiXin 已提交
779
        return slice_info.set_item(var, value)
780 781 782 783 784
    attrs = {
        'axes': axes,
        'starts': starts,
        'ends': ends,
        'steps': steps,
Z
zyfncg 已提交
785
        'decrease_axes': decrease_axes,
786
        'none_axes': none_axes,
787 788
    }

789 790 791 792
    if paddle.utils._contain_var(starts):
        inputs['StartsTensorList'] = paddle.utils._convert_to_tensor_list(
            starts
        )
793
        del attrs['starts']
794 795
    if paddle.utils._contain_var(ends):
        inputs['EndsTensorList'] = paddle.utils._convert_to_tensor_list(ends)
796
        del attrs['ends']
797 798
    if paddle.utils._contain_var(steps):
        inputs['StepsTensorList'] = paddle.utils._convert_to_tensor_list(steps)
799 800 801 802 803 804 805
        del attrs['steps']

    # 2. Parse value
    dtype = var.dtype
    attrs['dtype'] = dtype

    from .data_feeder import convert_dtype
806

807 808
    #  2.1 value is an integer, float or complex
    if isinstance(value, (bool, int, float, complex)):
809 810 811 812 813
        value = np.array([value]).astype(convert_dtype(dtype))

    #  2.2 value is a np.ndarray
    if isinstance(value, np.ndarray):
        shape = list(value.shape)
814 815
        values = value.ravel().tolist()
        attrs["values"] = values
816 817
        attrs["shape"] = shape

W
wanghuancoder 已提交
818
    elif isinstance(value, (Variable, core.eager.Tensor)):
819 820 821 822 823
        inputs["ValueTensor"] = value
    else:
        raise TypeError(
            "Only support to assign an integer, float, numpy.ndarray or "
            "paddle.Tensor to a paddle.Tensor, but received {}".format(
824 825 826
                type(value)
            )
        )
827

828
    if paddle.in_dynamic_mode():
Z
zyfncg 已提交
829
        var._bump_inplace_version()
830 831 832 833
        output = var
    else:
        helper = paddle.fluid.layer_helper.LayerHelper('set_value', **locals())
        output = helper.create_variable_for_type_inference(dtype=var.dtype)
Z
zyfncg 已提交
834

835
    cur_block = default_main_program().current_block()
836 837 838
    cur_block.append_op(
        type="set_value",
        inputs=inputs,
839
        outputs={'Out': output},
840 841 842
        attrs=attrs,
        inplace_map={"Input": "Out"},
    )
843

844 845 846 847 848 849 850 851 852 853 854
    if not paddle.in_dynamic_mode():
        # map var to the new output
        from paddle.jit.dy2static.program_translator import (
            ProgramTranslator,
        )

        ProgramTranslator.get_instance()._params_map.add(
            cur_block.program, var.desc.id(), output
        )

    return output
Z
zyfncg 已提交
855 856


857
# the item is a tensor of bool
Z
zyfncg 已提交
858 859
def set_value_for_bool_tensor(var, item, value):
    if len(item.shape) > len(var.shape):
860 861 862 863 864
        raise IndexError(
            "The dims of bool index doesn't match indexed array, "
            "the dims of bool index except to be equal or less "
            "than {}, but received {}.".format(len(var.shape), len(item.shape))
        )
Z
zyfncg 已提交
865
    for i, dim_len in enumerate(item.shape):
866
        if dim_len != -1 and var.shape[i] != -1 and dim_len != var.shape[i]:
Z
zyfncg 已提交
867 868
            raise IndexError(
                "The dimension of bool index doesn't match indexed array along "
869 870 871 872
                "dimension {}, the target dimension is {}, but received {}.".format(
                    i, var.shape[i], dim_len
                )
            )
Z
zyfncg 已提交
873 874 875 876 877 878

    def idx_not_empty(var, item, value):
        from .framework import Variable
        from ..tensor import gather_nd, scatter_nd_add

        if not isinstance(value, Variable):
879
            value = paddle.assign(value).cast(var.dtype)
Z
zyfncg 已提交
880

881
        idx = paddle.nonzero(item)
Z
zyfncg 已提交
882 883 884
        gather_val = gather_nd(var, idx)
        gather_val_new = value - gather_val
        out = scatter_nd_add(var, idx, gather_val_new)
885 886 887 888 889
        var = _setitem_impl_(var, ..., out)
        return var

    def idx_is_empty(var):
        return var
Z
zyfncg 已提交
890

891
    from paddle.static.nn import cond
892

Z
zyfncg 已提交
893
    # If all the bool index is False, just do nothing
894 895 896 897 898
    var = cond(
        item.any(),
        lambda: idx_not_empty(var, item, value),
        lambda: idx_is_empty(var),
    )
Z
zyfncg 已提交
899 900

    return var