utils.py 17.2 KB
Newer Older
C
chengduoZH 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
#   Copyright (c) 2018 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

G
Guo Sheng 已提交
15
import collections
16
import copy
G
Guo Sheng 已提交
17
import six
C
chengduoZH 已提交
18
import numpy as np
J
Jiabin Yang 已提交
19
from ..framework import Block, Variable, _non_static_mode
20 21 22 23 24 25
from ..data_feeder import (
    convert_dtype,
    check_variable_and_dtype,
    check_type,
    check_dtype,
)
W
wangchaochaohu 已提交
26
from ..layer_helper import LayerHelper
27
from sys import version_info
28

29 30 31 32
try:
    from collections.abc import Sequence
except:
    from collections import Sequence
C
chengduoZH 已提交
33 34


35
def convert_to_list(value, n, name, dtype=int):
C
chengduoZH 已提交
36 37 38
    """
    Converts a single numerical type or iterable of numerical
    types into an numerical type list.
C
chengduoZH 已提交
39 40 41 42 43 44 45

    Arguments:
      value: The value to validate and convert. Could an int, or any iterable
        of ints.
      n: The size of the list to be returned.
      name: The name of the argument being validated, e.g. "stride" or
        "filter_size". This is only used to format error messages.
C
chengduoZH 已提交
46
      dtype: the numerical type of the element of the list to be returned.
C
chengduoZH 已提交
47 48

    Returns:
C
chengduoZH 已提交
49
      A list of n dtypes.
C
chengduoZH 已提交
50 51 52 53 54

    Raises:
      ValueError: If something else than an int/long or iterable thereof was
        passed.
    """
C
chengduoZH 已提交
55
    if isinstance(value, dtype):
56 57 58
        return [
            value,
        ] * n
C
chengduoZH 已提交
59 60 61 62
    else:
        try:
            value_list = list(value)
        except TypeError:
63 64 65 66 67 68
            raise ValueError(
                "The "
                + name
                + "'s type must be list or tuple. Received: "
                + str(value)
            )
C
chengduoZH 已提交
69
        if len(value_list) != n:
70 71 72 73 74 75 76 77
            raise ValueError(
                "The "
                + name
                + "'s length must be "
                + str(n)
                + ". Received: "
                + str(value)
            )
C
chengduoZH 已提交
78
        for single_value in value_list:
79 80 81 82
            assert not isinstance(single_value, Variable), (
                "Required numerical type with '%s', but received Tensor."
                % dtype
            )
C
chengduoZH 已提交
83
            try:
C
chengduoZH 已提交
84
                dtype(single_value)
C
chengduoZH 已提交
85
            except (ValueError, TypeError):
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
                raise ValueError(
                    "The "
                    + name
                    + "'s type must be a list or tuple of "
                    + str(n)
                    + " "
                    + str(dtype)
                    + " . Received: "
                    + str(value)
                    + " "
                    "including element "
                    + str(single_value)
                    + " of type"
                    + " "
                    + str(type(single_value))
                )
C
chengduoZH 已提交
102
        return value_list
G
Guo Sheng 已提交
103 104 105 106 107 108 109 110


def is_sequence(seq):
    """
    Whether `seq` is an entry or nested structure
    """
    if isinstance(seq, dict):
        return True
111
    return isinstance(seq, Sequence) and not isinstance(seq, str)
G
Guo Sheng 已提交
112 113


114 115 116 117 118 119
def _hash_with_id(*args):
    """
    Return int hash value calculated by id(arg) or tuple(id1,id2, ...).
    """
    assert len(args) > 0
    info = tuple([id(v) for v in args])
120
    return hash(info) & 0xFFFFFFF
121 122


G
Guo Sheng 已提交
123 124 125 126 127
def _sorted(dict_):
    """
    Returns a sorted list of the dict keys, with error if keys not sortable.
    """
    try:
128
        return sorted(dict_.keys())
G
Guo Sheng 已提交
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
    except TypeError:
        raise TypeError("nest only supports dicts with sortable keys.")


def _yield_value(iterable):
    if isinstance(iterable, dict):
        # Iterate through dictionaries in a deterministic order by sorting the
        # keys. Notice this means that we ignore the original order of `OrderedDict`
        # instances. This is intentional, to avoid potential bugs caused by mixing
        # ordered and plain dicts (e.g., flattening a dict but using a
        # corresponding `OrderedDict` to pack it back).
        for key in _sorted(iterable):
            yield iterable[key]
    else:
        for value in iterable:
            yield value


def _yield_flat_nest(nest):
    for n in _yield_value(nest):
        if is_sequence(n):
            for ni in _yield_flat_nest(n):
                yield ni
        else:
            yield n


156 157 158 159 160 161 162
def to_sequence(nest):
    if is_sequence(nest):
        return nest
    else:
        return [nest]


G
Guo Sheng 已提交
163 164
def flatten(nest):
    """
165 166 167
        :alias_main: paddle.flatten
        :alias: paddle.flatten,paddle.tensor.flatten,paddle.tensor.manipulation.flatten
        :old_api: paddle.fluid.layers.flatten
S
swtkiwi 已提交
168

G
Guo Sheng 已提交
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
    Traverse all entries in the nested structure and put them into an list.
    """
    if is_sequence(nest):
        return list(_yield_flat_nest(nest))
    else:
        return [nest]


def _sequence_like(instance, args):
    """
    Convert the sequence `args` to the same type as `instance`.
    """
    if isinstance(instance, dict):
        # Pack dictionaries in a deterministic order by sorting the keys.
        # Notice this means that we ignore the original order of `OrderedDict`
        # instances. This is intentional, to avoid potential bugs caused by mixing
        # ordered and plain dicts (e.g., flattening a dict but using a
        # corresponding `OrderedDict` to pack it back).
        result = dict(zip(_sorted(instance), args))
188
        return type(instance)((key, result[key]) for key in instance.keys())
189 190 191 192 193 194
    elif (
        isinstance(instance, tuple)
        and hasattr(instance, "_fields")
        and isinstance(instance._fields, Sequence)
        and all(isinstance(f, str) for f in instance._fields)
    ):
G
Guo Sheng 已提交
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
        # This is a namedtuple
        return type(instance)(*args)
    else:
        # Not a namedtuple
        return type(instance)(args)


def _packed_nest_with_indices(structure, flat, index):
    """
    Helper function for pack_sequence_as.
    """
    packed = []
    for s in _yield_value(structure):
        if is_sequence(s):
            new_index, child = _packed_nest_with_indices(s, flat, index)
            packed.append(_sequence_like(s, child))
            index = new_index
        else:
            packed.append(flat[index])
            index += 1
    return index, packed


def pack_sequence_as(structure, flat_sequence):
    """
    Pack a given flattened sequence into a given structure.
    """
    if not is_sequence(flat_sequence):
        raise TypeError("flat_sequence must be a sequence")
    if not is_sequence(structure):
        if len(flat_sequence) != 1:
            raise ValueError(
227 228 229
                "Structure is a scalar but len(flat_sequence) == %d > 1"
                % len(flat_sequence)
            )
G
Guo Sheng 已提交
230 231 232 233 234
        return flat_sequence[0]
    flat_structure = flatten(structure)
    if len(flat_structure) != len(flat_sequence):
        raise ValueError(
            "Could not pack sequence. Structure had %d elements, but flat_sequence "
235 236 237 238 239 240 241 242
            "had %d elements.  Structure: %s, flat_sequence: %s."
            % (
                len(flat_structure),
                len(flat_sequence),
                structure,
                flat_sequence,
            )
        )
G
Guo Sheng 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255
    _, packed = _packed_nest_with_indices(structure, flat_sequence, 0)
    return _sequence_like(structure, packed)


def map_structure(func, *structure):
    """
    Apply `func` to each entry in `structure` and return a new structure.
    """
    flat_structure = [flatten(s) for s in structure]
    entries = zip(*flat_structure)
    return pack_sequence_as(structure[0], [func(*x) for x in entries])


256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
def hold_mutable_vars(structure):
    """
    Returns whether structure holds sequence like `list/dict`.
    """
    for s in structure:
        if is_sequence(s):
            return True
    return False


def copy_mutable_vars(structure):
    """
    Returns vars copied from sequence without mutable property.
    """
    flat_structure = copy.copy(flatten(structure))
    return pack_sequence_as(structure, flat_structure)


G
Guo Sheng 已提交
274 275 276 277 278 279 280 281
def _recursive_assert_same_structure(nest1, nest2, check_types):
    """
    Helper function for `assert_same_structure`.
    """
    is_sequence_nest1 = is_sequence(nest1)
    if is_sequence_nest1 != is_sequence(nest2):
        raise ValueError(
            "The two structures don't have the same nested structure.\n\n"
282 283
            "First structure: %s\n\nSecond structure: %s." % (nest1, nest2)
        )
G
Guo Sheng 已提交
284 285 286 287 288 289 290 291
    if not is_sequence_nest1:
        return  # finished checking
    if check_types:
        type_nest1 = type(nest1)
        type_nest2 = type(nest2)
        if type_nest1 != type_nest2:
            raise TypeError(
                "The two structures don't have the same sequence type. First "
292 293 294
                "structure has type %s, while second structure has type %s."
                % (type_nest1, type_nest2)
            )
G
Guo Sheng 已提交
295
        if isinstance(nest1, dict):
296 297
            keys1 = set(nest1.keys())
            keys2 = set(nest2.keys())
G
Guo Sheng 已提交
298 299 300
            if keys1 != keys2:
                raise ValueError(
                    "The two dictionaries don't have the same set of keys. First "
301 302 303 304
                    "structure has keys {}, while second structure has keys {}.".format(
                        keys1, keys2
                    )
                )
G
Guo Sheng 已提交
305 306 307 308 309 310
    nest1_as_sequence = [n for n in _yield_value(nest1)]
    nest2_as_sequence = [n for n in _yield_value(nest2)]
    for n1, n2 in zip(nest1_as_sequence, nest2_as_sequence):
        _recursive_assert_same_structure(n1, n2, check_types)


311 312 313
def padding_to_same_structure(nest1, nest2, obj=None):
    def _padding_to_same_structure_single(value, obj):
        def change_none_to_obj(x):
314 315
            if x is None:
                return obj
316 317 318 319
            return x

        if is_sequence(value):
            value = pack_sequence_as(
320 321
                value, [change_none_to_obj(item) for item in flatten(value)]
            )
322 323 324 325 326 327 328 329 330
        else:
            value = change_none_to_obj(value)
        return value

    nest1 = _padding_to_same_structure_single(nest1, obj)
    nest2 = _padding_to_same_structure_single(nest2, obj)
    return nest1, nest2


G
Guo Sheng 已提交
331 332 333 334 335 336 337
def assert_same_structure(nest1, nest2, check_types=True):
    """
    Confirm two nested structures with the same structure.
    """
    len_nest1 = len(flatten(nest1)) if is_sequence(nest1) else 1
    len_nest2 = len(flatten(nest2)) if is_sequence(nest2) else 1
    if len_nest1 != len_nest2:
338 339 340 341 342 343
        raise ValueError(
            "The two structures don't have the same number of "
            "elements.\n\nFirst structure (%i elements): %s\n\n"
            "Second structure (%i elements): %s"
            % (len_nest1, nest1, len_nest2, nest2)
        )
G
Guo Sheng 已提交
344
    _recursive_assert_same_structure(nest1, nest2, check_types)
345 346 347 348 349 350 351 352 353 354 355 356 357


def _is_symmetric_padding(padding, data_dim):
    """
    Check whether padding is symmetrical.
    """
    assert len(padding) == data_dim * 2 or len(padding) == data_dim
    is_sys = True
    if len(padding) == data_dim * 2:
        for i in range(data_dim):
            if padding[i * 2] != padding[i * 2 + 1]:
                is_sys = False
    return is_sys
L
Leo Chen 已提交
358 359 360 361 362 363 364 365 366 367


def _contain_var(list_or_tuple):
    """
    Check whether list or tuple contains variable.
    """
    for item in list_or_tuple:
        if isinstance(item, Variable):
            return True
    return False
W
wangchaochaohu 已提交
368 369


370
def get_shape_tensor_inputs(inputs, attrs, shape, op_type):
W
wangchaochaohu 已提交
371 372 373 374 375 376 377 378 379 380 381 382
    from .tensor import fill_constant, cast

    def _get_attr_shape(list_shape):
        attr_shape = []
        for idx, dim in enumerate(list_shape):
            if isinstance(dim, Variable):
                attr_shape.append(-1)
            else:
                attr_shape.append(dim)
        return attr_shape

    def _get_shape_tensor(list_shape):
383
        shape_tensor_list = []
W
wangchaochaohu 已提交
384 385 386 387
        for idx, dim in enumerate(list_shape):
            if isinstance(dim, Variable):
                dim.stop_gradient = True
                check_dtype(
388 389 390
                    dim.dtype,
                    'shape[' + str(idx) + ']',
                    ['int32', 'int64'],
W
wangchaochaohu 已提交
391
                    op_type,
392 393
                    '(When type of shape in' + op_type + 'is list or tuple.)',
                )
W
wangchaochaohu 已提交
394 395
                if convert_dtype(dim.dtype) == 'int64':
                    dim = cast(x=dim, dtype='int32')
396
                shape_tensor_list.append(dim)
W
wangchaochaohu 已提交
397 398
            else:
                temp_out = fill_constant([1], 'int32', dim, force_cpu=True)
399 400
                shape_tensor_list.append(temp_out)
        return shape_tensor_list
W
wangchaochaohu 已提交
401 402 403

    if isinstance(shape, Variable):
        shape.stop_gradient = True
404 405 406 407 408 409 410 411
        check_dtype(
            shape.dtype,
            'shape',
            ['int32', 'int64'],
            'fill_constant',
            '(When type of shape in' + op_type + ' is Variable.)',
        )
        if convert_dtype(shape.dtype) == 'int64':
W
wangchaochaohu 已提交
412 413 414 415 416 417
            shape = cast(shape, 'int32')
        inputs["ShapeTensor"] = shape
    elif isinstance(shape, (list, tuple)):
        attrs["shape"] = _get_attr_shape(shape)
        if _contain_var(shape):
            inputs['ShapeTensorList'] = _get_shape_tensor(shape)
418 419
    else:
        raise TypeError("Shape only supports Variable, or list, or tuple.")
420 421 422 423 424 425 426


def _convert_to_tensor_list(old_list, dtype="int32"):
    """
    Converts all elements of a list to Variable.
    """
    from .tensor import fill_constant
427

428 429 430 431 432 433 434
    new_list_tensor = []
    for ele in old_list:

        if isinstance(ele, Variable):
            ele.stop_gradient = True
            new_list_tensor.append(ele)
        else:
435
            assert isinstance(ele, int)
436 437 438
            temp_out = fill_constant([1], dtype, ele, force_cpu=True)
            new_list_tensor.append(temp_out)
    return new_list_tensor
439 440


441
def convert_shape_to_list(shape):
442 443 444 445 446
    """
    Convert shape(list, tuple, variable) to list in imperative mode
    """
    if isinstance(shape, (list, tuple)):
        shape = list(
447 448 449 450 451
            map(
                lambda x: x.numpy().flat[0] if isinstance(x, Variable) else x,
                shape,
            )
        )
452
    else:
453
        shape = shape.numpy().astype(int).tolist()
454
    return shape
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469


def check_shape(shape):
    """
    Check shape type and shape elements type before passing it to fill_constant
    """
    if isinstance(shape, Variable):
        check_dtype(shape.dtype, 'shape', ['int32', 'int64'], 'fill_constant')
    else:
        for ele in shape:
            if not isinstance(ele, Variable):
                if ele < 0:
                    raise ValueError(
                        "All elements in ``shape`` must be positive when it's a list or tuple"
                    )
470
                if not isinstance(ele, int):
471 472 473
                    raise TypeError(
                        "All elements in ``shape`` must be integers when it's a list or tuple"
                    )
474 475 476 477


def try_set_static_shape_tensor(tensor, shape):
    """Try to set static shape of tensor from a shape tensor.
478

479 480 481 482 483 484
    For example,

    import paddle
    paddle.enable_static()
    data = paddle.static.data(name="x", shape=[-1, 2], dtype='float32')
    shape = paddle.shape(data)  # shape should be [-1, 2] instead of [-1, -1]
485 486
    x = paddle.uniform(shape)
    print(x.shape)
487
    # (-1, 2)
488

489
    """
J
Jiabin Yang 已提交
490
    if not _non_static_mode():
491 492 493 494 495 496 497 498 499 500 501 502
        # static mode, and shape is not all inferred (contains -1)
        if -1 in tensor.shape:
            if isinstance(shape, Variable):
                shape = try_get_constant_shape_from_tensor(shape)
                if shape:
                    tensor.desc.set_shape(shape)


def try_get_constant_shape_from_tensor(shape_tensor):
    """Try to get shape from a tensor with constant value.

    For example,
503

504 505 506 507
    import paddle
    paddle.enable_static()
    data = paddle.static.data(name="x", shape=[-1, 2], dtype='float32')
    shape = paddle.shape(data)  # shape should be [-1, 2] instead of [-1, -1]
508 509
    x = paddle.uniform(shape)
    print(x.shape)
510
    # (-1, 2)
511

512
    """
J
Jiabin Yang 已提交
513
    if not _non_static_mode():
514 515 516 517
        try:
            if shape_tensor.op is not None:
                generate_op = shape_tensor.op
                if generate_op.type == 'shape':
518
                    var = shape_tensor.block.vars[
519 520
                        generate_op.input_arg_names[0]
                    ]
521 522 523 524 525
                    return var.shape
        except:
            return None

        return None
526 527 528 529 530 531 532 533


def get_inputs_outputs_in_block(block):
    """
    Returns the inputs and outputs variable used in this block but not
    created in this block.
    """
    assert isinstance(
534 535 536 537 538
        block, Block
    ), "input non-Block argument for get_inputs_outputs_in_block."
    assert (
        block.parent_idx != -1
    ), "input block should be a sub-block, not main block."
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555

    # Find input/output var names of all ops in block
    inner_inputs = set()
    inner_outputs = set()
    for op in block.ops:
        for iname in op.input_names:
            for in_var_name in op.input(iname):
                if not block.has_var(in_var_name):
                    # variable not created in this block
                    inner_inputs.add(in_var_name)
        for oname in op.output_names:
            for out_var_name in op.output(oname):
                if not block.has_var(out_var_name):
                    # variable not created in this block
                    inner_outputs.add(out_var_name)

    return inner_inputs, inner_outputs