Skip to content

Commit

Permalink
Feat/graph del by ref (#7857)
Browse files Browse the repository at this point in the history
* remove IsMultiClient() and single client logic

Signed-off-by: daquexian <daquexian566@gmail.com>

* rename eager.multi_client to eager

Signed-off-by: daquexian <daquexian566@gmail.com>

* auto format by CI

* add py ref

* refine new session

* clean code

* make scope api inner use

* use session with ref cnt

* run barrier callback in BarrierPhyInstrOperand::~BarrierPhyInstrOperand

* test pass

* lock gil in vm Callback thread

* more comments for VirtualMachineEngine::Callback()

* merge

* merge rm single client

* rm initenv

* merge and fix master

* refactor env c api

* add debug code

* fix and serving test pass

* test passed

* rm useless

* rm useless code

* format

* rm useless include

* rm sync in py

* the Env is never destroyed.

* export Env into python

* more unittests

* fix and pass tests

* revert virtual_machine.cpp

* revert core/vm

* remove outdated python class oneflow.unittest.TestCase

* graph test passed

* wait shared_ptr.use_count() == 0

* export unittest.TestCase in framework/unittest.py

* SwitchToShuttingDownPhase

* optional is_normal_exit

* VirtualMachine::CloseVMThreads

* Delete env_api.h

env_api.h is deleted by master

* address pr comments

* rm is env init

* Clear empty thread when graph destroy (#7633)

* Revert "Clear empty thread when graph destroy (#7633)" (#7860)

This reverts commit 3e8585e.

* fix a ref-cnt bug in TryRunBarrierInstruction.

* rm env_api

* fix clang-tidy error

* fix clang-tidy in env_imp

* refine env api

* format

* refine graph del and sync at shuttingdown

* fix typo

* add comment

* rm useless

* rm useless

Co-authored-by: daquexian <daquexian566@gmail.com>
Co-authored-by: oneflow-ci-bot <ci-bot@oneflow.org>
Co-authored-by: lixinqi <lixinqi0703106@163.com>
Co-authored-by: Li Xinqi <lixinqi2010@gmail.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
Co-authored-by: Luyang <flowingsun007@163.com>
Co-authored-by: cheng cheng <472491134@qq.com>
  • Loading branch information
8 people authored Apr 10, 2022
1 parent 0826518 commit 9c7d1a9
Show file tree
Hide file tree
Showing 28 changed files with 373 additions and 299 deletions.
123 changes: 3 additions & 120 deletions oneflow/api/cpp/env.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,136 +15,19 @@ limitations under the License.
*/

#include <glog/logging.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <random>
#include <type_traits>
#include "oneflow/api/cpp/env.h"
#include "oneflow/core/common/global.h"
#include "oneflow/core/common/just.h"
#include "oneflow/core/common/optional.h"
#include "oneflow/core/framework/multi_client_session_context.h"
#include "oneflow/core/framework/session_util.h"
#include "oneflow/api/cpp/env_impl.h"
#include "oneflow/core/framework/shut_down_util.h"
#include "oneflow/core/job/cluster_instruction.h"
#include "oneflow/core/job/env.pb.h"
#include "oneflow/core/job/env_global_objects_scope.h"
#include "oneflow/core/control/ctrl_bootstrap.h"
#include "oneflow/core/job/session.h"
#include "oneflow/core/rpc/include/base.h"
#include "oneflow/core/vm/vm_util.h"
#include "oneflow/core/thread/thread_consistent_id.h"

namespace oneflow_api {

namespace of = oneflow;

namespace { // for inltialize

inline bool IsEnvInited() { return of::Global<of::EnvGlobalObjectsScope>::Get() != nullptr; }

bool HasEnvVar(const std::string& key) {
const char* value = getenv(key.c_str());
return value != nullptr;
}

std::string GetEnvVar(const std::string& key, const std::string& default_value) {
const char* value = getenv(key.c_str());
if (value == nullptr) { return default_value; }
return std::string(value);
}

int64_t GetEnvVar(const std::string& key, int64_t default_value) {
const char* value = getenv(key.c_str());
if (value == nullptr) { return default_value; }
return std::atoll(value);
}

int32_t FindFreePort(const std::string& addr) {
#ifdef __linux__
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
CHECK_GE(sock, 0) << "fail to find a free port.";
int optval = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));

std::mt19937 rng;
rng.seed(std::random_device()());
std::uniform_int_distribution<std::mt19937::result_type> dist(1, 1000);

int count = 0;
int num_attempts = 200;
do {
int port = 5000 + dist(rng);
struct sockaddr_in sockaddr {};
memset(&sockaddr, 0, sizeof(sockaddr));
sockaddr.sin_family = AF_INET;
sockaddr.sin_port = htons(port);
sockaddr.sin_addr.s_addr = inet_addr(addr.c_str());
int error = bind(sock, (struct sockaddr*)&sockaddr, sizeof(sockaddr));
if (error == 0) { return port; }
++count;
} while (count < num_attempts);
CHECK_NE(count, num_attempts) << "fail to find a free port.";
#endif // __linux__
return -1;
}

void CompleteEnvProto(of::EnvProto& env_proto) {
auto bootstrap_conf = env_proto.mutable_ctrl_bootstrap_conf();
auto master_addr = bootstrap_conf->mutable_master_addr();
const std::string addr = GetEnvVar("MASTER_ADDR", "127.0.0.1");
master_addr->set_host(addr);
master_addr->set_port(GetEnvVar("MASTER_PORT", FindFreePort(addr)));
bootstrap_conf->set_world_size(GetEnvVar("WORLD_SIZE", 1));
bootstrap_conf->set_rank(GetEnvVar("RANK", 0));

auto cpp_logging_conf = env_proto.mutable_cpp_logging_conf();
if (HasEnvVar("GLOG_log_dir")) { cpp_logging_conf->set_log_dir(GetEnvVar("GLOG_log_dir", "")); }
if (HasEnvVar("GLOG_logtostderr")) {
cpp_logging_conf->set_logtostderr(GetEnvVar("GLOG_logtostderr", -1));
}
if (HasEnvVar("GLOG_logbuflevel")) {
cpp_logging_conf->set_logbuflevel(GetEnvVar("GLOG_logbuflevel", -1));
}
}

of::Maybe<void> initEnv() {
of::EnvProto env_proto;
CompleteEnvProto(env_proto);
of::Global<of::EnvGlobalObjectsScope>::SetAllocated(new of::EnvGlobalObjectsScope());
JUST(of::Global<of::EnvGlobalObjectsScope>::Get()->Init(env_proto));

of::ConfigProto config_proto;
config_proto.mutable_resource()->set_cpu_device_num(1); // useless, will be set in TryInit
const int64_t session_id = of::NewSessionId();
JUST(of::RegsiterSession(session_id));
config_proto.set_session_id(session_id);
of::Global<of::MultiClientSessionContext>::New();
of::Global<of::MultiClientSessionContext>::Get()->TryInit(config_proto).GetOrThrow();
return of::Maybe<void>::Ok();
}

} // namespace

void initialize() {
if (!IsEnvInited()) { initEnv().GetOrThrow(); }
if (of::Global<OneFlowEnv>::Get() == nullptr) { of::Global<OneFlowEnv>::New(); }
of::SetShuttingDown(false);
}

void release() {
if (IsEnvInited()) {
// sync multi_client
of::vm::ClusterSync().GetOrThrow();
of::Global<of::MultiClientSessionContext>::Get()->TryClose().GetOrThrow();
of::Global<of::MultiClientSessionContext>::Delete();
// destory env
OF_ENV_BARRIER();
of::Global<of::EnvGlobalObjectsScope>::Delete();
}
if (of::Global<OneFlowEnv>::Get() != nullptr) { of::Global<OneFlowEnv>::Delete(); }
of::SetShuttingDown();
of::ResetThisThreadUniqueConsistentId().GetOrThrow();
}
Expand Down
134 changes: 134 additions & 0 deletions oneflow/api/cpp/env_impl.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
/*
Copyright 2020 The OneFlow 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.
*/
#include <glog/logging.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <memory>
#include <random>
#include <type_traits>
#include "oneflow/api/cpp/env_impl.h"
#include "oneflow/core/common/global.h"
#include "oneflow/core/common/just.h"
#include "oneflow/core/common/optional.h"
#include "oneflow/core/common/util.h"
#include "oneflow/core/framework/session_util.h"
#include "oneflow/core/job/env.pb.h"
#include "oneflow/core/job/cluster_instruction.h"
#include "oneflow/core/control/ctrl_bootstrap.h"
#include "oneflow/core/job/session.h"
#include "oneflow/core/rpc/include/base.h"
#include "oneflow/core/vm/vm_util.h"

namespace oneflow_api {

namespace of = oneflow;

namespace { // for inltialize

inline bool IsEnvInited() { return of::Global<of::EnvGlobalObjectsScope>::Get() != nullptr; }

bool HasEnvVar(const std::string& key) {
const char* value = getenv(key.c_str());
return value != nullptr;
}

std::string GetEnvVar(const std::string& key, const std::string& default_value) {
const char* value = getenv(key.c_str());
if (value == nullptr) { return default_value; }
return std::string(value);
}

int64_t GetEnvVar(const std::string& key, int64_t default_value) {
const char* value = getenv(key.c_str());
if (value == nullptr) { return default_value; }
return std::atoll(value);
}

int32_t FindFreePort(const std::string& addr) {
#ifdef __linux__
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
CHECK_GE(sock, 0) << "fail to find a free port.";
int optval = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));

std::mt19937 rng;
rng.seed(std::random_device()());
std::uniform_int_distribution<std::mt19937::result_type> dist(1, 1000);

int count = 0;
int num_attempts = 200;
do {
int port = 5000 + dist(rng);
struct sockaddr_in sockaddr {};
memset(&sockaddr, 0, sizeof(sockaddr));
sockaddr.sin_family = AF_INET;
sockaddr.sin_port = htons(port);
sockaddr.sin_addr.s_addr = inet_addr(addr.c_str());
int error = bind(sock, (struct sockaddr*)&sockaddr, sizeof(sockaddr));
if (error == 0) { return port; }
++count;
} while (count < num_attempts);
CHECK_NE(count, num_attempts) << "fail to find a free port.";
#endif // __linux__
return -1;
}

void CompleteEnvProto(of::EnvProto& env_proto) {
auto bootstrap_conf = env_proto.mutable_ctrl_bootstrap_conf();
auto master_addr = bootstrap_conf->mutable_master_addr();
const std::string addr = GetEnvVar("MASTER_ADDR", "127.0.0.1");
master_addr->set_host(addr);
master_addr->set_port(GetEnvVar("MASTER_PORT", FindFreePort(addr)));
bootstrap_conf->set_world_size(GetEnvVar("WORLD_SIZE", 1));
bootstrap_conf->set_rank(GetEnvVar("RANK", 0));

auto cpp_logging_conf = env_proto.mutable_cpp_logging_conf();
if (HasEnvVar("GLOG_log_dir")) { cpp_logging_conf->set_log_dir(GetEnvVar("GLOG_log_dir", "")); }
if (HasEnvVar("GLOG_logtostderr")) {
cpp_logging_conf->set_logtostderr(GetEnvVar("GLOG_logtostderr", -1));
}
if (HasEnvVar("GLOG_logbuflevel")) {
cpp_logging_conf->set_logbuflevel(GetEnvVar("GLOG_logbuflevel", -1));
}
}
} // namespace

OneFlowEnv::OneFlowEnv() {
of::EnvProto env_proto;
CompleteEnvProto(env_proto);

env_ctx_ = std::make_shared<of::EnvGlobalObjectsScope>(env_proto);

of::ConfigProto config_proto;
config_proto.mutable_resource()->set_cpu_device_num(1); // useless, will be set in TryInit
const int64_t session_id = of::NewSessionId();
CHECK_JUST(of::RegsiterSession(session_id));
config_proto.set_session_id(session_id);

session_ctx_ = std::make_shared<of::MultiClientSessionContext>(env_ctx_);
CHECK_JUST(session_ctx_->TryInit(config_proto));
}

OneFlowEnv::~OneFlowEnv() {
session_ctx_.reset();
env_ctx_.reset();
}

} // namespace oneflow_api
38 changes: 38 additions & 0 deletions oneflow/api/cpp/env_impl.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
Copyright 2020 The OneFlow 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.
*/
#include <memory>
#include "oneflow/core/framework/multi_client_session_context.h"
#include "oneflow/core/job/env_global_objects_scope.h"

#ifndef ONEFLOW_API_CPP_ENV_IMPL_H_
#define ONEFLOW_API_CPP_ENV_IMPL_H_

namespace oneflow_api {
namespace of = oneflow;
class OneFlowEnv {
public:
OF_DISALLOW_COPY(OneFlowEnv);
OneFlowEnv();
~OneFlowEnv();
std::shared_ptr<of::MultiClientSessionContext> GetSessionCtx() { return session_ctx_; }

private:
std::shared_ptr<of::EnvGlobalObjectsScope> env_ctx_;
std::shared_ptr<of::MultiClientSessionContext> session_ctx_;
};
} // namespace oneflow_api

#endif // ONEFLOW_API_CPP_ENV_IMPL_H_
11 changes: 8 additions & 3 deletions oneflow/api/cpp/framework/graph.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ limitations under the License.
*/

#include "oneflow/api/common/ofblob.h"
#include "oneflow/api/cpp/env_impl.h"
#include "oneflow/api/cpp/framework/device.h"
#include "oneflow/api/cpp/framework/dtype.h"
#include "oneflow/api/cpp/framework/graph.h"
Expand Down Expand Up @@ -54,6 +55,7 @@ limitations under the License.
#include "oneflow/core/operator/interface_blob_conf.pb.h"
#include "oneflow/core/operator/op_conf.pb.h"
#include "oneflow/core/register/logical_blob_id.pb.h"
#include "oneflow/core/vm/vm_util.h"

namespace oneflow_api {

Expand Down Expand Up @@ -134,7 +136,7 @@ class Graph::GraphImpl final {
GraphImpl(const GraphImpl& graph) = delete;
GraphImpl(GraphImpl&& graph) = default;

~GraphImpl() = default;
~GraphImpl();

GraphImpl& operator=(const GraphImpl& graph) = delete;
GraphImpl& operator=(GraphImpl&& graph) = default;
Expand Down Expand Up @@ -228,8 +230,9 @@ Graph::GraphImpl::GraphImpl(const std::string& model_path, const Device& device)
if (of::ParseBooleanFromEnv("ONEFLOW_SERVING_DEBUG", false)) { LOG(ERROR) << job_.DebugString(); }
job_.mutable_job_conf()->mutable_predict_conf();
job_.mutable_job_conf()->set_job_name(job_.mutable_job_conf()->job_name() + of::NewUniqueId());
graph_ = std::make_shared<of::NNGraph>(job_.job_conf().job_name());
of::Global<of::MultiClientSessionContext>::Get()->AddCGraph(graph_).GetOrThrow();
CHECK(of::Global<OneFlowEnv>::Get() != nullptr);
graph_ = std::make_shared<of::NNGraph>(job_.job_conf().job_name(),
of::Global<OneFlowEnv>::Get()->GetSessionCtx());
}

InputOutputInfos Graph::GraphImpl::GetInputInfos() { return input_infos_; }
Expand Down Expand Up @@ -403,4 +406,6 @@ of::Maybe<void> Graph::GraphImpl::RegisterTensors(const std::vector<Tensor>& inp
return of::Maybe<void>::Ok();
}

Graph::GraphImpl::~GraphImpl() { of::vm::ClusterSync().GetOrThrow(); }

} // namespace oneflow_api
8 changes: 4 additions & 4 deletions oneflow/api/python/env/env.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ limitations under the License.
#include <pybind11/pybind11.h>
#include "oneflow/api/python/env/env.h"
#include "oneflow/api/python/of_api_registry.h"
#include "oneflow/core/job/env_global_objects_scope.h"
#include "oneflow/core/common/global.h"
#include "oneflow/core/vm/vm_util.h"
#include "oneflow/core/vm/virtual_machine.h"
Expand All @@ -42,10 +43,9 @@ ONEFLOW_API_PYBIND11_MODULE("", m) {
m.def("EnvResource", &EnvResource);
m.def("EnableEagerEnvironment", &EnableEagerEnvironment);

py::class_<EnvGlobalObjectsScope, std::shared_ptr<EnvGlobalObjectsScope>>(m, "Env")
.def(py::init([](const std::string& env_proto_str) {
return CreateEnv(env_proto_str).GetPtrOrThrow();
}))
py::class_<oneflow::EnvGlobalObjectsScope, std::shared_ptr<oneflow::EnvGlobalObjectsScope>>(
m, "EnvContext")
.def(py::init<const std::string&>())
.def("SwitchToShuttingDownPhase", &SwitchToShuttingDownPhase,
py::call_guard<py::gil_scoped_release>());

Expand Down
9 changes: 0 additions & 9 deletions oneflow/api/python/env/env.h
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,6 @@ inline Maybe<void> EnableEagerEnvironment(bool enable_eager_execution) {
return Maybe<void>::Ok();
}

inline Maybe<EnvGlobalObjectsScope> CreateEnv(const std::string& env_proto_str) {
EnvProto env_proto;
CHECK_OR_RETURN(TxtString2PbMessage(env_proto_str, &env_proto))
<< "failed to parse env_proto" << env_proto_str;
auto env = std::make_shared<EnvGlobalObjectsScope>();
JUST(env->Init(env_proto));
return env;
}

inline Maybe<long long> CurrentMachineId() { return GlobalProcessCtx::Rank(); }

inline Maybe<int64_t> GetRank() { return GlobalProcessCtx::Rank(); }
Expand Down
Loading

0 comments on commit 9c7d1a9

Please sign in to comment.