|
| 1 | +""" |
| 2 | +This is copied from https://github.com/chainer/chainer/pull/6031 and will be |
| 3 | +unnecessary once the PR is merged to Chainer. |
| 4 | +""" |
| 5 | +import functools |
| 6 | +import operator |
| 7 | + |
| 8 | +import numpy |
| 9 | + |
| 10 | +from chainer import cuda |
| 11 | +from chainer import initializer |
| 12 | + |
| 13 | + |
| 14 | +# Only Chainer v6 or later has chainer.utils.size_of_shape |
| 15 | +def size_of_shape(shape): |
| 16 | + return functools.reduce(operator.mul, shape, 1) |
| 17 | + |
| 18 | + |
| 19 | +_orthogonal_constraints = { # (assert emb., assert proj.) |
| 20 | + 'auto': (False, False), |
| 21 | + 'projection': (False, True), |
| 22 | + 'embedding': (True, False), |
| 23 | + 'basis': (True, True), |
| 24 | +} |
| 25 | + |
| 26 | + |
| 27 | +# Original code forked from MIT licensed keras project |
| 28 | +# https://github.com/fchollet/keras/blob/master/keras/initializations.py |
| 29 | + |
| 30 | +class Orthogonal(initializer.Initializer): |
| 31 | + """Initializes array with an orthogonal system. |
| 32 | +
|
| 33 | + This initializer first makes a matrix of the same shape as the |
| 34 | + array to be initialized whose elements are drawn independently from |
| 35 | + standard Gaussian distribution. |
| 36 | + Next, it applies QR decomposition to (the transpose of) the matrix. |
| 37 | + To make the decomposition (almost surely) unique, we require the diagonal |
| 38 | + of the triangular matrix R to be non-negative (see e.g. Edelman & Rao, |
| 39 | + https://web.eecs.umich.edu/~rajnrao/Acta05rmt.pdf). |
| 40 | + Then, it initializes the array with the (semi-)orthogonal matrix Q. |
| 41 | + Finally, the array is multiplied by the constant ``scale``. |
| 42 | +
|
| 43 | + If the ``ndim`` of the input array is more than 2, we consider the array |
| 44 | + to be a matrix by concatenating all axes except the first one. |
| 45 | +
|
| 46 | + The number of vectors consisting of the orthogonal system |
| 47 | + (i.e. first element of the shape of the array) must be equal to or smaller |
| 48 | + than the dimension of each vector (i.e. second element of the shape of |
| 49 | + the array). |
| 50 | +
|
| 51 | + Attributes: |
| 52 | + scale (float): A constant to be multiplied by. |
| 53 | + dtype: Data type specifier. |
| 54 | + mode (str): Assertion on the initialized shape. |
| 55 | + ``'auto'`` (default), ``'projection'`` (before v6), |
| 56 | + ``'embedding'``, or ``'basis'``. |
| 57 | +
|
| 58 | + Reference: Saxe et al., https://arxiv.org/abs/1312.6120 |
| 59 | +
|
| 60 | + """ |
| 61 | + |
| 62 | + def __init__(self, scale=1.1, dtype=None, mode='auto'): |
| 63 | + self.scale = scale |
| 64 | + self.mode = mode |
| 65 | + try: |
| 66 | + self._checks = _orthogonal_constraints[mode] |
| 67 | + except KeyError: |
| 68 | + raise ValueError( |
| 69 | + 'Invalid mode: {}. Choose from {}.'.format( |
| 70 | + repr(mode), |
| 71 | + ', '.join(repr(m) for m in _orthogonal_constraints))) |
| 72 | + super(Orthogonal, self).__init__(dtype) |
| 73 | + |
| 74 | + # TODO(Kenta Oono) |
| 75 | + # How do we treat overcomplete base-system case? |
| 76 | + def __call__(self, array): |
| 77 | + if self.dtype is not None: |
| 78 | + assert array.dtype == self.dtype |
| 79 | + xp = cuda.get_array_module(array) |
| 80 | + if not array.shape: # 0-dim case |
| 81 | + array[...] = self.scale * (2 * numpy.random.randint(2) - 1) |
| 82 | + elif not array.size: |
| 83 | + raise ValueError('Array to be initialized must be non-empty.') |
| 84 | + else: |
| 85 | + # numpy.prod returns float value when the argument is empty. |
| 86 | + out_dim = len(array) |
| 87 | + in_dim = size_of_shape(array.shape[1:]) |
| 88 | + if (in_dim > out_dim and self._checks[0]) or ( |
| 89 | + in_dim < out_dim and self._checks[1]): |
| 90 | + raise ValueError( |
| 91 | + 'Cannot make orthogonal {}.' |
| 92 | + 'shape = {}, interpreted as ' |
| 93 | + '{}-dim input and {}-dim output.'.format( |
| 94 | + self.mode, array.shape, in_dim, out_dim)) |
| 95 | + transpose = in_dim > out_dim |
| 96 | + a = numpy.random.normal(size=(out_dim, in_dim)) |
| 97 | + if transpose: |
| 98 | + a = a.T |
| 99 | + # cupy.linalg.qr requires cusolver in CUDA 8+ |
| 100 | + q, r = numpy.linalg.qr(a) |
| 101 | + q *= numpy.copysign(self.scale, numpy.diag(r)) |
| 102 | + if transpose: |
| 103 | + q = q.T |
| 104 | + array[...] = xp.asarray(q.reshape(array.shape)) |
0 commit comments