device_tracer.cc 14.0 KB
Newer Older
X
Xin Pan 已提交
1
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14

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. */
#include "paddle/fluid/platform/device_tracer.h"
15 16

#include <deque>
X
Xin Pan 已提交
17
#include <fstream>
18
#include <map>
19
#include <mutex>  // NOLINT
20
#include <numeric>
21 22 23 24
#include <string>
#include <thread>  // NOLINT
#include <vector>

25
#include "glog/logging.h"
26
#include "google/protobuf/text_format.h"
27 28 29 30 31 32
#include "paddle/fluid/framework/block_desc.h"
#include "paddle/fluid/string/printf.h"

namespace paddle {
namespace platform {
namespace {
X
Xin Pan 已提交
33 34 35 36
// Tracking the nested block stacks of each thread.
thread_local std::deque<int> block_id_stack;
// Tracking the nested event stacks.
thread_local std::deque<std::string> annotation_stack;
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64

std::once_flag tracer_once_flag;
DeviceTracer *tracer = nullptr;
}  // namespace
#ifdef PADDLE_WITH_CUPTI

namespace {
// TODO(panyx0718): Revisit the buffer size here.
uint64_t kBufSize = 32 * 1024;
uint64_t kAlignSize = 8;

#define ALIGN_BUFFER(buffer, align)                                 \
  (((uintptr_t)(buffer) & ((align)-1))                              \
       ? ((buffer) + (align) - ((uintptr_t)(buffer) & ((align)-1))) \
       : (buffer))

#define CUPTI_CALL(call)                                                   \
  do {                                                                     \
    CUptiResult _status = call;                                            \
    if (_status != CUPTI_SUCCESS) {                                        \
      const char *errstr;                                                  \
      dynload::cuptiGetResultString(_status, &errstr);                     \
      fprintf(stderr, "%s:%d: error: function %s failed with error %s.\n", \
              __FILE__, __LINE__, #call, errstr);                          \
      exit(-1);                                                            \
    }                                                                      \
  } while (0)

X
Xin Pan 已提交
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
std::string MemcpyKind(CUpti_ActivityMemcpyKind kind) {
  switch (kind) {
    case CUPTI_ACTIVITY_MEMCPY_KIND_HTOD:
      return "MEMCPY_HtoD";
    case CUPTI_ACTIVITY_MEMCPY_KIND_DTOH:
      return "MEMCPY_DtoH";
    case CUPTI_ACTIVITY_MEMCPY_KIND_HTOA:
      return "MEMCPY_HtoA";
    case CUPTI_ACTIVITY_MEMCPY_KIND_ATOH:
      return "MEMCPY_AtoH";
    case CUPTI_ACTIVITY_MEMCPY_KIND_ATOA:
      return "MEMCPY_AtoA";
    case CUPTI_ACTIVITY_MEMCPY_KIND_ATOD:
      return "MEMCPY_AtoD";
    case CUPTI_ACTIVITY_MEMCPY_KIND_DTOA:
      return "MEMCPY_DtoA";
    case CUPTI_ACTIVITY_MEMCPY_KIND_DTOD:
      return "MEMCPY_DtoD";
    case CUPTI_ACTIVITY_MEMCPY_KIND_HTOH:
      return "MEMCPY_HtoH";
    case CUPTI_ACTIVITY_MEMCPY_KIND_PTOP:
      return "MEMCPY_PtoP";
    case CUPTI_ACTIVITY_MEMCPY_KIND_FORCE_INT:
      return "MEMCPY_FORCE_INT";
    default:
      break;
  }
  return "MEMCPY";
}

95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
void EnableActivity() {
  // Device activity record is created when CUDA initializes, so we
  // want to enable it before cuInit() or any CUDA runtime call.
  CUPTI_CALL(dynload::cuptiActivityEnable(CUPTI_ACTIVITY_KIND_MEMCPY));
  CUPTI_CALL(dynload::cuptiActivityEnable(CUPTI_ACTIVITY_KIND_KERNEL));
  CUPTI_CALL(dynload::cuptiActivityEnable(CUPTI_ACTIVITY_KIND_DEVICE));
  CUPTI_CALL(dynload::cuptiActivityEnable(CUPTI_ACTIVITY_KIND_MEMSET));
  CUPTI_CALL(dynload::cuptiActivityEnable(CUPTI_ACTIVITY_KIND_OVERHEAD));
  // We don't track these activities for now.
  // CUPTI_CALL(dynload::cuptiActivityEnable(CUPTI_ACTIVITY_KIND_CONTEXT));
  // CUPTI_CALL(dynload::cuptiActivityEnable(CUPTI_ACTIVITY_KIND_DRIVER));
  // CUPTI_CALL(dynload::cuptiActivityEnable(CUPTI_ACTIVITY_KIND_RUNTIME));
  // CUPTI_CALL(dynload::cuptiActivityEnable(CUPTI_ACTIVITY_KIND_NAME));
  // CUPTI_CALL(dynload::cuptiActivityEnable(CUPTI_ACTIVITY_KIND_MARKER));
}

void DisableActivity() {
  CUPTI_CALL(dynload::cuptiActivityDisable(CUPTI_ACTIVITY_KIND_MEMCPY));
  CUPTI_CALL(dynload::cuptiActivityDisable(CUPTI_ACTIVITY_KIND_KERNEL));
  CUPTI_CALL(dynload::cuptiActivityDisable(CUPTI_ACTIVITY_KIND_DEVICE));
  // Disable all other activity record kinds.
  CUPTI_CALL(dynload::cuptiActivityDisable(CUPTI_ACTIVITY_KIND_CONTEXT));
  CUPTI_CALL(dynload::cuptiActivityDisable(CUPTI_ACTIVITY_KIND_DRIVER));
  CUPTI_CALL(dynload::cuptiActivityDisable(CUPTI_ACTIVITY_KIND_RUNTIME));
  CUPTI_CALL(dynload::cuptiActivityDisable(CUPTI_ACTIVITY_KIND_MEMSET));
  CUPTI_CALL(dynload::cuptiActivityDisable(CUPTI_ACTIVITY_KIND_NAME));
  CUPTI_CALL(dynload::cuptiActivityDisable(CUPTI_ACTIVITY_KIND_MARKER));
  CUPTI_CALL(dynload::cuptiActivityDisable(CUPTI_ACTIVITY_KIND_OVERHEAD));
}

void CUPTIAPI bufferRequested(uint8_t **buffer, size_t *size,
                              size_t *maxNumRecords) {
127
  uint8_t *buf = reinterpret_cast<uint8_t *>(malloc(kBufSize + kAlignSize));
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
  *size = kBufSize;
  *buffer = ALIGN_BUFFER(buf, kAlignSize);
  *maxNumRecords = 0;
}

void CUPTIAPI bufferCompleted(CUcontext ctx, uint32_t streamId, uint8_t *buffer,
                              size_t size, size_t validSize) {
  CUptiResult status;
  CUpti_Activity *record = NULL;
  if (validSize > 0) {
    do {
      status = dynload::cuptiActivityGetNextRecord(buffer, validSize, &record);
      if (status == CUPTI_SUCCESS) {
        switch (record->kind) {
          case CUPTI_ACTIVITY_KIND_KERNEL:
          case CUPTI_ACTIVITY_KIND_CONCURRENT_KERNEL: {
            auto *kernel =
                reinterpret_cast<const CUpti_ActivityKernel3 *>(record);
            tracer->AddKernelRecords(kernel->start, kernel->end,
                                     kernel->deviceId, kernel->streamId,
                                     kernel->correlationId);
            break;
          }
X
Xin Pan 已提交
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
          case CUPTI_ACTIVITY_KIND_MEMCPY: {
            auto *memcpy =
                reinterpret_cast<const CUpti_ActivityMemcpy *>(record);
            tracer->AddMemRecords(
                MemcpyKind(
                    static_cast<CUpti_ActivityMemcpyKind>(memcpy->copyKind)),
                memcpy->start, memcpy->end, memcpy->deviceId, memcpy->streamId,
                memcpy->correlationId, memcpy->bytes);
            break;
          }
          case CUPTI_ACTIVITY_KIND_MEMCPY2: {
            auto *memcpy =
                reinterpret_cast<const CUpti_ActivityMemcpy2 *>(record);
            tracer->AddMemRecords(
                MemcpyKind(
                    static_cast<CUpti_ActivityMemcpyKind>(memcpy->copyKind)),
                memcpy->start, memcpy->end, memcpy->deviceId, memcpy->streamId,
                memcpy->correlationId, memcpy->bytes);
            break;
          }
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
          default: { break; }
        }
      } else if (status == CUPTI_ERROR_MAX_LIMIT_REACHED) {
        // Seems not an error in this case.
        break;
      } else {
        CUPTI_CALL(status);
      }
    } while (1);

    size_t dropped;
    CUPTI_CALL(
        dynload::cuptiActivityGetNumDroppedRecords(ctx, streamId, &dropped));
    if (dropped != 0) {
      fprintf(stderr, "Dropped %u activity records\n", (unsigned int)dropped);
    }
  }
  free(buffer);
}
}  // namespace

Q
qiaolongfei 已提交
192 193
#endif  // PADDLE_WITH_CUPTI

194 195 196 197 198 199 200 201 202
class DeviceTracerImpl : public DeviceTracer {
 public:
  DeviceTracerImpl() : enabled_(false) {}

  void AddAnnotation(uint64_t id, const std::string &anno) {
    std::lock_guard<std::mutex> l(trace_mu_);
    correlations_[id] = anno;
  }

X
Xin Pan 已提交
203 204 205 206
  void AddCPURecords(const std::string &anno, uint64_t start_ns,
                     uint64_t end_ns, int64_t device_id, int64_t thread_id) {
    if (anno.empty()) {
      VLOG(1) << "Empty timeline annotation.";
207 208
      return;
    }
X
Xin Pan 已提交
209
    std::lock_guard<std::mutex> l(trace_mu_);
X
Xin Pan 已提交
210 211
    cpu_records_.push_back(
        CPURecord{anno, start_ns, end_ns, device_id, thread_id});
X
Xin Pan 已提交
212 213
  }

X
Xin Pan 已提交
214
  void AddMemRecords(const std::string &name, uint64_t start_ns,
X
Xin Pan 已提交
215
                     uint64_t end_ns, int64_t device_id, int64_t stream_id,
X
Xin Pan 已提交
216
                     uint32_t correlation_id, uint64_t bytes) {
X
Xin Pan 已提交
217 218
    // 0 means timestamp information could not be collected for the kernel.
    if (start_ns == 0 || end_ns == 0) {
X
Xin Pan 已提交
219
      VLOG(3) << name << " cannot be traced";
X
Xin Pan 已提交
220 221 222
      return;
    }
    std::lock_guard<std::mutex> l(trace_mu_);
X
Xin Pan 已提交
223 224 225 226
    mem_records_.push_back(MemRecord{name, start_ns, end_ns, device_id,
                                     stream_id, correlation_id, bytes});
  }

X
Xin Pan 已提交
227 228
  void AddKernelRecords(uint64_t start, uint64_t end, int64_t device_id,
                        int64_t stream_id, uint32_t correlation_id) {
X
Xin Pan 已提交
229 230
    // 0 means timestamp information could not be collected for the kernel.
    if (start == 0 || end == 0) {
X
Xin Pan 已提交
231
      VLOG(3) << correlation_id << " cannot be traced";
X
Xin Pan 已提交
232 233
      return;
    }
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
    std::lock_guard<std::mutex> l(trace_mu_);
    kernel_records_.push_back(
        KernelRecord{start, end, device_id, stream_id, correlation_id});
  }

  bool IsEnabled() {
    std::lock_guard<std::mutex> l(trace_mu_);
    return enabled_;
  }

  void Enable() {
    std::lock_guard<std::mutex> l(trace_mu_);
    if (enabled_) {
      return;
    }
Q
qiaolongfei 已提交
249 250

#ifdef PADDLE_WITH_CUPTI
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
    EnableActivity();

    // Register callbacks for buffer requests and completed by CUPTI.
    CUPTI_CALL(dynload::cuptiActivityRegisterCallbacks(bufferRequested,
                                                       bufferCompleted));

    CUptiResult ret;
    ret = dynload::cuptiSubscribe(
        &subscriber_, static_cast<CUpti_CallbackFunc>(ApiCallback), this);
    if (ret == CUPTI_ERROR_MAX_LIMIT_REACHED) {
      fprintf(stderr, "CUPTI subcriber limit reached.\n");
    } else if (ret != CUPTI_SUCCESS) {
      fprintf(stderr, "Failed to create CUPTI subscriber.\n");
    }
    CUPTI_CALL(
        dynload::cuptiEnableCallback(1, subscriber_, CUPTI_CB_DOMAIN_DRIVER_API,
                                     CUPTI_DRIVER_TRACE_CBID_cuLaunchKernel));
    CUPTI_CALL(dynload::cuptiGetTimestamp(&start_ns_));
Q
qiaolongfei 已提交
269
#endif  // PADDLE_WITH_CUPTI
270 271 272
    enabled_ = true;
  }

X
Xin Pan 已提交
273
  proto::Profile GenProfile(const std::string &profile_path) {
274 275 276 277 278 279 280 281 282 283
    std::lock_guard<std::mutex> l(trace_mu_);
    proto::Profile profile_pb;
    profile_pb.set_start_ns(start_ns_);
    profile_pb.set_end_ns(end_ns_);
    for (const KernelRecord &r : kernel_records_) {
      if (correlations_.find(r.correlation_id) == correlations_.end()) {
        fprintf(stderr, "cannot relate a kernel activity\n");
        continue;
      }
      auto *event = profile_pb.add_events();
X
Xin Pan 已提交
284
      event->set_type(proto::Event::GPUKernel);
285 286 287
      event->set_name(correlations_.at(r.correlation_id));
      event->set_start_ns(r.start_ns);
      event->set_end_ns(r.end_ns);
X
Xin Pan 已提交
288
      event->set_sub_device_id(r.stream_id);
289
      event->set_device_id(r.device_id);
X
Xin Pan 已提交
290 291 292 293
    }

    for (const CPURecord &r : cpu_records_) {
      auto *event = profile_pb.add_events();
X
Xin Pan 已提交
294
      event->set_type(proto::Event::CPU);
X
Xin Pan 已提交
295 296 297
      event->set_name(r.name);
      event->set_start_ns(r.start_ns);
      event->set_end_ns(r.end_ns);
X
Xin Pan 已提交
298 299
      event->set_sub_device_id(r.thread_id);
      event->set_device_id(r.device_id);
300
    }
X
Xin Pan 已提交
301 302
    for (const MemRecord &r : mem_records_) {
      auto *event = profile_pb.add_events();
X
Xin Pan 已提交
303
      event->set_type(proto::Event::GPUKernel);
X
Xin Pan 已提交
304 305 306
      event->set_name(r.name);
      event->set_start_ns(r.start_ns);
      event->set_end_ns(r.end_ns);
X
Xin Pan 已提交
307
      event->set_sub_device_id(r.stream_id);
X
Xin Pan 已提交
308 309 310
      event->set_device_id(r.device_id);
      event->mutable_memcopy()->set_bytes(r.bytes);
    }
X
Xin Pan 已提交
311 312
    std::ofstream profile_f;
    profile_f.open(profile_path, std::ios::out | std::ios::trunc);
X
Xin Pan 已提交
313 314
    std::string profile_str;
    profile_pb.SerializeToString(&profile_str);
X
Xin Pan 已提交
315 316
    profile_f << profile_str;
    profile_f.close();
317 318 319 320
    return profile_pb;
  }

  void Disable() {
Q
qiaolongfei 已提交
321 322
    std::lock_guard<std::mutex> l(trace_mu_);
#ifdef PADDLE_WITH_CUPTI
323 324
    // flush might cause additional calls to DeviceTracker.
    dynload::cuptiActivityFlushAll(CUPTI_ACTIVITY_FLAG_FLUSH_FORCED);
Q
qiaolongfei 已提交
325

326 327 328
    DisableActivity();
    dynload::cuptiUnsubscribe(subscriber_);
    CUPTI_CALL(dynload::cuptiGetTimestamp(&end_ns_));
Q
qiaolongfei 已提交
329
#endif  // PADDLE_WITH_CUPTI
330 331 332 333
    enabled_ = false;
  }

 private:
Q
qiaolongfei 已提交
334
#ifdef PADDLE_WITH_CUPTI
335 336 337 338 339 340 341 342
  static void CUPTIAPI ApiCallback(void *userdata, CUpti_CallbackDomain domain,
                                   CUpti_CallbackId cbid, const void *cbdata) {
    auto *cbInfo = reinterpret_cast<const CUpti_CallbackData *>(cbdata);
    DeviceTracer *tracer = reinterpret_cast<DeviceTracer *>(userdata);

    if ((domain == CUPTI_CB_DOMAIN_DRIVER_API) &&
        (cbid == CUPTI_DRIVER_TRACE_CBID_cuLaunchKernel)) {
      if (cbInfo->callbackSite == CUPTI_API_ENTER) {
X
Xin Pan 已提交
343 344 345
        const std::string anno = !annotation_stack.empty()
                                     ? annotation_stack.back()
                                     : cbInfo->symbolName;
346 347 348 349 350 351 352 353
        tracer->AddAnnotation(cbInfo->correlationId, anno);
      }
    } else {
      VLOG(1) << "Unhandled API Callback for " << domain << " " << cbid;
    }
  }
  CUpti_SubscriberHandle subscriber_;
#endif  // PADDLE_WITH_CUPTI
Q
qiaolongfei 已提交
354 355 356 357 358 359 360 361
  std::mutex trace_mu_;
  bool enabled_;
  uint64_t start_ns_;
  uint64_t end_ns_;
  std::vector<KernelRecord> kernel_records_;
  std::vector<MemRecord> mem_records_;
  std::vector<CPURecord> cpu_records_;
  std::unordered_map<uint32_t, std::string> correlations_;
362 363
};

Q
qiaolongfei 已提交
364
void CreateTracer(DeviceTracer **t) { *t = new DeviceTracerImpl(); }
365 366 367 368 369 370

DeviceTracer *GetDeviceTracer() {
  std::call_once(tracer_once_flag, CreateTracer, &tracer);
  return tracer;
}

X
Xin Pan 已提交
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
void SetCurAnnotation(const std::string &anno) {
  annotation_stack.push_back(anno);
}

void ClearCurAnnotation() { annotation_stack.pop_back(); }

std::string CurAnnotation() {
  if (annotation_stack.empty()) return "";
  return annotation_stack.back();
}

void SetCurBlock(int block_id) { block_id_stack.push_back(block_id); }

void ClearCurBlock() { block_id_stack.pop_back(); }

int BlockDepth() { return block_id_stack.size(); }
387 388
}  // namespace platform
}  // namespace paddle