/
matmul.py
276 lines (217 loc) · 8.65 KB
/
matmul.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
import warnings
import numpy
from chainer.backends import cuda
from chainer import function_node
from chainer import utils
from chainer.utils import type_check
def _mat_ptrs(a):
"""Creates an array of pointers to matrices
Args:
a: A batch of matrices on GPU.
Returns:
GPU array of pointers to matrices.
"""
if len(a) == 1:
return cuda.cupy.full((1,), a.data.ptr, dtype=numpy.uintp)
else:
stride = a.strides[0]
ptr = a.data.ptr
return cuda.cupy.arange(ptr, ptr + stride * len(a), stride,
dtype=numpy.uintp)
def _as_batch_mat(x):
return x.reshape(len(x), x.shape[1], -1)
def _get_ld(a):
strides = a.strides[-2:]
trans = numpy.argmin(strides)
return trans, int(max(a.shape[trans - 2], max(strides) // a.itemsize))
def _matmul(a, b, transa=False, transb=False, transout=False):
if transout:
transa, transb = not transb, not transa
a, b = b, a
if transa and a.ndim != 1:
a = a.swapaxes(-1, -2)
if transb and b.ndim != 1:
b = b.swapaxes(-1, -2)
xp = cuda.get_array_module(a)
if hasattr(xp, 'matmul'): # numpy.matmul is supported from version 1.10.0
return xp.matmul(a, b)
if a.ndim <= 2:
return numpy.dot(a, b)
else:
return numpy.einsum('...ij,...jk->...ik', a, b)
def _check_ndim(in_type, lower=1, upper=2):
type_check.expect(
in_type.ndim >= lower,
in_type.ndim <= upper
)
def _get_check_index(trans, right, row_idx=0, col_idx=1):
if trans ^ right:
return row_idx
else:
return col_idx
class MatMul(function_node.FunctionNode):
def __init__(self, transa=False, transb=False, transc=False, dtype=None):
self.transa = transa
self.transb = transb
self.transc = transc
self.dtype = dtype
def check_type_forward(self, in_types):
type_check.expect(in_types.size() == 2)
a_type, b_type = in_types
type_check.expect(
a_type.dtype.kind == 'f',
b_type.dtype.kind == 'f',
)
a_ndim = type_check.eval(a_type.ndim)
b_ndim = type_check.eval(b_type.ndim)
if a_ndim == 0 or b_ndim == 0:
pass
elif a_ndim == 1 or b_ndim == 1:
type_check.expect(
a_type.ndim == b_type.ndim,
a_type.shape == b_type.shape,
)
else:
a_idx = _get_check_index(self.transa, False,
row_idx=-2, col_idx=-1)
b_idx = _get_check_index(self.transb, True,
row_idx=-2, col_idx=-1)
type_check.expect(
a_type.ndim == b_type.ndim,
a_type.shape[:-2] == b_type.shape[:-2],
a_type.shape[a_idx] == b_type.shape[b_idx],
)
def forward(self, x):
self.retain_inputs((0, 1))
a, b = x
if a.ndim == 0 or b.ndim == 0:
y = a * b
else:
y = _matmul(a, b, self.transa, self.transb, self.transc)
if self.dtype is not None and y.dtype != self.dtype:
y = y.astype(self.dtype)
return utils.force_array(y),
def backward(self, indexes, grad_outputs):
a, b = self.get_retained_inputs()
gy, = grad_outputs
ga = None
if 0 in indexes:
ga, = MatMul(self.transc, not self.transb, self.transa,
a.dtype).apply((gy, b))
gb = None
if 1 in indexes:
gb, = MatMul(not self.transa, self.transc, self.transb,
b.dtype).apply((a, gy))
return ga, gb
def matmul(a, b, transa=False, transb=False):
"""Computes the matrix multiplication of two arrays.
Args:
a (Variable): The left operand of the matrix multiplication.
If ``a`` and ``b`` are both 1-D arrays, ``matmul`` returns a dot
product of vector `a` and vector `b`. If 2-D arrays, ``matmul``
returns matrix product of ``a`` and ``b``. If arrays' dimension is
larger than 2, they are treated as a stack of matrices residing in
the last two indexes. ``matmul`` returns a stack of each two
arrays. ``a`` and ``b`` must have the same dimension.
b (Variable): The right operand of the matrix multiplication.
Its array is treated as a matrix in the same way as ``a``'s array.
transa (bool): If ``True``, each matrices in ``a`` will be transposed.
If ``a.ndim == 1``, do nothing.
transb (bool): If ``True``, each matrices in ``b`` will be transposed.
If ``b.ndim == 1``, do nothing.
Returns:
~chainer.Variable: The result of the matrix multiplication.
.. admonition:: Example
>>> a = np.array([[1, 0], [0, 1]], np.float32)
>>> b = np.array([[4, 1], [2, 2]], np.float32)
>>> F.matmul(a, b).data
array([[4., 1.],
[2., 2.]], dtype=float32)
"""
return MatMul(transa=transa, transb=transb).apply((a, b))[0]
def _get_size(typ, index):
if index == 2 and type_check.eval(typ.ndim) == 2:
return 1
else:
return typ.shape[index]
def _batch_matmul(a, b, transa, transb, transout):
a = a.reshape(a.shape[:2] + (-1,))
b = b.reshape(b.shape[:2] + (-1,))
return _matmul(a, b, transa, transb, transout)
class BatchMatMul(function_node.FunctionNode):
def __init__(self, transa=False, transb=False):
self.transa = transa
self.transb = transb
def check_type_forward(self, in_types):
type_check.expect(in_types.size() == 2)
a_type, b_type = in_types
type_check.expect(
a_type.dtype == numpy.float32,
b_type.dtype == numpy.float32
)
_check_ndim(a_type, lower=2, upper=3)
_check_ndim(b_type, lower=2, upper=3)
a_idx = _get_check_index(self.transa, False, row_idx=1, col_idx=2)
b_idx = _get_check_index(self.transb, True, row_idx=1, col_idx=2)
a_size = _get_size(a_type, a_idx)
b_size = _get_size(b_type, b_idx)
type_check.expect(
a_size == b_size
)
def forward(self, x):
self.retain_inputs((0, 1))
a, b = x
return _batch_matmul(a, b, self.transa, self.transb, False),
def backward(self, indexes, grad_outputs):
a, b = self.get_retained_inputs()
return BatchMatMulGrad(self.transa, self.transb).apply(
(a, b, grad_outputs[0]))
class BatchMatMulGrad(function_node.FunctionNode):
def __init__(self, transa=False, transb=False):
self.transa = transa
self.transb = transb
def forward(self, inputs):
self.retain_inputs((0, 1, 2))
a, b, gy = inputs
ga = _batch_matmul(gy, b, False, not self.transb,
self.transa).reshape(a.shape)
gb = _batch_matmul(a, gy, not self.transa, False,
self.transb).reshape(b.shape)
return ga, gb
def backward(self, indexes, grad_outputs):
a, b, gy = self.get_retained_inputs()
gga, ggb = grad_outputs
ret = []
if 0 in indexes or 1 in indexes:
ga, gb = BatchMatMulGrad(self.transa, self.transb).apply(
(gga, ggb, gy))
if 0 in indexes:
ret.append(ga)
if 1 in indexes:
ret.append(gb)
if 2 in indexes:
ret.append(
BatchMatMul(self.transa, self.transb).apply((gga, b))[0] +
BatchMatMul(self.transa, self.transb).apply((a, ggb))[0])
return ret
def batch_matmul(a, b, transa=False, transb=False):
"""Computes the batch matrix multiplications of two sets of arrays.
Args:
a (Variable): The left operand of the batch matrix multiplications.
A 2-D array of shape ``(B, N)`` is considered as B
:math:`N \\times 1` matrices.
A 3-D array of shape ``(B, M, N)`` is considered as B
:math:`M \\times N` matrices.
b (Variable): The right operand of the batch matrix multiplications.
Its array is treated as matrices in the same way as ``a``'s array.
transa (bool): If ``True``, transpose each matrix in ``a``.
transb (bool): If ``True``, transpose each matrix in ``b``.
Returns:
~chainer.Variable: The result of the batch matrix multiplications as a
3-D array.
.. deprecated:: v3.0.0
batch_matmul is deprecated. Use ``matmul`` instead.
"""
warnings.warn('batch_matmul is deprecated. Use matmul instead.',
DeprecationWarning)
return BatchMatMul(transa=transa, transb=transb).apply((a, b))[0]