1# Copyright 2019 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"""Summary cpu st.""" 16import os 17import platform 18import tempfile 19 20import numpy as np 21import pytest 22 23import mindspore.context as context 24import mindspore.nn as nn 25from mindspore import Tensor 26from mindspore.ops import operations as P 27from mindspore.train.summary.summary_record import SummaryRecord 28from tests.summary_utils import SummaryReader 29from tests.security_utils import security_off_wrap 30 31context.set_context(mode=context.GRAPH_MODE, device_target='CPU') 32 33 34class SummaryNet(nn.Cell): 35 def __init__(self): 36 super().__init__() 37 self.scalar_summary = P.ScalarSummary() 38 self.image_summary = P.ImageSummary() 39 self.tensor_summary = P.TensorSummary() 40 self.histogram_summary = P.HistogramSummary() 41 42 def construct(self, image_tensor): 43 self.image_summary("image", image_tensor) 44 self.tensor_summary("tensor", image_tensor) 45 self.histogram_summary("histogram", image_tensor) 46 scalar = image_tensor[0][0][0][0] 47 self.scalar_summary("scalar", scalar) 48 return scalar 49 50 51def train_summary_record(test_writer, steps): 52 """Train and record summary.""" 53 net = SummaryNet() 54 out_me_dict = {} 55 for i in range(0, steps): 56 image_tensor = Tensor(np.array([[[[i]]]]).astype(np.float32)) 57 out_put = net(image_tensor) 58 test_writer.record(i) 59 out_me_dict[i] = out_put.asnumpy() 60 return out_me_dict 61 62 63@pytest.mark.level0 64@pytest.mark.platform_x86_cpu 65@pytest.mark.env_onecard 66@security_off_wrap 67def test_summary_step2_summary_record1(): 68 """Test record 10 step summary.""" 69 if platform.system() == "Windows": 70 # Summary does not support windows currently. 71 return 72 73 with tempfile.TemporaryDirectory() as tmp_dir: 74 steps = 2 75 with SummaryRecord(tmp_dir) as test_writer: 76 train_summary_record(test_writer, steps=steps) 77 78 file_name = os.path.realpath(test_writer.log_dir) 79 with SummaryReader(file_name) as summary_writer: 80 for _ in range(steps): 81 event = summary_writer.read_event() 82 tags = set(value.tag for value in event.summary.value) 83 assert tags == {'tensor', 'histogram', 'scalar', 'image'} 84