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_ops.py 4.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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 summary ops."""
  16. import os
  17. import shutil
  18. import tempfile
  19. import numpy as np
  20. import pytest
  21. from mindspore import nn, Tensor, context
  22. from mindspore.common.initializer import Normal
  23. from mindspore.nn.metrics import Loss
  24. from mindspore.nn.optim import Momentum
  25. from mindspore.ops import operations as P
  26. from mindspore.train import Model
  27. from mindspore.train.summary.summary_record import _get_summary_tensor_data
  28. from tests.st.summary.dataset import create_mnist_dataset
  29. class LeNet5(nn.Cell):
  30. """LeNet network"""
  31. def __init__(self, num_class=10, num_channel=1, include_top=True):
  32. super(LeNet5, self).__init__()
  33. self.conv1 = nn.Conv2d(num_channel, 6, 5, pad_mode='valid')
  34. self.conv2 = nn.Conv2d(6, 16, 5, pad_mode='valid')
  35. self.relu = nn.ReLU()
  36. self.max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2)
  37. self.include_top = include_top
  38. if self.include_top:
  39. self.flatten = nn.Flatten()
  40. self.fc1 = nn.Dense(16 * 5 * 5, 120, weight_init=Normal(0.02))
  41. self.fc2 = nn.Dense(120, 84, weight_init=Normal(0.02))
  42. self.fc3 = nn.Dense(84, num_class, weight_init=Normal(0.02))
  43. self.scalar_summary = P.ScalarSummary()
  44. self.image_summary = P.ImageSummary()
  45. self.tensor_summary = P.TensorSummary()
  46. self.channel = Tensor(num_channel)
  47. def construct(self, x):
  48. """construct"""
  49. self.image_summary('x', x)
  50. self.tensor_summary('x', x)
  51. x = self.conv1(x)
  52. x = self.relu(x)
  53. x = self.max_pool2d(x)
  54. x = self.conv2(x)
  55. x = self.relu(x)
  56. x = self.max_pool2d(x)
  57. if not self.include_top:
  58. return x
  59. x = self.flatten(x)
  60. x = self.relu(self.fc1(x))
  61. x = self.relu(self.fc2(x))
  62. x = self.fc3(x)
  63. self.scalar_summary('x_fc3', x[0][0])
  64. return x
  65. class TestSummaryOps:
  66. """Test summary ops."""
  67. base_summary_dir = ''
  68. @classmethod
  69. def setup_class(cls):
  70. """Run before test this class."""
  71. device_id = int(os.getenv('DEVICE_ID')) if os.getenv('DEVICE_ID') else 0
  72. context.set_context(mode=context.GRAPH_MODE, device_id=device_id)
  73. cls.base_summary_dir = tempfile.mkdtemp(suffix='summary')
  74. @classmethod
  75. def teardown_class(cls):
  76. """Run after test this class."""
  77. if os.path.exists(cls.base_summary_dir):
  78. shutil.rmtree(cls.base_summary_dir)
  79. @pytest.mark.level0
  80. @pytest.mark.platform_x86_ascend_training
  81. @pytest.mark.platform_arm_ascend_training
  82. @pytest.mark.platform_x86_gpu_training
  83. @pytest.mark.env_onecard
  84. def test_summary_ops(self):
  85. """Test summary operators."""
  86. ds_train = create_mnist_dataset('train', num_samples=1, batch_size=1)
  87. ds_train_iter = ds_train.create_dict_iterator()
  88. expected_data = next(ds_train_iter)['image'].asnumpy()
  89. net = LeNet5()
  90. loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction="mean")
  91. optim = Momentum(net.trainable_params(), learning_rate=0.1, momentum=0.9)
  92. model = Model(net, loss_fn=loss, optimizer=optim, metrics={'loss': Loss()})
  93. model.train(1, ds_train, dataset_sink_mode=False)
  94. summary_data = _get_summary_tensor_data()
  95. image_data = summary_data['x[:Image]'].asnumpy()
  96. tensor_data = summary_data['x[:Tensor]'].asnumpy()
  97. x_fc3 = summary_data['x_fc3[:Scalar]'].asnumpy()
  98. assert np.allclose(expected_data, image_data)
  99. assert np.allclose(expected_data, tensor_data)
  100. assert not np.allclose(0, x_fc3)