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

5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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. def _get_prefix_and_index(cells):
  32. """get prefix and index of parameter name in sequential cell or cell list"""
  33. prefix = ""
  34. index = 0
  35. if not cells:
  36. return prefix, index
  37. cell_list = list(cells.items())
  38. first_param, first_key = None, None
  39. second_param, second_key = None, None
  40. for key, cell in cell_list:
  41. try:
  42. _, param = next(cell.parameters_and_names())
  43. except StopIteration:
  44. continue
  45. if first_param is None:
  46. first_param = param
  47. first_key = key
  48. continue
  49. second_param = param
  50. second_key = key
  51. break
  52. if first_param is None:
  53. return prefix, index
  54. split_names = first_param.name.split(".")
  55. for idx, name in enumerate(split_names):
  56. if name == first_key:
  57. prefix = ".".join(split_names[:idx])
  58. prefix = prefix + "." if prefix else prefix
  59. index = idx
  60. if second_param is not None and second_param.name.split(".")[idx] == second_key:
  61. break
  62. return prefix, index
  63. class _CellListBase():
  64. """
  65. An interface for base the cell as list.
  66. The sequential cell may be iterated using the construct method using for-in statement.
  67. But there are some scenarios that the construct method built-in does not fit.
  68. For convenience, we provide an interface that indicates the sequential
  69. cell may be interpreted as list of cells, so it can be accessed using
  70. iterator or subscript when a sequential cell instantiate is accessed
  71. by iterator or subscript , it will be interpreted as a list of cells.
  72. """
  73. def __init__(self):
  74. self.__cell_as_list__ = True
  75. @abstractmethod
  76. def __len__(self):
  77. pass
  78. @abstractmethod
  79. def __getitem__(self, index):
  80. pass
  81. def construct(self):
  82. raise NotImplementedError
  83. class SequentialCell(Cell):
  84. """
  85. Sequential cell container.
  86. A list of Cells will be added to it in the order they are passed in the constructor.
  87. Alternatively, an ordered dict of cells can also be passed in.
  88. Args:
  89. args (list, OrderedDict): List of subclass of Cell.
  90. Inputs:
  91. - **input** (Tensor) - Tensor with shape according to the first Cell in the sequence.
  92. Outputs:
  93. Tensor, the output Tensor with shape depending on the input and defined sequence of Cells.
  94. Raises:
  95. TypeError: If the type of the `args` is not list or OrderedDict.
  96. Supported Platforms:
  97. ``Ascend`` ``GPU`` ``CPU``
  98. Examples:
  99. >>> conv = nn.Conv2d(3, 2, 3, pad_mode='valid', weight_init="ones")
  100. >>> relu = nn.ReLU()
  101. >>> seq = nn.SequentialCell([conv, relu])
  102. >>> x = Tensor(np.ones([1, 3, 4, 4]), dtype=mindspore.float32)
  103. >>> output = seq(x)
  104. >>> print(output)
  105. [[[[27. 27.]
  106. [27. 27.]]
  107. [[27. 27.]
  108. [27. 27.]]]]
  109. """
  110. def __init__(self, *args):
  111. super(SequentialCell, self).__init__()
  112. self._is_dynamic_name = []
  113. if len(args) == 1:
  114. cells = args[0]
  115. if isinstance(cells, list):
  116. for index, cell in enumerate(cells):
  117. self.insert_child_to_cell(str(index), cell)
  118. cell.update_parameters_name(str(index) + ".")
  119. self._is_dynamic_name.append(True)
  120. elif isinstance(cells, OrderedDict):
  121. for name, cell in cells.items():
  122. self.insert_child_to_cell(name, cell)
  123. cell.update_parameters_name(name + ".")
  124. self._is_dynamic_name.append(False)
  125. else:
  126. raise TypeError('Cells must be list or orderedDict')
  127. else:
  128. for index, cell in enumerate(args):
  129. self.insert_child_to_cell(str(index), cell)
  130. cell.update_parameters_name(str(index) + ".")
  131. self._is_dynamic_name.append(True)
  132. self.cell_list = list(self._cells.values())
  133. def __getitem__(self, index):
  134. if isinstance(index, slice):
  135. return self.__class__(
  136. OrderedDict(list(self._cells.items())[index]))
  137. index = _valid_index(len(self), index)
  138. return list(self._cells.values())[index]
  139. def __setitem__(self, index, cell):
  140. if _valid_cell(cell):
  141. prefix, _ = _get_prefix_and_index(self._cells)
  142. index = _valid_index(len(self), index)
  143. key = list(self._cells.keys())[index]
  144. self._cells[key] = cell
  145. cell.update_parameters_name(prefix + key + ".")
  146. self.cell_list = list(self._cells.values())
  147. def __delitem__(self, index):
  148. if isinstance(index, int):
  149. index = _valid_index(len(self), index)
  150. key = list(self._cells.keys())[index]
  151. del self._cells[key]
  152. del self._is_dynamic_name[index]
  153. elif isinstance(index, slice):
  154. keys = list(self._cells.keys())[index]
  155. for key in keys:
  156. del self._cells[key]
  157. del self._is_dynamic_name[index]
  158. else:
  159. raise TypeError('Index {} is not int type or slice type'.format(index))
  160. prefix, key_index = _get_prefix_and_index(self._cells)
  161. temp_dict = OrderedDict()
  162. for idx, key in enumerate(self._cells.keys()):
  163. cell = self._cells[key]
  164. if self._is_dynamic_name[idx]:
  165. for _, param in cell.parameters_and_names():
  166. param.name = prefix + str(idx) + "." + ".".join(param.name.split(".")[key_index+1:])
  167. temp_dict[str(idx)] = cell
  168. else:
  169. temp_dict[key] = cell
  170. self._cells = temp_dict
  171. self.cell_list = list(self._cells.values())
  172. def __len__(self):
  173. return len(self._cells)
  174. def set_grad(self, flag=True):
  175. self.requires_grad = flag
  176. for cell in self._cells.values():
  177. cell.set_grad(flag)
  178. def append(self, cell):
  179. """Appends a given cell to the end of the list.
  180. Examples:
  181. >>> conv = nn.Conv2d(3, 2, 3, pad_mode='valid', weight_init="ones")
  182. >>> bn = nn.BatchNorm2d(2)
  183. >>> relu = nn.ReLU()
  184. >>> seq = nn.SequentialCell([conv, bn])
  185. >>> seq.append(relu)
  186. >>> x = Tensor(np.ones([1, 3, 4, 4]), dtype=mindspore.float32)
  187. >>> output = seq(x)
  188. >>> print(output)
  189. [[[[26.999863 26.999863]
  190. [26.999863 26.999863]]
  191. [[26.999863 26.999863]
  192. [26.999863 26.999863]]]]
  193. """
  194. if _valid_cell(cell):
  195. prefix, _ = _get_prefix_and_index(self._cells)
  196. cell.update_parameters_name(prefix + str(len(self)) + ".")
  197. self._is_dynamic_name.append(True)
  198. self._cells[str(len(self))] = cell
  199. self.cell_list = list(self._cells.values())
  200. def construct(self, input_data):
  201. for cell in self.cell_list:
  202. input_data = cell(input_data)
  203. return input_data
  204. class CellList(_CellListBase, Cell):
  205. """
  206. Holds Cells in a list.
  207. CellList can be used like a regular Python list, support
  208. '__getitem__', '__setitem__', '__delitem__', '__len__', '__iter__' and '__iadd__',
  209. but cells it contains are properly registered, and will be visible by all Cell methods.
  210. Args:
  211. args (list, optional): List of subclass of Cell.
  212. Supported Platforms:
  213. ``Ascend`` ``GPU``
  214. Examples:
  215. >>> conv = nn.Conv2d(100, 20, 3)
  216. >>> bn = nn.BatchNorm2d(20)
  217. >>> relu = nn.ReLU()
  218. >>> cell_ls = nn.CellList([bn])
  219. >>> cell_ls.insert(0, conv)
  220. >>> cell_ls.append(relu)
  221. >>> cell_ls
  222. CellList<
  223. (0): Conv2d<input_channels=100, ..., bias_init=None>
  224. (1): BatchNorm2d<num_features=20, ..., moving_variance=Parameter (name=variance)>
  225. (2): ReLU<>
  226. >
  227. """
  228. def __init__(self, *args, **kwargs):
  229. auto_prefix = kwargs["auto_prefix"] if "auto_prefix" in kwargs.keys() else True
  230. _CellListBase.__init__(self)
  231. Cell.__init__(self, auto_prefix)
  232. if len(args) == 1:
  233. self.extend(args[0])
  234. def __getitem__(self, index):
  235. if isinstance(index, slice):
  236. return self.__class__(list(self._cells.values())[index])
  237. if isinstance(index, int):
  238. index = _valid_index(len(self), index)
  239. return self._cells[str(index)]
  240. raise TypeError('Index {} is not int type or slice type'.format(index))
  241. def __setitem__(self, index, cell):
  242. if not isinstance(index, int) and _valid_cell(cell):
  243. raise TypeError('Index {} is not int type'.format(index))
  244. index = _valid_index(len(self), index)
  245. if self._auto_prefix:
  246. prefix, _ = _get_prefix_and_index(self._cells)
  247. cell.update_parameters_name(prefix + str(index) + ".")
  248. self._cells[str(index)] = cell
  249. def __delitem__(self, index):
  250. if isinstance(index, int):
  251. index = _valid_index(len(self), index)
  252. del self._cells[str(index)]
  253. elif isinstance(index, slice):
  254. keys = list(self._cells.keys())[index]
  255. for key in keys:
  256. del self._cells[key]
  257. else:
  258. raise TypeError('Index {} is not int type or slice type'.format(index))
  259. # adjust orderedDict
  260. prefix, key_index = _get_prefix_and_index(self._cells)
  261. temp_dict = OrderedDict()
  262. for idx, cell in enumerate(self._cells.values()):
  263. if self._auto_prefix:
  264. for _, param in cell.parameters_and_names():
  265. param.name = prefix + str(idx) + "." + ".".join(param.name.split(".")[key_index+1:])
  266. temp_dict[str(idx)] = cell
  267. self._cells = temp_dict
  268. def __len__(self):
  269. return len(self._cells)
  270. def __iter__(self):
  271. return iter(self._cells.values())
  272. def __iadd__(self, cells):
  273. self.extend(cells)
  274. return self
  275. def insert(self, index, cell):
  276. """Inserts a given cell before a given index in the list."""
  277. idx = _valid_index(len(self), index)
  278. _valid_cell(cell)
  279. length = len(self)
  280. prefix, key_index = _get_prefix_and_index(self._cells)
  281. while length > idx:
  282. if self._auto_prefix:
  283. tmp_cell = self._cells[str(length-1)]
  284. for _, param in tmp_cell.parameters_and_names():
  285. param.name = prefix + str(length) + "." + ".".join(param.name.split(".")[key_index+1:])
  286. self._cells[str(length)] = self._cells[str(length - 1)]
  287. length -= 1
  288. self._cells[str(idx)] = cell
  289. if self._auto_prefix:
  290. cell.update_parameters_name(prefix + str(idx) + ".")
  291. def extend(self, cells):
  292. """
  293. Appends cells from a Python iterable to the end of the list.
  294. Raises:
  295. TypeError: If the cells are not a list of subcells.
  296. """
  297. if not isinstance(cells, list):
  298. raise TypeError('Cells {} should be list of subcells'.format(cells))
  299. prefix, _ = _get_prefix_and_index(self._cells)
  300. for cell in cells:
  301. if _valid_cell(cell):
  302. if self._auto_prefix:
  303. cell.update_parameters_name(prefix + str(len(self)) + ".")
  304. self._cells[str(len(self))] = cell
  305. return self
  306. def append(self, cell):
  307. """Appends a given cell to the end of the list."""
  308. if _valid_cell(cell):
  309. if self._auto_prefix:
  310. prefix, _ = _get_prefix_and_index(self._cells)
  311. cell.update_parameters_name(prefix + str(len(self)) + ".")
  312. self._cells[str(len(self))] = cell
  313. def set_grad(self, flag=True):
  314. self.requires_grad = flag
  315. for cell in self._cells.values():
  316. cell.set_grad(flag)
  317. def construct(self, *inputs):
  318. raise NotImplementedError