to_string.py 12.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Copyright (c) 2020 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 numpy as np
16

17
from paddle.fluid.data_feeder import check_type, convert_dtype
18

19 20
from ..framework import core

21 22
__all__ = []

23

24
class PrintOptions:
25 26 27 28 29 30 31 32 33 34
    precision = 8
    threshold = 1000
    edgeitems = 3
    linewidth = 80
    sci_mode = False


DEFAULT_PRINT_OPTIONS = PrintOptions()


35 36 37 38 39 40 41
def set_printoptions(
    precision=None,
    threshold=None,
    edgeitems=None,
    sci_mode=None,
    linewidth=None,
):
42 43 44 45 46
    """Set the printing options for Tensor.

    Args:
        precision (int, optional): Number of digits of the floating number, default 8.
        threshold (int, optional): Total number of elements printed, default 1000.
47
        edgeitems (int, optional): Number of elements in summary at the beginning and ending of each dimension, default 3.
48
        sci_mode (bool, optional): Format the floating number with scientific notation or not, default False.
49
        linewidth (int, optional): Number of characters each line, default 80.
50 51


52 53 54 55 56 57
    Returns:
        None.

    Examples:
        .. code-block:: python

58 59 60 61 62 63 64 65 66 67 68 69 70 71
            >>> import paddle

            >>> paddle.seed(10)
            >>> a = paddle.rand([10, 20])
            >>> paddle.set_printoptions(4, 100, 3)
            >>> print(a)
            Tensor(shape=[10, 20], dtype=float32, place=Place(cpu), stop_gradient=True,
            [[0.2727, 0.5489, 0.8655, ..., 0.2916, 0.8525, 0.9000],
             [0.3806, 0.8996, 0.0928, ..., 0.9535, 0.8378, 0.6409],
             [0.1484, 0.4038, 0.8294, ..., 0.0148, 0.6520, 0.4250],
             ...,
             [0.3426, 0.1909, 0.7240, ..., 0.4218, 0.2676, 0.5679],
             [0.5561, 0.2081, 0.0676, ..., 0.9778, 0.3302, 0.9559],
             [0.2665, 0.8483, 0.5389, ..., 0.4956, 0.6862, 0.9178]])
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
    """
    kwargs = {}

    if precision is not None:
        check_type(precision, 'precision', (int), 'set_printoptions')
        DEFAULT_PRINT_OPTIONS.precision = precision
        kwargs['precision'] = precision
    if threshold is not None:
        check_type(threshold, 'threshold', (int), 'set_printoptions')
        DEFAULT_PRINT_OPTIONS.threshold = threshold
        kwargs['threshold'] = threshold
    if edgeitems is not None:
        check_type(edgeitems, 'edgeitems', (int), 'set_printoptions')
        DEFAULT_PRINT_OPTIONS.edgeitems = edgeitems
        kwargs['edgeitems'] = edgeitems
87 88 89 90
    if linewidth is not None:
        check_type(linewidth, 'linewidth', (int), 'set_printoptions')
        DEFAULT_PRINT_OPTIONS.linewidth = linewidth
        kwargs['linewidth'] = linewidth
91 92 93 94 95 96 97
    if sci_mode is not None:
        check_type(sci_mode, 'sci_mode', (bool), 'set_printoptions')
        DEFAULT_PRINT_OPTIONS.sci_mode = sci_mode
        kwargs['sci_mode'] = sci_mode
    core.set_printoptions(**kwargs)


98
def _to_summary(var):
99 100
    edgeitems = DEFAULT_PRINT_OPTIONS.edgeitems

101 102 103 104
    # Handle tensor of shape contains 0, like [0, 2], [3, 0, 3]
    if np.prod(var.shape) == 0:
        return np.array([])

105 106 107 108
    if len(var.shape) == 0:
        return var
    elif len(var.shape) == 1:
        if var.shape[0] > 2 * edgeitems:
109
            return np.concatenate([var[:edgeitems], var[(-1 * edgeitems) :]])
110 111 112 113 114
        else:
            return var
    else:
        # recursively handle all dimensions
        if var.shape[0] > 2 * edgeitems:
115 116
            begin = list(var[:edgeitems])
            end = list(var[(-1 * edgeitems) :])
117
            return np.stack([_to_summary(x) for x in (begin + end)])
118
        else:
119
            return np.stack([_to_summary(x) for x in var])
120 121


122
def _format_item(np_var, max_width=0, signed=False):
123 124 125 126 127
    if (
        np_var.dtype == np.float32
        or np_var.dtype == np.float64
        or np_var.dtype == np.float16
    ):
128 129
        if DEFAULT_PRINT_OPTIONS.sci_mode:
            item_str = '{{:.{}e}}'.format(
130 131
                DEFAULT_PRINT_OPTIONS.precision
            ).format(np_var)
132
        elif np.ceil(np_var) == np_var:
133
            item_str = f'{np_var:.0f}.'
134 135
        else:
            item_str = '{{:.{}f}}'.format(
136 137
                DEFAULT_PRINT_OPTIONS.precision
            ).format(np_var)
138
    else:
139
        item_str = f'{np_var}'
140 141

    if max_width > len(item_str):
142 143 144 145 146 147 148 149
        if signed:  # handle sign character for tenosr with negative item
            if np_var < 0:
                return item_str.ljust(max_width)
            else:
                return ' ' + item_str.ljust(max_width - 1)
        else:
            return item_str.ljust(max_width)
    else:  # used for _get_max_width
150 151 152 153
        return item_str


def _get_max_width(var):
154
    # return max_width for a scalar
155
    max_width = 0
156 157 158 159
    signed = False
    for item in list(var.flatten()):
        if (not signed) and (item < 0):
            signed = True
160 161 162
        item_str = _format_item(item)
        max_width = max(max_width, len(item_str))

163
    return max_width, signed
164

165

166 167 168 169 170 171 172 173 174 175 176
def _format_tensor(var, summary, indent=0, max_width=0, signed=False):
    """
    Format a tensor

    Args:
        var(Tensor): The tensor to be formatted.
        summary(bool): Do summary or not. If true, some elements will not be printed, and be replaced with "...".
        indent(int): The indent of each line.
        max_width(int): The max width of each elements in var.
        signed(bool): Print +/- or not.
    """
177
    edgeitems = DEFAULT_PRINT_OPTIONS.edgeitems
178
    linewidth = DEFAULT_PRINT_OPTIONS.linewidth
179 180

    if len(var.shape) == 0:
181
        # 0-D Tensor, whose shape = [], should be formatted like this.
182
        return _format_item(var, max_width, signed)
183
    elif len(var.shape) == 1:
184 185 186 187 188
        item_length = max_width + 2
        items_per_line = (linewidth - indent) // item_length
        items_per_line = max(1, items_per_line)

        if summary and var.shape[0] > 2 * edgeitems:
189 190 191 192 193 194 195 196 197 198 199
            items = (
                [
                    _format_item(item, max_width, signed)
                    for item in list(var)[:edgeitems]
                ]
                + ['...']
                + [
                    _format_item(item, max_width, signed)
                    for item in list(var)[(-1 * edgeitems) :]
                ]
            )
200 201
        else:
            items = [
202
                _format_item(item, max_width, signed) for item in list(var)
203
            ]
204
        lines = [
205
            items[i : i + items_per_line]
206 207
            for i in range(0, len(items), items_per_line)
        ]
208
        s = (',\n' + ' ' * (indent + 1)).join(
209 210
            [', '.join(line) for line in lines]
        )
211 212 213
        return '[' + s + ']'
    else:
        # recursively handle all dimensions
214
        if summary and var.shape[0] > 2 * edgeitems:
215 216 217 218 219 220 221 222 223 224 225
            vars = (
                [
                    _format_tensor(x, summary, indent + 1, max_width, signed)
                    for x in var[:edgeitems]
                ]
                + ['...']
                + [
                    _format_tensor(x, summary, indent + 1, max_width, signed)
                    for x in var[(-1 * edgeitems) :]
                ]
            )
226
        else:
227
            vars = [
228
                _format_tensor(x, summary, indent + 1, max_width, signed)
229 230
                for x in var
            ]
231

232 233 234 235 236 237 238
        return (
            '['
            + (',' + '\n' * (len(var.shape) - 1) + ' ' * (indent + 1)).join(
                vars
            )
            + ']'
        )
239 240 241 242 243


def to_string(var, prefix='Tensor'):
    indent = len(prefix) + 1

244 245 246 247
    dtype = convert_dtype(var.dtype)
    if var.dtype == core.VarDesc.VarType.BF16:
        dtype = 'bfloat16'

248 249 250 251 252 253
    _template = "{prefix}(shape={shape}, dtype={dtype}, place={place}, stop_gradient={stop_gradient},\n{indent}{data})"

    tensor = var.value().get_tensor()
    if not tensor._is_initialized():
        return "Tensor(Not initialized)"

254 255
    if var.dtype == core.VarDesc.VarType.BF16:
        var = var.astype('float32')
256
    np_var = var.numpy(False)
257

258 259 260 261 262 263 264
    if len(var.shape) == 0:
        size = 0
    else:
        size = 1
        for dim in var.shape:
            size *= dim

265
    summary = False
266
    if size > DEFAULT_PRINT_OPTIONS.threshold:
267
        summary = True
268

269
    max_width, signed = _get_max_width(_to_summary(np_var))
270

271 272 273
    data = _format_tensor(
        np_var, summary, indent=indent, max_width=max_width, signed=signed
    )
274

275 276 277 278 279 280 281 282 283
    return _template.format(
        prefix=prefix,
        shape=var.shape,
        dtype=dtype,
        place=var._place_str,
        stop_gradient=var.stop_gradient,
        indent=' ' * indent,
        data=data,
    )
284 285


286
def _format_dense_tensor(tensor, indent):
287 288 289
    if tensor.dtype == core.VarDesc.VarType.BF16:
        tensor = tensor.astype('float32')

290
    # TODO(zhouwei): will remove 0-D Tensor.numpy() hack
291
    np_tensor = tensor.numpy(False)
292 293 294 295 296 297 298 299 300 301 302 303 304 305

    if len(tensor.shape) == 0:
        size = 0
    else:
        size = 1
        for dim in tensor.shape:
            size *= dim

    sumary = False
    if size > DEFAULT_PRINT_OPTIONS.threshold:
        sumary = True

    max_width, signed = _get_max_width(_to_summary(np_tensor))

306 307 308
    data = _format_tensor(
        np_tensor, sumary, indent=indent, max_width=max_width, signed=signed
    )
309 310 311 312 313 314
    return data


def sparse_tensor_to_string(tensor, prefix='Tensor'):
    indent = len(prefix) + 1
    if tensor.is_sparse_coo():
315
        _template = "{prefix}(shape={shape}, dtype={dtype}, place={place}, stop_gradient={stop_gradient}, \n{indent}{indices}, \n{indent}{values})"
316 317
        indices_tensor = tensor.indices()
        values_tensor = tensor.values()
318
        indices_data = 'indices=' + _format_dense_tensor(
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
            indices_tensor, indent + len('indices=')
        )
        values_data = 'values=' + _format_dense_tensor(
            values_tensor, indent + len('values=')
        )
        return _template.format(
            prefix=prefix,
            shape=tensor.shape,
            dtype=tensor.dtype,
            place=tensor._place_str,
            stop_gradient=tensor.stop_gradient,
            indent=' ' * indent,
            indices=indices_data,
            values=values_data,
        )
334
    else:
335
        _template = "{prefix}(shape={shape}, dtype={dtype}, place={place}, stop_gradient={stop_gradient}, \n{indent}{crows}, \n{indent}{cols}, \n{indent}{values})"
336 337 338
        crows_tensor = tensor.crows()
        cols_tensor = tensor.cols()
        elements_tensor = tensor.values()
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
        crows_data = 'crows=' + _format_dense_tensor(
            crows_tensor, indent + len('crows=')
        )
        cols_data = 'cols=' + _format_dense_tensor(
            cols_tensor, indent + len('cols=')
        )
        values_data = 'values=' + _format_dense_tensor(
            elements_tensor, indent + len('values=')
        )

        return _template.format(
            prefix=prefix,
            shape=tensor.shape,
            dtype=tensor.dtype,
            place=tensor._place_str,
            stop_gradient=tensor.stop_gradient,
            indent=' ' * indent,
            crows=crows_data,
            cols=cols_data,
            values=values_data,
        )
360 361


L
LiYuRio 已提交
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
def dist_tensor_to_string(tensor, prefix='Tensor'):
    # TODO(dev): Complete tensor will be printed after reshard
    # is ready.
    indent = len(prefix) + 1
    dtype = convert_dtype(tensor.dtype)
    if tensor.dtype == core.VarDesc.VarType.BF16:
        dtype = 'bfloat16'

    _template = "{prefix}(shape={shape}, dtype={dtype}, place={place}, stop_gradient={stop_gradient}, dist_attr={dist_attr},\n{indent}{data})"
    return _template.format(
        prefix=prefix,
        shape=tensor.shape,
        dtype=dtype,
        place=tensor._place_str,
        stop_gradient=tensor.stop_gradient,
        dist_attr=tensor.dist_attr,
        indent=' ' * indent,
        data=None,
    )


383 384 385
def tensor_to_string(tensor, prefix='Tensor'):
    indent = len(prefix) + 1

386 387 388 389
    dtype = convert_dtype(tensor.dtype)
    if tensor.dtype == core.VarDesc.VarType.BF16:
        dtype = 'bfloat16'

390 391 392 393
    _template = "{prefix}(shape={shape}, dtype={dtype}, place={place}, stop_gradient={stop_gradient},\n{indent}{data})"

    if tensor.is_sparse():
        return sparse_tensor_to_string(tensor, prefix)
394

L
LiYuRio 已提交
395 396 397
    if tensor.is_dist():
        return dist_tensor_to_string(tensor, prefix)

398 399
    if not tensor._is_dense_tensor_hold_allocation():
        return "Tensor(Not initialized)"
400 401
    else:
        data = _format_dense_tensor(tensor, indent)
402 403 404 405 406 407 408 409 410
        return _template.format(
            prefix=prefix,
            shape=tensor.shape,
            dtype=dtype,
            place=tensor._place_str,
            stop_gradient=tensor.stop_gradient,
            indent=' ' * indent,
            data=data,
        )