/
norms.py
299 lines (249 loc) · 9.72 KB
/
norms.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import numpy
from numpy import linalg
import cupy
from cupy.cuda import cusolver
from cupy.cuda import device
from cupy.linalg import decomposition
from cupy.linalg import util
def norm(x, ord=None, axis=None, keepdims=False):
"""Returns one of matrix norms specified by ``ord`` parameter.
See numpy.linalg.norm for more detail.
Args:
x (cupy.ndarray): Array to take norm. If ``axis`` is None,
``x`` must be 1-D or 2-D.
ord (non-zero int, inf, -inf, 'fro'): Norm type.
axis (int, 2-tuple of ints, None): 1-D or 2-D norm is cumputed over
``axis``.
keepdims (bool): If this is set ``True``, the axes which are normed
over are left.
Returns:
cupy.ndarray
"""
if not issubclass(x.dtype.type, numpy.inexact):
x = x.astype(float)
# Immediately handle some default, simple, fast, and common cases.
if axis is None:
ndim = x.ndim
if (ord is None or (ndim == 1 and ord == 2) or
(ndim == 2 and ord in ('f', 'fro'))):
if x.dtype.kind == 'c':
s = abs(x.ravel())
s *= s
ret = cupy.sqrt(s.sum())
else:
ret = cupy.sqrt((x * x).sum())
if keepdims:
ret = ret.reshape((1,) * ndim)
return ret
# Normalize the `axis` argument to a tuple.
nd = x.ndim
if axis is None:
axis = tuple(range(nd))
elif not isinstance(axis, tuple):
try:
axis = int(axis)
except Exception:
raise TypeError(
'\'axis\' must be None, an integer or a tuple of integers')
axis = (axis,)
if len(axis) == 1:
if ord == numpy.Inf:
return abs(x).max(axis=axis, keepdims=keepdims)
elif ord == -numpy.Inf:
return abs(x).min(axis=axis, keepdims=keepdims)
elif ord == 0:
# Zero norm
# Convert to Python float in accordance with NumPy
return (x != 0).astype(x.real.dtype).sum(
axis=axis, keepdims=keepdims)
elif ord == 1:
# special case for speedup
return abs(x).sum(axis=axis, keepdims=keepdims)
elif ord is None or ord == 2:
# special case for speedup
if x.dtype.kind == 'c':
s = abs(x)
s *= s
else:
s = x * x
return cupy.sqrt(s.sum(axis=axis, keepdims=keepdims))
else:
try:
float(ord)
except TypeError:
raise ValueError('Invalid norm order for vectors.')
absx = abs(x)
absx **= ord
ret = absx.sum(axis=axis, keepdims=keepdims)
ret **= cupy.reciprocal(ord, dtype=ret.dtype)
return ret
elif len(axis) == 2:
row_axis, col_axis = axis
if row_axis < 0:
row_axis += nd
if col_axis < 0:
col_axis += nd
if not (0 <= row_axis < nd and 0 <= col_axis < nd):
raise ValueError('Invalid axis %r for an array with shape %r' %
(axis, x.shape))
if row_axis == col_axis:
raise ValueError('Duplicate axes given.')
if ord == 1:
if col_axis > row_axis:
col_axis -= 1
ret = abs(x).sum(axis=row_axis).max(axis=col_axis)
elif ord == numpy.Inf:
if row_axis > col_axis:
row_axis -= 1
ret = abs(x).sum(axis=col_axis).max(axis=row_axis)
elif ord == -1:
if col_axis > row_axis:
col_axis -= 1
ret = abs(x).sum(axis=row_axis).min(axis=col_axis)
elif ord == -numpy.Inf:
if row_axis > col_axis:
row_axis -= 1
ret = abs(x).sum(axis=col_axis).min(axis=row_axis)
elif ord in [None, 'fro', 'f']:
if x.dtype.kind == 'c':
s = abs(x)
s *= s
ret = cupy.sqrt(s.sum(axis=axis))
else:
ret = cupy.sqrt((x * x).sum(axis=axis))
else:
raise ValueError('Invalid norm order for matrices.')
if keepdims:
ret_shape = list(x.shape)
ret_shape[axis[0]] = 1
ret_shape[axis[1]] = 1
ret = ret.reshape(ret_shape)
return ret
else:
raise ValueError('Improper number of dimensions to norm.')
# TODO(okuta): Implement cond
def det(a):
"""Retruns the deteminant of an array.
Args:
a (cupy.ndarray): The input matrix with dimension ``(..., N, N)``.
Returns:
cupy.ndarray: Determinant of ``a``. Its shape is ``a.shape[:-2]``.
.. seealso:: :func:`numpy.linalg.det`
"""
sign, logdet = slogdet(a)
return sign * cupy.exp(logdet)
def matrix_rank(M, tol=None):
"""Return matrix rank of array using SVD method
Args:
M (cupy.ndarray): Input array. Its `ndim` must be less than or equal to
2.
tol (None or float): Threshold of singular value of `M`.
When `tol` is `None`, and `eps` is the epsilon value for datatype
of `M`, then `tol` is set to `S.max() * max(M.shape) * eps`,
where `S` is the singular value of `M`.
It obeys :func:`numpy.linalg.matrix_rank`.
Returns:
cupy.ndarray: Rank of `M`.
.. seealso:: :func:`numpy.linalg.matrix_rank`
"""
if M.ndim < 2:
return (M != 0).any().astype(int)
S = decomposition.svd(M, compute_uv=False)
if tol is None:
tol = (S.max(axis=-1, keepdims=True) * max(M.shape[-2:]) *
numpy.finfo(S.dtype).eps)
return (S > tol).sum(axis=-1, dtype=numpy.intp)
def slogdet(a):
"""Returns sign and logarithm of the determinant of an array.
It calculates the natural logarithm of the determinant of a given value.
Args:
a (cupy.ndarray): The input matrix with dimension ``(..., N, N)``.
Returns:
tuple of :class:`~cupy.ndarray`:
It returns a tuple ``(sign, logdet)``. ``sign`` represents each
sign of the determinant as a real number ``0``, ``1`` or ``-1``.
'logdet' represents the natural logarithm of the absolute of the
determinant.
If the determinant is zero, ``sign`` will be ``0`` and ``logdet``
will be ``-inf``.
The shapes of both ``sign`` and ``logdet`` are equal to
``a.shape[:-2]``.
.. warning::
This function calls one or more cuSOLVER routine(s) which may yield
invalid results if input conditions are not met.
To detect these invalid results, you can set the `linalg`
configuration to a value that is not `ignore` in
:func:`cupyx.errstate` or :func:`cupyx.seterr`.
.. warning::
To produce the same results as :func:`numpy.linalg.slogdet` for
singular inputs, set the `linalg` configuration to `raise`.
.. seealso:: :func:`numpy.linalg.slogdet`
"""
if a.ndim < 2:
msg = ('%d-dimensional array given. '
'Array must be at least two-dimensional' % a.ndim)
raise linalg.LinAlgError(msg)
dtype = numpy.promote_types(a.dtype.char, 'f')
shape = a.shape[:-2]
sign = cupy.empty(shape, dtype)
logdet = cupy.empty(shape, dtype)
a = a.astype(dtype)
for index in numpy.ndindex(*shape):
s, logd = _slogdet_one(a[index])
sign[index] = s
logdet[index] = logd
return sign, logdet
def _slogdet_one(a):
util._assert_rank2(a)
util._assert_nd_squareness(a)
dtype = a.dtype
handle = device.get_cusolver_handle()
m = len(a)
ipiv = cupy.empty(m, dtype=numpy.int32)
dev_info = cupy.empty((), dtype=numpy.int32)
# Need to make a copy because getrf works inplace
a_copy = a.copy(order='F')
if dtype == 'f':
getrf_bufferSize = cusolver.sgetrf_bufferSize
getrf = cusolver.sgetrf
else:
getrf_bufferSize = cusolver.dgetrf_bufferSize
getrf = cusolver.dgetrf
buffersize = getrf_bufferSize(handle, m, m, a_copy.data.ptr, m)
workspace = cupy.empty(buffersize, dtype=dtype)
getrf(handle, m, m, a_copy.data.ptr, m, workspace.data.ptr,
ipiv.data.ptr, dev_info.data.ptr)
# dev_info < 0 means illegal value (in dimensions, strides, and etc.) that
# should never happen even if the matrix contains nan or inf.
# TODO(kataoka): assert dev_info >= 0 if synchronization is allowed for
# debugging purposes.
diag = cupy.diag(a_copy)
# ipiv is 1-origin
non_zero = (cupy.count_nonzero(ipiv != cupy.arange(1, m + 1)) +
cupy.count_nonzero(diag < 0))
# Note: sign == -1 ** (non_zero % 2)
sign = (non_zero % 2) * -2 + 1
logdet = cupy.log(abs(diag)).sum()
singular = dev_info > 0
return (
cupy.where(singular, dtype.type(0), sign),
cupy.where(singular, dtype.type('-inf'), logdet),
)
def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
"""Returns the sum along the diagonals of an array.
It computes the sum along the diagonals at ``axis1`` and ``axis2``.
Args:
a (cupy.ndarray): Array to take trace.
offset (int): Index of diagonals. Zero indicates the main diagonal, a
positive value an upper diagonal, and a negative value a lower
diagonal.
axis1 (int): The first axis along which the trace is taken.
axis2 (int): The second axis along which the trace is taken.
dtype: Data type specifier of the output.
out (cupy.ndarray): Output array.
Returns:
cupy.ndarray: The trace of ``a`` along axes ``(axis1, axis2)``.
.. seealso:: :func:`numpy.trace`
"""
# TODO(okuta): check type
return a.trace(offset, axis1, axis2, dtype, out)