TVMRuntime.mm 4.94 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

Tianqi Chen committed
20 21 22 23 24 25
/*!
 *  Copyright (c) 2017 by Contributors
 * \file TVMRuntime.mm
 */
#include "TVMRuntime.h"
// Runtime API
26 27 28 29 30 31 32 33 34 35 36 37
#include "../../../src/runtime/c_runtime_api.cc"
#include "../../../src/runtime/cpu_device_api.cc"
#include "../../../src/runtime/workspace_pool.cc"
#include "../../../src/runtime/thread_pool.cc"
#include "../../../src/runtime/threading_backend.cc"
#include "../../../src/runtime/module_util.cc"
#include "../../../src/runtime/system_lib_module.cc"
#include "../../../src/runtime/module.cc"
#include "../../../src/runtime/registry.cc"
#include "../../../src/runtime/file_util.cc"
#include "../../../src/runtime/dso_module.cc"
#include "../../../src/runtime/ndarray.cc"
Tianqi Chen committed
38
// RPC server
39 40 41 42
#include "../../../src/runtime/rpc/rpc_session.cc"
#include "../../../src/runtime/rpc/rpc_server_env.cc"
#include "../../../src/runtime/rpc/rpc_socket_impl.cc"
#include "../../../src/runtime/rpc/rpc_module.cc"
43
// Graph runtime
44
#include "../../../src/runtime/graph/graph_runtime.cc"
Tianqi Chen committed
45
// Metal
46 47
#include "../../../src/runtime/metal/metal_module.mm"
#include "../../../src/runtime/metal/metal_device_api.mm"
Tianqi Chen committed
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82

namespace dmlc {
// Override logging mechanism
void CustomLogMessage::Log(const std::string& msg) {
  NSLog(@"%s", msg.c_str());
}
}  // namespace dmlc

namespace tvm {
namespace runtime {

class NSStreamChannel final : public RPCChannel {
 public:
  explicit NSStreamChannel(NSOutputStream* stream)
      : stream_(stream) {}

  size_t Send(const void* data, size_t size) final {
    ssize_t nbytes = [stream_ write:reinterpret_cast<const uint8_t*>(data)
                              maxLength:size];
    if (nbytes < 0) {
      NSLog(@"%@",[stream_ streamError].localizedDescription);
      throw dmlc::Error("Stream error");
    }
    return nbytes;
  }

  size_t Recv(void* data, size_t size) final {
    LOG(FATAL) << "Do not allow explicit receive for";
    return 0;
  }

 private:
  NSOutputStream* stream_;
};

83 84
FEventHandler CreateServerEventHandler(
    NSOutputStream *outputStream, std::string name, std::string remote_key) {
Tianqi Chen committed
85
  std::unique_ptr<NSStreamChannel> ch(new NSStreamChannel(outputStream));
86
  std::shared_ptr<RPCSession> sess = RPCSession::Create(std::move(ch), name, remote_key);
Tianqi Chen committed
87 88 89 90 91 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 118 119 120 121 122 123 124 125
  return [sess](const std::string& in_bytes, int flag) {
    return sess->ServerEventHandler(in_bytes, flag);
  };
}

// Runtime environment
struct RPCEnv {
 public:
  RPCEnv() {
    NSString* path = NSTemporaryDirectory();
    base_ = [path UTF8String];
    if (base_[base_.length() - 1] != '/') {
      base_ = base_ + '/';
    }
  }
  // Get Path.
  std::string GetPath(const std::string& file_name) {
    return base_  + file_name;
  }

 private:
  std::string base_;
};

void LaunchSyncServer() {
  // only load dylib from frameworks.
  NSBundle* bundle = [NSBundle mainBundle];
  NSString* base = [bundle privateFrameworksPath];
  NSString* path = [base stringByAppendingPathComponent: @"tvm/rpc_config.txt"];
  std::string name = [path UTF8String];
  std::ifstream fs(name, std::ios::in);
  std::string url, key;
  int port;
  CHECK(fs >> url >> port >> key)
      << "Invalid RPC config file " << name;
  RPCConnect(url, port, "server:" + key)
      ->ServerLoop();
}

126
TVM_REGISTER_GLOBAL("tvm.rpc.server.workpath")
Tianqi Chen committed
127 128 129 130 131
.set_body([](TVMArgs args, TVMRetValue* rv) {
    static RPCEnv env;
    *rv = env.GetPath(args[0]);
  });

132
TVM_REGISTER_GLOBAL("tvm.rpc.server.load_module")
Tianqi Chen committed
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
.set_body([](TVMArgs args, TVMRetValue *rv) {
    std::string name = args[0];
    std::string fmt = GetFileFormat(name, "");
    NSString* base;
    if (fmt == "dylib") {
      // only load dylib from frameworks.
      NSBundle* bundle = [NSBundle mainBundle];
      base = [[bundle privateFrameworksPath]
               stringByAppendingPathComponent: @"tvm"];
    } else {
      // Load other modules in tempdir.
      base = NSTemporaryDirectory();
    }
    NSString* path = [base stringByAppendingPathComponent:
                             [NSString stringWithUTF8String:name.c_str()]];
    name = [path UTF8String];
    *rv = Module::LoadFromFile(name, fmt);
    LOG(INFO) << "Load module from " << name << " ...";
  });
}  // namespace runtime
}  // namespace tvm

@implementation TVMRuntime

+(void) launchSyncServer {
  tvm::runtime::LaunchSyncServer();
}

@end