Skip to content
The Chat Archive
o1-mini-2024-09-12· OpenAI WildChat-4.8M (AI2)

請幫我建立一個基於 OpenAI CLIP model 的 C++ Shared Library 另外我的模型是 ONNX 格式 使用的環境是 Ubuntu 22.04 我需要…

  1. User

    請幫我建立一個基於 OpenAI CLIP model 的 C++ Shared Library 另外我的模型是 ONNX 格式 使用的環境是 Ubuntu 22.04 我需要 C++ code 和 makefile

  2. Assistant

    要在 Ubuntu 22.04 上使用 C++ 建立基於 OpenAI CLIP 模型(ONNX 格式)的共享庫,您可以遵循以下步驟。這包括安裝必要的依賴項、撰寫 C++ 代碼以及建立 Makefile 來編譯共享庫。

    步驟概覽

    1. 安裝 ONNX Runtime
    2. 撰寫 C++ 代碼
    3. 撰寫 Makefile
    4. 編譯共享庫
    5. 使用共享庫

    1. 安裝 ONNX Runtime

    ONNX Runtime 是一個高性能的推理引擎,支持多種平台和語言。本指南將使用預先編譯的 ONNX Runtime 庫。

    下載並安裝 ONNX Runtime 庫

    1. 下載 ONNX Runtime C++ 預編譯庫

      前往 ONNX Runtime Release Page 並下載適用於 Linux 的最新版本。例如,下載 onnxruntime-linux-x64-*.tgz 文件。

      wget https://github.com/microsoft/onnxruntime/releases/download/vX.Y.Z/onnxruntime-linux-x64-*.tgz
      

      替換 vX.Y.Z 為實際版本號,例如 v1.15.0。

    2. 解壓縮並安裝

      tar -xzf onnxruntime-linux-x64-*.tgz
      sudo cp -r onnxruntime-linux-x64-*/ /opt/onnxruntime
      
    3. 設置環境變量

      為了在編譯和運行時找到 ONNX Runtime 庫,設置相關的環境變量。

      export LD_LIBRARY_PATH=/opt/onnxruntime/lib:$LD_LIBRARY_PATH
      export CPLUS_INCLUDE_PATH=/opt/onnxruntime/include:$CPLUS_INCLUDE_PATH
      

      您可以將上述命令添加到 ~/.bashrc 或 ~/.profile 以便持久化。

    2. 撰寫 C++ 代碼

    以下是一個簡單的 C++ 共享庫範例,該庫使用 ONNX Runtime 加載和執行 CLIP 模型。

    假設您的 CLIP ONNX 模型文件名為 clip.onnx,並放置在模型目錄中(例如 models/clip.onnx)。

    文件結構

    clip_shared_lib/
    ├── include/
    │   └── clip_wrapper.h
    ├── src/
    │   └── clip_wrapper.cpp
    ├── models/
    │   └── clip.onnx
    └── Makefile
    

    include/clip_wrapper.h

    #ifndef CLIP_WRAPPER_H
    #define CLIP_WRAPPER_H
    
    #include <string>
    #include <vector>
    
    // 定義數據類型,根據您的模型需求調整
    typedef std::vector<float> Tensor;
    
    // 封裝 CLIP 模型的類
    class CLIPWrapper {
    public:
        // 構造函數,接受模型路徑
        CLIPWrapper(const std::string& model_path);
    
        // 解構函數
        ~CLIPWrapper();
    
        // 初始化模型
        bool Initialize();
    
        // 執行推理,根據模型需求調整輸入和輸出
        // 這裡假設輸入為單個 tensor,輸出為單個 tensor
        bool RunInference(const std::vector<Tensor>& input_tensors, std::vector<Tensor>& output_tensors);
    
    private:
        // 內部狀態,例如 ONNX Runtime 相關對象
        // 實際實現時需要添加相應的成員
        std::string model_path_;
        // 添加 ONNX Runtime 相關成員,如 Ort::Env, Ort::Session 等
    };
    
    extern "C" {
        // C 接口,用於共享庫
        CLIPWrapper* CLIP_Create(const char* model_path);
        bool CLIP_Initialize(CLIPWrapper* clip);
        bool CLIP_RunInference(CLIPWrapper* clip, const float* input_data, size_t input_size, float* output_data, size_t output_size);
        void CLIP_Destroy(CLIPWrapper* clip);
    }
    
    #endif // CLIP_WRAPPER_H
    

    src/clip_wrapper.cpp

    #include "clip_wrapper.h"
    #include <onnxruntime_cxx_api.h>
    #include <iostream>
    
    // 使用 ONNX Runtime 命名空間
    using namespace Ort;
    
    // 實現 CLIPWrapper 類
    CLIPWrapper::CLIPWrapper(const std::string& model_path) : model_path_(model_path) {}
    
    CLIPWrapper::~CLIPWrapper() {
        // 釋放 ONNX Runtime 相關資源
    }
    
    bool CLIPWrapper::Initialize() {
        // 初始化 ONNX Runtime 環境和會話
        try {
            // 創建環境
            Env env(ORT_LOGGING_LEVEL_WARNING, "clip");
    
            // 會話選項
            SessionOptions session_options;
            session_options.SetIntraOpNumThreads(1);
            session_options.SetGraphOptimizationLevel(GraphOptimizationLevel::ORT_ENABLE_EXTENDED);
    
            // 創建會話
            // 需要持久化 Env 和 Session 作為類成員以避免被釋放
            // 以下僅為示例,實際需要將 Env 和 Session 作為 CLIPWrapper 成員
            Session session(env, model_path_.c_str(), session_options);
        }
        catch (const Ort::Exception& e) {
            std::cerr << "ONNX Runtime 初始化失敗: " << e.what() << std::endl;
            return false;
        }
        return true;
    }
    
    bool CLIPWrapper::RunInference(const std::vector<Tensor>& input_tensors, std::vector<Tensor>& output_tensors) {
        // 實現模型推理
        // 這需要根據 CLIP 模型的具體輸入輸出進行調整
        // 此處僅為示例
        return true;
    }
    
    // C 接口實現
    extern "C" {
    
    CLIPWrapper* CLIP_Create(const char* model_path) {
        return new CLIPWrapper(std::string(model_path));
    }
    
    bool CLIP_Initialize(CLIPWrapper* clip) {
        if (!clip) return false;
        return clip->Initialize();
    }
    
    bool CLIP_RunInference(CLIPWrapper* clip, const float* input_data, size_t input_size, float* output_data, size_t output_size) {
        if (!clip) return false;
    
        // 將 input_data 轉換為 Tensor
        Tensor input_tensor(input_data, input_data + input_size);
        std::vector<Tensor> inputs = { input_tensor };
    
        // 執行推理
        std::vector<Tensor> outputs;
        if (!clip->RunInference(inputs, outputs)) {
            return false;
        }
    
        // 將輸出數據複製到 output_data
        if (outputs.empty() || outputs[0].size() < output_size) {
            return false;
        }
        std::copy(outputs[0].begin(), outputs[0] + output_size, output_data);
        return true;
    }
    
    void CLIP_Destroy(CLIPWrapper* clip) {
        delete clip;
    }
    
    } // extern "C"
    

    注意: 上述代碼是簡化範例,實際應用中需要在 CLIPWrapper 類中添加 ONNX Runtime 的 Env 和 Session 成員,並在構造函數和解構函數中正確管理它們。此外,RunInference 方法需要根據 CLIP 模型的具體輸入和輸出進行實現。

    3. 撰寫 Makefile

    在 clip_shared_lib 目錄下創建 Makefile 文件。

    Makefile

    # 編譯器和鏈接器
    CXX := g++
    CXXFLAGS := -O2 -fPIC -I./include -I/opt/onnxruntime/include
    LDFLAGS := -shared -L/opt/onnxruntime/lib -lonnxruntime
    
    # 目標共享庫
    TARGET := libclip.so
    
    # 源碼和對象文件
    SRCS := src/clip_wrapper.cpp
    OBJS := $(SRCS:.cpp=.o)
    
    # 預設目標
    all: $(TARGET)
    
    # 編譯共享庫
    $(TARGET): $(OBJS)
    	$(CXX) $(CXXFLAGS) $(LDFLAGS) -o $@ $^
    
    # 編譯對象文件
    %.o: %.cpp
    	$(CXX) $(CXXFLAGS) -c $< -o $@
    
    # 清理
    clean:
    	rm -f $(OBJS) $(TARGET)
    
    .PHONY: all clean
    

    4. 編譯共享庫

    在 clip_shared_lib 目錄下運行以下命令來編譯共享庫:

    make
    

    如果一切順利,將生成 libclip.so 共享庫。

    5. 使用共享庫

    以下是一個簡單的 C++ 示例,展示如何使用剛才創建的共享庫。

    example.cpp

    #include <iostream>
    #include "clip_wrapper.h"
    
    int main() {
        // 創建 CLIPWrapper 實例
        CLIPWrapper* clip = CLIP_Create("models/clip.onnx");
        if (!clip) {
            std::cerr << "無法創建 CLIPWrapper 實例" << std::endl;
            return -1;
        }
    
        // 初始化模型
        if (!CLIP_Initialize(clip)) {
            std::cerr << "模型初始化失敗" << std::endl;
            CLIP_Destroy(clip);
            return -1;
        }
    
        // 準備輸入數據
        // 根據模型需求準備實際的輸入
        float input_data[/* size */] = { /* ... */ };
        size_t input_size = sizeof(input_data) / sizeof(float);
    
        // 準備輸出數據
        float output_data[/* size */];
        size_t output_size = sizeof(output_data) / sizeof(float);
    
        // 執行推理
        if (!CLIP_RunInference(clip, input_data, input_size, output_data, output_size)) {
            std::cerr << "推理失敗" << std::endl;
            CLIP_Destroy(clip);
            return -1;
        }
    
        // 使用輸出數據
        // 根據模型輸出進行處理
        std::cout << "推理成功" << std::endl;
    
        // 釋放資源
        CLIP_Destroy(clip);
        return 0;
    }
    

    編譯示例

    假設 example.cpp 位於 clip_shared_lib 目錄下,並且 libclip.so 放在相同目錄,可以使用以下命令編譯:

    g++ -o example example.cpp -L. -lclip -I./include -I/opt/onnxruntime/include -L/opt/onnxruntime/lib -lonnxruntime -Wl,-rpath,/opt/onnxruntime/lib
    

    說明:

    • -L. 和 -lclip 用於鏈接剛才創建的 libclip.so。
    • -I./include 和 -I/opt/onnxruntime/include 用於設置頭文件搜索路徑。
    • -L/opt/onnxruntime/lib 和 -lonnxruntime 用於鏈接 ONNX Runtime 庫。
    • -Wl,-rpath,/opt/onnxruntime/lib 用於在運行時設置庫的搜索路徑,確保系統能找到 libonnxruntime.so。

    運行示例

    ./example
    

    確保在運行前設置好 LD_LIBRARY_PATH,例如:

    export LD_LIBRARY_PATH=/opt/onnxruntime/lib:$LD_LIBRARY_PATH
    

    完整代碼示例

    include/clip_wrapper.h

    #ifndef CLIP_WRAPPER_H
    #define CLIP_WRAPPER_H
    
    #include <string>
    #include <vector>
    
    // 定義數據類型,根據您的模型需求調整
    typedef std::vector<float> Tensor;
    
    // 封裝 CLIP 模型的類
    class CLIPWrapper {
    public:
        // 構造函數,接受模型路徑
        CLIPWrapper(const std::string& model_path);
    
        // 解構函數
        ~CLIPWrapper();
    
        // 初始化模型
        bool Initialize();
    
        // 執行推理,根據模型需求調整輸入和輸出
        bool RunInference(const std::vector<Tensor>& input_tensors, std::vector<Tensor>& output_tensors);
    
    private:
        // 內部狀態
        std::string model_path_;
        // 使用 unique_ptr 管理 ONNX Runtime 對象
        class Impl;
        Impl* pImpl;
    };
    
    extern "C" {
        // C 接口,用於共享庫
        CLIPWrapper* CLIP_Create(const char* model_path);
        bool CLIP_Initialize(CLIPWrapper* clip);
        bool CLIP_RunInference(CLIPWrapper* clip, const float* input_data, size_t input_size, float* output_data, size_t output_size);
        void CLIP_Destroy(CLIPWrapper* clip);
    }
    
    #endif // CLIP_WRAPPER_H
    

    src/clip_wrapper.cpp

    #include "clip_wrapper.h"
    #include <onnxruntime_cxx_api.h>
    #include <iostream>
    
    // 使用 ONNX Runtime 命名空間
    using namespace Ort;
    
    // 定義 Impl 類以隱藏實現細節
    class CLIPWrapper::Impl {
    public:
        Impl(const std::string& model_path) : model_path_(model_path), env(ORT_LOGGING_LEVEL_WARNING, "clip"), session(nullptr) {}
    
        bool Initialize() {
            SessionOptions session_options;
            session_options.SetIntraOpNumThreads(1);
            session_options.SetGraphOptimizationLevel(GraphOptimizationLevel::ORT_ENABLE_EXTENDED);
    
            try {
                session = std::make_unique<Session>(env, model_path_.c_str(), session_options);
            }
            catch (const Ort::Exception& e) {
                std::cerr << "ONNX Runtime 初始化失敗: " << e.what() << std::endl;
                return false;
            }
            return true;
        }
    
        bool RunInference(const std::vector<Tensor>& input_tensors, std::vector<Tensor>& output_tensors) {
            if (!session) return false;
    
            // 獲取輸入和輸出名稱
            size_t num_input_nodes = session->GetInputCount();
            size_t num_output_nodes = session->GetOutputCount();
    
            std::vector<const char*> input_names(num_input_nodes);
            std::vector<const char*> output_names(num_output_nodes);
    
            for (size_t i = 0; i < num_input_nodes; ++i) {
                char* input_name = session->GetInputName(i, AllocatorWithDefaultOptions());
                input_names[i] = input_name;
            }
    
            for (size_t i = 0; i < num_output_nodes; ++i) {
                char* output_name = session->GetOutputName(i, AllocatorWithDefaultOptions());
                output_names[i] = output_name;
            }
    
            // 構建輸入張量
            std::vector<Value> ort_inputs;
            std::vector<int64_t> input_shape = { static_cast<int64_t>(input_tensors[0].size()) };
            Ort::MemoryInfo memory_info = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU);
            for (const auto& tensor : input_tensors) {
                ort_inputs.emplace_back(Value::CreateTensor<float>(memory_info, const_cast<float*>(tensor.data()), tensor.size(), input_shape.data(), input_shape.size()));
            }
    
            // 執行推理
            std::vector<Value> ort_outputs;
            try {
                ort_outputs = session->Run(RunOptions{ nullptr }, input_names.data(), ort_inputs.data(), num_input_nodes, output_names.data(), num_output_nodes);
            }
            catch (const Ort::Exception& e) {
                std::cerr << "ONNX Runtime 推理失敗: " << e.what() << std::endl;
                return false;
            }
    
            // 處理輸出
            for (auto& output : ort_outputs) {
                float* float_array = output.GetTensorMutableData<float>();
                size_t tensor_size = output.GetTensorTypeAndShapeInfo().GetElementCount();
                output_tensors.emplace_back(Tensor(float_array, float_array + tensor_size));
            }
    
            // 釋放輸入和輸出名稱
            for (size_t i = 0; i < num_input_nodes; ++i) {
                Ort::AllocatorWithDefaultOptions().Free(const_cast<char*>(input_names[i]));
            }
    
            for (size_t i = 0; i < num_output_nodes; ++i) {
                Ort::AllocatorWithDefaultOptions().Free(const_cast<char*>(output_names[i]));
            }
    
            return true;
        }
    
    private:
        std::string model_path_;
        Env env;
        std::unique_ptr<Session> session;
    };
    
    CLIPWrapper::CLIPWrapper(const std::string& model_path) : pImpl(new Impl(model_path)) {}
    
    CLIPWrapper::~CLIPWrapper() {
        delete pImpl;
    }
    
    bool CLIPWrapper::Initialize() {
        return pImpl->Initialize();
    }
    
    bool CLIPWrapper::RunInference(const std::vector<Tensor>& input_tensors, std::vector<Tensor>& output_tensors) {
        return pImpl->RunInference(input_tensors, output_tensors);
    }
    
    // C 接口實現
    extern "C" {
    
    CLIPWrapper* CLIP_Create(const char* model_path) {
        return new CLIPWrapper(std::string(model_path));
    }
    
    bool CLIP_Initialize(CLIPWrapper* clip) {
        if (!clip) return false;
        return clip->Initialize();
    }
    
    bool CLIP_RunInference(CLIPWrapper* clip, const float* input_data, size_t input_size, float* output_data, size_t output_size) {
        if (!clip) return false;
    
        // 將 input_data 轉換為 Tensor
        Tensor input_tensor(input_data, input_data + input_size);
        std::vector<Tensor> inputs = { input_tensor };
    
        // 執行推理
        std::vector<Tensor> outputs;
        if (!clip->RunInference(inputs, outputs)) {
            return false;
        }
    
        // 將輸出數據複製到 output_data
        if (outputs.empty() || outputs[0].size() < output_size) {
            return false;
        }
        std::copy(outputs[0].begin(), outputs[0] + output_size, output_data);
        return true;
    }
    
    void CLIP_Destroy(CLIPWrapper* clip) {
        delete clip;
    }
    
    } // extern "C"
    

    Makefile

    如上所述,這裡再次貼出 Makefile 以便參考。

    # 編譯器和鏈接器
    CXX := g++
    CXXFLAGS := -O2 -fPIC -I./include -I/opt/onnxruntime/include
    LDFLAGS := -shared -L/opt/onnxruntime/lib -lonnxruntime
    
    # 目標共享庫
    TARGET := libclip.so
    
    # 源碼和對象文件
    SRCS := src/clip_wrapper.cpp
    OBJS := $(SRCS:.cpp=.o)
    
    # 預設目標
    all: $(TARGET)
    
    # 編譯共享庫
    $(TARGET): $(OBJS)
    	$(CXX) $(CXXFLAGS) $(LDFLAGS) -o $@ $^
    
    # 編譯對象文件
    %.o: %.cpp
    	$(CXX) $(CXXFLAGS) -c $< -o $@
    
    # 清理
    clean:
    	rm -f $(OBJS) $(TARGET)
    
    .PHONY: all clean
    

    結論

    通過上述步驟,您可以在 Ubuntu 22.04 上使用 C++ 建立一個基於 OpenAI CLIP 模型(ONNX 格式)的共享庫。這個共享庫可以被其他應用程序調用,以進行文本和圖像的編碼和相似度計算。根據具體需求,您可能需要擴展 CLIPWrapper 類以支持更多功能,如處理不同類型的輸入、優化性能等。

    進一步的建議

    • 模型優化:考慮使用 ONNX Runtime 的各種優化選項 來提升推理效率。
    • 多線程支持:如果需要高併發,可以考慮多線程推理,注意線程安全性。
    • 異常處理:增強錯誤檢測和處理,以提高穩定性。
    • 擴展接口:根據 CLIP 模型的具體輸入輸出,擴展 C 接口以支持更複雜的數據結構。

    如果在實現過程中遇到問題,建議參考 ONNX Runtime 的官方文檔 以及相關的 C++ 範例代碼。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.