// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "core/session/lora_adapters.h" #include "lora/adapter_format_utils.h" #include #include "core/framework/data_transfer.h" #include "core/framework/error_code_helper.h" #include "core/session/onnxruntime_c_api.h" #include "core/session/allocator_adapters.h" #include "core/session/ort_apis.h" #if defined(USE_CUDA) || defined(USE_CUDA_PROVIDER_INTERFACE) #include "core/providers/cuda/cuda_provider_factory.h" #endif namespace onnxruntime { #if defined(USE_CUDA) || defined(USE_CUDA_PROVIDER_INTERFACE) ProviderInfo_CUDA* TryGetProviderInfo_CUDA(); #endif namespace lora { LoraAdapter::Param::Param(OrtValue ort_value_mapped) noexcept : ort_value_mapped_(std::move(ort_value_mapped)) {} LoraAdapter::Param::Param(OrtValue ort_value_mapped, OrtValue ort_value_device) noexcept : ort_value_mapped_(std::move(ort_value_mapped)), ort_value_device_(std::move(ort_value_device)) { } void LoraAdapter::Load(const std::filesystem::path& file_path) { auto buffer = adapters::utils::LoadLoraAdapterBytes(file_path); Load(std::move(buffer)); } void LoraAdapter::Load(std::vector buffer) { // Build everything that can throw against locals first, so a malformed adapter // leaves *this unchanged (strong exception guarantee). Only after the new // parameter map has been fully constructed do we release the previous backing // storage and swap in the new state. ValidateAndGetAdapterFromBytes returns a // pointer that aliases `buffer`'s data; std::vector's move preserves the data // pointer, so the alias remains valid after we move `buffer` into buffer_. const auto* new_adapter = adapters::utils::ValidateAndGetAdapterFromBytes(buffer); auto new_params_values = BuildParamsValues(new_adapter); // Commit. None of the operations below can throw. buffer_.emplace(std::move(buffer)); adapter_ = new_adapter; params_values_ = std::move(new_params_values); } void LoraAdapter::MemoryMap(const std::filesystem::path& file_path) { auto [mapped_memory, file_size] = adapters::utils::MemoryMapAdapterFile(file_path); auto u8_span = ReinterpretAsSpan(gsl::make_span(mapped_memory.get(), file_size)); // Build everything that can throw against locals first; see Load() above. // Moving Env::MappedMemoryPtr preserves the underlying pointer, so OrtValues // built against `mapped_memory.get()` remain valid after the move into buffer_. const auto* new_adapter = adapters::utils::ValidateAndGetAdapterFromBytes(u8_span); auto new_params_values = BuildParamsValues(new_adapter); // Commit. None of the operations below can throw. buffer_.emplace(std::move(mapped_memory), file_size); adapter_ = new_adapter; params_values_ = std::move(new_params_values); } static std::unique_ptr GetDataTransfer(const OrtMemoryInfo& mem_info) { std::unique_ptr data_transfer; if (mem_info.device.Type() == OrtDevice::CPU) { return data_transfer; } if (mem_info.device.Type() == OrtDevice::GPU && mem_info.device.Vendor() == OrtDevice::VendorIds::NVIDIA) { #if defined(USE_CUDA) || defined(USE_CUDA_PROVIDER_INTERFACE) auto* cuda_provider_info = TryGetProviderInfo_CUDA(); if (cuda_provider_info != nullptr) { data_transfer = cuda_provider_info->CreateGPUDataTransfer(); } #endif } return data_transfer; } static Status CreateOrtValueOnDevice(const OrtValue& ort_value_mapped, const AllocatorPtr& device_allocator, const IDataTransfer& data_transfer, OrtValue& out) { OrtValue result; const auto& src = ort_value_mapped.Get(); Tensor on_device(src.DataType(), src.Shape(), device_allocator); ORT_RETURN_IF_ERROR(data_transfer.CopyTensor(src, on_device)); Tensor::InitOrtValue(std::move(on_device), result); out = std::move(result); return Status::OK(); } std::unordered_map LoraAdapter::BuildParamsValues(const adapters::Adapter* adapter) const { ORT_ENFORCE(adapter != nullptr, "Adapter is not loaded yet."); std::unique_ptr data_transfer; if (device_allocator_) { const auto& allocator_info = device_allocator_->Info(); if (allocator_info.device.Type() == OrtDevice::CPU) { ORT_THROW("The specified allocator must be a device allocator"); } data_transfer = GetDataTransfer(allocator_info); // Plugin EP data transfers are registered with the environment/session and are not // available during adapter creation. Keep the mapped CPU values in that case so Run() // can copy them through the session's data transfer manager. } const auto* params = adapter->parameters(); ORT_ENFORCE(params != nullptr, "Params absent"); std::unordered_map params_values; params_values.reserve(params->size()); // Re-work in two separate loops due to compiler issues if (data_transfer) { for (const auto* param : *params) { auto [name, ort_value] = adapters::utils::CreateOrtValueOverLoraParameter(*param); OrtValue ort_value_ondevice; ORT_THROW_IF_ERROR(CreateOrtValueOnDevice(ort_value, device_allocator_, *data_transfer, ort_value_ondevice)); Param lora_param(std::move(ort_value), std::move(ort_value_ondevice)); params_values.emplace(std::move(name), std::move(lora_param)); } } else { for (const auto* param : *params) { auto [name, ort_value] = adapters::utils::CreateOrtValueOverLoraParameter(*param); Param lora_param(std::move(ort_value)); params_values.emplace(std::move(name), std::move(lora_param)); } } return params_values; } } // namespace lora } // namespace onnxruntime ORT_API_STATUS_IMPL(OrtApis::CreateLoraAdapter, _In_ const ORTCHAR_T* adapter_file_path, _In_ OrtAllocator* allocator, _Outptr_ OrtLoraAdapter** adapter) { API_IMPL_BEGIN std::unique_ptr lora_adapter; if (allocator != nullptr) { auto alloc_ptr = std::make_shared(allocator); lora_adapter = std::make_unique(std::move(alloc_ptr)); } else { lora_adapter = std::make_unique(); } // For platforms that do not support Memmap, we can #ifdef it to ->Load(adapter_file_path) lora_adapter->MemoryMap(adapter_file_path); *adapter = reinterpret_cast(lora_adapter.release()); return nullptr; API_IMPL_END } ORT_API_STATUS_IMPL(OrtApis::CreateLoraAdapterFromArray, _In_ const void* bytes, size_t num_bytes, _In_ OrtAllocator* allocator, _Outptr_ OrtLoraAdapter** adapter) { API_IMPL_BEGIN std::unique_ptr lora_adapter; if (allocator != nullptr) { auto alloc_ptr = std::make_shared(allocator); lora_adapter = std::make_unique(std::move(alloc_ptr)); } else { lora_adapter = std::make_unique(); } std::vector buffer(num_bytes); memcpy(buffer.data(), bytes, num_bytes); lora_adapter->Load(std::move(buffer)); *adapter = reinterpret_cast(lora_adapter.release()); return nullptr; API_IMPL_END } ORT_API(void, OrtApis::ReleaseLoraAdapter, _Frees_ptr_opt_ OrtLoraAdapter* adapter) { delete reinterpret_cast(adapter); }