/
sparse.py
214 lines (185 loc) · 7.5 KB
/
sparse.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
import numpy
import chainer
from chainer import backend
from chainer import cuda
def _add_at(add_at, x, row, col, data):
assert data.size > 0
last_nz = data.size - (data != 0)[::-1].argmax()
add_at(x, (row[:last_nz], col[:last_nz]), data[:last_nz])
class CooMatrix(object):
"""A sparse matrix in COO format.
Args:
data (:ref:`ndarray`): The entries of the matrix.
The entries are usually non-zero-elements in the matrix.
row (:ref:`ndarray`): The row indices of the matrix
entries.
col (:ref:`ndarray`): The column indices of the matrix
entries.
shape (tuple of int): The shape of the matrix in dense format.
order ('C', 'F', 'other' or None): If ``'C'``, the maxtix is assumed
that its row indices are sorted. If ``'F'``, the matrix is assumed
that its column indices are sorted. If ``'other'``, the matrix is
assumed as neither 'C' order nor 'F' order. If ``None`` (this is
the default), the matrix is automatically checked if it is 'C'
order, 'F' order or another. This information will be used by some
functions like :func:`~chainer.functions.sparse_matmul` as a hint
to improve performance.
requires_grad (bool): If ``True``, gradient of this sparse matrix will
be computed in back-propagation.
.. seealso::
See :func:`~chainer.utils.to_coo` for how to construct a COO matrix
from an array.
"""
def __init__(self, data, row, col, shape, order=None,
requires_grad=False):
if not (1 <= data.ndim <= 2):
raise ValueError('ndim of data must be 1 or 2.')
if not (data.ndim == row.ndim == col.ndim):
raise ValueError('ndim of data, row and col must be the same.')
if len(shape) != 2:
raise ValueError('length of shape must be 2.')
if not (shape[0] > 0 and shape[1] > 0):
raise ValueError('numbers in shape must be greater than 0.')
if order not in ('C', 'F', 'other', None):
raise ValueError('order must be \'C\', \'F\', \'other\' or None.')
self.data = chainer.Variable(data, requires_grad=requires_grad)
self.row = row
self.col = col
self.shape = shape # (row, col)
self.order = order
if order is None:
self.order = get_order(row, col)
def to_dense(self):
"""Returns a dense matrix format of this sparse matrix."""
data = self.data
if data.ndim == 1:
shape = self.shape
elif data.ndim == 2:
shape = (data.shape[0], *self.shape)
else:
assert False
xp = data.xp
x = xp.zeros(shape, dtype=data.dtype)
if data.size > 0:
row = self.row
col = self.col
if xp is numpy:
add_at = numpy.add.at
elif xp is cuda.cupy:
add_at = cuda.cupyx.scatter_add
data = data.array
if data.ndim == 1:
_add_at(add_at, x, row, col, data)
elif data.ndim == 2:
for i in range(data.shape[0]):
_add_at(add_at, x[i], row[i], col[i], data[i])
else:
assert False
return x
def to_coo(x, ldnz=None, requires_grad=False):
"""Returns a single or a batch of matrices in COO format.
Args:
x (:ref:`ndarray`): Input dense matrix. The ndim of
``x`` must be two or three. If ndim is two, it is treated as
a single matrix. If three, it is treated as batched matrices.
ldnz (int): Size of arrays for data, row index and column index to be
created. The Actual size becomes max(nnz, ldnz) where nnz is number
of non-zero elements in a input dense matrix.
requires_grad (bool): If ``True``, gradient of sparse matrix will be
computed in back-propagation.
Returns:
~chainer.utils.CooMatrix: A sparse matrix or batched sparse matrices
in COO format of a given dense matrix or batched dense matrices.
.. admonition:: Example
Create a :class:`~chainer.utils.CooMatrix` from an array with 2
non-zero elements and 4 zeros and access its attributes. No batch
dimension is involved.
.. doctest::
>>> data = np.array([[0, 2, 0], [-1, 0, 0]], np.float32)
>>> x = chainer.utils.to_coo(data)
>>> x.data
variable([ 2., -1.])
>>> x.row
array([0, 1], dtype=int32)
>>> x.col
array([1, 0], dtype=int32)
>>> x.shape
(2, 3)
"""
xp = backend.get_array_module(x)
if x.ndim == 2:
_row, _col = xp.where(x != 0)
nnz = len(_row)
if ldnz is None or ldnz < nnz:
ldnz = nnz
data = xp.zeros((ldnz), dtype=x.dtype)
row = xp.full((ldnz), -1, dtype=xp.int32)
col = xp.full((ldnz), -1, dtype=xp.int32)
data[:nnz] = x[_row, _col]
row[:nnz] = xp.array(_row).astype(xp.int32)
col[:nnz] = xp.array(_col).astype(xp.int32)
shape = x.shape
return CooMatrix(data, row, col, shape,
requires_grad=requires_grad)
elif x.ndim == 3:
# first axis is batch axis
nb = x.shape[0]
if ldnz is None:
ldnz = 0
for i in range(nb):
ldnz = max(ldnz, len(xp.where(x[i] != 0)[0]))
data = xp.empty((nb, ldnz), dtype=x.dtype)
row = xp.empty((nb, ldnz), dtype=xp.int32)
col = xp.empty((nb, ldnz), dtype=xp.int32)
for i in range(nb):
coo = to_coo(x[i], ldnz)
data[i] = coo.data.data
row[i] = coo.row
col[i] = coo.col
shape = x.shape[1:]
return CooMatrix(data, row, col, shape,
requires_grad=requires_grad)
else:
raise ValueError('ndim of x must be 2 or 3.')
def get_order(row, col):
"""Check if a coo matrix with given row and col is C or F order.
Args:
row (:ref:`ndarray`): The row indices of the matrix
entries.
col (:ref:`ndarray`): The column indices of the matrix
entries.
Returns:
Returns ``'C'`` when a coo matrix with given row and column indices is
C order, in other words, the row indices are sorted. Returns ``'F'``
when it is F order, in other words, the column indices are sorted.
Returns ``'other'`` otherwise.
"""
if _is_c_order(row, col):
return 'C'
if _is_c_order(col, row):
return 'F'
return 'other'
def _is_c_order(row, col):
"""Check if a coo matrix with given row and col is c_order"""
if row.shape != col.shape:
raise ValueError('shape of row and col must be the same.')
if row.ndim != 1:
for i in range(row.shape[0]):
if not _is_c_order(row[i], col[i]):
return False
return True
xp = backend.get_array_module(row)
_row = row[col >= 0]
_col = col[row >= 0]
if _row[_row < 0].size > 0 or _col[_col < 0].size:
raise ValueError('invalid index combination of row and col.')
if _row.shape[0] <= 1:
return True
row_diff = xp.zeros(_row.shape, dtype=_row.dtype)
row_diff[1:] = _row[1:] - _row[:-1]
if xp.amin(row_diff) < 0:
return False
col_diff = xp.zeros(_col.shape, dtype=_col.dtype)
col_diff[1:] = _col[1:] - _col[:-1]
col_diff[(row_diff > 0)] = 0
return xp.amin(col_diff) >= 0