device_api.cc 2.55 KB
Newer Older
1 2
/*!
 *  Copyright (c) 2018 by Contributors
3 4
 * \file device_api.cc
 * \brief TVM device API for VTA
5 6
 */

7 8 9
#include <tvm/runtime/registry.h>
#include <dmlc/thread_local.h>
#include <vta/runtime.h>
10

11
#include "../../src/runtime/workspace_pool.h"
12 13


14 15
namespace tvm {
namespace runtime {
16 17 18 19 20 21 22 23 24 25 26 27

class VTADeviceAPI final : public DeviceAPI {
 public:
  void SetDevice(TVMContext ctx) final {}

  void GetAttr(TVMContext ctx, DeviceAttrKind kind, TVMRetValue* rv) final {
    if (kind == kExist) {
      *rv = 1;
    }
  }

  void* AllocDataSpace(TVMContext ctx,
28 29
                       size_t size,
                       size_t alignment,
30
                       TVMType type_hint) final {
31
    return VTABufferAlloc(size);
32 33 34
  }

  void FreeDataSpace(TVMContext ctx, void* ptr) final {
35
    VTABufferFree(ptr);
36 37 38 39 40 41 42 43 44
  }

  void CopyDataFromTo(const void* from,
                      size_t from_offset,
                      void* to,
                      size_t to_offset,
                      size_t size,
                      TVMContext ctx_from,
                      TVMContext ctx_to,
45
                      TVMType type_hint,
46 47 48 49 50 51 52 53
                      TVMStreamHandle stream) final {
    int kind_mask = 0;
    if (ctx_from.device_type != kDLCPU) {
      kind_mask |= 2;
    }
    if (ctx_to.device_type != kDLCPU) {
      kind_mask |= 1;
    }
54
    VTABufferCopy(from, from_offset,
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
                  to, to_offset,
                  size, kind_mask);
  }

  void StreamSync(TVMContext ctx, TVMStreamHandle stream) final {
  }

  void* AllocWorkspace(TVMContext ctx, size_t size, TVMType type_hint) final;

  void FreeWorkspace(TVMContext ctx, void* data) final;

  static const std::shared_ptr<VTADeviceAPI>& Global() {
    static std::shared_ptr<VTADeviceAPI> inst =
        std::make_shared<VTADeviceAPI>();
    return inst;
  }
};

struct VTAWorkspacePool : public WorkspacePool {
  VTAWorkspacePool() :
75
      WorkspacePool(kDLExtDev, VTADeviceAPI::Global()) {}
76 77 78 79 80 81 82 83 84 85 86
};

void* VTADeviceAPI::AllocWorkspace(TVMContext ctx, size_t size, TVMType type_hint) {
  return dmlc::ThreadLocalStore<VTAWorkspacePool>::Get()
      ->AllocWorkspace(ctx, size);
}

void VTADeviceAPI::FreeWorkspace(TVMContext ctx, void* data) {
  dmlc::ThreadLocalStore<VTAWorkspacePool>::Get()->FreeWorkspace(ctx, data);
}

87 88 89
// Register device api with override.
static TVM_ATTRIBUTE_UNUSED auto& __register_dev__ =
::tvm::runtime::Registry::Register("device_api.ext_dev", true)
90 91 92 93 94 95
.set_body([](TVMArgs args, TVMRetValue* rv) {
    DeviceAPI* ptr = VTADeviceAPI::Global().get();
    *rv = static_cast<void*>(ptr);
  });
}  // namespace runtime
}  // namespace tvm