test_newprofiler.py 13.4 KB
Newer Older
C
chenjian 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

15 16
import os
import tempfile
C
chenjian 已提交
17
import unittest
18

C
chenjian 已提交
19
import numpy as np
20

C
chenjian 已提交
21
import paddle
Z
Zhang Ting 已提交
22 23
import paddle.nn as nn
import paddle.nn.functional as F
24 25 26
import paddle.profiler as profiler
import paddle.profiler.utils as utils
from paddle.io import DataLoader, Dataset
C
chenjian 已提交
27 28 29


class TestProfiler(unittest.TestCase):
30 31 32
    def tearDown(self):
        self.temp_dir.cleanup()

C
chenjian 已提交
33 34
    def test_profiler(self):
        def my_trace_back(prof):
35 36 37
            path = os.path.join(
                self.temp_dir.name, './test_profiler_chrometracing'
            )
38 39 40
            profiler.export_chrome_tracing(path)(prof)
            path = os.path.join(self.temp_dir.name, './test_profiler_pb')
            profiler.export_protobuf(path)(prof)
C
chenjian 已提交
41

42
        self.temp_dir = tempfile.TemporaryDirectory()
C
chenjian 已提交
43
        x_value = np.random.randn(2, 3, 3)
44 45 46
        x = paddle.to_tensor(
            x_value, stop_gradient=False, place=paddle.CPUPlace()
        )
C
chenjian 已提交
47 48
        y = x / 2.0
        ones_like_y = paddle.ones_like(y)
49 50 51
        with profiler.Profiler(
            targets=[profiler.ProfilerTarget.CPU],
        ) as prof:
C
chenjian 已提交
52 53
            y = x / 2.0
        prof = None
54 55 56 57
        self.assertEqual(utils._is_profiler_used, False)
        with profiler.RecordEvent(name='test'):
            y = x / 2.0

58 59 60
        with profiler.Profiler(
            targets=[profiler.ProfilerTarget.CPU], scheduler=(1, 2)
        ) as prof:
61
            self.assertEqual(utils._is_profiler_used, True)
C
chenjian 已提交
62 63
            with profiler.RecordEvent(name='test'):
                y = x / 2.0
64

C
chenjian 已提交
65
        prof = None
66 67 68 69 70 71 72
        with profiler.Profiler(
            targets=[profiler.ProfilerTarget.CPU],
            scheduler=profiler.make_scheduler(
                closed=0, ready=1, record=1, repeat=1
            ),
            on_trace_ready=my_trace_back,
        ) as prof:
C
chenjian 已提交
73 74
            y = x / 2.0
        prof = None
75 76 77 78 79 80 81
        with profiler.Profiler(
            targets=[profiler.ProfilerTarget.CPU],
            scheduler=profiler.make_scheduler(
                closed=0, ready=0, record=2, repeat=1
            ),
            on_trace_ready=my_trace_back,
        ) as prof:
C
chenjian 已提交
82 83 84 85 86
            for i in range(3):
                y = x / 2.0
                prof.step()
        prof = None
        with profiler.Profiler(
87 88 89
            targets=[profiler.ProfilerTarget.CPU],
            scheduler=lambda x: profiler.ProfilerState.RECORD_AND_RETURN,
            on_trace_ready=my_trace_back,
90
            with_flops=True,
91
        ) as prof:
C
chenjian 已提交
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
            for i in range(2):
                y = x / 2.0
                prof.step()

        def my_sheduler(num_step):
            if num_step % 5 < 2:
                return profiler.ProfilerState.RECORD_AND_RETURN
            elif num_step % 5 < 3:
                return profiler.ProfilerState.READY
            elif num_step % 5 < 4:
                return profiler.ProfilerState.RECORD
            else:
                return profiler.ProfilerState.CLOSED

        def my_sheduler1(num_step):
            if num_step % 5 < 2:
                return profiler.ProfilerState.RECORD
            elif num_step % 5 < 3:
                return profiler.ProfilerState.READY
            elif num_step % 5 < 4:
                return profiler.ProfilerState.RECORD
            else:
                return profiler.ProfilerState.CLOSED

        prof = None
        with profiler.Profiler(
118 119 120 121
            targets=[profiler.ProfilerTarget.CPU],
            scheduler=lambda x: profiler.ProfilerState.RECORD_AND_RETURN,
            on_trace_ready=my_trace_back,
        ) as prof:
C
chenjian 已提交
122 123 124 125
            for i in range(2):
                y = x / 2.0
                prof.step()
        prof = None
126 127 128 129 130
        with profiler.Profiler(
            targets=[profiler.ProfilerTarget.CPU],
            scheduler=my_sheduler,
            on_trace_ready=my_trace_back,
        ) as prof:
C
chenjian 已提交
131 132 133 134
            for i in range(5):
                y = x / 2.0
                prof.step()
        prof = None
135 136 137
        with profiler.Profiler(
            targets=[profiler.ProfilerTarget.CPU], scheduler=my_sheduler1
        ) as prof:
C
chenjian 已提交
138 139 140 141
            for i in range(5):
                y = x / 2.0
                prof.step()
        prof = None
142 143 144 145 146 147 148 149 150
        with profiler.Profiler(
            targets=[profiler.ProfilerTarget.CPU],
            scheduler=profiler.make_scheduler(
                closed=1, ready=1, record=2, repeat=1, skip_first=1
            ),
            on_trace_ready=my_trace_back,
            profile_memory=True,
            record_shapes=True,
        ) as prof:
C
chenjian 已提交
151 152 153 154 155
            for i in range(5):
                y = x / 2.0
                paddle.grad(outputs=y, inputs=[x], grad_outputs=ones_like_y)
                prof.step()

156 157
        path = os.path.join(self.temp_dir.name, './test_profiler_pb.pb')
        prof.export(path=path, format='pb')
C
chenjian 已提交
158
        prof.summary()
159
        result = profiler.utils.load_profiler_result(path)
160 161 162
        prof = None
        dataset = RandomDataset(10 * 4)
        simple_net = SimpleNet()
163 164 165 166 167 168
        opt = paddle.optimizer.SGD(
            learning_rate=1e-3, parameters=simple_net.parameters()
        )
        loader = DataLoader(
            dataset, batch_size=4, shuffle=True, drop_last=True, num_workers=2
        )
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
        prof = profiler.Profiler(on_trace_ready=lambda prof: None)
        prof.start()
        for i, (image, label) in enumerate(loader()):
            out = simple_net(image)
            loss = F.cross_entropy(out, label)
            avg_loss = paddle.mean(loss)
            avg_loss.backward()
            opt.minimize(avg_loss)
            simple_net.clear_gradients()
            prof.step()
        prof.stop()
        prof.summary()
        prof = None
        dataset = RandomDataset(10 * 4)
        simple_net = SimpleNet()
        loader = DataLoader(dataset, batch_size=4, shuffle=True, drop_last=True)
185 186 187
        opt = paddle.optimizer.Adam(
            learning_rate=1e-3, parameters=simple_net.parameters()
        )
188 189 190 191 192 193 194 195 196 197 198
        prof = profiler.Profiler(on_trace_ready=lambda prof: None)
        prof.start()
        for i, (image, label) in enumerate(loader()):
            out = simple_net(image)
            loss = F.cross_entropy(out, label)
            avg_loss = paddle.mean(loss)
            avg_loss.backward()
            opt.step()
            simple_net.clear_gradients()
            prof.step()
        prof.stop()
C
chenjian 已提交
199 200


201 202 203 204 205
class TestNvprof(unittest.TestCase):
    def test_nvprof(self):
        for i in range(10):
            paddle.fluid.profiler._nvprof_range(i, 10, 20)
            x_value = np.random.randn(2, 3, 3)
206 207 208
            x = paddle.to_tensor(
                x_value, stop_gradient=False, place=paddle.CPUPlace()
            )
209 210 211
            y = x / 2.0


C
chenjian 已提交
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
class TestGetProfiler(unittest.TestCase):
    def test_getprofiler(self):
        config_content = '''
        {
        "targets": ["CPU"],
        "scheduler": [3,4],
        "on_trace_ready": {
            "export_chrome_tracing":{
                "module": "paddle.profiler",
                "use_direct": false,
                "args": [],
                "kwargs": {
                        "dir_name": "testdebug/"
                    }
                }
            },
          "timer_only": false
        }
        '''
        filehandle = tempfile.NamedTemporaryFile(mode='w')
        filehandle.write(config_content)
        filehandle.flush()
        import paddle.profiler.profiler as profiler
235

C
chenjian 已提交
236 237
        profiler = profiler.get_profiler(filehandle.name)
        x_value = np.random.randn(2, 3, 3)
238 239 240
        x = paddle.to_tensor(
            x_value, stop_gradient=False, place=paddle.CPUPlace()
        )
C
chenjian 已提交
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
        with profiler:
            for i in range(5):
                y = x / 2.0
                ones_like_y = paddle.ones_like(y)
                profiler.step()

        # below tests are just for coverage, wrong config
        # test use_direct
        config_content = '''
        {
        "targets": ["Cpu", "Gpu"],
        "scheduler": {
            "make_scheduler":{
                "module": "paddle.profiler",
                "use_direct": true,
                "args": [],
                "kwargs": {}
            }
        },
        "on_trace_ready": {
            "export_chrome_tracing":{
                "module": "paddle.profiler1",
                "use_direct": true,
                "args": [],
                "kwargs": {
                    }
                }
            },
          "timer_only": false
        }
        '''
        filehandle = tempfile.NamedTemporaryFile(mode='w')
        filehandle.write(config_content)
        filehandle.flush()
        import paddle.profiler.profiler as profiler
276

C
chenjian 已提交
277 278 279 280 281
        try:
            profiler = profiler.get_profiler(filehandle.name)
        except:
            pass

282
        # test scheduler
C
chenjian 已提交
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
        config_content = '''
        {
        "targets": ["Cpu", "Gpu"],
        "scheduler": {
           "make_scheduler":{
                "module": "paddle.profiler",
                "use_direct": false,
                "args": [],
                "kwargs": {
                        "closed": 1,
                        "ready": 1,
                        "record": 2
                    }
            }
        },
        "on_trace_ready": {
            "export_chrome_tracing":{
                "module": "paddle.profiler",
                "use_direct": true,
                "args": [],
                "kwargs": {
                    }
                }
            },
          "timer_only": false
        }
        '''
        filehandle = tempfile.NamedTemporaryFile(mode='w')
        filehandle.write(config_content)
        filehandle.flush()
        import paddle.profiler.profiler as profiler
314

C
chenjian 已提交
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
        profiler = profiler.get_profiler(filehandle.name)

        # test exception
        config_content = '''
        {
        "targets": [1],
        "scheduler": {
            "make_scheduler1":{
                "module": "paddle.profiler",
                "use_direct": false,
                "args": [],
                "kwargs": {
                        "closed": 1,
                        "ready": 1,
                        "record": 2
                    }
            }
        },
        "on_trace_ready": {
            "export_chrome_tracing1":{
                "module": "paddle.profiler",
                "use_direct": false,
                "args": [],
                "kwargs": {
                        "dir_name": "testdebug/"
                    }
                }
            },
          "timer_only": 1
        }
        '''
        filehandle = tempfile.NamedTemporaryFile(mode='w')
        filehandle.write(config_content)
        filehandle.flush()
        import paddle.profiler.profiler as profiler
350

C
chenjian 已提交
351 352 353
        profiler = profiler.get_profiler(filehandle.name)
        # test path error
        import paddle.profiler.profiler as profiler
354

C
chenjian 已提交
355 356 357
        profiler = profiler.get_profiler('nopath.json')


Z
Zhang Ting 已提交
358 359 360 361 362 363
class RandomDataset(Dataset):
    def __init__(self, num_samples):
        self.num_samples = num_samples

    def __getitem__(self, idx):
        image = np.random.random([100]).astype('float32')
364
        label = np.random.randint(0, 10 - 1, (1,)).astype('int64')
Z
Zhang Ting 已提交
365 366 367 368 369 370 371 372
        return image, label

    def __len__(self):
        return self.num_samples


class SimpleNet(nn.Layer):
    def __init__(self):
373
        super().__init__()
Z
Zhang Ting 已提交
374 375 376 377 378 379 380 381 382 383 384
        self.fc = nn.Linear(100, 10)

    def forward(self, image, label=None):
        return self.fc(image)


class TestTimerOnly(unittest.TestCase):
    def test_with_dataloader(self):
        def train(step_num_samples=None):
            dataset = RandomDataset(20 * 4)
            simple_net = SimpleNet()
385 386 387 388 389 390 391 392 393 394
            opt = paddle.optimizer.SGD(
                learning_rate=1e-3, parameters=simple_net.parameters()
            )
            loader = DataLoader(
                dataset,
                batch_size=4,
                shuffle=True,
                drop_last=True,
                num_workers=2,
            )
Z
Zhang Ting 已提交
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
            step_info = ''
            p = profiler.Profiler(timer_only=True)
            p.start()
            for i, (image, label) in enumerate(loader()):
                out = simple_net(image)
                loss = F.cross_entropy(out, label)
                avg_loss = paddle.mean(loss)
                avg_loss.backward()
                opt.minimize(avg_loss)
                simple_net.clear_gradients()
                p.step(num_samples=step_num_samples)
                if i % 10 == 0:
                    step_info = p.step_info()
                    print("Iter {}: {}".format(i, step_info))
            p.stop()
            return step_info

        step_info = train(step_num_samples=None)
        self.assertTrue('steps/s' in step_info)
        step_info = train(step_num_samples=4)
        self.assertTrue('samples/s' in step_info)

    def test_without_dataloader(self):
        x = paddle.to_tensor(np.random.randn(10, 10))
        y = paddle.to_tensor(np.random.randn(10, 10))
        p = profiler.Profiler(timer_only=True)
        p.start()
        step_info = ''
        for i in range(20):
            out = x + y
            p.step()
        p.stop()


C
chenjian 已提交
429 430
if __name__ == '__main__':
    unittest.main()