chrometracing_logger.cc 26.2 KB
Newer Older
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
#include "paddle/fluid/platform/profiler/chrometracing_logger.h"

17 18
#include <cstdio>
#include <ctime>
19
#include <limits>
20
#include <regex>
21 22 23

#include "glog/logging.h"
#include "paddle/fluid/platform/device/gpu/gpu_info.h"
C
chenjian 已提交
24
#include "paddle/fluid/platform/enforce.h"
25
#include "paddle/fluid/platform/profiler/event_node.h"
C
chenjian 已提交
26
#include "paddle/fluid/platform/profiler/utils.h"
27 28 29 30 31 32 33 34

namespace paddle {
namespace platform {

static const char* kDefaultFilename = "pid_%s_time_%s.paddle_trace.json";

static std::string DefaultFileName() {
  auto pid = GetProcessId();
35 36
  return string_format(
      std::string(kDefaultFilename), pid, GetStringFormatLocalTime().c_str());
37 38 39 40 41 42
}

void ChromeTracingLogger::OpenFile() {
  output_file_stream_.open(filename_,
                           std::ofstream::out | std::ofstream::trunc);
  if (!output_file_stream_) {
C
chenjian 已提交
43 44
    LOG(WARNING) << "Unable to open file for writing profiling data."
                 << std::endl;
45
  } else {
C
chenjian 已提交
46
    LOG(INFO) << "writing profiling data to " << filename_ << std::endl;
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
  }
}

ChromeTracingLogger::ChromeTracingLogger(const std::string& filename) {
  filename_ = filename.empty() ? DefaultFileName() : filename;
  OpenFile();
  StartLog();
}

ChromeTracingLogger::ChromeTracingLogger(const char* filename_cstr) {
  std::string filename(filename_cstr);
  filename_ = filename.empty() ? DefaultFileName() : filename;
  OpenFile();
  StartLog();
}

ChromeTracingLogger::~ChromeTracingLogger() {
  EndLog();
  output_file_stream_.close();
}

void ChromeTracingLogger::LogNodeTrees(const NodeTrees& node_trees) {
69 70 71 72
  output_file_stream_ << std::string(
      R"JSON(
    "traceEvents": [
  )JSON");
73 74 75
  // log all nodes except root node, root node is a helper node.
  const std::map<uint64_t, std::vector<HostTraceEventNode*>>
      thread2host_event_nodes = node_trees.Traverse(true);
76 77 78
  // find the earliest time in current timeline
  start_time_ = std::numeric_limits<uint64_t>::max();
  for (auto it = thread2host_event_nodes.begin();
79 80
       it != thread2host_event_nodes.end();
       ++it) {
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
    if (it->second.begin() + 1 != it->second.end()) {
      if ((*(it->second.begin() + 1))->StartNs() < start_time_) {
        start_time_ = (*(it->second.begin() + 1))->StartNs();
      }
    } else {
      auto runtimenode =
          (*(it->second.begin()))->GetRuntimeTraceEventNodes().begin();
      if (runtimenode !=
          (*(it->second.begin()))->GetRuntimeTraceEventNodes().end()) {
        if ((*runtimenode)->StartNs() < start_time_) {
          start_time_ = (*runtimenode)->StartNs();
        }
      }
    }
  }

97
  for (auto it = thread2host_event_nodes.begin();
98 99
       it != thread2host_event_nodes.end();
       ++it) {
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
    for (auto hostnode = it->second.begin(); hostnode != it->second.end();
         ++hostnode) {
      if (hostnode != it->second.begin()) {  // skip root node
        (*hostnode)->LogMe(this);
      }
      for (auto runtimenode = (*hostnode)->GetRuntimeTraceEventNodes().begin();
           runtimenode != (*hostnode)->GetRuntimeTraceEventNodes().end();
           ++runtimenode) {
        (*runtimenode)->LogMe(this);
        for (auto devicenode =
                 (*runtimenode)->GetDeviceTraceEventNodes().begin();
             devicenode != (*runtimenode)->GetDeviceTraceEventNodes().end();
             ++devicenode) {
          (*devicenode)->LogMe(this);
        }
      }
C
chenjian 已提交
116
      for (auto memnode = (*hostnode)->GetMemTraceEventNodes().begin();
117 118
           memnode != (*hostnode)->GetMemTraceEventNodes().end();
           ++memnode) {
C
chenjian 已提交
119 120
        (*memnode)->LogMe(this);
      }
121 122 123 124
    }
  }
}

C
chenjian 已提交
125 126 127 128 129 130 131 132 133
void ChromeTracingLogger::LogMemTraceEventNode(
    const MemTraceEventNode& mem_node) {
  if (!output_file_stream_) {
    return;
  }
  output_file_stream_ << string_format(
      std::string(
          R"JSON(
  { 
134
    "name": "[memory]", "pid": %lld, "tid": "%lld(C++)",
C
chenjian 已提交
135 136 137 138 139
    "ts": %lld, 
    "ph": "i", "cat": "%s", 
    "args": {
      "place": "%s",
      "addr": "%llu",
140
      "increase_bytes": %lld,
C
chenjian 已提交
141 142
      "current_allocated": %llu,
      "current_reserved": %llu,
143 144
      "peak_allocated": %llu,
      "peak_reserved": %llu
C
chenjian 已提交
145 146 147
    }
  },
  )JSON"),
148 149 150 151 152 153 154 155 156 157
      mem_node.ProcessId(),
      mem_node.ThreadId(),
      nsToUs(mem_node.TimeStampNs()),
      StringTracerMemEventType(mem_node.Type()),
      mem_node.Place().c_str(),
      mem_node.Addr(),
      mem_node.IncreaseBytes(),
      mem_node.CurrentAllocated(),
      mem_node.CurrentReserved(),
      mem_node.PeakAllocated(),
158 159
      mem_node.PeakReserved());
  pid_tid_set_.insert({mem_node.ProcessId(), mem_node.ThreadId()});
C
chenjian 已提交
160 161
}

162 163 164 165 166
void ChromeTracingLogger::LogHostTraceEventNode(
    const HostTraceEventNode& host_node) {
  if (!output_file_stream_) {
    return;
  }
167 168 169 170 171 172 173
  std::string dur_display;
  float dur = nsToMsFloat(host_node.Duration());
  if (dur > 1.0) {
    dur_display = string_format(std::string("%.3f ms"), dur);
  } else {
    dur_display = string_format(std::string("%.3f us"), dur * 1000);
  }
C
chenjian 已提交
174 175 176 177 178 179 180 181 182
  std::map<std::string, std::vector<std::vector<int64_t>>> input_shapes;
  std::map<std::string, std::vector<std::string>> input_dtypes;
  std::string callstack;
  OperatorSupplementEventNode* op_supplement_node =
      host_node.GetOperatorSupplementEventNode();
  if (op_supplement_node != nullptr) {
    input_shapes = op_supplement_node->InputShapes();
    input_dtypes = op_supplement_node->Dtypes();
    callstack = op_supplement_node->CallStack();
183 184
    callstack = std::regex_replace(callstack, std::regex("\""), "\'");
    callstack = std::regex_replace(callstack, std::regex("\n"), "\\n");
C
chenjian 已提交
185
  }
C
chenjian 已提交
186 187 188 189 190 191 192 193
  switch (host_node.Type()) {
    case TracerEventType::ProfileStep:
    case TracerEventType::Forward:
    case TracerEventType::Backward:
    case TracerEventType::Dataloader:
    case TracerEventType::Optimization:
    case TracerEventType::PythonOp:
    case TracerEventType::PythonUserDefined:
194 195
      // cname value comes from tracing.js reservedColorsByName variable

C
chenjian 已提交
196 197 198
      output_file_stream_ << string_format(
          std::string(
              R"JSON(
199
  { 
200 201
    "name": "%s[%s]", "pid": %lld, "tid": "%lld(Python)",
    "ts": %lld, "dur": %.3f,
202
    "ph": "X", "cat": "%s", 
203
    "cname": "thread_state_runnable",
204
    "args": {
205 206
      "start_time": "%.3f us",
      "end_time": "%.3f us"
207 208 209
    }
  },
  )JSON"),
210 211 212 213 214
          host_node.Name().c_str(),
          dur_display.c_str(),
          host_node.ProcessId(),
          host_node.ThreadId(),
          nsToUs(host_node.StartNs()),
215
          nsToUsFloat(host_node.Duration()),
C
chenjian 已提交
216
          StringTracerEventType(host_node.Type()),
217 218
          nsToUsFloat(host_node.StartNs(), start_time_),
          nsToUsFloat(host_node.EndNs(), start_time_));
C
chenjian 已提交
219
      break;
C
chenjian 已提交
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239

    case TracerEventType::Operator:

      output_file_stream_ << string_format(
          std::string(
              R"JSON(
  { 
    "name": "%s[%s]", "pid": %lld, "tid": "%lld(C++)",
    "ts": %lld, "dur": %.3f,
    "ph": "X", "cat": "%s", 
    "cname": "thread_state_runnable",
    "args": {
      "start_time": "%.3f us",
      "end_time": "%.3f us",
      "input_shapes": %s,
      "input_dtypes": %s,
      "callstack": "%s"
    }
  },
  )JSON"),
240 241 242 243 244
          host_node.Name().c_str(),
          dur_display.c_str(),
          host_node.ProcessId(),
          host_node.ThreadId(),
          nsToUs(host_node.StartNs()),
C
chenjian 已提交
245 246 247 248
          nsToUsFloat(host_node.Duration()),
          StringTracerEventType(host_node.Type()),
          nsToUsFloat(host_node.StartNs(), start_time_),
          nsToUsFloat(host_node.EndNs(), start_time_),
249 250
          json_dict(input_shapes).c_str(),
          json_dict(input_dtypes).c_str(),
C
chenjian 已提交
251 252 253 254 255 256 257 258 259 260 261
          callstack.c_str());
      break;
    case TracerEventType::CudaRuntime:
    case TracerEventType::Kernel:
    case TracerEventType::Memcpy:
    case TracerEventType::Memset:
    case TracerEventType::UserDefined:
    case TracerEventType::OperatorInner:
    case TracerEventType::Communication:
    case TracerEventType::MluRuntime:
    case TracerEventType::NumTypes:
C
chenjian 已提交
262 263 264 265 266
    default:
      output_file_stream_ << string_format(
          std::string(
              R"JSON(
  { 
267 268
    "name": "%s[%s]", "pid": %lld, "tid": "%lld(C++)",
    "ts": %lld, "dur": %.3f,
C
chenjian 已提交
269
    "ph": "X", "cat": "%s", 
270
    "cname": "thread_state_runnable",
C
chenjian 已提交
271
    "args": {
272 273
      "start_time": "%.3f us",
      "end_time": "%.3f us"
C
chenjian 已提交
274 275 276
    }
  },
  )JSON"),
277 278 279 280 281
          host_node.Name().c_str(),
          dur_display.c_str(),
          host_node.ProcessId(),
          host_node.ThreadId(),
          nsToUs(host_node.StartNs()),
282
          nsToUsFloat(host_node.Duration()),
C
chenjian 已提交
283
          StringTracerEventType(host_node.Type()),
284 285
          nsToUsFloat(host_node.StartNs(), start_time_),
          nsToUsFloat(host_node.EndNs(), start_time_));
C
chenjian 已提交
286 287 288 289
      break;
  }

  pid_tid_set_.insert({host_node.ProcessId(), host_node.ThreadId()});
290 291 292 293 294 295 296
}

void ChromeTracingLogger::LogRuntimeTraceEventNode(
    const CudaRuntimeTraceEventNode& runtime_node) {
  if (!output_file_stream_) {
    return;
  }
297 298 299 300 301 302 303
  float dur = nsToMsFloat(runtime_node.Duration());
  std::string dur_display;
  if (dur > 1.0) {
    dur_display = string_format(std::string("%.3f ms"), dur);
  } else {
    dur_display = string_format(std::string("%.3f us"), dur * 1000);
  }
304 305 306 307
  output_file_stream_ << string_format(
      std::string(
          R"JSON(
  { 
308 309
    "name": "%s[%s]", "pid": %lld, "tid": "%lld(C++)",
    "ts": %lld, "dur": %.3f,
310
    "ph": "X", "cat": "%s", 
311
    "cname": "thread_state_running",
312
    "args": {
C
chenjian 已提交
313
      "correlation id": %d,
314 315
      "start_time": "%.3f us",
      "end_time": "%.3f us"
316 317 318
    }
  },
  )JSON"),
319 320 321 322 323 324 325 326
      runtime_node.Name().c_str(),
      dur_display.c_str(),
      runtime_node.ProcessId(),
      runtime_node.ThreadId(),
      nsToUs(runtime_node.StartNs()),
      nsToUsFloat(runtime_node.Duration()),
      StringTracerEventType(runtime_node.Type()),
      runtime_node.CorrelationId(),
327 328
      nsToUsFloat(runtime_node.StartNs(), start_time_),
      nsToUsFloat(runtime_node.EndNs(), start_time_));
C
chenjian 已提交
329 330 331 332 333 334 335 336 337 338 339
  pid_tid_set_.insert({runtime_node.ProcessId(), runtime_node.ThreadId()});

  output_file_stream_ << string_format(
      std::string(
          R"JSON(
  { 
    "name": "launch", "id": %d, "pid": %lld, "tid": "%lld(C++)",
    "ts": %lld, 
    "ph": "s", "cat": "async"
  },
  )JSON"),
340 341
      runtime_node.CorrelationId(),
      runtime_node.ProcessId(),
C
chenjian 已提交
342 343 344
      runtime_node.ThreadId(),
      nsToUs((runtime_node.StartNs() + runtime_node.EndNs()) >> 1));
  pid_tid_set_.insert({runtime_node.ProcessId(), runtime_node.ThreadId()});
345 346 347 348 349 350 351
}

void ChromeTracingLogger::LogDeviceTraceEventNode(
    const DeviceTraceEventNode& device_node) {
  if (!output_file_stream_) {
    return;
  }
352

353 354 355 356 357 358 359 360 361 362 363 364
  switch (device_node.Type()) {
    case TracerEventType::Kernel:
      HandleTypeKernel(device_node);
      break;
    case TracerEventType::Memcpy:
      HandleTypeMemcpy(device_node);
      break;
    case TracerEventType::Memset:
      HandleTypeMemset(device_node);
    default:
      break;
  }
C
chenjian 已提交
365
  if (nsToUs(device_node.Duration()) == 0) {
366 367
    output_file_stream_ << string_format(std::string(
                                             R"JSON(
C
chenjian 已提交
368 369 370 371 372 373
  { 
    "name": "launch", "id": %d, "pid": %lld, "tid": %lld,
    "ts": %lld, 
    "ph": "f", "cat": "async"
  },
  )JSON"),
374 375 376 377
                                         device_node.CorrelationId(),
                                         device_node.DeviceId(),
                                         device_node.StreamId(),
                                         nsToUs(device_node.StartNs()));
C
chenjian 已提交
378 379 380 381 382 383 384 385 386 387 388 389
    deviceid_streamid_set_.insert(
        {device_node.DeviceId(), device_node.StreamId()});
  } else {
    output_file_stream_ << string_format(
        std::string(
            R"JSON(
  { 
    "name": "launch", "id": %d, "pid": %lld, "tid": %lld,
    "ts": %lld, 
    "ph": "f", "cat": "async", "bp": "e"
  },
  )JSON"),
390 391
        device_node.CorrelationId(),
        device_node.DeviceId(),
C
chenjian 已提交
392 393 394 395 396
        device_node.StreamId(),
        nsToUs((device_node.StartNs() + device_node.EndNs()) >> 1));
    deviceid_streamid_set_.insert(
        {device_node.DeviceId(), device_node.StreamId()});
  }
397 398 399 400 401
}

void ChromeTracingLogger::HandleTypeKernel(
    const DeviceTraceEventNode& device_node) {
  KernelEventInfo kernel_info = device_node.KernelInfo();
402

403 404 405 406 407 408 409
  float dur = nsToMsFloat(device_node.Duration());
  std::string dur_display;
  if (dur > 1.0) {
    dur_display = string_format(std::string("%.3f ms"), dur);
  } else {
    dur_display = string_format(std::string("%.3f us"), dur * 1000);
  }
410 411 412 413
  output_file_stream_ << string_format(
      std::string(
          R"JSON(
  { 
414 415
    "name": "%s[%s]", "pid": %lld, "tid": %lld,
    "ts": %lld, "dur": %.3f,
416
    "ph": "X", "cat": "%s", 
417
    "cname": "cq_build_failed",
418
    "args": {
419 420
      "start_time": "%.3f us",
      "end_time": "%.3f us",
421 422 423
      "device": %d, "context": %d,
      "stream": %d, "correlation id": %d,
      "registers per thread": %d,
C
chenjian 已提交
424
      "shared memory": %d,
425 426 427 428
      "blocks per SM": %f,
      "warps per SM": %f,
      "grid": [%d, %d, %d],
      "block": [%d, %d, %d],
429
      "theoretical achieved occupancy %%": %.3f
430 431 432
    }
  },
  )JSON"),
433 434 435 436 437
      device_node.Name().c_str(),
      dur_display.c_str(),
      device_node.DeviceId(),
      device_node.StreamId(),
      nsToUs(device_node.StartNs()),
438
      nsToUsFloat(device_node.Duration()),
C
chenjian 已提交
439
      StringTracerEventType(device_node.Type()),
440
      nsToUsFloat(device_node.StartNs(), start_time_),
441 442 443 444 445 446
      nsToUsFloat(device_node.EndNs(), start_time_),
      device_node.DeviceId(),
      device_node.ContextId(),
      device_node.StreamId(),
      device_node.CorrelationId(),
      kernel_info.registers_per_thread,
447
      kernel_info.static_shared_memory + kernel_info.dynamic_shared_memory,
448 449
      kernel_info.blocks_per_sm,
      kernel_info.warps_per_sm,
450 451 452 453 454 455
      kernel_info.grid_x,
      kernel_info.grid_y,
      kernel_info.grid_z,
      kernel_info.block_x,
      kernel_info.block_y,
      kernel_info.block_z,
456
      kernel_info.occupancy * 100);
457 458 459 460 461 462 463 464 465
}

void ChromeTracingLogger::HandleTypeMemcpy(
    const DeviceTraceEventNode& device_node) {
  MemcpyEventInfo memcpy_info = device_node.MemcpyInfo();
  float memory_bandwidth = 0;
  if (device_node.Duration() > 0) {
    memory_bandwidth = memcpy_info.num_bytes * 1.0 / device_node.Duration();
  }
466 467 468 469 470 471 472
  float dur = nsToMsFloat(device_node.Duration());
  std::string dur_display;
  if (dur > 1.0) {
    dur_display = string_format(std::string("%.3f ms"), dur);
  } else {
    dur_display = string_format(std::string("%.3f us"), dur * 1000);
  }
473 474 475 476
  output_file_stream_ << string_format(
      std::string(
          R"JSON(
  {
477 478
    "name": "%s[%s]", "pid": %lld, "tid": %lld,
    "ts": %lld, "dur": %.3f,
479
    "ph": "X", "cat": "%s", 
480
    "cname": "cq_build_failed",
481
    "args": {
482 483
      "start_time": "%.3f us",
      "end_time": "%.3f us",
484
      "stream": %d, "correlation id": %d,
485
      "bytes": %d, "memory bandwidth (GB/s)": %.3f
486 487 488
    }
  },
  )JSON"),
489 490 491 492 493
      device_node.Name().c_str(),
      dur_display.c_str(),
      device_node.DeviceId(),
      device_node.StreamId(),
      nsToUs(device_node.StartNs()),
494
      nsToUsFloat(device_node.Duration()),
C
chenjian 已提交
495
      StringTracerEventType(device_node.Type()),
496
      nsToUsFloat(device_node.StartNs(), start_time_),
497 498 499 500 501
      nsToUsFloat(device_node.EndNs(), start_time_),
      device_node.StreamId(),
      device_node.CorrelationId(),
      memcpy_info.num_bytes,
      memory_bandwidth);
502 503 504 505 506
}

void ChromeTracingLogger::HandleTypeMemset(
    const DeviceTraceEventNode& device_node) {
  MemsetEventInfo memset_info = device_node.MemsetInfo();
507 508 509 510 511 512 513
  float dur = nsToMsFloat(device_node.Duration());
  std::string dur_display;
  if (dur > 1.0) {
    dur_display = string_format(std::string("%.3f ms"), dur);
  } else {
    dur_display = string_format(std::string("%.3f us"), dur * 1000);
  }
514 515 516 517
  output_file_stream_ << string_format(
      std::string(
          R"JSON(
  {
518 519
    "name": "%s[%s]", "pid": %lld, "tid": %lld,
    "ts": %lld, "dur": %.3f,
520
    "ph": "X", "cat": "%s", 
521
    "cname": "cq_build_failed",
522
    "args": {
523 524
      "start_time": "%.3f us",
      "end_time": "%.3f us",
525 526 527 528 529 530
      "device": %d, "context": %d,
      "stream": %d, "correlation id": %d,
      "bytes": %d, "value": %d
    }
  },
  )JSON"),
531 532 533 534 535
      device_node.Name().c_str(),
      dur_display.c_str(),
      device_node.DeviceId(),
      device_node.StreamId(),
      nsToUs(device_node.StartNs()),
536
      nsToUsFloat(device_node.Duration()),
C
chenjian 已提交
537
      StringTracerEventType(device_node.Type()),
538
      nsToUsFloat(device_node.StartNs(), start_time_),
539 540 541 542 543 544 545
      nsToUsFloat(device_node.EndNs(), start_time_),
      device_node.DeviceId(),
      device_node.ContextId(),
      device_node.StreamId(),
      device_node.CorrelationId(),
      memset_info.num_bytes,
      memset_info.value);
546 547 548
}

void ChromeTracingLogger::StartLog() {
C
chenjian 已提交
549
  output_file_stream_ << std::string(
550
      R"JSON(
551
  { 
C
chenjian 已提交
552
    "displayTimeUnit": "ms",)JSON");
553 554 555 556 557 558
}

void ChromeTracingLogger::LogMetaInfo(const std::string& version,
                                      uint32_t span_indx) {
  output_file_stream_ << string_format(std::string(
                                           R"JSON(
559
    "schemaVersion": "%s",
560 561 562 563 564 565 566 567 568
    "span_indx": "%d",)JSON"),
                                       version.c_str(),
                                       span_indx);
}

#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
void ChromeTracingLogger::LogDeviceProperty(
    const std::map<uint32_t, gpuDeviceProp>& device_property_map) {
  // add device property information
569 570
  output_file_stream_ << std::string(R"JSON(
    "deviceProperties": [
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
    )JSON");
  auto device_nums = device_property_map.size();
  if (device_nums == 0) {
    output_file_stream_ << std::string(R"JSON(
      ],
    )JSON");
  }
#if defined(PADDLE_WITH_CUDA)
  for (auto it = device_property_map.begin(); it != device_property_map.end();
       it++) {
    const gpuDeviceProp& device_property = it->second;
    if (device_nums > 1) {
      output_file_stream_ << string_format(
          std::string(
              R"JSON(
586
    {
587
      "id": %u, "name": "%s", "totalGlobalMem": %llu,
588 589 590 591 592 593 594
      "computeMajor": %d, "computeMinor": %d,
      "maxThreadsPerBlock": %d, "maxThreadsPerMultiprocessor": %d,
      "regsPerBlock": %d, "regsPerMultiprocessor": %d, "warpSize": %d,
      "sharedMemPerBlock": %d, "sharedMemPerMultiprocessor": %d,
      "smCount": %d, "sharedMemPerBlockOptin": %d
    },
  )JSON"),
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
          it->first,
          device_property.name,
          device_property.totalGlobalMem,
          device_property.major,
          device_property.minor,
          device_property.maxThreadsPerBlock,
          device_property.maxThreadsPerMultiProcessor,
          device_property.regsPerBlock,
          device_property.regsPerMultiprocessor,
          device_property.warpSize,
          device_property.sharedMemPerBlock,
          device_property.sharedMemPerMultiprocessor,
          device_property.multiProcessorCount,
          device_property.sharedMemPerBlockOptin);
    } else {
      output_file_stream_ << string_format(
          std::string(
              R"JSON(
      {
        "id": %u, "name": "%s", "totalGlobalMem": %llu,
        "computeMajor": %d, "computeMinor": %d,
        "maxThreadsPerBlock": %d, "maxThreadsPerMultiprocessor": %d,
        "regsPerBlock": %d, "regsPerMultiprocessor": %d, "warpSize": %d,
        "sharedMemPerBlock": %d, "sharedMemPerMultiprocessor": %d,
        "smCount": %d, "sharedMemPerBlockOptin": %d
      }],
    )JSON"),
          it->first,
          device_property.name,
          device_property.totalGlobalMem,
          device_property.major,
          device_property.minor,
          device_property.maxThreadsPerBlock,
          device_property.maxThreadsPerMultiProcessor,
          device_property.regsPerBlock,
          device_property.regsPerMultiprocessor,
          device_property.warpSize,
          device_property.sharedMemPerBlock,
          device_property.sharedMemPerMultiprocessor,
          device_property.multiProcessorCount,
          device_property.sharedMemPerBlockOptin);
    }
    device_nums -= 1;
638
  }
639 640 641 642 643 644 645 646
#endif
#if defined(PADDLE_WITH_HIP)
  for (auto it = device_property_map.begin(); it != device_property_map.end();
       it++) {
    const gpuDeviceProp& device_property = it->second;
    if (device_nums > 1) {
      output_file_stream_ << string_format(std::string(
                                               R"JSON(
647
    {
648
      "id": %u, "name": "%s", "totalGlobalMem": %llu,
649
      "computeMajor": %d, "computeMinor": %d,
650 651
      "smCount": %d
    },
652
  )JSON"),
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
                                           it->first,
                                           device_property.name,
                                           device_property.totalGlobalMem,
                                           device_property.major,
                                           device_property.minor,
                                           device_property.multiProcessorCount);
    } else {
      output_file_stream_ << string_format(std::string(
                                               R"JSON(
      {
        "id": %u, "name": "%s", "totalGlobalMem": %llu,
        "computeMajor": %d, "computeMinor": %d,
        "smCount": %d
      }],
    )JSON"),
                                           it->first,
                                           device_property.name,
                                           device_property.totalGlobalMem,
                                           device_property.major,
                                           device_property.minor,
                                           device_property.multiProcessorCount);
    }
    device_nums -= 1;
676 677 678
  }
#endif
}
679
#endif
680

681
void ChromeTracingLogger::LogExtraInfo(
C
chenjian 已提交
682 683
    const std::unordered_map<std::string, std::string> extra_info) {
  RefineDisplayName(extra_info);
684 685 686
  output_file_stream_ << std::string(
      R"JSON(
  {}
C
chenjian 已提交
687 688 689 690 691 692 693 694 695 696
  ],
  )JSON");
  output_file_stream_ << std::string(R"JSON(
  "ExtraInfo": {)JSON");
  size_t count = extra_info.size();
  for (const auto& kv : extra_info) {
    if (count > 1) {
      output_file_stream_ << string_format(std::string(R"JSON(
     "%s": "%s",
   )JSON"),
697 698
                                           kv.first.c_str(),
                                           kv.second.c_str());
C
chenjian 已提交
699 700 701 702
    } else {
      output_file_stream_ << string_format(std::string(R"JSON(
     "%s": "%s"
   )JSON"),
703 704
                                           kv.first.c_str(),
                                           kv.second.c_str());
C
chenjian 已提交
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
    }
    count--;
  }
  output_file_stream_ << std::string(R"JSON(
  })JSON");
}

void ChromeTracingLogger::RefineDisplayName(
    std::unordered_map<std::string, std::string> extra_info) {
  for (auto it = pid_tid_set_.begin(); it != pid_tid_set_.end(); ++it) {
    output_file_stream_ << string_format(
        std::string(
            R"JSON(
  {
    "name": "process_name", "pid": %lld, "tid": "%lld(Python)",
    "ph": "M", 
    "args": {
      "name": "Process %lld (CPU)"
    }
  },
  {
    "name": "process_name", "pid": %lld, "tid": "%lld(C++)",
    "ph": "M", 
    "args": {
      "name": "Process %lld (CPU)"
    }
  },
   {
    "name": "thread_name", "pid": %lld, "tid": "%lld(Python)",
    "ph": "M", 
    "args": {
      "name": "thread %lld:%s(Python)"
    }
  },
  {
    "name": "thread_name", "pid": %lld, "tid": "%lld(C++)",
    "ph": "M", 
    "args": {
      "name": "thread %lld:%s(C++)"
    }
  },
  {
    "name": "process_sort_index", "pid": %lld, "tid": %lld,
    "ph": "M", 
    "args": {
      "sort_index": %lld
    }
  },  
  {
    "name": "thread_sort_index", "pid": %lld, "tid": "%lld(Python)",
    "ph": "M", 
    "args": {
      "sort_index": %lld
    }
  },
  {
    "name": "thread_sort_index", "pid": %lld, "tid": "%lld(C++)",
    "ph": "M", 
    "args": {
      "sort_index": %lld
    }
  },
  )JSON"),
768 769 770 771 772 773 774 775 776
        (*it).first,
        (*it).second,
        (*it).first,
        (*it).first,
        (*it).second,
        (*it).first,
        (*it).first,
        (*it).second,
        (*it).second,
C
chenjian 已提交
777
        extra_info[string_format(std::string("%lld"), (*it).second)].c_str(),
778 779 780
        (*it).first,
        (*it).second,
        (*it).second,
C
chenjian 已提交
781
        extra_info[string_format(std::string("%lld"), (*it).second)].c_str(),
782 783 784 785 786 787 788 789 790
        (*it).first,
        (*it).second,
        (*it).first,
        (*it).first,
        (*it).second,
        (*it).second * 2,
        (*it).first,
        (*it).second,
        (*it).second * 2 + 1);
C
chenjian 已提交
791 792
  }

F
fwenguang 已提交
793 794 795 796 797 798
#ifdef PADDLE_WITH_MLU
  static std::string device_type("MLU");
#else
  static std::string device_type("GPU");
#endif

C
chenjian 已提交
799
  for (auto it = deviceid_streamid_set_.begin();
800 801 802 803
       it != deviceid_streamid_set_.end();
       ++it) {
    output_file_stream_ << string_format(std::string(
                                             R"JSON(
C
chenjian 已提交
804 805 806 807
  {
    "name": "process_name", "pid": %lld, "tid": %lld,
    "ph": "M", 
    "args": {
F
fwenguang 已提交
808
      "name": "Deivce %lld (%s)"
C
chenjian 已提交
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
    }
  },
   {
    "name": "thread_name", "pid": %lld, "tid": %lld,
    "ph": "M", 
    "args": {
      "name": "stream %lld"
    }
  },
  {
    "name": "process_sort_index", "pid": %lld, "tid": %lld,
    "ph": "M", 
    "args": {
      "sort_index": %lld
    }
  },  
  {
    "name": "thread_sort_index", "pid": %lld, "tid": %lld,
    "ph": "M", 
    "args": {
      "sort_index": %lld
    }
  },  
  )JSON"),
833 834 835 836 837 838 839 840 841 842 843 844 845
                                         (*it).first,
                                         (*it).second,
                                         (*it).first,
                                         device_type.c_str(),
                                         (*it).first,
                                         (*it).second,
                                         (*it).second,
                                         (*it).first,
                                         (*it).second,
                                         (*it).first + 0x10000000,
                                         (*it).first,
                                         (*it).second,
                                         (*it).second);
C
chenjian 已提交
846 847 848 849 850 851
  }
}

void ChromeTracingLogger::EndLog() {
  output_file_stream_ << std::string(
      R"JSON(
852 853 854 855 856 857
  }
  )JSON");
}

}  // namespace platform
}  // namespace paddle