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.

container.py 8.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. # Copyright 2020 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. """container"""
  16. from collections import OrderedDict
  17. from abc import abstractmethod, ABCMeta
  18. from ..cell import Cell
  19. def _valid_index(cell_num, index):
  20. if not isinstance(index, int):
  21. raise TypeError("Index {} is not int type")
  22. if not -cell_num <= index < cell_num:
  23. raise IndexError("Index should be a number in range [{}, {}), but got {}"
  24. .format(-cell_num, cell_num, index))
  25. return index % cell_num
  26. def _valid_cell(cell):
  27. if issubclass(cell.__class__, Cell):
  28. return True
  29. raise TypeError('Cell {} is not subclass of Cell'.format(cell))
  30. class _CellListBase(metaclass=ABCMeta):
  31. """
  32. An interface for base the cell as list.
  33. The sequential cell may be iterated using the construct method using for-in statement.
  34. But there are some scenarios that the construct method built-in does not fit.
  35. For convenience, we provide an interface that indicates the sequential
  36. cell may be interpretated as list of cells, so it can be accessed using
  37. iterator or subscript when a sequential cell instantiate is accessed
  38. by iterator or subscript , it will be interpretated as a list of cells.
  39. """
  40. def __init__(self):
  41. super(_CellListBase, self).__init__()
  42. self.__cell_as_list__ = True
  43. @abstractmethod
  44. def __len__(self):
  45. pass
  46. @abstractmethod
  47. def __getitem__(self, index):
  48. pass
  49. def construct(self):
  50. raise NotImplementedError
  51. class SequentialCell(Cell):
  52. """
  53. Sequential cell container.
  54. A list of Cells will be added to it in the order they are passed in the constructor.
  55. Alternatively, an ordered dict of cells can also be passed in.
  56. Args:
  57. args (list, optional): List of subclass of Cell.
  58. Raises:
  59. TypeError: If arg is not of type list or OrderedDict.
  60. Inputs:
  61. - **input** (Tensor) - Tensor with shape according to the first Cell in the sequence.
  62. Outputs:
  63. Tensor, the output Tensor with shape depending on the input and defined sequence of Cells.
  64. Examples:
  65. >>> conv = nn.Conv2d(3, 2, 3, pad_mode='valid')
  66. >>> bn = nn.BatchNorm2d(2)
  67. >>> relu = nn.ReLU()
  68. >>> seq = nn.SequentialCell([conv, bn, relu])
  69. >>>
  70. >>> x = Tensor(np.random.random((1, 3, 4, 4)), dtype=mindspore.float32)
  71. >>> seq(x)
  72. [[[[0.02531557 0. ]
  73. [0.04933941 0.04880078]]
  74. [[0. 0. ]
  75. [0. 0. ]]]]
  76. """
  77. def __init__(self, *args):
  78. super(SequentialCell, self).__init__()
  79. if len(args) == 1:
  80. cells = args[0]
  81. if isinstance(cells, list):
  82. for index, cell in enumerate(cells):
  83. self.insert_child_to_cell(str(index), cell)
  84. elif isinstance(cells, OrderedDict):
  85. for name, cell in cells.items():
  86. self.insert_child_to_cell(name, cell)
  87. else:
  88. raise TypeError('Cells must be list or orderedDict')
  89. self.cell_list = list(self._cells.values())
  90. def __getitem__(self, index):
  91. if isinstance(index, slice):
  92. return self.__class__(
  93. OrderedDict(list(self._cells.items())[index]))
  94. index = _valid_index(len(self), index)
  95. return list(self._cells.values())[index]
  96. def __setitem__(self, index, cell):
  97. if _valid_cell(cell):
  98. index = _valid_index(len(self), index)
  99. key = list(self._cells.keys())[index]
  100. self._cells[key] = cell
  101. self.cell_list = list(self._cells.values())
  102. def __delitem__(self, index):
  103. if isinstance(index, int):
  104. index = _valid_index(len(self), index)
  105. key = list(self._cells.keys())[index]
  106. del self._cells[key]
  107. elif isinstance(index, slice):
  108. keys = list(self._cells.keys())[index]
  109. for key in keys:
  110. del self._cells[key]
  111. else:
  112. raise TypeError('Index {} is not int type or slice type'.format(index))
  113. self.cell_list = list(self._cells.values())
  114. def __len__(self):
  115. return len(self._cells)
  116. def construct(self, input_data):
  117. for cell in self.cell_list:
  118. input_data = cell(input_data)
  119. return input_data
  120. class CellList(_CellListBase, Cell):
  121. """
  122. Holds Cells in a list.
  123. CellList can be indexed like a regular Python list, but cells it
  124. contains are properly registered, and will be visible by all Cell methods.
  125. Args:
  126. args (list, optional): List of subclass of Cell.
  127. Examples:
  128. >>> conv = nn.Conv2d(100, 20, 3)
  129. >>> bn = nn.BatchNorm2d(20)
  130. >>> relu = nn.ReLU()
  131. >>> cell_ls = nn.CellList([bn])
  132. >>> cell_ls.insert(0, conv)
  133. >>> cell_ls.append(relu)
  134. >>> x = Tensor(np.random.random((1, 3, 4, 4)), dtype=mindspore.float32)
  135. >>> # not same as nn.SequentialCell, `cell_ls(x)` is not correct
  136. >>> cell_ls
  137. CellList< (0): Conv2d<input_channels=100, ..., bias_init=None>
  138. (1): BatchNorm2d<num_features=20, ..., moving_variance=Parameter (name=variance)>
  139. (2): ReLU<> >
  140. """
  141. def __init__(self, *args):
  142. super(CellList, self).__init__()
  143. if len(args) == 1:
  144. self.extend(args[0])
  145. def __getitem__(self, index):
  146. if isinstance(index, slice):
  147. return self.__class__(list(self._cells.values())[index])
  148. if isinstance(index, int):
  149. index = _valid_index(len(self), index)
  150. return self._cells[str(index)]
  151. raise TypeError('Index {} is not int type or slice type'.format(index))
  152. def __setitem__(self, index, cell):
  153. if not isinstance(index, int) and _valid_cell(cell):
  154. raise TypeError('Index {} is not int type'.format(index))
  155. index = _valid_index(len(self), index)
  156. self._cells[str(index)] = cell
  157. def __delitem__(self, index):
  158. if isinstance(index, int):
  159. index = _valid_index(len(self), index)
  160. del self._cells[str(index)]
  161. elif isinstance(index, slice):
  162. keys = list(self._cells.keys())[index]
  163. for key in keys:
  164. del self._cells[key]
  165. else:
  166. raise TypeError('Index {} is not int type or slice type'.format(index))
  167. # adjust orderedDict
  168. temp_dict = OrderedDict()
  169. for idx, cell in enumerate(self._cells.values()):
  170. temp_dict[str(idx)] = cell
  171. self._cells = temp_dict
  172. def __len__(self):
  173. return len(self._cells)
  174. def __iter__(self):
  175. return iter(self._cells.values())
  176. def __iadd__(self, cells):
  177. self.extend(cells)
  178. return self
  179. def insert(self, index, cell):
  180. """Inserts a given cell before a given index in the list."""
  181. idx = _valid_index(len(self), index)
  182. _valid_cell(cell)
  183. length = len(self)
  184. while length > idx:
  185. self._cells[str(length)] = self._cells[str(length - 1)]
  186. length -= 1
  187. self._cells[str(idx)] = cell
  188. def extend(self, cells):
  189. """
  190. Appends cells from a Python iterable to the end of the list.
  191. Raises:
  192. TypeError: If the cells is not a list of subcells.
  193. """
  194. if not isinstance(cells, list):
  195. raise TypeError('Cells {} should be list of subcells'.format(cells))
  196. for cell in cells:
  197. if _valid_cell(cell):
  198. self._cells[str(len(self))] = cell
  199. return self
  200. def append(self, cell):
  201. """Appends a given cell to the end of the list."""
  202. if _valid_cell(cell):
  203. self._cells[str(len(self))] = cell
  204. return self
  205. def construct(self, *inputs):
  206. raise NotImplementedError