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_wrapper.py 13 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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_wrapper."""
  16. from mindspore.parallel._utils import (_get_device_num, _get_mirror_mean,
  17. _get_parallel_mode)
  18. from mindspore.train.parallel_utils import ParallelMode
  19. from ...common import dtype as mstype
  20. from ...common.parameter import Parameter, ParameterTuple
  21. from ...ops import composite as C
  22. from ...ops import functional as F
  23. from ...ops import operations as P
  24. from ...ops.composite.base import _mp_cast_helper
  25. from ...ops.operations.comm_ops import _VirtualDataset
  26. from ..cell import Cell
  27. from .grad_reducer import DistributedGradReducer
  28. class WithLossCell(Cell):
  29. r"""
  30. Cell with loss function.
  31. Wraps the network with loss function. This Cell accepts data and label as inputs and
  32. the computed loss will be returned.
  33. Args:
  34. backbone (Cell): The target network to wrap.
  35. loss_fn (Cell): The loss function used to compute loss.
  36. Inputs:
  37. - **data** (Tensor) - Tensor of shape :math:`(N, \ldots)`.
  38. - **label** (Tensor) - Tensor of shape :math:`(N, \ldots)`.
  39. Outputs:
  40. Tensor, a scalar tensor with shape :math:`()`.
  41. Examples:
  42. >>> net = Net()
  43. >>> loss_fn = nn.SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=True)
  44. >>> net_with_criterion = nn.WithLossCell(net, loss_fn)
  45. >>>
  46. >>> batch_size = 2
  47. >>> data = Tensor(np.ones([batch_size, 3, 64, 64]).astype(np.float32) * 0.01)
  48. >>> label = Tensor(np.ones([batch_size, 1, 1, 1]).astype(np.int32))
  49. >>>
  50. >>> net_with_criterion(data, label)
  51. """
  52. def __init__(self, backbone, loss_fn):
  53. super(WithLossCell, self).__init__(auto_prefix=False)
  54. self._backbone = backbone
  55. self._loss_fn = loss_fn
  56. def construct(self, data, label):
  57. out = self._backbone(data)
  58. return self._loss_fn(out, label)
  59. @property
  60. def backbone_network(self):
  61. """
  62. Returns the backbone network.
  63. Returns:
  64. Cell, the backbone network.
  65. """
  66. return self._backbone
  67. class WithGradCell(Cell):
  68. r"""
  69. Cell that returns the gradients.
  70. Wraps the network with backward cell to compute gradients. A network with a loss function is necessary
  71. as argument. If loss function in None, the network must be a wrapper of network and loss function. This
  72. Cell accepts data and label as inputs and returns gradients for each trainable parameter.
  73. Note:
  74. Run in PyNative mode.
  75. Args:
  76. network (Cell): The target network to wrap.
  77. loss_fn (Cell): Primitive loss function used to compute gradients. Default: None.
  78. sens (Union[None, Tensor, Scalar, Tuple ...]): The sensitive for backpropagation, the type and shape
  79. should be same as the `network` output. If None, we will fill one to a same type shape of
  80. output value. Default: None.
  81. Inputs:
  82. - **data** (Tensor) - Tensor of shape :math:`(N, \ldots)`.
  83. - **label** (Tensor) - Tensor of shape :math:`(N, \ldots)`.
  84. Outputs:
  85. list, a list of Tensors with identical shapes as trainable weights.
  86. Examples:
  87. >>> # For a defined network Net without loss function
  88. >>> net = Net()
  89. >>> loss_fn = nn.SoftmaxCrossEntropyWithLogits()
  90. >>> grad_net = nn.WithGradCell(net, loss_fn)
  91. >>>
  92. >>> # For a network wrapped with loss function
  93. >>> net = Net()
  94. >>> net_with_criterion = nn.WithLossCell(net, loss_fn)
  95. >>> grad_net = nn.WithGradCell(net_with_criterion)
  96. """
  97. def __init__(self, network, loss_fn=None, sens=None):
  98. super(WithGradCell, self).__init__(auto_prefix=False)
  99. self.network = network
  100. self.loss_fn = loss_fn
  101. self.weights = ParameterTuple(network.trainable_params())
  102. self.grad = C.GradOperation('grad', get_by_list=True, sens_param=(sens is not None))
  103. self.sens = sens
  104. if loss_fn is None:
  105. self.network_with_loss = network
  106. else:
  107. self.network_with_loss = WithLossCell(self.network, self.loss_fn)
  108. self.network_with_loss.set_train()
  109. def construct(self, data, label):
  110. weights = self.weights
  111. if self.sens is None:
  112. grads = self.grad(self.network_with_loss, weights)(data, label)
  113. else:
  114. grads = self.grad(self.network_with_loss, weights)(data, label, self.sens)
  115. return grads
  116. class TrainOneStepCell(Cell):
  117. r"""
  118. Network training package class.
  119. Wraps the network with an optimizer. The resulting Cell be trained with input data and label.
  120. Backward graph will be created in the construct function to do parameter updating. Different
  121. parallel modes are available to run the training.
  122. Args:
  123. network (Cell): The training network.
  124. optimizer (Cell): Optimizer for updating the weights.
  125. sens (Number): The scaling number to be filled as the input of backpropagation. Default value is 1.0.
  126. Inputs:
  127. - **data** (Tensor) - Tensor of shape :math:`(N, \ldots)`.
  128. - **label** (Tensor) - Tensor of shape :math:`(N, \ldots)`.
  129. Outputs:
  130. Tensor, a scalar Tensor with shape :math:`()`.
  131. Examples:
  132. >>> net = Net()
  133. >>> loss_fn = nn.SoftmaxCrossEntropyWithLogits()
  134. >>> optim = nn.Momentum(net.trainable_params(), learning_rate=0.1, momentum=0.9)
  135. >>> loss_net = nn.WithLossCell(net, loss_fn)
  136. >>> train_net = nn.TrainOneStepCell(loss_net, optim)
  137. """
  138. def __init__(self, network, optimizer, sens=1.0):
  139. super(TrainOneStepCell, self).__init__(auto_prefix=False)
  140. self.network = network
  141. self.network.add_flags(defer_inline=True)
  142. self.weights = ParameterTuple(network.trainable_params())
  143. self.optimizer = optimizer
  144. self.grad = C.GradOperation('grad', get_by_list=True, sens_param=True)
  145. self.sens = sens
  146. self.reducer_flag = False
  147. self.grad_reducer = None
  148. parallel_mode = _get_parallel_mode()
  149. if parallel_mode in (ParallelMode.DATA_PARALLEL, ParallelMode.HYBRID_PARALLEL):
  150. self.reducer_flag = True
  151. if self.reducer_flag:
  152. mean = _get_mirror_mean()
  153. degree = _get_device_num()
  154. self.grad_reducer = DistributedGradReducer(optimizer.parameters, mean, degree)
  155. def construct(self, data, label):
  156. weights = self.weights
  157. loss = self.network(data, label)
  158. sens = P.Fill()(P.DType()(loss), P.Shape()(loss), self.sens)
  159. grads = self.grad(self.network, weights)(data, label, sens)
  160. if self.reducer_flag:
  161. # apply grad reducer on grads
  162. grads = self.grad_reducer(grads)
  163. return F.depend(loss, self.optimizer(grads))
  164. class DataWrapper(Cell):
  165. """
  166. Network training package class for dataset.
  167. DataWrapper wraps the input network with a dataset which automatically fetches data with 'GetNext'
  168. function from the dataset channel 'queue_name' and does forward computation in the construct function.
  169. Args:
  170. network (Cell): The training network for dataset.
  171. dataset_types (list): The type of dataset. The list contains describes the types of the inputs.
  172. dataset_shapes (list): The shapes of dataset. The list contains multiple sublists that describes
  173. the shape of the inputs.
  174. queue_name (str): The identification of dataset channel which specifies the dataset channel to supply
  175. data for the network.
  176. Outputs:
  177. Tensor, network output whose shape depends on the network.
  178. Examples:
  179. >>> # call create_dataset function to create a regular dataset, refer to mindspore.dataset
  180. >>> train_dataset = create_dataset()
  181. >>> dataset_helper = mindspore.DatasetHelper(train_dataset)
  182. >>> net = Net()
  183. >>> net = DataWrapper(net, *(dataset_helper.types_shapes()), train_dataset.queue_name)
  184. """
  185. def __init__(self, network, dataset_types, dataset_shapes, queue_name):
  186. super(DataWrapper, self).__init__(auto_prefix=False, flags=network.get_flags())
  187. self.get_next = P.GetNext(dataset_types, dataset_shapes, len(dataset_types), queue_name)
  188. self.network = network
  189. def construct(self):
  190. outputs = self.get_next()
  191. return self.network(*outputs)
  192. class GetNextSingleOp(Cell):
  193. """
  194. Cell to run get next operation.
  195. Args:
  196. dataset_types (list[:class:`mindspore.dtype`]): The types of dataset.
  197. dataset_shapes (list[tuple[int]]): The shapes of dataset.
  198. queue_name (str): Queue name to fetch the data.
  199. Detailed information, please refer to `ops.operations.GetNext`.
  200. """
  201. def __init__(self, dataset_types, dataset_shapes, queue_name):
  202. super(GetNextSingleOp, self).__init__()
  203. self.get_next = P.GetNext(dataset_types, dataset_shapes, len(dataset_types), queue_name)
  204. def construct(self):
  205. return self.get_next()
  206. class _VirtualDatasetCell(Cell):
  207. """
  208. Wrap the network with virtual dataset to convert data parallel layout to model parallel layout.
  209. _VirtualDataset is a virtual Primitive, it does not exist in the final executing graph. Inputs and outpus
  210. of _VirtualDataset are distributed in data parallel pattern, tensor redistribution Primitives is inserted
  211. dynamically during the graph compile process.
  212. Note:
  213. Only used in semi auto parallel and auto parallel mode.
  214. Args:
  215. backbone (Cell): The target network to wrap.
  216. Examples:
  217. >>> net = Net()
  218. >>> net = _VirtualDatasetCell(net)
  219. """
  220. def __init__(self, backbone):
  221. super(_VirtualDatasetCell, self).__init__(auto_prefix=False)
  222. self._backbone = backbone
  223. self._virtual_dataset = _VirtualDataset()
  224. def construct(self, data, label):
  225. data_, label_ = self._virtual_dataset(data, label)
  226. return self._backbone(data_, label_)
  227. class WithEvalCell(Cell):
  228. r"""
  229. Cell that returns loss, output and label for evaluation.
  230. This Cell accepts a network and loss function as arguments and computes loss for model.
  231. It returns loss, output and label to calculate the metrics.
  232. Args:
  233. network (Cell): The network Cell.
  234. loss_fn (Cell): The loss Cell.
  235. Inputs:
  236. - **data** (Tensor) - Tensor of shape :math:`(N, \ldots)`.
  237. - **label** (Tensor) - Tensor of shape :math:`(N, \ldots)`.
  238. Outputs:
  239. Tuple, containing a scalar loss Tensor, a network output Tensor of shape :math:`(N, \ldots)`
  240. and a label Tensor of shape :math:`(N, \ldots)`.
  241. Examples:
  242. >>> # For a defined network Net without loss function
  243. >>> net = Net()
  244. >>> loss_fn = nn.SoftmaxCrossEntropyWithLogits()
  245. >>> eval_net = nn.WithEvalCell(net, loss_fn)
  246. """
  247. def __init__(self, network, loss_fn):
  248. super(WithEvalCell, self).__init__(auto_prefix=False)
  249. self._network = network
  250. self._loss_fn = loss_fn
  251. def construct(self, data, label):
  252. outputs = self._network(data)
  253. label = _mp_cast_helper(mstype.float32, label)
  254. loss = self._loss_fn(F.cast(outputs, mstype.float32), label)
  255. return loss, outputs, label
  256. class ParameterUpdate(Cell):
  257. """
  258. Cell that updates parameters.
  259. With this Cell, one can manually update `param` with the input `Tensor`.
  260. Args:
  261. param (Parameter): The parameter to be updated manually.
  262. Raises:
  263. KeyError: If parameter with the specified name do not exist.
  264. Examples:
  265. >>> network = Net()
  266. >>> param = network.parameters_dict()['learning_rate']
  267. >>> update = nn.ParameterUpdate(param)
  268. >>> update.phase = "update_param"
  269. >>> lr = Tensor(0.001, mindspore.float32)
  270. >>> update(lr)
  271. """
  272. def __init__(self, param):
  273. super(ParameterUpdate, self).__init__(auto_prefix=False)
  274. if not isinstance(param, Parameter):
  275. raise TypeError("`param` must be `Parameter`, but got {}".format(param))
  276. self._param = param
  277. def construct(self, x):
  278. F.assign(self._param, x)
  279. return x