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.

test_summary.py 7.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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. """ test model train """
  16. import os
  17. import re
  18. import tempfile
  19. import shutil
  20. import pytest
  21. from mindspore import dataset as ds
  22. from mindspore import nn, Tensor, context
  23. from mindspore.nn.metrics import Accuracy
  24. from mindspore.nn.optim import Momentum
  25. from mindspore.dataset.transforms import c_transforms as C
  26. from mindspore.dataset.transforms.vision import c_transforms as CV
  27. from mindspore.dataset.transforms.vision import Inter
  28. from mindspore.common import dtype as mstype
  29. from mindspore.common.initializer import TruncatedNormal
  30. from mindspore.ops import operations as P
  31. from mindspore.train import Model
  32. from mindspore.train.callback import SummaryCollector
  33. from tests.summary_utils import SummaryReader
  34. def conv(in_channels, out_channels, kernel_size, stride=1, padding=0):
  35. """weight initial for conv layer"""
  36. weight = weight_variable()
  37. return nn.Conv2d(in_channels, out_channels,
  38. kernel_size=kernel_size, stride=stride, padding=padding,
  39. weight_init=weight, has_bias=False, pad_mode="valid")
  40. def fc_with_initialize(input_channels, out_channels):
  41. """weight initial for fc layer"""
  42. weight = weight_variable()
  43. bias = weight_variable()
  44. return nn.Dense(input_channels, out_channels, weight, bias)
  45. def weight_variable():
  46. """weight initial"""
  47. return TruncatedNormal(0.02)
  48. class LeNet5(nn.Cell):
  49. """Define LeNet5 network."""
  50. def __init__(self, num_class=10, channel=1):
  51. super(LeNet5, self).__init__()
  52. self.num_class = num_class
  53. self.conv1 = conv(channel, 6, 5)
  54. self.conv2 = conv(6, 16, 5)
  55. self.fc1 = fc_with_initialize(16 * 5 * 5, 120)
  56. self.fc2 = fc_with_initialize(120, 84)
  57. self.fc3 = fc_with_initialize(84, self.num_class)
  58. self.relu = nn.ReLU()
  59. self.max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2)
  60. self.flatten = nn.Flatten()
  61. self.scalar_summary = P.ScalarSummary()
  62. self.image_summary = P.ImageSummary()
  63. self.histogram_summary = P.HistogramSummary()
  64. self.tensor_summary = P.TensorSummary()
  65. self.channel = Tensor(channel)
  66. def construct(self, data):
  67. """define construct."""
  68. self.image_summary('image', data)
  69. output = self.conv1(data)
  70. self.histogram_summary('histogram', output)
  71. output = self.relu(output)
  72. self.tensor_summary('tensor', output)
  73. output = self.max_pool2d(output)
  74. output = self.conv2(output)
  75. output = self.relu(output)
  76. output = self.max_pool2d(output)
  77. output = self.flatten(output)
  78. output = self.fc1(output)
  79. output = self.relu(output)
  80. output = self.fc2(output)
  81. output = self.relu(output)
  82. output = self.fc3(output)
  83. self.scalar_summary('scalar', self.channel)
  84. return output
  85. def create_dataset(data_path, batch_size=32, repeat_size=1, num_parallel_workers=1):
  86. """create dataset for train or test"""
  87. # define dataset
  88. mnist_ds = ds.MnistDataset(data_path)
  89. resize_height, resize_width = 32, 32
  90. rescale = 1.0 / 255.0
  91. rescale_nml = 1 / 0.3081
  92. shift_nml = -1 * 0.1307 / 0.3081
  93. # define map operations
  94. resize_op = CV.Resize((resize_height, resize_width), interpolation=Inter.LINEAR) # Bilinear mode
  95. rescale_nml_op = CV.Rescale(rescale_nml, shift_nml)
  96. rescale_op = CV.Rescale(rescale, shift=0.0)
  97. hwc2chw_op = CV.HWC2CHW()
  98. type_cast_op = C.TypeCast(mstype.int32)
  99. # apply map operations on images
  100. mnist_ds = mnist_ds.map(input_columns="label", operations=type_cast_op, num_parallel_workers=num_parallel_workers)
  101. mnist_ds = mnist_ds.map(input_columns="image", operations=resize_op, num_parallel_workers=num_parallel_workers)
  102. mnist_ds = mnist_ds.map(input_columns="image", operations=rescale_op, num_parallel_workers=num_parallel_workers)
  103. mnist_ds = mnist_ds.map(input_columns="image", operations=rescale_nml_op, num_parallel_workers=num_parallel_workers)
  104. mnist_ds = mnist_ds.map(input_columns="image", operations=hwc2chw_op, num_parallel_workers=num_parallel_workers)
  105. # apply DatasetOps
  106. mnist_ds = mnist_ds.shuffle(buffer_size=10000) # 10000 as in LeNet train script
  107. mnist_ds = mnist_ds.batch(batch_size, drop_remainder=True)
  108. mnist_ds = mnist_ds.repeat(repeat_size)
  109. return mnist_ds
  110. class TestSummary:
  111. """Test summary collector the basic function."""
  112. base_summary_dir = ''
  113. mnist_path = '/home/workspace/mindspore_dataset/mnist'
  114. @classmethod
  115. def setup_class(cls):
  116. """Run before test this class."""
  117. cls.base_summary_dir = tempfile.mkdtemp(suffix='summary')
  118. @classmethod
  119. def teardown_class(cls):
  120. """Run after test this class."""
  121. if os.path.exists(cls.base_summary_dir):
  122. shutil.rmtree(cls.base_summary_dir)
  123. @pytest.mark.level0
  124. @pytest.mark.platform_x86_ascend_training
  125. @pytest.mark.env_onecard
  126. def test_summary_ascend(self):
  127. """Test summary ascend."""
  128. context.set_context(mode=context.GRAPH_MODE)
  129. self._run_network()
  130. def _run_network(self, dataset_sink_mode=True):
  131. lenet = LeNet5()
  132. loss = nn.SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=True, reduction="mean")
  133. optim = Momentum(lenet.trainable_params(), learning_rate=0.1, momentum=0.9)
  134. model = Model(lenet, loss_fn=loss, optimizer=optim, metrics={'acc': Accuracy()})
  135. summary_dir = tempfile.mkdtemp(dir=self.base_summary_dir)
  136. summary_collector = SummaryCollector(summary_dir=summary_dir, collect_freq=1)
  137. ds_train = create_dataset(os.path.join(self.mnist_path, "train"))
  138. model.train(1, ds_train, callbacks=[summary_collector], dataset_sink_mode=dataset_sink_mode)
  139. ds_eval = create_dataset(os.path.join(self.mnist_path, "test"))
  140. model.eval(ds_eval, dataset_sink_mode=dataset_sink_mode, callbacks=[summary_collector])
  141. self._check_summary_result(summary_dir)
  142. @staticmethod
  143. def _check_summary_result(summary_dir):
  144. summary_file_path = ''
  145. for file in os.listdir(summary_dir):
  146. if re.search("_MS", file):
  147. summary_file_path = os.path.join(summary_dir, file)
  148. break
  149. assert not summary_file_path
  150. with SummaryReader(summary_file_path) as summary_reader:
  151. tags = set()
  152. # Read the event that record by SummaryCollector.begin
  153. summary_reader.read_event()
  154. summary_event = summary_reader.read_event()
  155. for value in summary_event.summary.value:
  156. tags.add(value.tag)
  157. # There will not record input data when dataset sink mode is True
  158. expected_tags = ['conv1.weight/auto', 'conv2.weight/auto', 'fc1.weight/auto', 'fc1.bias/auto',
  159. 'fc2.weight/auto', 'histogram', 'image', 'scalar', 'tensor']
  160. assert set(expected_tags) == tags