You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

timedistributed.py 6.8 kB

4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. # Copyright 2020-2021 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """Time Distributed."""
  16. from mindspore.ops.primitive import constexpr, Primitive
  17. from mindspore.ops import Reshape, Transpose, Stack, Unstack
  18. from mindspore.common import Tensor
  19. from mindspore._checkparam import Validator
  20. from ..cell import Cell
  21. __all__ = ['TimeDistributed']
  22. @constexpr
  23. def _check_reshape_pos(reshape_pos, inputs_shape, outputs_shape, prim_name=None):
  24. msg_prefix = f"For '{prim_name}', the" if prim_name else "The"
  25. if reshape_pos >= len(outputs_shape) or inputs_shape[reshape_pos] != outputs_shape[reshape_pos]:
  26. raise ValueError(f"{msg_prefix} 'reshape_with_axis' is invalid in the input and output. "
  27. f"The 'reshape_pos' should be less than the length of 'outputs_shape', and the "
  28. f"'inputs_shape[reshape_pos]' should be equal to 'outputs_shape[reshape_pos]', but got "
  29. f"'reshape_pos': {reshape_pos}, 'inputs_shape': {inputs_shape}, 'outputs_shape': "
  30. f"{outputs_shape}. You may try pass parameters without 'reshape_with_axis'.")
  31. @constexpr
  32. def _check_expand_dims_axis(time_axis, ndim, prim_name=None):
  33. msg_prefix = f"For '{prim_name}', the" if prim_name else "The"
  34. if time_axis > ndim:
  35. raise ValueError(f"{msg_prefix} value of 'time_axis' should be in range of [{-ndim - 1}, {ndim}], "
  36. f"but got {time_axis}.")
  37. @constexpr
  38. def _generate_perm(axis_a, axis_b, length):
  39. perm = tuple(range(length))
  40. axis_a, axis_b = (axis_a, axis_b) if axis_a < axis_b else (axis_b, axis_a)
  41. return perm[:axis_a] + (perm[axis_b],) + perm[axis_a: axis_b] + perm[axis_b + 1:]
  42. @constexpr
  43. def _check_data(flag, prim_name=None):
  44. msg_prefix = f"For '{prim_name}', the" if prim_name else "The"
  45. if not flag:
  46. raise TypeError(f"{msg_prefix} inputs and outputs should be a Tensor.")
  47. @constexpr
  48. def _check_inputs_dim(shape, prim_name=None):
  49. msg_prefix = f"For '{prim_name}', the" if prim_name else "The"
  50. if len(shape) < 3:
  51. raise ValueError(f"{msg_prefix} inputs shape should be at least 3D, but got {len(shape)}.")
  52. class TimeDistributed(Cell):
  53. r"""
  54. The time distributed layer.
  55. Time distributed is a wrapper which allows to apply a layer to every temporal slice of an input.
  56. And the `x` should be at least 3D.
  57. There are two cases in the implementation.
  58. When reshape_with_axis provided, the reshape method will be chosen, which is more efficient;
  59. otherwise, the method of dividing the inputs along time axis will be used, which is more general.
  60. For example, reshape_with_axis could not be provided when deal with Batch Normalization.
  61. Args:
  62. layer(Union[Cell, Primitive]): The Cell or Primitive which will be wrapped.
  63. time_axis(int): The axis of time_step.
  64. reshape_with_axis(int): The axis which will be reshaped with time_axis. Default: None.
  65. Inputs:
  66. - **x** (Tensor) - Tensor of shape :math:`(N, T, *)`,
  67. where :math:`*` means any number of additional dimensions.
  68. Outputs:
  69. Tensor of shape :math:`(N, T, *)`
  70. Supported Platforms:
  71. ``Ascend`` ``GPU`` ``CPU``
  72. Raises:
  73. TypeError: If layer is not a Cell or Primitive.
  74. Examples:
  75. >>> x = Tensor(np.random.random([32, 10, 3]), mindspore.float32)
  76. >>> dense = nn.Dense(3, 6)
  77. >>> net = nn.TimeDistributed(dense, time_axis=1, reshape_with_axis=0)
  78. >>> output = net(x)
  79. >>> print(output.shape)
  80. (32, 10, 6)
  81. """
  82. def __init__(self, layer, time_axis, reshape_with_axis=None):
  83. """Initialize TimeDistributed."""
  84. if not isinstance(layer, (Cell, Primitive)):
  85. raise TypeError(f"For '{self.cls_name}', the 'layer' should be Cell or Primitive instance, "
  86. f"but got type: {type(layer).__name__}.")
  87. super(TimeDistributed, self).__init__()
  88. Validator.check_is_int(time_axis, "time_axis", self.cls_name)
  89. if reshape_with_axis is not None:
  90. Validator.check_is_int(reshape_with_axis, "reshape_with_axis", self.cls_name)
  91. self.layer = layer
  92. self.time_axis = time_axis
  93. self.reshape_with_axis = reshape_with_axis
  94. self.transpose = Transpose()
  95. self.reshape = Reshape()
  96. def construct(self, inputs):
  97. _check_data(isinstance(inputs, Tensor), self.cls_name)
  98. _check_inputs_dim(inputs.shape, self.cls_name)
  99. time_axis = self.time_axis % len(inputs.shape)
  100. if self.reshape_with_axis is not None:
  101. reshape_with_axis = self.reshape_with_axis % len(inputs.shape)
  102. inputs_shape = inputs.shape
  103. time_axis_new = len(inputs_shape) - 2 if reshape_with_axis == len(inputs_shape) - 1 \
  104. else (reshape_with_axis + 1 if time_axis > reshape_with_axis else
  105. reshape_with_axis - 1)
  106. reshape_pos = time_axis_new if time_axis_new < reshape_with_axis else reshape_with_axis
  107. perm = _generate_perm(time_axis_new, time_axis, len(inputs_shape))
  108. inputs = self.transpose(inputs, perm)
  109. inputs_shape_new = inputs.shape
  110. inputs = self.reshape(inputs, inputs_shape_new[: reshape_pos] + (-1,) + inputs_shape_new[reshape_pos + 2:])
  111. outputs = self.layer(inputs)
  112. _check_data(isinstance(outputs, Tensor), self.cls_name)
  113. _check_reshape_pos(reshape_pos, inputs.shape, outputs.shape, self.cls_name)
  114. outputs_shape_new = outputs.shape[:reshape_pos] + inputs_shape_new[reshape_pos: reshape_pos + 2]
  115. if reshape_pos + 1 < len(outputs.shape):
  116. outputs_shape_new += outputs.shape[reshape_pos + 1:]
  117. return self.reshape(outputs, outputs_shape_new)
  118. unstack = Unstack(time_axis)
  119. inputs = unstack(inputs)
  120. y = ()
  121. for item in inputs:
  122. outputs = self.layer(item)
  123. _check_data(isinstance(outputs, Tensor), self.cls_name)
  124. _check_expand_dims_axis(time_axis, outputs.ndim, self.cls_name)
  125. y += (outputs,)
  126. y = Stack(time_axis)(y)
  127. return y