|
| 1 | +# Copyright (c) 2024 Intel Corporation |
| 2 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +# you may not use this file except in compliance with the License. |
| 4 | +# You may obtain a copy of the License at |
| 5 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | +# Unless required by applicable law or agreed to in writing, software |
| 7 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 8 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 9 | +# See the License for the specific language governing permissions and |
| 10 | +# limitations under the License. |
| 11 | + |
| 12 | +import functools |
| 13 | +from typing import Optional, Tuple, Union |
| 14 | + |
| 15 | +from nncf.experimental.tensor import Tensor |
| 16 | +from nncf.experimental.tensor.functions.dispatcher import tensor_guard |
| 17 | + |
| 18 | + |
| 19 | +@functools.singledispatch |
| 20 | +@tensor_guard |
| 21 | +def norm( |
| 22 | + a: Tensor, |
| 23 | + ord: Optional[Union[str, float, int]] = None, |
| 24 | + axis: Optional[Union[int, Tuple[int, ...]]] = None, |
| 25 | + keepdims: bool = False, |
| 26 | +) -> Tensor: |
| 27 | + """ |
| 28 | + Computes a vector or matrix norm. |
| 29 | +
|
| 30 | + The following norms can be calculated: |
| 31 | +
|
| 32 | + ===== ============================ ========================== |
| 33 | + ord norm for matrices norm for vectors |
| 34 | + ===== ============================ ========================== |
| 35 | + None Frobenius norm 2-norm |
| 36 | + 'fro' Frobenius norm -- |
| 37 | + 'nuc' nuclear norm -- |
| 38 | + inf max(sum(abs(x), axis=1)) max(abs(x)) |
| 39 | + -inf min(sum(abs(x), axis=1)) min(abs(x)) |
| 40 | + 0 -- sum(x != 0) |
| 41 | + 1 max(sum(abs(x), axis=0)) as below |
| 42 | + -1 min(sum(abs(x), axis=0)) as below |
| 43 | + 2 2-norm (largest sing. value) as below |
| 44 | + -2 smallest singular value as below |
| 45 | + other -- sum(abs(x)**ord)**(1./ord) |
| 46 | + ===== ============================ ========================== |
| 47 | +
|
| 48 | + The Frobenius norm is given by [1]_: |
| 49 | +
|
| 50 | + :math:`||A||_F = [\\sum_{i,j} abs(a_{i,j})^2]^{1/2}` |
| 51 | +
|
| 52 | + The nuclear norm is the sum of the singular values. |
| 53 | +
|
| 54 | + Both the Frobenius and nuclear norm orders are only defined for |
| 55 | + matrices and otherwise raise a ValueError. |
| 56 | +
|
| 57 | + :param a: The input tensor. |
| 58 | + :param ord: Order of norm. Default: None. |
| 59 | + :param axis: Axis over which to compute the vector or matrix norm. Default: None. |
| 60 | + :param keepdims: If set to True, the reduced dimensions are retained in the result |
| 61 | + as dimensions with size one. Default: False. |
| 62 | + :return: Norm of the matrix or vector. |
| 63 | + """ |
| 64 | + return Tensor(norm(a.data, ord, axis, keepdims)) |
0 commit comments