// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include "core/common/flatbuffers.h" #include "core/framework/allocator.h" #include "core/platform/env.h" #include #include #include "adapter_format/adapter_schema.fbs.h" #include #include #include #include struct OrtValue; namespace onnxruntime { namespace adapters { namespace utils { /// /// Helper class to serialize Lora adapter /// class AdapterFormatBuilder { public: AdapterFormatBuilder() = default; /// /// Appends parameter tensor to the adapter builder /// /// parameter name /// /// /// void AddParameter(const std::string& name, adapters::TensorDataType data_type, gsl::span shape, gsl::span data); /// /// Finishes serialization and returns a serialized byte vector /// /// /// /// std::vector Finish(int adapter_version, int model_version); /// /// Finishes serialization and returns a span to internal buffer. /// /// /// /// gsl::span FinishWithSpan(int adapter_version, int model_version); private: void FinishImpl(int adapter_version, int model_version); flatbuffers::FlatBufferBuilder builder_; std::vector> params_; }; /// /// /// /// /// /// bool IsAdapterFormatModelBytes(const void* bytes, size_t num_bytes); void LoadStringFromLoraFormat(std::string& dst, const flatbuffers::String* fbs_string); /// /// The function loads the lora adapter bytes from the file system /// /// file path /// bytes in a vector /// If the path can not be found std::vector LoadLoraAdapterBytes(const std::filesystem::path& file_path); /// /// This function memory maps the adapter file in memory /// /// /// memory handle and file size in a tuple std::pair MemoryMapAdapterFile(const std::filesystem::path& file_path); /// /// Validates underlying format and the format version /// /// /// Adapter ptr const Adapter* ValidateAndGetAdapterFromBytes(gsl::span bytes); /// /// Serializes tensor data into flatbuffer /// /// /// parameter name /// doc, optional /// /// /// /// output offset void SaveLoraParameter(flatbuffers::FlatBufferBuilder& flat_builder, std::string_view name, TensorDataType data_type, gsl::span shape, gsl::span data, flatbuffers::Offset& fbs_tensor); /// /// Create an OrtValue on top of the flatbuffer tensor /// No copying of data is done here. The caller is responsible for managing the lifetime of flatbuffer /// structures. /// /// In this scenario, one can memory map the entire flatbuffer tensor data into OrtValue without copying. /// /// /// std::pair CreateOrtValueOverLoraParameter(const Parameter& param); } // namespace utils } // namespace adapters } // namespace onnxruntime