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.

cell.py 40 kB

5 years ago
5 years ago
5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  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. """cell"""
  16. import inspect
  17. import time
  18. import gc
  19. import os
  20. from collections import OrderedDict
  21. import numpy
  22. from mindspore import log as logger
  23. from .. import context
  24. from ..common import dtype as mstype
  25. from ..common.api import _executor, _pynative_exec
  26. from .._checkparam import Validator
  27. from ..common.parameter import Parameter, ParameterTuple
  28. from .._c_expression import init_backend, Cell_
  29. from ..ops.primitive import Primitive
  30. from ..ops.operations import HookBackward
  31. from ..ops.functional import cast
  32. from ..parallel._tensor import _load_tensor_by_layout
  33. from ..common.tensor import Tensor
  34. class Cell(Cell_):
  35. """
  36. Base class for all neural networks.
  37. A 'Cell' could be a single neural network cell, such as conv2d, relu, batch_norm, etc. or a composition of
  38. cells to constructing a network.
  39. Note:
  40. In general, the autograd algorithm will automatically generate the implementation of the gradient function,
  41. but if back-propagation(bprop) method is implemented, the gradient function will be replaced by the bprop.
  42. The bprop implementation will receive a Tensor `dout` containing the gradient of the loss w.r.t.
  43. the output, and a Tensor `out` containing the forward result. The bprop needs to compute the
  44. gradient of the loss w.r.t. the inputs, gradient of the loss w.r.t. Parameter variables are not supported
  45. currently.
  46. Args:
  47. auto_prefix (bool): Recursively generate namespaces. Default: True.
  48. Examples:
  49. >>> class MyCell(Cell):
  50. >>> def __init__(self):
  51. >>> super(MyCell, self).__init__()
  52. >>> self.relu = P.ReLU()
  53. >>>
  54. >>> def construct(self, x):
  55. >>> return self.relu(x)
  56. """
  57. IGNORE_LIST = ['_scope', '_cell_init_args', '_auto_prefix', '_cells', '_params', '_construct_inputs_names',
  58. '_construct_inputs_num', '_create_time', '_mindspore_flags', '_parallel_inputs_run',
  59. '_parameter_layout_dict', '_already_run', '_params_list', '_tensor_list', '_phase',
  60. '_auto_parallel_mode', '_backward_hook', '_bprop_debug', '_is_run', '_param_prefix',
  61. '_attr_synced', 'enable_hook', 'pynative', 'requires_grad',
  62. '_auto_parallel_compile_and_run', 'cell_type']
  63. def __init__(self, auto_prefix=True, flags=None):
  64. Cell_.__init__(self, self._cell_tag)
  65. self._params = OrderedDict()
  66. self._cells = OrderedDict()
  67. self._params_list = OrderedDict()
  68. self._tensor_list = OrderedDict()
  69. self.training = False
  70. self.requires_grad = False
  71. self.pynative = False
  72. self._attr_synced = False
  73. self._param_prefix = ''
  74. self._auto_prefix = auto_prefix
  75. self._scope = None
  76. self._phase = 'train'
  77. self._parameter_layout_dict = {}
  78. self._create_time = int(time.time() * 1e9)
  79. init_backend()
  80. # call gc to release GE session resources used by non-used cell objects
  81. if os.getenv('GC_COLLECT_IN_CELL') == '1':
  82. gc.collect()
  83. self._construct_inputs_num = 0
  84. self._construct_inputs_names = []
  85. self._auto_parallel_mode = False
  86. self._parallel_inputs_run = None
  87. if flags:
  88. self.add_flags(**flags)
  89. self._backward_hook = None
  90. self.enable_hook = False
  91. self._bprop_debug = False
  92. self._already_run = False
  93. self.cell_type = None
  94. self._auto_parallel_compile_and_run = False
  95. @property
  96. def already_run(self):
  97. return self._already_run
  98. def __getstate__(self):
  99. base = Cell_.__getstate__(self)
  100. return base, self.__dict__
  101. def __setstate__(self, state):
  102. base, dict_ = state
  103. Cell_.__setstate__(self, base)
  104. self.__dict__ = dict_
  105. self._attr_synced = False
  106. @property
  107. def _cell_tag(self):
  108. # `<class 'xxxxxxx'>` to `xxxxxxx`
  109. return str(self.__class__)[8:-2]
  110. @already_run.setter
  111. def already_run(self, value):
  112. self._already_run = value
  113. @property
  114. def create_time(self):
  115. return self._create_time
  116. @property
  117. def cell_init_args(self):
  118. return self._cell_init_args
  119. @property
  120. def param_prefix(self):
  121. """
  122. Param prefix is the prefix of current cell's direct child parameter.
  123. """
  124. return self._param_prefix
  125. @property
  126. def bprop_debug(self):
  127. """
  128. Get whether cell custom bprop debug is enabled.
  129. """
  130. return self._bprop_debug
  131. @bprop_debug.setter
  132. def bprop_debug(self, value):
  133. """
  134. Set whether to enable cell custom bprop debug.
  135. Note:
  136. When bprop is defined in cell, the bprop function will be executed
  137. in python interpreter when bprop debug is true, and will be parsed
  138. and add to graph when bprop debug is false.
  139. Args:
  140. value (bool): Specifies whether to enable bprop debug. Default: False.
  141. """
  142. if not isinstance(value, bool):
  143. raise TypeError("'bprop debug' value must be bool type.")
  144. self._bprop_debug = value
  145. def update_cell_prefix(self):
  146. """
  147. Update the all child cells' self.param_prefix.
  148. After being invoked, it can get all the cell's children's name prefix by '_param_prefix'.
  149. """
  150. cells_name = self.cells_and_names()
  151. for cell_name, cell in cells_name:
  152. cell._param_prefix = cell_name
  153. def update_cell_type(self, cell_type):
  154. """
  155. The current cell type is updated when a quantization aware training network is encountered.
  156. After being invoked, it can set the cell type to 'cell_type'.
  157. """
  158. self.cell_type = cell_type
  159. @cell_init_args.setter
  160. def cell_init_args(self, value):
  161. if not isinstance(value, str):
  162. raise TypeError("'cell_init_args' must be string type.")
  163. self._cell_init_args = value
  164. @property
  165. def phase(self):
  166. return self._phase
  167. @phase.setter
  168. def phase(self, value):
  169. if not isinstance(value, str):
  170. raise TypeError("'phase' must be string type.")
  171. self._phase = value
  172. @property
  173. def parameter_layout_dict(self):
  174. return self._parameter_layout_dict
  175. @property
  176. def cls_name(self):
  177. return self.__class__.__name__
  178. @parameter_layout_dict.setter
  179. def parameter_layout_dict(self, value):
  180. if not isinstance(value, dict):
  181. raise TypeError("'parameter_layout_dict' must be dict type.")
  182. self._parameter_layout_dict = value
  183. def get_func_graph_proto(self):
  184. """Return graph binary proto."""
  185. return _executor._get_func_graph_proto(self.phase + "." + str(self.create_time), "anf_ir", True)
  186. def __getattr__(self, name):
  187. if '_params' in self.__dict__:
  188. params = self.__dict__['_params']
  189. if name in params:
  190. if context.get_context("mode") == context.PYNATIVE_MODE:
  191. return self.cast_param(params[name])
  192. return params[name]
  193. if '_cells' in self.__dict__:
  194. cells = self.__dict__['_cells']
  195. if name in cells:
  196. return cells[name]
  197. if '_tensor_list' in self.__dict__:
  198. tensor_list = self.__dict__['_tensor_list']
  199. if name in tensor_list:
  200. return self.cast_param(tensor_list[name])
  201. if '_params_list' in self.__dict__:
  202. params_list = self.__dict__['_params_list']
  203. if name in params_list:
  204. para_list = params_list[name]
  205. cast_list = list()
  206. for para in para_list:
  207. cast_list.append(self.cast_param(para))
  208. para_list = ParameterTuple(cast_list)
  209. return para_list
  210. raise AttributeError("'{}' object has no attribute '{}'.".format(type(self).__name__, name))
  211. def __del__(self):
  212. _pynative_exec.clear(str(id(self)))
  213. if hasattr(self, "_create_time"):
  214. _executor.del_net_res(str(self._create_time))
  215. def __delattr__(self, name):
  216. if name in self._params:
  217. del self._params[name]
  218. elif name in self._cells:
  219. del self._cells[name]
  220. else:
  221. if '_params_list' in self.__dict__ and name in self._params_list:
  222. del self._params_list[name]
  223. elif '_tensor_list' in self.__dict__ and name in self._tensor_list:
  224. del self._tensor_list[name]
  225. object.__delattr__(self, name)
  226. self._attr_synced = False
  227. def cast_inputs(self, inputs, dst_type):
  228. res = list()
  229. for item in inputs:
  230. if isinstance(item, tuple):
  231. res.append(self.cast_inputs(item, dst_type))
  232. else:
  233. res.append(cast(item, dst_type))
  234. return tuple(res)
  235. def __call__(self, *inputs, **kwargs):
  236. if context.get_context("mode") == context.GRAPH_MODE:
  237. if kwargs:
  238. raise ValueError("For 'graph' mode, the outermost network does not support passing "
  239. "key-value pair parameters and variable key-value pair parameters.")
  240. if self.enable_hook:
  241. raise ValueError("The graph mode does not support hook function.")
  242. out = self.compile_and_run(*inputs)
  243. return out
  244. if kwargs:
  245. bound_args = inspect.signature(self.construct).bind(*inputs, **kwargs)
  246. inputs = bound_args.args
  247. kwargs = bound_args.kwargs
  248. for item in inputs:
  249. if isinstance(item, numpy.ndarray):
  250. raise TypeError("cell inputs should not be numpy array.")
  251. origin_grad = []
  252. if self.requires_grad is True:
  253. _pynative_exec.set_grad_flag(True)
  254. _pynative_exec.new_graph(self, *inputs, **kwargs)
  255. for cell in self.cells():
  256. origin_grad.append(cell.requires_grad)
  257. cell.set_grad(True)
  258. else:
  259. _pynative_exec.set_grad_flag(False)
  260. cast_inputs = list()
  261. if hasattr(self, "_mindspore_flags"):
  262. if self._mindspore_flags.get('fp16'):
  263. cast_inputs = self.cast_inputs(inputs, mstype.float16)
  264. if self._mindspore_flags.get('fp32'):
  265. cast_inputs = self.cast_inputs(inputs, mstype.float32)
  266. if not cast_inputs:
  267. cast_inputs = inputs
  268. if self.enable_hook:
  269. output = self._hook_construct(*cast_inputs, **kwargs)
  270. else:
  271. output = self.construct(*cast_inputs, **kwargs)
  272. if isinstance(output, Parameter):
  273. output = output.data
  274. if self.requires_grad is True:
  275. _pynative_exec.end_graph(self, output, *inputs, **kwargs)
  276. for i, cell in enumerate(self.cells()):
  277. cell.set_grad(origin_grad[i])
  278. self._already_run = True
  279. return output
  280. def _add_attr(self, name, value):
  281. if name and name[:2] != '__' and name not in Cell.IGNORE_LIST:
  282. super(Cell, self)._add_attr(name, value)
  283. def _sync_attr_for_compile(self):
  284. """Sync the attr to c++ object."""
  285. if self._attr_synced:
  286. return
  287. cells = self.__dict__.get('_cells')
  288. for key in cells:
  289. cell = cells[key]
  290. cell._sync_attr_for_compile()
  291. self._add_attr(key, cell)
  292. params = self.__dict__.get('_params')
  293. for key in params:
  294. if '.' in key:
  295. continue
  296. param = params[key]
  297. self._add_attr(key, param)
  298. params_list = self.__dict__.get('_params_list')
  299. for key in params_list:
  300. params_list_item = params_list[key]
  301. self._add_attr(key, params_list_item)
  302. for key in self.__dict__:
  303. value = self.__dict__[key]
  304. self._add_attr(key, value)
  305. self._attr_synced = True
  306. def __setattr__(self, name, value):
  307. cells = self.__dict__.get('_cells')
  308. params = self.__dict__.get('_params')
  309. params_list = self.__dict__.get('_params_list')
  310. tensor_list = self.__dict__.get('_tensor_list')
  311. if isinstance(value, Parameter):
  312. if params is None:
  313. raise AttributeError("Can not assign params before Cell.__init__() call.")
  314. if name in self.__dict__:
  315. if self.__dict__[name] is not None:
  316. raise TypeError("Expected type is not in (Parameter, Cell), but got Parameter.")
  317. del self.__dict__[name]
  318. if cells and name in cells:
  319. raise TypeError("Expected type is Cell, but got Parameter.")
  320. self.insert_param_to_cell(name, value)
  321. elif isinstance(value, ParameterTuple):
  322. if params is None:
  323. raise AttributeError("Can not assign params before Cell.__init__() call.")
  324. for item in value:
  325. self.insert_param_to_cell(item.name, item, check_name=False)
  326. if context.get_context("mode") == context.PYNATIVE_MODE:
  327. if name in self.__dict__:
  328. del self.__dict__[name]
  329. if name in params:
  330. del params[name]
  331. params_list[name] = value
  332. else:
  333. object.__setattr__(self, name, value)
  334. elif isinstance(value, Cell):
  335. if cells is None:
  336. raise AttributeError("Can not assign cells before Cell.__init__() call.")
  337. if name in self.__dict__:
  338. del self.__dict__[name]
  339. if params and name in params:
  340. raise TypeError("Expected type is Parameter, but got Cell.")
  341. if self._auto_prefix:
  342. value.update_parameters_name(name + '.')
  343. cells[name] = value
  344. elif params and name in params:
  345. if isinstance(value, Tensor) and self._params[name] is not None:
  346. self._params[name].set_data(value)
  347. elif value is not None:
  348. raise TypeError("Expected type in (Parameter, ParameterTuple), but got {}.".format(type(value)))
  349. else:
  350. self.insert_param_to_cell(name, None)
  351. elif cells and name in cells:
  352. if value is not None:
  353. raise TypeError("Expected type is cell, but got {}.".format(type(value)))
  354. self._cells[name] = None
  355. elif isinstance(value, Tensor):
  356. if context.get_context("mode") == context.PYNATIVE_MODE:
  357. if name in self.__dict__:
  358. del self.__dict__[name]
  359. tensor_list[name] = value
  360. else:
  361. object.__setattr__(self, name, value)
  362. else:
  363. if isinstance(value, Primitive):
  364. value.set_prim_instance_name(name)
  365. object.__setattr__(self, name, value)
  366. if name not in Cell.IGNORE_LIST:
  367. self._attr_synced = False
  368. def extend_repr(self):
  369. """
  370. Sets the extended representation of the Cell.
  371. To print customized extended information, re-implement this method in your own cells.
  372. """
  373. return ''
  374. def __str__(self):
  375. return self.__repr__()
  376. def __repr__(self):
  377. extra_str = self.extend_repr()
  378. info_str = self.__class__.__name__ + '<'
  379. if self._cells:
  380. sub_str = '\n'
  381. if extra_str:
  382. sub_str += '{}\n'.format(self.extend_repr())
  383. for key, value in self._cells.items():
  384. sub_str += '({}): {}\n'.format(key, repr(value))
  385. sub_str = sub_str.replace('\n', '\n ') + '>'
  386. info_str += sub_str
  387. else:
  388. info_str += extra_str + '>'
  389. return info_str
  390. def load_parameter_slice(self, params):
  391. """
  392. Replace parameters with sliced tensors by parallel strategies.
  393. Please refer to the usage in source code of `mindspore.common._Executor.compile`.
  394. Args:
  395. params (dict): The parameters dictionary used for initializing the data graph.
  396. """
  397. if params is None:
  398. params = self.parameters_dict()
  399. if isinstance(params, OrderedDict):
  400. for key in params:
  401. tensor = params[key].data
  402. if key not in self.parameter_layout_dict:
  403. logger.info("layout dict does not contain the key %s.", key)
  404. continue
  405. if params[key].sliced:
  406. logger.debug("Param %s is already sliced.", key)
  407. continue
  408. layout = self.parameter_layout_dict[key]
  409. new_tensor = _load_tensor_by_layout(tensor, layout)
  410. params[key].set_data(new_tensor, True)
  411. else:
  412. raise TypeError("Parameters need OrderedDict type, but got {}.".format(type(params)))
  413. def _load_inputs(self, *inputs):
  414. """
  415. Slice inputs tensors by parallel strategies.
  416. Args:
  417. inputs (Function or Cell): inputs of construct method.
  418. """
  419. parallel_inputs_run = []
  420. # judge if *args exists in input
  421. if self.argspec[1] is not None:
  422. prefix = self.argspec[1]
  423. for i in range(len(inputs)):
  424. key = prefix + str(i)
  425. self._construct_inputs_names = self._construct_inputs_names + (key,)
  426. self._construct_inputs_num = self._construct_inputs_num + 1
  427. for i, tensor in enumerate(inputs):
  428. key = self._construct_inputs_names[i]
  429. # if input is not used, self.parameter_layout_dict may not contain the key
  430. if key not in self.parameter_layout_dict:
  431. logger.warning("Layout dict does not contain the key %s.", key)
  432. parallel_inputs_run.append(tensor)
  433. else:
  434. layout = self.parameter_layout_dict[key]
  435. new_tensor = _load_tensor_by_layout(tensor, layout)
  436. parallel_inputs_run.append(new_tensor)
  437. return tuple(parallel_inputs_run)
  438. def set_parallel_input_with_inputs(self, *inputs):
  439. """
  440. Slice inputs tensors by parallel strategies, and set the sliced inputs to `_parallel_input_run`
  441. Args:
  442. inputs (tuple): inputs of construct method.
  443. """
  444. self._parallel_inputs_run = self._load_inputs(*inputs)
  445. def _get_construct_inputs_number_and_name(self):
  446. """Compute self._construct_inputs_names and self._construct_inputs_num"""
  447. from mindspore._extends.parse.parser import get_parse_method_of_class
  448. fn = get_parse_method_of_class(self)
  449. self.argspec = inspect.getfullargspec(fn)
  450. self._construct_inputs_num = fn.__code__.co_argcount
  451. self._construct_inputs_names = fn.__code__.co_varnames
  452. assert self._construct_inputs_num > 0
  453. assert self._construct_inputs_names[0] == 'self'
  454. assert self._construct_inputs_num - 1 <= len(self._construct_inputs_names)
  455. self._construct_inputs_names = self._construct_inputs_names[1:self._construct_inputs_num]
  456. self._construct_inputs_num = self._construct_inputs_num - 1
  457. def compile(self, *inputs):
  458. """
  459. Compiles cell.
  460. Args:
  461. inputs (tuple): Input parameters.
  462. """
  463. _executor.compile(self, *inputs, phase=self.phase, auto_parallel_mode=self._auto_parallel_mode)
  464. def compile_and_run(self, *inputs):
  465. """
  466. Compiles and runs cell.
  467. Args:
  468. inputs (tuple): Input parameters.
  469. Returns:
  470. Object, the result of executing.
  471. """
  472. self._auto_parallel_compile_and_run = True
  473. self.compile(*inputs)
  474. if self._auto_parallel_mode:
  475. if inputs and isinstance(inputs[0], Tensor) and inputs[0].virtual_flag:
  476. # get parallel inputs in sink mode, parallel inputs set in _executor.compile
  477. parallel_inputs_run = self._parallel_inputs_run
  478. else:
  479. parallel_inputs_run = inputs
  480. return _executor(self, *parallel_inputs_run, phase=self.phase)
  481. return _executor(self, *inputs, phase=self.phase)
  482. def auto_parallel_compile_and_run(self):
  483. return self._auto_parallel_compile_and_run
  484. def exec_checkpoint_graph(self):
  485. """Executes saving checkpoint graph operation."""
  486. _executor(self, phase='save')
  487. def insert_param_to_cell(self, param_name, param, check_name=True):
  488. """
  489. Adds a parameter to the current cell.
  490. Inserts a parameter with given name to the cell. Please refer to the usage in
  491. source code of `mindspore.nn.Cell.__setattr__`.
  492. Args:
  493. param_name (str): Name of the parameter.
  494. param (Parameter): Parameter to be inserted to the cell.
  495. check_name (bool): Determines whether the name input is compatible. Default: True.
  496. Raises:
  497. KeyError: If the name of parameter is null or contains dot.
  498. AttributeError: If user did not call init() first.
  499. TypeError: If the type of parameter is not Parameter.
  500. """
  501. if not param_name:
  502. raise KeyError("The name of parameter should not be null.")
  503. if check_name and '.' in param_name:
  504. raise KeyError("The name of parameter should not contain \".\"")
  505. if '_params' not in self.__dict__:
  506. raise AttributeError("You need call init() first.")
  507. if hasattr(self, param_name) and param_name not in self._params:
  508. raise KeyError("Duplicated parameter name '{}'.".format(param_name))
  509. if not isinstance(param, Parameter) and param is not None:
  510. raise TypeError("The type of parameter should be 'Parameter' if not None.")
  511. self._params[param_name] = param
  512. def cast_param(self, param):
  513. """
  514. Cast parameter according to auto mix precision level in pynative mode.
  515. Args:
  516. param (Parameter): The parameter to cast.
  517. """
  518. if hasattr(self, "_mindspore_flags"):
  519. if self._mindspore_flags.get('fp32'):
  520. param.set_cast_dtype(mstype.float32)
  521. elif self._mindspore_flags.get('fp16'):
  522. param.set_cast_dtype(mstype.float16)
  523. else:
  524. # retest dtype
  525. param.set_cast_dtype()
  526. return param
  527. def insert_child_to_cell(self, child_name, child_cell):
  528. """
  529. Adds a child cell to the current cell with a given name.
  530. Args:
  531. child_name (str): Name of the child cell.
  532. child_cell (Cell): The child cell to be inserted.
  533. Raises:
  534. KeyError: Child Cell's name is incorrect or duplicated with the other child name.
  535. TypeError: Child Cell's type is incorrect.
  536. """
  537. if not child_name or '.' in child_name:
  538. raise KeyError("Child cell name is incorrect.")
  539. if hasattr(self, child_name) and child_name not in self._cells:
  540. raise KeyError("Duplicate child name '{}'.".format(child_name))
  541. if not isinstance(child_cell, Cell) and child_cell is not None:
  542. raise TypeError("Child cell type is incorrect.")
  543. self._cells[child_name] = child_cell
  544. def construct(self, *inputs, **kwargs):
  545. """
  546. Defines the computation to be performed. This method must be overridden by all subclasses.
  547. Note:
  548. The inputs of the top cell only allow Tensor.
  549. Other types (tuple, list, int etc.) are forbidden.
  550. Returns:
  551. Tensor, returns the computed result.
  552. """
  553. raise NotImplementedError
  554. def init_parameters_data(self, auto_parallel_mode=False):
  555. """
  556. Initialize all parameters and replace the original saved parameters in cell.
  557. Notes:
  558. trainable_params() and other similar interfaces may return different parameter instance after
  559. `init_parameters_data`, do not save these result.
  560. Args:
  561. auto_parallel_mode (bool): If running in auto_parallel_mode.
  562. Returns:
  563. Dict[Parameter, Parameter], returns a dict of original parameter and replaced parameter.
  564. """
  565. replace = dict()
  566. def _updata(param):
  567. if param in replace:
  568. return replace[param]
  569. layout = None
  570. set_sliced = False
  571. if auto_parallel_mode:
  572. set_sliced = True
  573. if param.name not in self.parameter_layout_dict:
  574. logger.debug("Layout dict does not contain the key %s.", param.name)
  575. else:
  576. layout = self.parameter_layout_dict[param.name]
  577. new_p = param.init_data(layout, set_sliced=set_sliced)
  578. replace[param] = new_p
  579. return new_p
  580. # replace all original usage.
  581. cells = self.cells_and_names()
  582. for _, cell in cells:
  583. params = cell._params.items()
  584. for param_name, param in params:
  585. cell._params[param_name] = _updata(param)
  586. cell_dict = cell.__dict__
  587. for key in cell_dict:
  588. if isinstance(cell_dict[key], ParameterTuple):
  589. param_tuple = cell_dict[key]
  590. new_param_tuple = []
  591. for param in param_tuple:
  592. new_param_tuple.append(_updata(param))
  593. cell.__dict__[key] = ParameterTuple(new_param_tuple)
  594. return replace
  595. def parameters_dict(self, recurse=True):
  596. """
  597. Gets parameters dictionary.
  598. Gets the parameters dictionary of this cell.
  599. Args:
  600. recurse (bool): Whether contains the parameters of subcells. Default: True.
  601. Returns:
  602. OrderedDict, return parameters dictionary.
  603. """
  604. param_dict = OrderedDict()
  605. for param in self.get_parameters(expand=recurse):
  606. param_dict[param.name] = param
  607. return param_dict
  608. def parameters_broadcast_dict(self, recurse=True):
  609. param_dict = OrderedDict()
  610. for param in self.get_parameters(expand=recurse):
  611. if param.layerwise_parallel is False:
  612. param_dict[param.name] = param
  613. if not param_dict:
  614. return None
  615. return param_dict
  616. def update_parameters_name(self, prefix='', recurse=True):
  617. """
  618. Updates the names of parameters with given prefix string.
  619. Adds the given prefix to the names of parameters.
  620. Args:
  621. prefix (str): The prefix string.
  622. recurse (bool): Whether contains the parameters of subcells. Default: True.
  623. """
  624. Validator.check_str_by_regular(prefix)
  625. for name, param in self.parameters_and_names(expand=recurse):
  626. if prefix != '':
  627. param.is_init = False
  628. param.name = prefix + name
  629. def trainable_params(self, recurse=True):
  630. """
  631. Returns all trainable parameters.
  632. Returns a list of all trainable parmeters.
  633. Args:
  634. recurse (bool): Whether contains the trainable parameters of subcells. Default: True.
  635. Returns:
  636. List, the list of trainable parameters.
  637. """
  638. return list(filter(lambda x: x.requires_grad, self.get_parameters(expand=recurse)))
  639. def untrainable_params(self, recurse=True):
  640. """
  641. Returns all untrainable parameters.
  642. Returns a list of all untrainable parameters.
  643. Args:
  644. recurse (bool): Whether contains the untrainable parameters of subcells. Default: True.
  645. Returns:
  646. List, the list of untrainable parameters.
  647. """
  648. return list(filter(lambda x: not x.requires_grad, self.get_parameters(expand=recurse)))
  649. def get_parameters(self, expand=True):
  650. """
  651. Returns an iterator over cell parameters.
  652. Yields parameters of this cell. If `expand` is True, yield parameters of this cell and all subcells.
  653. Args:
  654. expand (bool): If true, yields parameters of this cell and all subcells. Otherwise, only yield parameters
  655. that are direct members of this cell. Default: True.
  656. Examples:
  657. >>> net = Net()
  658. >>> for item in net.get_parameters():
  659. >>> print(item)
  660. """
  661. for _, param in self.parameters_and_names(expand=expand):
  662. yield param
  663. def check_names(self):
  664. names = set("")
  665. for value, param in self.parameters_and_names():
  666. if param.name in names:
  667. raise ValueError("The value of {} is {}, its name '{}' already exists.".
  668. format(value, param, param.name))
  669. names.add(param.name)
  670. def parameters_and_names(self, name_prefix='', expand=True):
  671. """
  672. Returns an iterator over cell parameters.
  673. Includes the parameter's name and itself.
  674. Args:
  675. name_prefix (str): Namespace. Default: ''.
  676. expand (bool): If true, yields parameters of this cell and all subcells. Otherwise, only yield parameters
  677. that are direct members of this cell. Default: True.
  678. Examples:
  679. >>> n = Net()
  680. >>> names = []
  681. >>> for m in n.parameters_and_names():
  682. >>> if m[0]:
  683. >>> names.append(m[0])
  684. """
  685. cells = []
  686. if expand:
  687. cells = self.cells_and_names(name_prefix=name_prefix)
  688. else:
  689. cells.append((name_prefix, self))
  690. params_set = set()
  691. for cell_name, cell in cells:
  692. params = cell._params.items()
  693. for par_name, par in params:
  694. if par.inited_param is not None:
  695. par = par.inited_param
  696. if par is not None and id(par) not in params_set:
  697. params_set.add(id(par))
  698. par_new_name = par_name
  699. if cell_name:
  700. par_new_name = cell_name + '.' + par_new_name
  701. yield par_new_name, par
  702. def cells_and_names(self, cells=None, name_prefix=''):
  703. """
  704. Returns an iterator over all cells in the network.
  705. Includes the cell's name and itself.
  706. Args:
  707. cells (str): Cells to iterate over. Default: None.
  708. name_prefix (str): Namespace. Default: ''.
  709. Examples:
  710. >>> n = Net()
  711. >>> names = []
  712. >>> for m in n.cells_and_names():
  713. >>> if m[0]:
  714. >>> names.append(m[0])
  715. """
  716. t_cells = cells if cells else set()
  717. if self in t_cells:
  718. return
  719. t_cells.add(self)
  720. yield name_prefix, self
  721. for name, cell in self._cells.items():
  722. if cell:
  723. cells_name_prefix = name
  724. if name_prefix:
  725. cells_name_prefix = name_prefix + '.' + cells_name_prefix
  726. for ele in cell.cells_and_names(t_cells, cells_name_prefix):
  727. yield ele
  728. def cells(self):
  729. """Returns an iterator over immediate cells."""
  730. return self.name_cells().values()
  731. def _set_scope(self, name):
  732. """Sets the name on the first time."""
  733. if self._scope is None:
  734. self._scope = name
  735. def _children_scope_recursive(self, parent_prefix='Default'):
  736. """Generates the scope of each layer of the network recursively."""
  737. reserve_class_name_in_scope = context.get_context("reserve_class_name_in_scope")
  738. for name, cell in self.name_cells().items():
  739. yield parent_prefix + "/" + name + (("-" + cell.__class__.__name__)
  740. if reserve_class_name_in_scope else ""), cell
  741. for name, cell in self.name_cells().items():
  742. for key, value in cell._children_scope_recursive(parent_prefix + "/" + name +
  743. (("-" + cell.__class__.__name__)
  744. if reserve_class_name_in_scope else "")):
  745. yield key, value
  746. def get_scope(self):
  747. """Returns the scope of a cell object in one network."""
  748. return self._scope
  749. def generate_scope(self):
  750. """Generate the scope for each cell object in the network."""
  751. for name, cell in self._children_scope_recursive():
  752. cell._set_scope(name)
  753. def name_cells(self):
  754. """
  755. Returns an iterator over all cells in the network.
  756. Include name of the cell and cell itself.
  757. """
  758. value_set = set()
  759. cells = OrderedDict()
  760. for name, cell in self._cells.items():
  761. if cell is not None and cell not in value_set:
  762. value_set.add(cell)
  763. cells[name] = cell
  764. return cells
  765. def add_flags(self, **flags):
  766. if not hasattr(self, "_mindspore_flags"):
  767. self._mindspore_flags = {}
  768. self._mindspore_flags.update({**flags})
  769. self.__dict__.update({**flags})
  770. return self
  771. def add_flags_recursive(self, **flags):
  772. self.add_flags(**flags)
  773. if hasattr(self, '_cell_init_args'):
  774. self._cell_init_args += str({**flags})
  775. for cell in self.cells():
  776. cell.add_flags_recursive(**flags)
  777. return self
  778. def get_flags(self):
  779. if not hasattr(self, "_mindspore_flags"):
  780. self._mindspore_flags = {}
  781. return self._mindspore_flags
  782. def to_float(self, dst_type):
  783. """
  784. Add cast on all inputs of cell and child cells to run with certain float type.
  785. If `dst_type is mindspore.dtype.float16`, all the inputs of Cell including input, Parameter, Tensor
  786. as const will be cast to float16. Please refer to the usage in source code of
  787. `mindspore.train.amp.build_train_network`.
  788. Note:
  789. Multiple calls will overwrite.
  790. Args:
  791. dst_type (:class:`mindspore.dtype`): Transfer Cell to Run with dst_type.
  792. dst_type can be `mindspore.dtype.float16` or `mindspore.dtype.float32`.
  793. Raises:
  794. ValueError: If dst_type is not float32 nor float16.
  795. """
  796. if dst_type not in (mstype.float16, mstype.float32):
  797. raise ValueError("dst_type should inside float32 or float16.")
  798. flags = {'fp16': dst_type == mstype.float16, 'fp32': dst_type == mstype.float32}
  799. self.add_flags_recursive(**flags)
  800. return self
  801. def set_grad(self, requires_grad=True):
  802. """
  803. Sets the cell flag for gradient.
  804. Args:
  805. requires_grad (bool): Specifies if the net need to grad, if it is
  806. True, cell will construct backward network in pynative mode. Default: True.
  807. """
  808. self.requires_grad = requires_grad
  809. return self
  810. def set_train(self, mode=True):
  811. """
  812. Sets the cell to training mode.
  813. The cell itself and all children cells will be set to training mode.
  814. Args:
  815. mode (bool): Specifies whether the model is training. Default: True.
  816. """
  817. if mode is False:
  818. self._phase = 'predict'
  819. else:
  820. self._phase = 'train'
  821. self.add_flags_recursive(training=mode)
  822. return self
  823. def set_broadcast_flag(self, mode=True):
  824. """
  825. Set the cell to data_parallel mode.
  826. The cell can be accessed as an attribute using the given name.
  827. Args:
  828. mode (bool): Specifies whether the model is data_parallel. Default: True.
  829. """
  830. self.add_flags_recursive(broadcast_flag=mode)
  831. return self
  832. def set_auto_parallel(self):
  833. """
  834. Set the cell to auto parallel mode.
  835. Note:
  836. If a cell needs to use the auto parallel or semi auto parallel mode for training, evaluation or prediction,
  837. this interface needs to be called by the cell.
  838. """
  839. self._auto_parallel_mode = True
  840. self.add_flags(auto_parallel=True)
  841. self._get_construct_inputs_number_and_name()
  842. def _hook_construct(self, *inputs, **kwargs):
  843. """Hook construct method to replace original construct method when hook function enabled."""
  844. inputs = self._backward_hook(*inputs)
  845. inputs = self.construct(inputs)
  846. outputs = self._backward_hook(inputs)
  847. return outputs
  848. def register_backward_hook(self, fn):
  849. """
  850. Set the cell backward hook function. Note that this function is only supported in Pynative Mode.
  851. Note:
  852. fn must be defined as the following code. `cell_name` is the name of registered cell.
  853. `grad_input` is gradient passed to the cell. `grad_output` is the gradient computed and passed to the
  854. next cell or primitve, which may be modified and returned.
  855. >>> hook_fn(cell_name, grad_input, grad_output) -> Tensor or None
  856. Args:
  857. fn (function): Specifies the hook function with grad as input.
  858. """
  859. self._backward_hook = HookBackward(fn, self.cls_name + "(" + str(id(self)) + ")")
  860. self.enable_hook = True
  861. def set_param_ps(self, recurse=True, init_in_server=False):
  862. """
  863. Set whether the trainable parameter is updated by parameter server.
  864. Note:
  865. It only works when a running task is in the parameter server mode.
  866. Args:
  867. recurse (bool): Whether sets the trainable parameters of subcells. Default: True.
  868. """
  869. params = self.trainable_params(recurse)
  870. for param in params:
  871. param.set_param_ps(init_in_server)
  872. class GraphKernel(Cell):
  873. """
  874. Base class for GraphKernel.
  875. A `GraphKernel` a composite of basic primitives and can be compiled into a fused kernel automatically when
  876. enable_graph_kernel in context is set to True.
  877. Examples:
  878. >>> class Relu(GraphKernel):
  879. >>> def __init__(self):
  880. >>> super(Relu, self).__init__()
  881. >>> self.max = P.Maximum()
  882. >>>
  883. >>> def construct(self, x):
  884. >>> return self.max(P.Fill()(P.DType()(x), P.Shape()(x), 0.0), x)
  885. """
  886. def __init__(self, auto_prefix=True, pips=None):
  887. super(GraphKernel, self).__init__(auto_prefix, pips)
  888. class_name = self.__class__.__name__
  889. self.add_flags(graph_kernel=class_name)
  890. def construct(self):
  891. raise NotImplementedError