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# ============================================================================ 15import os 16import shutil 17 18import sys 19 20from tests.security_utils import security_off_wrap 21import pytest 22 23from mindspore import dataset as ds 24from mindspore import nn, Tensor, context 25from mindspore.nn.metrics import Accuracy 26from mindspore.nn.optim import Momentum 27from mindspore.dataset.transforms import c_transforms as C 28from mindspore.dataset.vision import c_transforms as CV 29from mindspore.dataset.vision import Inter 30from mindspore.common import dtype as mstype 31from mindspore.common.initializer import TruncatedNormal 32from mindspore.train import Model 33from mindspore.profiler import Profiler 34 35 36def conv(in_channels, out_channels, kernel_size, stride=1, padding=0): 37 """weight initial for conv layer""" 38 weight = weight_variable() 39 return nn.Conv2d(in_channels, out_channels, 40 kernel_size=kernel_size, stride=stride, padding=padding, 41 weight_init=weight, has_bias=False, pad_mode="valid") 42 43 44def fc_with_initialize(input_channels, out_channels): 45 """weight initial for fc layer""" 46 weight = weight_variable() 47 bias = weight_variable() 48 return nn.Dense(input_channels, out_channels, weight, bias) 49 50 51def weight_variable(): 52 """weight initial""" 53 return TruncatedNormal(0.02) 54 55 56class LeNet5(nn.Cell): 57 """Define LeNet5 network.""" 58 59 def __init__(self, num_class=10, channel=1): 60 super(LeNet5, self).__init__() 61 self.num_class = num_class 62 self.conv1 = conv(channel, 6, 5) 63 self.conv2 = conv(6, 16, 5) 64 self.fc1 = fc_with_initialize(16 * 5 * 5, 120) 65 self.fc2 = fc_with_initialize(120, 84) 66 self.fc3 = fc_with_initialize(84, self.num_class) 67 self.relu = nn.ReLU() 68 self.max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2) 69 self.flatten = nn.Flatten() 70 self.channel = Tensor(channel) 71 72 def construct(self, data): 73 """define construct.""" 74 output = self.conv1(data) 75 output = self.relu(output) 76 output = self.max_pool2d(output) 77 output = self.conv2(output) 78 output = self.relu(output) 79 output = self.max_pool2d(output) 80 output = self.flatten(output) 81 output = self.fc1(output) 82 output = self.relu(output) 83 output = self.fc2(output) 84 output = self.relu(output) 85 output = self.fc3(output) 86 return output 87 88 89def create_dataset(data_path, batch_size=32, repeat_size=1, num_parallel_workers=1): 90 """create dataset for train""" 91 # define dataset 92 mnist_ds = ds.MnistDataset(data_path, num_samples=batch_size * 100) 93 94 resize_height, resize_width = 32, 32 95 rescale = 1.0 / 255.0 96 rescale_nml = 1 / 0.3081 97 shift_nml = -1 * 0.1307 / 0.3081 98 99 # define map operations 100 resize_op = CV.Resize((resize_height, resize_width), interpolation=Inter.LINEAR) # Bilinear mode 101 rescale_nml_op = CV.Rescale(rescale_nml, shift_nml) 102 rescale_op = CV.Rescale(rescale, shift=0.0) 103 hwc2chw_op = CV.HWC2CHW() 104 type_cast_op = C.TypeCast(mstype.int32) 105 106 # apply map operations on images 107 mnist_ds = mnist_ds.map(operations=type_cast_op, input_columns="label", num_parallel_workers=num_parallel_workers) 108 mnist_ds = mnist_ds.map(operations=resize_op, input_columns="image", num_parallel_workers=num_parallel_workers) 109 mnist_ds = mnist_ds.map(operations=rescale_op, input_columns="image", num_parallel_workers=num_parallel_workers) 110 mnist_ds = mnist_ds.map(operations=rescale_nml_op, input_columns="image", num_parallel_workers=num_parallel_workers) 111 mnist_ds = mnist_ds.map(operations=hwc2chw_op, input_columns="image", num_parallel_workers=num_parallel_workers) 112 113 # apply DatasetOps 114 mnist_ds = mnist_ds.batch(batch_size, drop_remainder=True) 115 mnist_ds = mnist_ds.repeat(repeat_size) 116 117 return mnist_ds 118 119 120def cleanup(): 121 data_path = os.path.join(os.getcwd(), "data") 122 kernel_meta_path = os.path.join(os.getcwd(), "kernel_data") 123 cache_path = os.path.join(os.getcwd(), "__pycache__") 124 if os.path.exists(data_path): 125 shutil.rmtree(data_path) 126 if os.path.exists(kernel_meta_path): 127 shutil.rmtree(kernel_meta_path) 128 if os.path.exists(cache_path): 129 shutil.rmtree(cache_path) 130 131 132class TestProfiler: 133 device_id = int(os.getenv('DEVICE_ID')) if os.getenv('DEVICE_ID') else 0 134 rank_id = int(os.getenv('RANK_ID')) if os.getenv('RANK_ID') else 0 135 mnist_path = '/home/workspace/mindspore_dataset/mnist' 136 137 @classmethod 138 def setup_class(cls): 139 """Run begin all test case start.""" 140 cleanup() 141 142 @staticmethod 143 def teardown(): 144 """Run after each test case end.""" 145 cleanup() 146 147 @pytest.mark.level2 148 @pytest.mark.platform_x86_cpu 149 @pytest.mark.env_onecard 150 @security_off_wrap 151 def test_cpu_profiler(self): 152 if sys.platform != 'linux': 153 return 154 self._train_with_profiler(device_target="CPU") 155 self._check_cpu_profiling_file() 156 157 @pytest.mark.level1 158 @pytest.mark.platform_x86_gpu_training 159 @pytest.mark.env_onecard 160 @security_off_wrap 161 def test_gpu_profiler(self): 162 self._train_with_profiler(device_target="GPU") 163 self._check_gpu_profiling_file() 164 165 @pytest.mark.level0 166 @pytest.mark.platform_arm_ascend_training 167 @pytest.mark.platform_x86_ascend_training 168 @pytest.mark.env_onecard 169 @security_off_wrap 170 def test_ascend_profiler(self): 171 self._train_with_profiler(device_target="Ascend") 172 self._check_d_profiling_file() 173 174 def _train_with_profiler(self, device_target): 175 context.set_context(mode=context.GRAPH_MODE, device_target=device_target) 176 profiler = Profiler(profile_memory=True, output_path='data') 177 profiler_name = os.listdir(os.path.join(os.getcwd(), 'data'))[0] 178 self.profiler_path = os.path.join(os.getcwd(), f'data/{profiler_name}/') 179 ds_train = create_dataset(os.path.join(self.mnist_path, "train")) 180 if ds_train.get_dataset_size() == 0: 181 raise ValueError("Please check dataset size > 0 and batch_size <= dataset size") 182 183 lenet = LeNet5() 184 loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction="mean") 185 optim = Momentum(lenet.trainable_params(), learning_rate=0.1, momentum=0.9) 186 model = Model(lenet, loss_fn=loss, optimizer=optim, metrics={'acc': Accuracy()}) 187 188 model.train(1, ds_train, dataset_sink_mode=True) 189 profiler.analyse() 190 191 def _check_gpu_profiling_file(self): 192 op_detail_file = self.profiler_path + f'gpu_op_detail_info_{self.device_id}.csv' 193 op_type_file = self.profiler_path + f'gpu_op_type_info_{self.device_id}.csv' 194 activity_file = self.profiler_path + f'gpu_activity_data_{self.device_id}.csv' 195 timeline_file = self.profiler_path + f'gpu_timeline_display_{self.device_id}.json' 196 getnext_file = self.profiler_path + f'minddata_getnext_profiling_{self.device_id}.txt' 197 pipeline_file = self.profiler_path + f'minddata_pipeline_raw_{self.device_id}.csv' 198 199 gpu_profiler_files = (op_detail_file, op_type_file, activity_file, 200 timeline_file, getnext_file, pipeline_file) 201 for file in gpu_profiler_files: 202 assert os.path.isfile(file) 203 204 def _check_d_profiling_file(self): 205 aicore_file = self.profiler_path + f'aicore_intermediate_{self.rank_id}_detail.csv' 206 step_trace_file = self.profiler_path + f'step_trace_raw_{self.rank_id}_detail_time.csv' 207 timeline_file = self.profiler_path + f'ascend_timeline_display_{self.rank_id}.json' 208 aicpu_file = self.profiler_path + f'aicpu_intermediate_{self.rank_id}.csv' 209 minddata_pipeline_file = self.profiler_path + f'minddata_pipeline_raw_{self.rank_id}.csv' 210 queue_profiling_file = self.profiler_path + f'device_queue_profiling_{self.rank_id}.txt' 211 memory_file = self.profiler_path + f'memory_usage_{self.rank_id}.pb' 212 213 d_profiler_files = (aicore_file, step_trace_file, timeline_file, aicpu_file, 214 minddata_pipeline_file, queue_profiling_file, memory_file) 215 for file in d_profiler_files: 216 assert os.path.isfile(file) 217 218 def _check_cpu_profiling_file(self): 219 op_detail_file = self.profiler_path + f'cpu_op_detail_info_{self.device_id}.csv' 220 op_type_file = self.profiler_path + f'cpu_op_type_info_{self.device_id}.csv' 221 timeline_file = self.profiler_path + f'cpu_op_execute_timestamp_{self.device_id}.txt' 222 223 cpu_profiler_files = (op_detail_file, op_type_file, timeline_file) 224 for file in cpu_profiler_files: 225 assert os.path.isfile(file) 226