#include <cstddef>
#include <cstdint>
#include <map>
#include <memory>
#include <string>
#include "ge/ge_ir_build.h"
#include "parser/onnx_parser.h"
using ge::graphStatus;
namespace {
thread_local std::map<void*, std::shared_ptr<ge::Graph>> g_graph_registry;
thread_local std::uintptr_t g_next_handle = 1;
void* register_graph(ge::Graph&& graph) {
void* handle = reinterpret_cast<void*>(g_next_handle++);
g_graph_registry.emplace(handle, std::make_shared<ge::Graph>(std::move(graph)));
return handle;
}
std::shared_ptr<ge::Graph>* lookup_graph(void* handle) {
auto it = g_graph_registry.find(handle);
return it == g_graph_registry.end() ? nullptr : &it->second;
}
}
extern "C" {
graphStatus cann_grph_parse_onnx_from_file(const char* path, void** handle_out) {
if (path == nullptr || handle_out == nullptr) {
return ge::GRAPH_PARAM_INVALID;
}
*handle_out = nullptr;
try {
ge::Graph graph;
std::map<ge::AscendString, ge::AscendString> parser_params;
graphStatus st = ge::aclgrphParseONNX(path, parser_params, graph);
if (st != ge::GRAPH_SUCCESS) {
return st;
}
*handle_out = register_graph(std::move(graph));
return ge::GRAPH_SUCCESS;
} catch (...) {
return ge::GRAPH_FAILED;
}
}
graphStatus cann_grph_parse_onnx_from_mem(const char* buffer, size_t size,
void** handle_out) {
if (buffer == nullptr || size == 0 || handle_out == nullptr) {
return ge::GRAPH_PARAM_INVALID;
}
*handle_out = nullptr;
try {
ge::Graph graph;
std::map<ge::AscendString, ge::AscendString> parser_params;
graphStatus st = ge::aclgrphParseONNXFromMem(buffer, size, parser_params, graph);
if (st != ge::GRAPH_SUCCESS) {
return st;
}
*handle_out = register_graph(std::move(graph));
return ge::GRAPH_SUCCESS;
} catch (...) {
return ge::GRAPH_FAILED;
}
}
graphStatus cann_grph_build_model(void* handle, const char* save_path) {
if (handle == nullptr || save_path == nullptr) {
return ge::GRAPH_PARAM_INVALID;
}
try {
std::shared_ptr<ge::Graph>* graph = lookup_graph(handle);
if (graph == nullptr) {
return ge::GRAPH_PARAM_INVALID;
}
std::map<ge::AscendString, ge::AscendString> build_options;
ge::ModelBufferData model;
graphStatus st = ge::aclgrphBuildModel(**graph, build_options, model);
if (st != ge::GRAPH_SUCCESS) {
return st;
}
if (model.data == nullptr || model.length == 0) {
return ge::GRAPH_FAILED;
}
return ge::aclgrphSaveModel(save_path, model);
} catch (...) {
return ge::GRAPH_FAILED;
}
}
graphStatus cann_grph_destroy(void* handle) {
if (handle == nullptr) {
return ge::GRAPH_PARAM_INVALID;
}
return g_graph_registry.erase(handle) == 1 ? ge::GRAPH_SUCCESS
: ge::GRAPH_PARAM_INVALID;
}
}