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

5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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. """container"""
  16. from collections import OrderedDict
  17. from abc import abstractmethod
  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():
  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 interpreted 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 interpreted as a list of cells.
  40. """
  41. def __init__(self):
  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, OrderedDict): List of subclass of Cell.
  58. Inputs:
  59. - **input** (Tensor) - Tensor with shape according to the first Cell in the sequence.
  60. Outputs:
  61. Tensor, the output Tensor with shape depending on the input and defined sequence of Cells.
  62. Raises:
  63. TypeError: If the type of the `args` is not list or OrderedDict.
  64. Supported Platforms:
  65. ``Ascend`` ``GPU``
  66. Examples:
  67. >>> conv = nn.Conv2d(3, 2, 3, pad_mode='valid', weight_init="ones")
  68. >>> relu = nn.ReLU()
  69. >>> seq = nn.SequentialCell([conv, relu])
  70. >>> x = Tensor(np.ones([1, 3, 4, 4]), dtype=mindspore.float32)
  71. >>> output = seq(x)
  72. >>> print(output)
  73. [[[[27. 27.]
  74. [27. 27.]]
  75. [[27. 27.]
  76. [27. 27.]]]]
  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 append(self, cell):
  125. """Appends a given cell to the end of the list.
  126. Examples:
  127. >>> conv = nn.Conv2d(3, 2, 3, pad_mode='valid', weight_init="ones")
  128. >>> bn = nn.BatchNorm2d(2)
  129. >>> relu = nn.ReLU()
  130. >>> seq = nn.SequentialCell([conv, bn])
  131. >>> seq.append(relu)
  132. >>> x = Tensor(np.ones([1, 3, 4, 4]), dtype=mindspore.float32)
  133. >>> output = seq(x)
  134. >>> print(output)
  135. [[[[26.999863 26.999863]
  136. [26.999863 26.999863]]
  137. [[26.999863 26.999863]
  138. [26.999863 26.999863]]]]
  139. """
  140. if _valid_cell(cell):
  141. self._cells[str(len(self))] = cell
  142. self.cell_list = list(self._cells.values())
  143. def construct(self, input_data):
  144. for cell in self.cell_list:
  145. input_data = cell(input_data)
  146. return input_data
  147. class CellList(_CellListBase, Cell):
  148. """
  149. Holds Cells in a list.
  150. CellList can be used like a regular Python list, support
  151. '__getitem__', '__setitem__', '__delitem__', '__len__', '__iter__' and '__iadd__',
  152. but cells it contains are properly registered, and will be visible by all Cell methods.
  153. Args:
  154. args (list, optional): List of subclass of Cell.
  155. Supported Platforms:
  156. ``Ascend`` ``GPU``
  157. Examples:
  158. >>> conv = nn.Conv2d(100, 20, 3)
  159. >>> bn = nn.BatchNorm2d(20)
  160. >>> relu = nn.ReLU()
  161. >>> cell_ls = nn.CellList([bn])
  162. >>> cell_ls.insert(0, conv)
  163. >>> cell_ls.append(relu)
  164. >>> cell_ls
  165. CellList<
  166. (0): Conv2d<input_channels=100, ..., bias_init=None>
  167. (1): BatchNorm2d<num_features=20, ..., moving_variance=Parameter (name=variance)>
  168. (2): ReLU<>
  169. >
  170. """
  171. def __init__(self, *args):
  172. _CellListBase.__init__(self)
  173. Cell.__init__(self)
  174. if len(args) == 1:
  175. self.extend(args[0])
  176. def __getitem__(self, index):
  177. if isinstance(index, slice):
  178. return self.__class__(list(self._cells.values())[index])
  179. if isinstance(index, int):
  180. index = _valid_index(len(self), index)
  181. return self._cells[str(index)]
  182. raise TypeError('Index {} is not int type or slice type'.format(index))
  183. def __setitem__(self, index, cell):
  184. if not isinstance(index, int) and _valid_cell(cell):
  185. raise TypeError('Index {} is not int type'.format(index))
  186. index = _valid_index(len(self), index)
  187. self._cells[str(index)] = cell
  188. def __delitem__(self, index):
  189. if isinstance(index, int):
  190. index = _valid_index(len(self), index)
  191. del self._cells[str(index)]
  192. elif isinstance(index, slice):
  193. keys = list(self._cells.keys())[index]
  194. for key in keys:
  195. del self._cells[key]
  196. else:
  197. raise TypeError('Index {} is not int type or slice type'.format(index))
  198. # adjust orderedDict
  199. temp_dict = OrderedDict()
  200. for idx, cell in enumerate(self._cells.values()):
  201. temp_dict[str(idx)] = cell
  202. self._cells = temp_dict
  203. def __len__(self):
  204. return len(self._cells)
  205. def __iter__(self):
  206. return iter(self._cells.values())
  207. def __iadd__(self, cells):
  208. self.extend(cells)
  209. return self
  210. def insert(self, index, cell):
  211. """Inserts a given cell before a given index in the list."""
  212. idx = _valid_index(len(self), index)
  213. _valid_cell(cell)
  214. length = len(self)
  215. while length > idx:
  216. self._cells[str(length)] = self._cells[str(length - 1)]
  217. length -= 1
  218. self._cells[str(idx)] = cell
  219. def extend(self, cells):
  220. """
  221. Appends cells from a Python iterable to the end of the list.
  222. Raises:
  223. TypeError: If the cells are not a list of subcells.
  224. """
  225. if not isinstance(cells, list):
  226. raise TypeError('Cells {} should be list of subcells'.format(cells))
  227. for cell in cells:
  228. if _valid_cell(cell):
  229. self._cells[str(len(self))] = cell
  230. return self
  231. def append(self, cell):
  232. """Appends a given cell to the end of the list."""
  233. if _valid_cell(cell):
  234. self._cells[str(len(self))] = cell
  235. def set_grad(self, flag=True):
  236. self.requires_grad = flag
  237. for cell in self._cells.values():
  238. cell.set_grad(flag)
  239. def construct(self, *inputs):
  240. raise NotImplementedError