utils.py 21.3 KB
Newer Older
1 2
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
# Copyright (c) 2021 NVIDIA Corporation.  All rights reserved.
3
#
4 5 6
# 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
7
#
8
#     http://www.apache.org/licenses/LICENSE-2.0
9
#
10 11 12 13 14 15 16 17 18 19
# 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.
"""
Utilities of Auto SParsity (ASP).
"""

import collections
20 21
import sys
import threading
22 23 24
from enum import Enum
from itertools import permutations

25 26 27
import numpy as np

__all__ = []
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


class MaskAlgo(Enum):
    r"""
    A collection of all mask generating algorithms.
    There currently are three algorithms, `MASK_1D`, `MASK_2D_GREEDY` and `MASK_2D_BEST`
    """
    MASK_1D = 'get_mask_1d'
    MASK_2D_GREEDY = 'get_mask_2d_greedy'
    MASK_2D_BEST = 'get_mask_2d_best'


class CheckMethod(Enum):
    r"""
    A collection of all sparsity checking approaches.
    There currently are two methods, `CHECK_1D` and `CHECK_2D`
    """
    CHECK_1D = 'check_mask_1d'
    CHECK_2D = 'check_mask_2d'

    @staticmethod
    def get_checking_method(mask_algo):
        r"""
        Get sparsity checking method by mask generating algorithm.

        Args:
            mask_algo (MaskAlgo): The algorithm of mask generating.
        Returns:
            CheckMethod: The corresponded sparsity checking method.
        Examples:
            .. code-block:: python

60 61 62 63 64 65 66 67
                >>> import numpy as np
                >>> from paddle.incubate.asp import CheckMethod, MaskAlgo
                >>> print(CheckMethod.get_checking_method(MaskAlgo.MASK_1D))
                CheckMethod.CHECK_1D
                >>> print(CheckMethod.get_checking_method(MaskAlgo.MASK_2D_GREEDY))
                CheckMethod.CHECK_2D
                >>> print(CheckMethod.get_checking_method(MaskAlgo.MASK_2D_BEST))
                CheckMethod.CHECK_2D
68
        """
69 70 71
        assert isinstance(
            mask_algo, MaskAlgo
        ), "mask_algo should be MaskAlgo type"
72 73 74 75 76 77
        if mask_algo == MaskAlgo.MASK_1D:
            return CheckMethod.CHECK_1D
        else:
            return CheckMethod.CHECK_2D


78
def calculate_density(x):
79
    r"""
U
ustiniankw 已提交
80

81 82 83 84
    Return the density of the input tensor.

    Args:
        x (nparray): The input tensor.
U
ustiniankw 已提交
85

86
    Returns:
U
ustiniankw 已提交
87 88
        float, The density of :attr:`x`.

89 90 91
    Examples:
        .. code-block:: python

92 93
            >>> import paddle
            >>> import numpy as np
U
ustiniankw 已提交
94

95 96 97 98 99
            >>> x = np.array([[0, 1, 3, 0],
            ...             [1, 1, 0, 1]])
            >>> out = paddle.incubate.asp.calculate_density(x)
            >>> print(out)
            0.625
U
ustiniankw 已提交
100

101 102 103 104 105
    """
    x_flattened = x.flatten()
    return float(np.nonzero(x_flattened)[0].size) / x_flattened.size


106
def _reshape_1d(mat, m):
107
    r"""
108
    Reshape the input 2D matrix to shape (-1, m).
109
    If the second dimension of :attr:`mat` is not a multiples of :attr:`m`,
110 111 112 113 114 115 116
    then this function would pad the remainder with 0 before reshaping.

    .. math::

        remainder = mat.shape[1] % m

    Args:
117
        mat (nparray): The input 2D matrix.
118 119 120 121
        m (int): The second dimension of reshaped matrix.
    Returns:
        tuple: A pair of the reshaped and padded matrix and the shape of padded matrix (non-reshaping).
    """
122 123
    assert len(mat.shape) == 2, "The input mat should be a 2D matrix!"

124 125 126
    remainder = mat.shape[1] % m
    if mat.shape[1] % m > 0:
        mat_padded = np.zeros((mat.shape[0], mat.shape[1] + (m - remainder)))
127
        mat_padded[:, : mat.shape[1]] = mat
128 129 130 131 132 133 134 135 136
        shape = mat_padded.shape
        return mat_padded.reshape(-1, m), shape
    else:
        return mat.reshape(-1, m), mat.shape


def check_mask_1d(mat, n, m):
    r"""
    Check if every row of the input matrix :attr:`mat` is in 1D `n:m` sparse pattern.
137
    This function would pad the second dimension of :attr:`mat` by zero
138 139 140 141 142 143 144 145 146 147 148 149 150
    to be a multiples of :attr:`m` if necessary.

    1D `n:m` sparse pattern: At least :attr:`n` zeros in every :math:`1 \times m` block.

    Args:
        mat (nparray): The input matrix.
        n (int): n of `n:m` sparse pattern.
        m (int): m of `n:m` sparse pattern.
    Returns:
        bool: True if every row of :attr:`mat` is in 1D n:m sparse pattern, else False.
    Examples:
        .. code-block:: python

151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
          >>> import numpy as np
          >>> import paddle.incubate.asp as sparsity

          >>> x = np.array([[0, 1, 3, 0],
          ...               [1, 0, 0, 1]])
          >>> y = sparsity.check_mask_1d(x, 2, 4)
          >>> print(y)
          True

          >>> x = np.array([[0, 1, 5, 4],
          ...               [1, 0, 0, 1]])
          >>> y = sparsity.check_mask_1d(x, 2, 4)
          >>> print(y)
          False

          >>> # x would be padded to shape (2, 8)
          >>> x = np.array([[0, 1, 0, 4, 6],
          ...               [1, 0, 0, 1, 7]])
          >>> y = sparsity.check_mask_1d(x, 2, 4)
          >>> print(y)
          True
172 173
    """
    if len(mat.shape) <= 1:
174
        mat_flattern, shape = _reshape_1d(mat.reshape(1, mat.shape[0]), m)
175
    else:
176
        mat_flattern, shape = _reshape_1d(mat, m)
177 178 179 180 181 182 183 184 185

    for sub_mat in mat_flattern:
        if np.nonzero(sub_mat)[0].size > (m - n):
            return False
    return True


def get_mask_1d(mat, n, m):
    r"""
186 187
    Generate 1D `n:m` sparse pattern mask of the input matrix :attr:`mat`
    in row-directory. This function would pad the second dimension of :attr:`mat`
188 189 190 191 192 193 194 195 196 197 198 199 200
    by zero to be a multiples of :attr:`m` before mask generation.

    1D `n:m` sparse pattern: At least :attr:`n` zeros in every :math:`1 \times m` block.

    Args:
        mat (nparray): The input matrix.
        n (int): n of `n:m` sparse pattern.
        m (int): m of `n:m` sparse pattern.
    Returns:
        nparray: The 1D `n:m` sparse mask of :attr:`mat`.
    Examples:
        .. code-block:: python

201 202 203 204 205 206 207 208 209 210 211
          >>> import numpy as np
          >>> import paddle.incubate.asp as sparsity
          >>> mat = np.array([[0, 1, 5, 4],
          ...                 [2, 7, 3, 6]])
          >>> mask = sparsity.get_mask_1d(mat, 2, 4)
          >>> print(mask)
          [[0 0 1 1]
          [0 1 0 1]]
          >>> y = sparsity.check_mask_1d(mask, 2, 4)
          >>> print(y)
          True
212
    """
213
    mat_flattern, shape = _reshape_1d(mat, m)
214 215 216 217 218 219 220 221

    mask_flattern = np.ones_like(mat_flattern)
    mask = np.ones_like(mat)
    for i in range(mat_flattern.shape[0]):
        sub_mat = mat_flattern[i]
        min_order_indices = np.argsort(np.absolute(sub_mat))
        mask_flattern[i, min_order_indices[:n].tolist()] = 0
    mask_flattern = mask_flattern.reshape(shape)
222
    mask[:, :] = mask_flattern[:, : mat.shape[1]]
223 224 225
    return mask


226
def _reshape_2d(mat, m):
227
    r"""
228
    Reshape the input 2D matrix to shape (-1, :math:`m \times m`).
229
    In each dimension of :attr:`mat`, if it is not a multiples of :attr:`m`,
230 231 232 233 234 235 236 237
    then this function would pad the remainder with 0 before reshaping.

    .. math::

        remainder_0 = mat.shape[0] % m \\
        remainder_1 = mat.shape[1] % m

    Args:
238
        mat (nparray): The input 2D matrix.
239 240 241 242
        m (int): The square root of second dimension of reshaped matrix.
    Returns:
        tuple: A pair of the reshaped and padded matrix and the shape of padded matrix (non-reshaping).
    """
243 244
    assert len(mat.shape) == 2, "The input mat should be a 2D matrix!"

245 246 247
    remainder_0 = mat.shape[0] % m
    remainder_1 = mat.shape[1] % m

248 249 250 251
    new_shape = (
        mat.shape[0] if remainder_0 == 0 else mat.shape[0] + (m - remainder_0),
        mat.shape[1] if remainder_1 == 0 else mat.shape[1] + (m - remainder_1),
    )
252
    mat_padded = np.zeros(new_shape)
253
    mat_padded[: mat.shape[0], : mat.shape[1]] = mat
254 255 256 257 258 259 260

    mat_flattern = np.empty(new_shape).reshape(-1, m * m)
    curr_idx = 0
    for row_start in range(0, mat_padded.shape[0], m):
        row_end = row_start + m
        for col_start in range(0, mat_padded.shape[1], m):
            col_end = col_start + m
261 262 263
            sub_mat = np.squeeze(
                mat_padded[row_start:row_end, col_start:col_end].reshape(-1)
            )
264 265 266 267 268 269 270 271
            mat_flattern[curr_idx] = sub_mat
            curr_idx += 1
    return mat_flattern, mat_padded.shape


def check_mask_2d(mat, n, m):
    r"""
    Check if every :math:`m \times m` block of the input matrix :attr:`mat` is in 2D `n:m` sparse pattern.
272
    This function would pad each dimension of :attr:`mat` by zero to be a multiples of
273 274
    :attr:`m` if necessary.

275
    2D `n:m` sparse pattern: At least :math:`n \times n` zeros in every :math:`m \times m` block
276 277 278 279 280 281 282 283 284 285 286
    under the constraint of at least :attr:`n` zeros for each row and column.

    Args:
        mat (nparray): The input matrix.
        n (int): n of `n:m` sparse pattern.
        m (int): m of `n:m` sparse pattern.
    Returns:
        bool: True if  every :math:`m \times m` block of the input matrix :attr:`mat` is in 2D `n:m` sparse pattern, else False.
    Examples:
        .. code-block:: python

287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
          >>> import numpy as np
          >>> import paddle.incubate.asp as sparsity

          >>> x = np.array([[0, 8, 9, 0],
          ...               [9, 0, 0, 10],
          ...               [5, 0, 0, 6],
          ...               [0, 4, 6, 0]])
          >>> y = sparsity.check_mask_2d(x, 2, 4)
          >>> print(y)
          True

          >>> x = np.array([[0, 8, 0, 9],
          ...               [9, 0, 0, 10],
          ...               [0, 5, 0, 6],
          ...               [0, 4, 6, 0]])
          >>> y = sparsity.check_mask_2d(x, 2, 4)
          >>> print(y)
          True

          >>> # x would be padded to shape (8, 8)
          >>> x = np.array([[0, 8, 0, 9],
          ...               [9, 0, 7, 0],
          ...               [0, 5, 0, 6],
          ...               [3, 0, 6, 0],
          ...               [1, 1, 0, 1]])
          >>> y = sparsity.check_mask_2d(x, 2, 4)
          >>> print(y)
          True
315
    """
316
    mat_padded, shape = _reshape_2d(mat, m)
317 318
    for sub_mat in mat_padded:
        sub_mask = np.absolute(np.squeeze(sub_mat.reshape(m, m))) > 0
319 320 321
        if (np.sum(np.sum(sub_mask, axis=1) > (m - n)) != 0) and (
            np.sum(np.sum(sub_mask, axis=0) > (m - n)) != 0
        ):
322 323 324 325 326 327
            return False
    return True


def get_mask_2d_greedy(mat, n, m):
    r"""
328
    Greedily generate 2D `n:m` sparse pattern mask of the input matrix :attr:`mat`.
329 330
    This function would pad each dimension of :attr:`mat` by zero to be a multiples of :attr:`m` before mask generation.

331
    2D `n:m` sparse pattern: At least :math:`n \times n` zeros in every :math:`m \times m` block
332 333 334 335 336 337 338 339 340 341 342 343
    under the constraint of at least :attr:`n` zeros for each row and column.
    Greedily generating: For each :math:`m \times m` block, selecting values to keep in descent order.

    Args:
        mat (nparray): The input matrix.
        n (int): n of `n:m` sparse pattern.
        m (int): m of `n:m` sparse pattern.
    Returns:
        nparray: The 2D `n:m` sparse mask of :attr:`mat`.
    Examples:
        .. code-block:: python

344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
          >>> import numpy as np
          >>> import paddle.incubate.asp as sparsity

          >>> mat = np.array([[9, 8, 3, 7],
          ...                 [9, 2, 1, 10],
          ...                 [5, 1, 3, 6],
          ...                 [2, 4, 6, 1]])
          >>> mask = sparsity.get_mask_2d_greedy(mat, 2, 4)
          >>> print(mask)
          [[1. 1. 0. 0.]
          [1. 0. 0. 1.]
          [0. 0. 1. 1.]
          [0. 1. 1. 0.]]
          >>> y = sparsity.check_mask_2d(mask, 2, 4)
          >>> print(y)
          True
360
    """
361
    mat_padded, shape = _reshape_2d(mat, m)
362 363 364 365 366 367 368
    mask_padded = np.zeros_like(mat_padded).reshape(-1, m, m)

    for idx in range(len(mat_padded)):
        sub_mat = np.absolute(np.squeeze(mat_padded[idx]))
        sub_mask = np.squeeze(mask_padded[idx])

        min_order_1d_indices = np.argsort(sub_mat)
369 370 371
        min_order_2d_indices = [
            (int(x / m), x % m) for x in min_order_1d_indices
        ]
372 373 374 375 376
        row_counter = collections.Counter()
        col_counter = collections.Counter()

        for i in range(len(min_order_1d_indices) - 1, -1, -1):
            matrix_entry = min_order_2d_indices[i]
377 378 379
            if (row_counter[matrix_entry[0]] == n) or (
                col_counter[matrix_entry[1]] == n
            ):
380 381 382 383 384 385 386 387 388 389 390 391 392 393
                continue

            sub_mask[matrix_entry[0], matrix_entry[1]] = 1.0
            row_counter[matrix_entry[0]] += 1
            col_counter[matrix_entry[1]] += 1

    mask = np.empty(shape)
    curr_idx = 0
    for row_start in range(0, shape[0], m):
        row_end = row_start + m
        for col_start in range(0, shape[1], m):
            col_end = col_start + m
            mask[row_start:row_end, col_start:col_end] = mask_padded[curr_idx]
            curr_idx += 1
394
    return mask[: mat.shape[0], : mat.shape[1]]
395 396


397 398
_valid_2d_patterns_lock = threading.Lock()
_valid_2d_patterns = {}
399 400


401
def _compute_valid_2d_patterns(n, m):
402 403 404
    r"""
    Compute all vaild 2D `n:m` sparse patterns.

405
    2D `n:m` sparse pattern: At least :math:`n \times n` zeros in every :math:`m \times m` block
406 407 408 409 410 411 412 413
    under the constraint of at least :attr:`n` zeros for each row and column.

    Args:
        n (int): n of `n:m` sparse pattern.
        m (int): m of `n:m` sparse pattern.
    Returns:
        dictionary: A dictionary with key: *m_n* (string) and value: all vaild 2D `n:m` sparse patterns.
    """
414 415
    global _valid_2d_patterns_lock
    global _valid_2d_patterns
416

417
    valid_key = f'{m}_{n}'
418 419
    if valid_key in _valid_2d_patterns:
        return _valid_2d_patterns[valid_key]
420 421 422 423 424 425 426
    else:
        patterns = np.zeros(m)
        patterns[:n] = 1
        patterns = list(set(permutations(patterns.tolist())))
        patterns = patterns + patterns
        patterns = np.asarray(list(set(permutations(patterns, m))))

427 428 429 430 431
        valid = (
            ((patterns.sum(axis=1) <= n).sum(axis=1) == m)
            .nonzero()[0]
            .reshape(-1)
        )
432 433 434
        valid_patterns = np.empty((valid.shape[0], m, m))
        valid_patterns[:] = patterns[valid[:]]

435 436 437
        _valid_2d_patterns_lock.acquire()
        _valid_2d_patterns[valid_key] = valid_patterns
        _valid_2d_patterns_lock.release()
438 439 440 441 442 443

        return valid_patterns


def get_mask_2d_best(mat, n, m):
    r"""
444 445
    Generate 2D `n:m` sparse pattern mask of the input matrix :attr:`mat`
    to form sparse matrix with maximun L1 norm .This function would pad each
446 447
    dimension of :attr:`mat` by zero to be a multiples of :attr:`m` before mask generation.

448
    2D `n:m` sparse pattern: At least :math:`n \times n` zeros in every :math:`m \times m` block
449 450 451 452 453 454 455 456 457 458 459 460 461
    under the constraint of at least :attr:`n` zeros for each row and column.

    *Note*: L1 norm of sparse matrix from `Best` API is greater than or equal to the one from `Greedy`.

    Args:
        mat (nparray): The input matrix.
        n (int): n of `n:m` sparse pattern.
        m (int): m of `n:m` sparse pattern.
    Returns:
        nparray: The 1D `n:m` sparse mask of :attr:`mat`.
    Examples:
        .. code-block:: python

462 463 464 465 466 467 468 469 470 471 472 473 474
          >>> import numpy as np
          >>> import paddle.incubate.asp as sparsity

          >>> mat = np.array([[2, 8, 9, 9],
          ...                 [9, 1, 3, 9],
          ...                 [5, 6, 3, 9],
          ...                 [2, 4, 6, 9]])
          >>> mask_greedy = sparsity.get_mask_2d_greedy(mat, 2, 4)
          >>> mask_best = sparsity.get_mask_2d_best(mat, 2, 4)
          >>> print("L1 norm of `greedy` sparse matrix", np.multiply(mat, mask_greedy).sum())
          L1 norm of `greedy` sparse matrix 56.0
          >>> print("L1 norm of `best` sparse matrix", np.multiply(mat, mask_best).sum())
          L1 norm of `best` sparse matrix 61.0
475
    """
476
    patterns = _compute_valid_2d_patterns(n, m)
477

478
    mat_flattern, shape = _reshape_2d(mat, m)
479
    mask_flattern = np.ones_like(mat_flattern).reshape(-1, m, m)
480 481 482 483
    pmax = np.argmax(
        np.matmul(mat_flattern, patterns.reshape(patterns.shape[0], m * m).T),
        axis=1,
    )
484 485 486 487 488 489 490 491 492 493 494

    mask_flattern[:] = patterns[pmax[:]]
    mask = np.empty(shape)

    curr_idx = 0
    for row_start in range(0, shape[0], m):
        row_end = row_start + m
        for col_start in range(0, shape[1], m):
            col_end = col_start + m
            mask[row_start:row_end, col_start:col_end] = mask_flattern[curr_idx]
            curr_idx += 1
495
    return mask[: mat.shape[0], : mat.shape[1]]
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512


def create_mask(tensor, func_name=MaskAlgo.MASK_1D, n=2, m=4):
    r"""
    Create `n:m` sparse pattern mask of the input tensor via function given by :attr:`func_name`.
    Currently only support tensor with dimension less than or equal to 4.

    Args:
        tensor (nparray): The input tensor.
        func_name (MaskAlgo, optional): The function name to generate spase mask. Default is `MaskAlgo.MASK_1D`. All options please refer to `MaskAlgo`.
        n (int, optional): n of `n:m` sparse pattern. Default is 2.
        m (int, optional): m of `n:m` sparse pattern. Default is 4.
    Returns:
        nparray: The `n:m` sparse mask of :attr:`tensor` generated by :attr:`func_name`.
    Examples:
        .. code-block:: python

513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
          >>> import numpy as np
          >>> import paddle.incubate.asp as sparsity

          >>> tensor = np.array([[2, 8, 9, 9],
          ...                    [9, 1, 3, 9],
          ...                    [5, 6, 3, 9],
          ...                    [2, 4, 6, 9]])
          >>> mask_1d = sparsity.create_mask(tensor, func_name=sparsity.MaskAlgo.MASK_1D)
          >>> print(mask_1d)
          [[0 0 1 1]
          [1 0 0 1]
          [0 1 0 1]
          [0 0 1 1]]
          >>> mask_2d = sparsity.create_mask(tensor, func_name=sparsity.MaskAlgo.MASK_2D_BEST)
          >>> print(mask_2d)
          [[0 1 1 0]
          [1 0 0 1]
          [1 1 0 0]
          [0 0 1 1]]
532 533 534 535 536
    """
    shape = tensor.shape
    dtype = tensor.dtype
    t = tensor.astype(float)

537 538 539 540
    assert isinstance(func_name, MaskAlgo), (
        "func_name argumet of create_mask is only accepted as type MaskAlgo. "
        "But got {}".format(type(func_name))
    )
541 542 543 544 545 546 547
    func = getattr(sys.modules[__name__], func_name.value, None)
    if len(shape) == 1:
        t = t.reshape(1, shape[0])
    elif len(shape) == 2:
        t = t.reshape(shape[0], shape[1])
    elif len(shape) == 3:
        t = t.reshape(shape[0] * shape[1], shape[2])
548
    # 4d-tensor conv (h, w, in, out) -> (h*w*out, in) in GemmConvKernel Op
549
    elif len(shape) == 4:
550 551 552
        t = t.transpose([0, 1, 3, 2]).reshape(
            shape[0] * shape[1] * shape[3], shape[2]
        )
553
        mask = func(t, n=n, m=m)
554 555 556 557 558
        return (
            mask.reshape([shape[0], shape[1], shape[3], shape[2]])
            .transpose([0, 1, 3, 2])
            .astype(dtype)
        )
559
    else:
560 561 562 563
        raise ValueError(
            "The dimension of input tensor is not supported in create_mask, "
            "Only dimension < 4 is supported but got {}".format(len(shape))
        )
564 565 566

    mask = func(t, n=n, m=m)
    return mask.reshape(shape).astype(dtype)
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583


def check_sparsity(tensor, func_name=CheckMethod.CHECK_1D, n=2, m=4):
    r"""
    Check if input tensor is in `n:m` sparse pattern via function given by :attr:`func_name`.
    Currently only support tensor with dimension less than or equal to 4.

    Args:
        tensor (nparray): The input tensor.
        func_name (CheckMethod, optional): The function name to generate spase mask. Default is `CheckMethod.CHECK_1D`. All options please refer to `CheckMethod`.
        n (int, optional): n of `n:m` sparse pattern. Default is 2.
        m (int, optional): m of `n:m` sparse pattern. Default is 4.
    Returns:
        bool: True if tensor pass checking of function given by :attr:`func_name`, else False.
    Examples:
        .. code-block:: python

584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
          >>> import numpy as np
          >>> import paddle.incubate.asp as sparsity

          >>> tensor = np.array([[2, 8, 9, 9],
          ...                    [9, 1, 3, 9],
          ...                    [5, 6, 3, 9],
          ...                    [2, 4, 6, 9]])
          >>> mask_1d = sparsity.create_mask(tensor, func_name=sparsity.MaskAlgo.MASK_1D)
          >>> print(mask_1d)
          [[0 0 1 1]
          [1 0 0 1]
          [0 1 0 1]
          [0 0 1 1]]
          >>> y = sparsity.check_sparsity(mask_1d, func_name=sparsity.CheckMethod.CHECK_1D)
          >>> print(y)
          True
          >>> y = sparsity.check_sparsity(mask_1d, func_name=sparsity.CheckMethod.CHECK_2D)
          >>> print(y)
          True
603 604 605 606
    """
    shape = tensor.shape
    t = tensor.astype(float)

607 608 609 610
    assert type(func_name) == CheckMethod, (
        "func_name argumet of check_sparsity is only accepted as type CheckMethod. "
        "But got {}".format(type(func_name))
    )
611 612 613 614 615 616 617
    func = getattr(sys.modules[__name__], func_name.value, None)
    if len(shape) == 1:
        t = t.reshape(1, shape[0])
    elif len(shape) == 2:
        t = t.reshape(shape[0], shape[1])
    elif len(shape) == 3:
        t = t.reshape(shape[0] * shape[1], shape[2])
618
    # 4d-tensor conv (h, w, in, out) -> (h*w*out, in) in GemmConvKernel Op
619
    elif len(shape) == 4:
620 621 622
        t = t.transpose([0, 1, 3, 2]).reshape(
            [shape[0] * shape[1] * shape[3], shape[2]]
        )
623
    else:
624 625 626 627
        raise ValueError(
            "The dimension of input tensor is not supported in create_mask, "
            "Only dimension < 4 is supported but got {}".format(len(shape))
        )
628

629
    return func(t, n=n, m=m)