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 9.1 kB

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