From ffc81d61e7a2c28bf7982b4ee3fd00f56d426f73 Mon Sep 17 00:00:00 2001 From: chuntl-qti Date: Thu, 29 Oct 2026 14:10:09 +0800 Subject: [PATCH] Qualcomm AI Engine Direct - Refactor QNN context config construction. Summary: - Add context config builder. - Refactor qnn_manager to use context config. - Refactor how we enable context config via compiler plugin. --- litert/vendors/qualcomm/BUILD | 1 + litert/vendors/qualcomm/CMakeLists.txt | 1 + .../qualcomm/compiler/qnn_compiler_plugin.cc | 36 +-- litert/vendors/qualcomm/core/BUILD | 37 ++++ litert/vendors/qualcomm/core/CMakeLists.txt | 11 + .../qualcomm/core/context_config_builder.cc | 29 +++ .../qualcomm/core/context_config_builder.h | 209 ++++++++++++++++++ .../core/context_config_builder_test.cc | 185 ++++++++++++++++ .../litert_dispatch_device_context.cc | 56 +++-- .../qualcomm/qnn_backend_test/test_utils.cc | 12 +- litert/vendors/qualcomm/qnn_manager.cc | 143 ++---------- litert/vendors/qualcomm/qnn_manager.h | 26 +-- litert/vendors/qualcomm/qnn_manager_test.cc | 35 --- 13 files changed, 564 insertions(+), 217 deletions(-) create mode 100644 litert/vendors/qualcomm/core/context_config_builder.cc create mode 100644 litert/vendors/qualcomm/core/context_config_builder.h create mode 100644 litert/vendors/qualcomm/core/context_config_builder_test.cc diff --git a/litert/vendors/qualcomm/BUILD b/litert/vendors/qualcomm/BUILD index bdfa539044..374acf2e75 100644 --- a/litert/vendors/qualcomm/BUILD +++ b/litert/vendors/qualcomm/BUILD @@ -84,6 +84,7 @@ litert_cc_lib_with_qnn( "//litert/core:dynamic_loading", "//litert/core:filesystem", "//litert/vendors/qualcomm/core:common", + "//litert/vendors/qualcomm/core:context_config_builder", "//litert/vendors/qualcomm/core:op_code", "//litert/vendors/qualcomm/core/backends:backend_utils", "//litert/vendors/qualcomm/core/backends:dsp_backend", diff --git a/litert/vendors/qualcomm/CMakeLists.txt b/litert/vendors/qualcomm/CMakeLists.txt index 2c6aaff25b..d358b6cace 100644 --- a/litert/vendors/qualcomm/CMakeLists.txt +++ b/litert/vendors/qualcomm/CMakeLists.txt @@ -65,6 +65,7 @@ target_link_libraries(qnn_manager absl::strings absl::str_format qnn_backends + qnn_context_config_builder qnn_wrappers PRIVATE qnn_saver_utils diff --git a/litert/vendors/qualcomm/compiler/qnn_compiler_plugin.cc b/litert/vendors/qualcomm/compiler/qnn_compiler_plugin.cc index 330359cbe2..482a1cb019 100644 --- a/litert/vendors/qualcomm/compiler/qnn_compiler_plugin.cc +++ b/litert/vendors/qualcomm/compiler/qnn_compiler_plugin.cc @@ -37,6 +37,7 @@ #include "absl/strings/str_format.h" // from @com_google_absl #include "absl/strings/str_split.h" // from @com_google_absl #include "absl/strings/string_view.h" // from @com_google_absl +#include "absl/types/span.h" // from @com_google_absl #include "litert/c/internal/litert_logging.h" #include "litert/c/internal/litert_logging_helper_with_compiler_context.h" #include "litert/c/litert_any.h" @@ -65,6 +66,7 @@ #include "litert/vendors/qualcomm/core/backends/backend_factory.h" #include "litert/vendors/qualcomm/core/backends/qnn_backend.h" #include "litert/vendors/qualcomm/core/common.h" +#include "litert/vendors/qualcomm/core/context_config_builder.h" #include "litert/vendors/qualcomm/core/schema/soc_table.h" #include "litert/vendors/qualcomm/core/tensor_pool.h" #include "litert/vendors/qualcomm/core/wrappers/op_wrapper.h" @@ -181,6 +183,20 @@ LiteRtStatus MoveSchematic(absl::string_view graph_name, return kLiteRtStatusOk; } +::qnn::ContextConfigs BuildCompileContextConfigs( + const ::qnn::Options& options, bool enable_effective_weight_sharing) { + ::qnn::ContextConfigsBuilder builder; + if (enable_effective_weight_sharing) { + builder.Emplace<::qnn::HtpWeightSharingConfig>(true); + LITERT_LOG(LITERT_INFO, "Enable weight sharing feature"); + } else if (const auto performance_mode = options.GetGpuPerformanceMode(); + options.GetBackendType() == ::qnn::BackendType::kGpuBackend && + performance_mode != ::qnn::GpuPerformanceMode::kDefault) { + builder.Emplace<::qnn::GpuPerformanceConfig>(performance_mode); + } + return std::move(builder).Build(); +} + } // namespace LiteRtStatus LiteRtGetCompilerPluginVersion(LiteRtApiVersion* api_version) { @@ -671,7 +687,7 @@ LiteRtStatus LiteRtCompilerPluginCompile( if (context_handle_idx == next_context_handle_idx) { // Initialize context. LITERT_LOG(LITERT_INFO, "%s", "Creating context handle"); - auto context_configs = QnnManager::DefaultContextConfigs(); + bool enable_effective_weight_sharing = false; if (backend_options.GetEnableWeightSharing()) { if (backend_options.GetBackendType() != ::qnn::BackendType::kHtpBackend) { @@ -681,25 +697,19 @@ LiteRtStatus LiteRtCompilerPluginCompile( } if (num_partitions != kDefaultPartitionNum && IsWeightSharingSupported()) { - context_configs = QnnManager::WeightSharingContextConfigs(); - LITERT_LOG(LITERT_INFO, "Enable weight sharing feature"); + enable_effective_weight_sharing = true; } else { LITERT_LOG(LITERT_WARNING, "Disable weight sharing feature. Only support with " "multiple partitions and on x86-64 host"); } - } else if (backend_options.GetBackendType() == - ::qnn::BackendType::kGpuBackend) { - if (backend_options.GetGpuPerformanceMode() != - ::qnn::GpuPerformanceMode::kDefault) { - context_configs = QnnManager::GpuPerformanceContextConfigs( - backend_options.GetGpuPerformanceMode()); - LITERT_LOG(LITERT_INFO, "Enable GPU performance mode: %d", - static_cast(backend_options.GetGpuPerformanceMode())); - } } + const auto context_configs = BuildCompileContextConfigs( + backend_options, enable_effective_weight_sharing); auto context_handle = qnn_manager->CreateContextHandle( - *qnn_backend, context_configs, backend_options.GetProfiling()); + *qnn_backend, + context_configs.NullTerminatedConfigs(), + backend_options.GetProfiling()); if (!context_handle) { LITERT_LOG(LITERT_ERROR, "%s", context_handle.Error().Message().data()); return context_handle.Error().Status(); diff --git a/litert/vendors/qualcomm/core/BUILD b/litert/vendors/qualcomm/core/BUILD index 7f4386bebe..a8b5296126 100644 --- a/litert/vendors/qualcomm/core/BUILD +++ b/litert/vendors/qualcomm/core/BUILD @@ -88,6 +88,43 @@ cc_library( ], ) +cc_library( + name = "context_config_builder", + srcs = ["context_config_builder.cc"], + hdrs = ["context_config_builder.h"], + deps = [ + ":common", + "@com_google_absl//absl/types:span", + "@qairt//:qnn_lib_headers", + ], +) + +litert_test( + name = "context_config_builder_test", + srcs = [ + "context_config_builder_test.cc", + ], + no_main = True, + tags = [ + "noasan", + "nomsan", + "nosan", + "notsan", + ], + # This test can be run only on Android and Linux. + target_compatible_with = select({ + "@platforms//os:android": [], + "@platforms//os:linux": [], + "//conditions:default": ["@platforms//:incompatible"], + }), + ungrte = True, + use_sys_malloc = True, + deps = [ + ":context_config_builder", + "@qairt//:qnn_lib_headers", + ] + gtest_main_no_heapcheck_deps(), +) + litert_test( name = "common_test", srcs = [ diff --git a/litert/vendors/qualcomm/core/CMakeLists.txt b/litert/vendors/qualcomm/core/CMakeLists.txt index 7f4b854f6a..d93f072120 100644 --- a/litert/vendors/qualcomm/core/CMakeLists.txt +++ b/litert/vendors/qualcomm/core/CMakeLists.txt @@ -23,6 +23,17 @@ target_link_libraries(qnn_common absl::str_format ) +# context config builder +add_library(qnn_context_config_builder STATIC) + +target_sources(qnn_context_config_builder PRIVATE context_config_builder.cc) + +target_link_libraries(qnn_context_config_builder + PUBLIC + qnn_common + absl::span +) + # tensor pool add_library(qnn_tensor_pool STATIC) diff --git a/litert/vendors/qualcomm/core/context_config_builder.cc b/litert/vendors/qualcomm/core/context_config_builder.cc new file mode 100644 index 0000000000..48995a97a7 --- /dev/null +++ b/litert/vendors/qualcomm/core/context_config_builder.cc @@ -0,0 +1,29 @@ +// Copyright (c) Qualcomm Innovation Center, Inc. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +#include "litert/vendors/qualcomm/core/context_config_builder.h" + +#include +#include +#include + +namespace qnn { + +ContextConfigs::ContextConfigs(std::vector entries) + : entries_(std::move(entries)) { + // `entries_` is final from here on, so the pointers that BuildQnnConfig() + // hands out into the wrappers stay valid for the lifetime of this object. + configs_.reserve(entries_.size()); + for (auto& entry : entries_) { + configs_.push_back( + std::visit([](auto& config) { return config.BuildQnnConfig(); }, entry)); + } + + config_ptrs_.reserve(configs_.size() + 1); + for (const auto& config : configs_) { + config_ptrs_.push_back(&config); + } + config_ptrs_.push_back(nullptr); +} + +} // namespace qnn diff --git a/litert/vendors/qualcomm/core/context_config_builder.h b/litert/vendors/qualcomm/core/context_config_builder.h new file mode 100644 index 0000000000..d5b7061dc4 --- /dev/null +++ b/litert/vendors/qualcomm/core/context_config_builder.h @@ -0,0 +1,209 @@ +// Copyright (c) Qualcomm Innovation Center, Inc. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +#ifndef ODML_LITERT_LITERT_VENDORS_QUALCOMM_CORE_CONTEXT_CONFIG_BUILDER_H_ +#define ODML_LITERT_LITERT_VENDORS_QUALCOMM_CORE_CONTEXT_CONFIG_BUILDER_H_ + +#include +#include +#include +#include +#include + +#include "QnnCommon.h" // from @qairt +#include "QnnContext.h" // from @qairt +#include "GPU/QnnGpuContext.h" // from @qairt +#include "HTP/QnnHtpContext.h" // from @qairt +#include "absl/types/span.h" // from @com_google_absl +#include "litert/vendors/qualcomm/core/common.h" + +namespace qnn { + +// Every wrapper below owns the payload that its QnnContext_Config_t points to +// and exposes `QnnContext_Config_t BuildQnnConfig()`. BuildQnnConfig() may +// return pointers into the wrapper itself, so it must only be called once the +// wrapper has reached its final address (see ContextConfigs). + +class PriorityConfig { + public: + explicit PriorityConfig(Qnn_Priority_t priority) : priority_(priority) {} + + QnnContext_Config_t BuildQnnConfig() { + QnnContext_Config_t config = QNN_CONTEXT_CONFIG_INIT; + config.option = QNN_CONTEXT_CONFIG_OPTION_PRIORITY; + config.priority = priority_; + return config; + } + + private: + Qnn_Priority_t priority_; +}; + +// Loads only the named graphs of a context binary. +class EnableGraphsConfig { + public: + explicit EnableGraphsConfig(std::vector names) + : names_(std::move(names)) {} + + QnnContext_Config_t BuildQnnConfig() { + name_ptrs_.clear(); + name_ptrs_.reserve(names_.size() + 1); + for (const std::string& name : names_) { + name_ptrs_.push_back(name.c_str()); + } + name_ptrs_.push_back(nullptr); + + QnnContext_Config_t config = QNN_CONTEXT_CONFIG_INIT; + config.option = QNN_CONTEXT_CONFIG_ENABLE_GRAPHS; + config.enableGraphs = name_ptrs_.data(); + return config; + } + + private: + std::vector names_; + std::vector name_ptrs_; +}; + +class GpuPerformanceConfig { + public: + explicit GpuPerformanceConfig(GpuPerformanceMode performance_mode) + : config_(QNN_GPU_CONTEXT_CUSTOM_CONFIG_INIT) { + config_.option = QNN_GPU_CONTEXT_CONFIG_OPTION_PERF_HINT; + config_.perfHint = ToQnnPerfHint(performance_mode); + } + + QnnContext_Config_t BuildQnnConfig() { + QnnContext_Config_t config = QNN_CONTEXT_CONFIG_INIT; + config.option = QNN_CONTEXT_CONFIG_OPTION_CUSTOM; + config.customConfig = &config_; + return config; + } + + private: + static QnnGpuContext_PerfHint_t ToQnnPerfHint(GpuPerformanceMode mode) { + switch (mode) { + case GpuPerformanceMode::kHigh: + return QNN_GPU_CONTEXT_PERF_HINT_HIGH; + case GpuPerformanceMode::kNormal: + return QNN_GPU_CONTEXT_PERF_HINT_NORMAL; + case GpuPerformanceMode::kLow: + return QNN_GPU_CONTEXT_PERF_HINT_LOW; + case GpuPerformanceMode::kDefault: + return QNN_GPU_CONTEXT_PERF_HINT_HIGH; + } + return QNN_GPU_CONTEXT_PERF_HINT_HIGH; + } + + QnnGpuContext_CustomConfig_t config_; +}; + +class HtpWeightSharingConfig { + public: + explicit HtpWeightSharingConfig(bool enabled) + : config_(QNN_HTP_CONTEXT_CUSTOM_CONFIG_INIT) { + config_.option = QNN_HTP_CONTEXT_CONFIG_OPTION_WEIGHT_SHARING_ENABLED; + config_.weightSharingEnabled = enabled; + } + + QnnContext_Config_t BuildQnnConfig() { + QnnContext_Config_t config = QNN_CONTEXT_CONFIG_INIT; + config.option = QNN_CONTEXT_CONFIG_OPTION_CUSTOM; + config.customConfig = &config_; + return config; + } + + private: + QnnHtpContext_CustomConfig_t config_; +}; + +class HtpFileReadMemoryBudgetConfig { + public: + explicit HtpFileReadMemoryBudgetConfig(uint32_t budget_mb) + : config_(QNN_HTP_CONTEXT_CUSTOM_CONFIG_INIT) { + config_.option = QNN_HTP_CONTEXT_CONFIG_OPTION_FILE_READ_MEMORY_BUDGET; + config_.fileReadMemoryBudgetInMb = budget_mb; + } + + QnnContext_Config_t BuildQnnConfig() { + QnnContext_Config_t config = QNN_CONTEXT_CONFIG_INIT; + config.option = QNN_CONTEXT_CONFIG_OPTION_CUSTOM; + config.customConfig = &config_; + return config; + } + + private: + QnnHtpContext_CustomConfig_t config_; +}; + +class HtpInitAccelerationConfig { + public: + explicit HtpInitAccelerationConfig(bool enabled) + : config_(QNN_HTP_CONTEXT_CUSTOM_CONFIG_INIT) { + config_.option = QNN_HTP_CONTEXT_CONFIG_OPTION_INIT_ACCELERATION; + config_.initAcceleration = enabled; + } + + QnnContext_Config_t BuildQnnConfig() { + QnnContext_Config_t config = QNN_CONTEXT_CONFIG_INIT; + config.option = QNN_CONTEXT_CONFIG_OPTION_CUSTOM; + config.customConfig = &config_; + return config; + } + + private: + QnnHtpContext_CustomConfig_t config_; +}; + +using ContextConfigVariant = + std::variant; + +class ContextConfigsBuilder; + +// Immutable, null-terminated QNN context config list. The container owns all +// config payloads referenced by Data(). +class ContextConfigs { + public: + ContextConfigs(const ContextConfigs&) = delete; + ContextConfigs& operator=(const ContextConfigs&) = delete; + ContextConfigs(ContextConfigs&&) = delete; + ContextConfigs& operator=(ContextConfigs&&) = delete; + + absl::Span NullTerminatedConfigs() const { + return absl::MakeConstSpan(config_ptrs_); + } + + private: + friend class ContextConfigsBuilder; + + explicit ContextConfigs(std::vector entries); + + std::vector entries_; + std::vector configs_; + std::vector config_ptrs_; +}; + +class ContextConfigsBuilder { + public: + ContextConfigsBuilder() = default; + ContextConfigsBuilder(ContextConfigsBuilder&&) = default; + ContextConfigsBuilder& operator=(ContextConfigsBuilder&&) = default; + ContextConfigsBuilder(const ContextConfigsBuilder&) = delete; + ContextConfigsBuilder& operator=(const ContextConfigsBuilder&) = delete; + + template + ContextConfigsBuilder& Emplace(Args&&... args) { + entries_.emplace_back(std::in_place_type, std::forward(args)...); + return *this; + } + + ContextConfigs Build() && { return ContextConfigs(std::move(entries_)); } + + private: + std::vector entries_; +}; + +} // namespace qnn + +#endif // ODML_LITERT_LITERT_VENDORS_QUALCOMM_CORE_CONTEXT_CONFIG_BUILDER_H_ diff --git a/litert/vendors/qualcomm/core/context_config_builder_test.cc b/litert/vendors/qualcomm/core/context_config_builder_test.cc new file mode 100644 index 0000000000..6392e15e9e --- /dev/null +++ b/litert/vendors/qualcomm/core/context_config_builder_test.cc @@ -0,0 +1,185 @@ +// Copyright (c) Qualcomm Innovation Center, Inc. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +#include "litert/vendors/qualcomm/core/context_config_builder.h" + +#include +#include +#include + +#include +#include "litert/vendors/qualcomm/core/common.h" + +namespace qnn { +namespace { + +const QnnGpuContext_CustomConfig_t* AsGpuConfig(const QnnContext_Config_t* c) { + return static_cast(c->customConfig); +} + +const QnnHtpContext_CustomConfig_t* AsHtpConfig(const QnnContext_Config_t* c) { + return static_cast(c->customConfig); +} + +TEST(ContextConfigBuilderTest, EmptyBuilderHasOnlyTerminator) { + const auto configs = ContextConfigsBuilder().Build(); + const auto span = configs.NullTerminatedConfigs(); + ASSERT_EQ(span.size(), 1); + EXPECT_EQ(span[0], nullptr); +} + +TEST(ContextConfigBuilderTest, PriorityConfig) { + ContextConfigsBuilder builder; + builder.Emplace(QNN_PRIORITY_HIGH); + const auto configs = std::move(builder).Build(); + + const auto span = configs.NullTerminatedConfigs(); + ASSERT_EQ(span.size(), 2); + EXPECT_EQ(span[1], nullptr); + EXPECT_EQ(span[0]->option, QNN_CONTEXT_CONFIG_OPTION_PRIORITY); + EXPECT_EQ(span[0]->priority, QNN_PRIORITY_HIGH); +} + +TEST(ContextConfigBuilderTest, EnableGraphsConfig) { + ContextConfigsBuilder builder; + builder.Emplace( + std::vector{"prefill", "decode"}); + const auto configs = std::move(builder).Build(); + + const auto span = configs.NullTerminatedConfigs(); + ASSERT_EQ(span.size(), 2); + EXPECT_EQ(span[1], nullptr); + EXPECT_EQ(span[0]->option, QNN_CONTEXT_CONFIG_ENABLE_GRAPHS); + const char* const* graphs = span[0]->enableGraphs; + ASSERT_NE(graphs, nullptr); + EXPECT_STREQ(graphs[0], "prefill"); + EXPECT_STREQ(graphs[1], "decode"); + EXPECT_EQ(graphs[2], nullptr); +} + +TEST(ContextConfigBuilderTest, EnableGraphsConfigSingleGraph) { + ContextConfigsBuilder builder; + builder.Emplace(std::vector{"only"}); + const auto configs = std::move(builder).Build(); + + const char* const* graphs = configs.NullTerminatedConfigs()[0]->enableGraphs; + ASSERT_NE(graphs, nullptr); + EXPECT_STREQ(graphs[0], "only"); + EXPECT_EQ(graphs[1], nullptr); +} + +struct GpuModeCase { + GpuPerformanceMode mode; + QnnGpuContext_PerfHint_t expected; +}; + +class GpuPerformanceConfigTest : public ::testing::TestWithParam { +}; + +TEST_P(GpuPerformanceConfigTest, MapsModeToPerfHint) { + ContextConfigsBuilder builder; + builder.Emplace(GetParam().mode); + const auto configs = std::move(builder).Build(); + + const auto span = configs.NullTerminatedConfigs(); + ASSERT_EQ(span.size(), 2); + EXPECT_EQ(span[1], nullptr); + EXPECT_EQ(span[0]->option, QNN_CONTEXT_CONFIG_OPTION_CUSTOM); + const auto* gpu = AsGpuConfig(span[0]); + ASSERT_NE(gpu, nullptr); + EXPECT_EQ(gpu->option, QNN_GPU_CONTEXT_CONFIG_OPTION_PERF_HINT); + EXPECT_EQ(gpu->perfHint, GetParam().expected); +} + +INSTANTIATE_TEST_SUITE_P( + AllModes, GpuPerformanceConfigTest, + ::testing::Values( + GpuModeCase{GpuPerformanceMode::kHigh, QNN_GPU_CONTEXT_PERF_HINT_HIGH}, + GpuModeCase{GpuPerformanceMode::kNormal, + QNN_GPU_CONTEXT_PERF_HINT_NORMAL}, + GpuModeCase{GpuPerformanceMode::kLow, QNN_GPU_CONTEXT_PERF_HINT_LOW}, + // kDefault follows the QNN default, which is HIGH. + GpuModeCase{GpuPerformanceMode::kDefault, + QNN_GPU_CONTEXT_PERF_HINT_HIGH})); + +class HtpWeightSharingConfigTest : public ::testing::TestWithParam {}; + +TEST_P(HtpWeightSharingConfigTest, SetsEnabledFlag) { + ContextConfigsBuilder builder; + builder.Emplace(GetParam()); + const auto configs = std::move(builder).Build(); + + const auto span = configs.NullTerminatedConfigs(); + ASSERT_EQ(span.size(), 2); + EXPECT_EQ(span[1], nullptr); + EXPECT_EQ(span[0]->option, QNN_CONTEXT_CONFIG_OPTION_CUSTOM); + const auto* htp = AsHtpConfig(span[0]); + ASSERT_NE(htp, nullptr); + EXPECT_EQ(htp->option, QNN_HTP_CONTEXT_CONFIG_OPTION_WEIGHT_SHARING_ENABLED); + EXPECT_EQ(htp->weightSharingEnabled, GetParam()); +} + +INSTANTIATE_TEST_SUITE_P(EnabledAndDisabled, HtpWeightSharingConfigTest, + ::testing::Bool()); + +TEST(ContextConfigBuilderTest, HtpFileReadMemoryBudgetConfig) { + ContextConfigsBuilder builder; + builder.Emplace(16); + const auto configs = std::move(builder).Build(); + + const auto span = configs.NullTerminatedConfigs(); + ASSERT_EQ(span.size(), 2); + EXPECT_EQ(span[1], nullptr); + EXPECT_EQ(span[0]->option, QNN_CONTEXT_CONFIG_OPTION_CUSTOM); + const auto* htp = AsHtpConfig(span[0]); + ASSERT_NE(htp, nullptr); + EXPECT_EQ(htp->option, QNN_HTP_CONTEXT_CONFIG_OPTION_FILE_READ_MEMORY_BUDGET); + EXPECT_EQ(htp->fileReadMemoryBudgetInMb, 16); +} + +class HtpInitAccelerationConfigTest : public ::testing::TestWithParam {}; + +TEST_P(HtpInitAccelerationConfigTest, SetsEnabledFlag) { + ContextConfigsBuilder builder; + builder.Emplace(GetParam()); + const auto configs = std::move(builder).Build(); + + const auto span = configs.NullTerminatedConfigs(); + ASSERT_EQ(span.size(), 2); + EXPECT_EQ(span[1], nullptr); + EXPECT_EQ(span[0]->option, QNN_CONTEXT_CONFIG_OPTION_CUSTOM); + const auto* htp = AsHtpConfig(span[0]); + ASSERT_NE(htp, nullptr); + EXPECT_EQ(htp->option, QNN_HTP_CONTEXT_CONFIG_OPTION_INIT_ACCELERATION); + EXPECT_EQ(htp->initAcceleration, GetParam()); +} + +INSTANTIATE_TEST_SUITE_P(EnabledAndDisabled, HtpInitAccelerationConfigTest, + ::testing::Bool()); + +// Many entries make the builder's vector grow and the entries move. The +// pointers handed to QNN must still reference the final storage. +TEST(ContextConfigBuilderTest, PointersStayValidAfterBuilderGrows) { + ContextConfigsBuilder builder; + for (int i = 0; i < 32; ++i) { + builder.Emplace(i); + } + builder.Emplace(std::vector{"a", "b"}); + const auto configs = std::move(builder).Build(); + + const auto span = configs.NullTerminatedConfigs(); + ASSERT_EQ(span.size(), 34); + EXPECT_EQ(span[33], nullptr); + for (int i = 0; i < 32; ++i) { + EXPECT_EQ(AsHtpConfig(span[i])->fileReadMemoryBudgetInMb, + static_cast(i)); + } + const char* const* graphs = span[32]->enableGraphs; + ASSERT_NE(graphs, nullptr); + EXPECT_STREQ(graphs[0], "a"); + EXPECT_STREQ(graphs[1], "b"); + EXPECT_EQ(graphs[2], nullptr); +} + +} // namespace +} // namespace qnn diff --git a/litert/vendors/qualcomm/dispatch/litert_dispatch_device_context.cc b/litert/vendors/qualcomm/dispatch/litert_dispatch_device_context.cc index 45a8df5712..32b0a418af 100644 --- a/litert/vendors/qualcomm/dispatch/litert_dispatch_device_context.cc +++ b/litert/vendors/qualcomm/dispatch/litert_dispatch_device_context.cc @@ -42,14 +42,43 @@ #include "litert/cc/litert_macros.h" #include "litert/vendors/c/litert_dispatch.h" #include "litert/vendors/qualcomm/common.h" +#include "litert/vendors/qualcomm/core/backends/backend_utils.h" #include "litert/vendors/qualcomm/core/backends/qnn_backend.h" #include "litert/vendors/qualcomm/core/common.h" +#include "litert/vendors/qualcomm/core/context_config_builder.h" #include "litert/vendors/qualcomm/qnn_manager.h" using litert::Expected; using litert::Unexpected; using litert::qnn::QnnManager; +namespace { + +::qnn::ContextConfigs BuildDispatchContextConfigs( + const ::qnn::Options& options, std::vector enable_graphs) { + ::qnn::ContextConfigsBuilder builder; + if (!enable_graphs.empty()) { + builder.Emplace<::qnn::EnableGraphsConfig>(std::move(enable_graphs)); + } + if (options.GetBackendType() != ::qnn::BackendType::kHtpBackend) { + return std::move(builder).Build(); + } + if (options.GetGraphPriority() != ::qnn::GraphPriority::kDefault) { + builder.Emplace<::qnn::PriorityConfig>( + ::qnn::GetGraphPriorityValue(options.GetGraphPriority())); + } + if (const uint32_t budget_mb = options.GetHtpFileReadMemoryBudgetMB(); + budget_mb > 0) { + builder.Emplace<::qnn::HtpFileReadMemoryBudgetConfig>(budget_mb); + } + if (options.GetHtpContextInitAcceleration()) { + builder.Emplace<::qnn::HtpInitAccelerationConfig>(true); + } + return std::move(builder).Build(); +} + +} // namespace + Expected LiteRtDispatchDeviceContextT::Create( const LiteRtRuntimeContext* runtime_context, QnnManager& qnn, @@ -294,19 +323,11 @@ LiteRtDispatchDeviceContextT::GetOrCreateContext( bytecode_ptr, bytecode_size, graphs_to_enable.size(), available_graph_count, absl::StrJoin(graphs_to_enable, ", ").c_str()); - std::vector graph_names; - graph_names.reserve(graphs_to_enable.size() + 1); - for (const std::string& name : graphs_to_enable) { - graph_names.emplace_back(name.c_str()); - } - graph_names.emplace_back(nullptr); - QnnContext_Config_t enable_graphs_config = QNN_CONTEXT_CONFIG_INIT; - enable_graphs_config.option = QNN_CONTEXT_CONFIG_ENABLE_GRAPHS; - enable_graphs_config.enableGraphs = graph_names.data(); - std::array configs = {&enable_graphs_config, - nullptr}; + const auto context_configs = BuildDispatchContextConfigs( + qnn_manager_.GetOptions(), graphs_to_enable); if (auto handle = qnn_manager_.CreateContextHandle( - qnn_backend_, absl::MakeSpan(configs), bytecode, profile_handle); + qnn_backend_, + context_configs.NullTerminatedConfigs(), bytecode, profile_handle); handle) { return registry.RegisterContext( std::make_unique(std::move(*handle)), @@ -321,10 +342,13 @@ LiteRtDispatchDeviceContextT::GetOrCreateContext( LITERT_LOG(LITERT_INFO, "Creating new QNN context for bytecode %p (size %zu)", bytecode_ptr, bytecode_size); - LITERT_ASSIGN_OR_RETURN(auto handle, - qnn_manager_.CreateContextHandle( - qnn_backend_, QnnManager::DefaultContextConfigs(), - bytecode, profile_handle)); + const auto context_configs = BuildDispatchContextConfigs( + qnn_manager_.GetOptions(), /*enable_graphs=*/{}); + LITERT_ASSIGN_OR_RETURN( + auto handle, + qnn_manager_.CreateContextHandle( + qnn_backend_, + context_configs.NullTerminatedConfigs(), bytecode, profile_handle)); return registry.RegisterContextWithAllAvailableGraphs( std::make_unique(std::move(handle))); } diff --git a/litert/vendors/qualcomm/qnn_backend_test/test_utils.cc b/litert/vendors/qualcomm/qnn_backend_test/test_utils.cc index eed32da4de..ed64b639d4 100644 --- a/litert/vendors/qualcomm/qnn_backend_test/test_utils.cc +++ b/litert/vendors/qualcomm/qnn_backend_test/test_utils.cc @@ -13,6 +13,7 @@ #include "litert/vendors/qualcomm/core/backends/backend_factory.h" #include "litert/vendors/qualcomm/core/backends/qnn_backend.h" #include "litert/vendors/qualcomm/core/common.h" +#include "litert/vendors/qualcomm/core/context_config_builder.h" #include "litert/vendors/qualcomm/core/schema/soc_table.h" #include "litert/vendors/qualcomm/core/utils/qnn_model.h" #include "litert/vendors/qualcomm/qnn_manager.h" @@ -67,10 +68,13 @@ void QnnModelTest::SetUpQnnModel(const ::qnn::Options& options, ::qnn::CreateBackend((**qnn_manager).Api(), options, soc_info, true); ASSERT_TRUE(qnn_backend); - auto context_configs = QnnManager::DefaultContextConfigs(); - auto context_handle = (**qnn_manager) - .CreateContextHandle(*qnn_backend, context_configs, - options.GetProfiling()); + // Default (empty) context configs, independent of `options`. + const auto context_configs = ::qnn::ContextConfigsBuilder().Build(); + auto context_handle = + (**qnn_manager) + .CreateContextHandle(*qnn_backend, + context_configs.NullTerminatedConfigs(), + options.GetProfiling()); ASSERT_TRUE(context_handle) << context_handle.Error(); std::swap(qnn_manager_ptr_, *qnn_manager); diff --git a/litert/vendors/qualcomm/qnn_manager.cc b/litert/vendors/qualcomm/qnn_manager.cc index 060b0a0d64..3240b10a91 100644 --- a/litert/vendors/qualcomm/qnn_manager.cc +++ b/litert/vendors/qualcomm/qnn_manager.cc @@ -31,8 +31,6 @@ #include #include -#include "GPU/QnnGpuContext.h" // from @qairt -#include "HTP/QnnHtpContext.h" // from @qairt #include "HTP/QnnHtpProfile.h" // from @qairt #include "QnnCommon.h" // from @qairt #include "QnnContext.h" // from @qairt @@ -53,7 +51,6 @@ #include "litert/cc/litert_macros.h" #include "litert/core/filesystem.h" #include "litert/vendors/qualcomm/common.h" -#include "litert/vendors/qualcomm/core/backends/backend_utils.h" #include "litert/vendors/qualcomm/core/backends/dsp_backend.h" #include "litert/vendors/qualcomm/core/backends/gpu_backend.h" #include "litert/vendors/qualcomm/core/backends/htp_backend.h" @@ -137,52 +134,6 @@ Expected> LoadSystemProvidersFromLib( } // namespace -absl::Span QnnManager::BuildHtpContextConfigs( - const ::qnn::Options& options, - absl::Span configs, - HtpContextConfigs& storage) { - std::vector htp_context_configs_to_add; - if (options.GetGraphPriority() != ::qnn::GraphPriority::kDefault) { - storage.priority.option = QNN_CONTEXT_CONFIG_OPTION_PRIORITY; - storage.priority.priority = - GetGraphPriorityValue(options.GetGraphPriority()); - htp_context_configs_to_add.push_back(&storage.priority); - } - if (const uint32_t budget_mb = options.GetHtpFileReadMemoryBudgetMB(); - budget_mb > 0) { - storage.budget_custom.option = - QNN_HTP_CONTEXT_CONFIG_OPTION_FILE_READ_MEMORY_BUDGET; - storage.budget_custom.fileReadMemoryBudgetInMb = budget_mb; - storage.budget.option = QNN_CONTEXT_CONFIG_OPTION_CUSTOM; - storage.budget.customConfig = &storage.budget_custom; - htp_context_configs_to_add.push_back(&storage.budget); - } - if (options.GetHtpContextInitAcceleration()) { - storage.init_acceleration_custom.option = - QNN_HTP_CONTEXT_CONFIG_OPTION_INIT_ACCELERATION; - storage.init_acceleration_custom.initAcceleration = true; - storage.init_acceleration.option = QNN_CONTEXT_CONFIG_OPTION_CUSTOM; - storage.init_acceleration.customConfig = - &storage.init_acceleration_custom; - htp_context_configs_to_add.push_back(&storage.init_acceleration); - } - - if (htp_context_configs_to_add.empty()) { - return {}; - } - storage.ptrs.reserve(configs.size() + htp_context_configs_to_add.size() + - 1); - for (const auto* cfg : configs) { - if (cfg != nullptr) { - storage.ptrs.push_back(cfg); - } - } - storage.ptrs.insert(storage.ptrs.end(), htp_context_configs_to_add.begin(), - htp_context_configs_to_add.end()); - storage.ptrs.push_back(nullptr); - return absl::MakeSpan(storage.ptrs); -} - LiteRtStatus QnnManager::LoadSharedLibHelper(absl::string_view path, bool needs_global_symbols, SharedLibrary& out_lib) { @@ -655,15 +606,16 @@ QnnManager::CreateSystemContextHandle() { Expected QnnManager::CreateContextHandle( ::qnn::QnnBackend& qnn_backend, - absl::Span configs, + absl::Span configs, ::qnn::Profiling profiling_level) { + auto* qnn_configs = const_cast(configs.data()); Qnn_ContextHandle_t context_handle; if (auto status = Api()->contextCreate( qnn_backend.GetBackendHandle(), qnn_backend.GetDeviceHandle(), // `configs` should be null-terminated. For empty `configs`, most // backend libraries accept nullptr so we use nullptr directly instead // of a array which contains only one nullptr. - configs.size() <= 1 ? nullptr : configs.data(), &context_handle); + configs.size() <= 1 ? nullptr : qnn_configs, &context_handle); status != QNN_SUCCESS) { LITERT_LOG(LITERT_ERROR, "Failed to create QNN context: %d", status); return Unexpected(kLiteRtStatusErrorRuntimeFailure, @@ -710,7 +662,7 @@ Expected QnnManager::CreateContextHandle( Expected QnnManager::CreateContextHandle( ::qnn::QnnBackend& qnn_backend, - absl::Span configs, + absl::Span configs, absl::Span bytecode, Qnn_ProfileHandle_t profile_handle) { #if !defined(_WIN32) const int64_t page_size = sysconf(_SC_PAGESIZE); @@ -733,35 +685,21 @@ Expected QnnManager::CreateContextHandle( } #endif + auto* qnn_configs = const_cast(configs.data()); Qnn_ContextHandle_t context_handle; - Qnn_ErrorHandle_t status; - if (options_.GetBackendType() == ::qnn::BackendType::kHtpBackend) { - HtpContextConfigs htp_configs; - const auto htp_span = - BuildHtpContextConfigs(options_, configs, htp_configs); - const auto context_configs = - htp_span.empty() ? configs.data() : htp_span.data(); - const bool vote_during_load = - options_.GetHtpPerfCtrlMode() == ::qnn::HtpPerfCtrlMode::kAuto && - options_.GetHtpPerformanceMode() != - ::qnn::HtpPerformanceMode::kDefault; - - if (vote_during_load) { - qnn_backend.UpVote(); - } - status = Api()->contextCreateFromBinary( - qnn_backend.GetBackendHandle(), qnn_backend.GetDeviceHandle(), - context_configs, bytecode.data(), bytecode.size(), &context_handle, - profile_handle); - - if (vote_during_load) { - qnn_backend.ScheduleDownVote(); - } - } else { - status = Api()->contextCreateFromBinary( - qnn_backend.GetBackendHandle(), qnn_backend.GetDeviceHandle(), - configs.data(), bytecode.data(), bytecode.size(), &context_handle, - profile_handle); + const bool vote_during_load = + options_.GetBackendType() == ::qnn::BackendType::kHtpBackend && + options_.GetHtpPerfCtrlMode() == ::qnn::HtpPerfCtrlMode::kAuto && + options_.GetHtpPerformanceMode() != ::qnn::HtpPerformanceMode::kDefault; + if (vote_during_load) { + qnn_backend.UpVote(); + } + const Qnn_ErrorHandle_t status = Api()->contextCreateFromBinary( + qnn_backend.GetBackendHandle(), qnn_backend.GetDeviceHandle(), + qnn_configs, bytecode.data(), bytecode.size(), &context_handle, + profile_handle); + if (vote_during_load) { + qnn_backend.ScheduleDownVote(); } if (status != QNN_SUCCESS) { LITERT_LOG(LITERT_ERROR, "Failed to create QNN context: %d", status); @@ -793,49 +731,4 @@ Expected QnnManager::Create( return qnn_manager; } -absl::Span QnnManager::DefaultContextConfigs() { - static const QnnContext_Config_t* configs[] = {nullptr}; - return absl::MakeSpan(configs); -} - -absl::Span -QnnManager::WeightSharingContextConfigs() { - static QnnHtpContext_CustomConfig_t customConfig = - QNN_HTP_CONTEXT_CUSTOM_CONFIG_INIT; - customConfig.option = QNN_HTP_CONTEXT_CONFIG_OPTION_WEIGHT_SHARING_ENABLED; - customConfig.weightSharingEnabled = true; - static QnnContext_Config_t contextConfig = QNN_CONTEXT_CONFIG_INIT; - contextConfig.option = QNN_CONTEXT_CONFIG_OPTION_CUSTOM; - contextConfig.customConfig = &customConfig; - static const QnnContext_Config_t* configs[2] = {&contextConfig, nullptr}; - return absl::MakeSpan(configs); -} - -absl::Span QnnManager::GpuPerformanceContextConfigs( - ::qnn::GpuPerformanceMode performance_mode) { - static QnnGpuContext_CustomConfig_t customConfig = - QNN_GPU_CONTEXT_CUSTOM_CONFIG_INIT; - customConfig.option = QNN_GPU_CONTEXT_CONFIG_OPTION_PERF_HINT; - switch (performance_mode) { - case ::qnn::GpuPerformanceMode::kHigh: - customConfig.perfHint = QNN_GPU_CONTEXT_PERF_HINT_HIGH; - break; - case ::qnn::GpuPerformanceMode::kNormal: - customConfig.perfHint = QNN_GPU_CONTEXT_PERF_HINT_NORMAL; - break; - case ::qnn::GpuPerformanceMode::kLow: - customConfig.perfHint = QNN_GPU_CONTEXT_PERF_HINT_LOW; - break; - case ::qnn::GpuPerformanceMode::kDefault: - default: - return DefaultContextConfigs(); - } - - static QnnContext_Config_t contextConfig = QNN_CONTEXT_CONFIG_INIT; - contextConfig.option = QNN_CONTEXT_CONFIG_OPTION_CUSTOM; - contextConfig.customConfig = &customConfig; - static const QnnContext_Config_t* configs[2] = {&contextConfig, nullptr}; - return absl::MakeSpan(configs); -} - }; // namespace litert::qnn diff --git a/litert/vendors/qualcomm/qnn_manager.h b/litert/vendors/qualcomm/qnn_manager.h index 0ad6b4de68..71643bb6df 100644 --- a/litert/vendors/qualcomm/qnn_manager.h +++ b/litert/vendors/qualcomm/qnn_manager.h @@ -26,7 +26,6 @@ #include #include -#include "HTP/QnnHtpContext.h" // from @qairt #include "QnnCommon.h" // from @qairt #include "QnnContext.h" // from @qairt #include "QnnInterface.h" // from @qairt @@ -74,17 +73,6 @@ std::string Dump(const QnnManager& qnn); } // namespace internal -struct HtpContextConfigs { - QnnContext_Config_t priority = QNN_CONTEXT_CONFIG_INIT; - QnnHtpContext_CustomConfig_t budget_custom = - QNN_HTP_CONTEXT_CUSTOM_CONFIG_INIT; - QnnContext_Config_t budget = QNN_CONTEXT_CONFIG_INIT; - QnnHtpContext_CustomConfig_t init_acceleration_custom = - QNN_HTP_CONTEXT_CUSTOM_CONFIG_INIT; - QnnContext_Config_t init_acceleration = QNN_CONTEXT_CONFIG_INIT; - std::vector ptrs; -}; - class QnnManager { friend std::string internal::Dump(const QnnManager& qnn); @@ -99,16 +87,6 @@ class QnnManager { const ::qnn::Options& options, std::optional shared_library_dir = std::nullopt); - static absl::Span DefaultContextConfigs(); - static absl::Span WeightSharingContextConfigs(); - static absl::Span GpuPerformanceContextConfigs( - ::qnn::GpuPerformanceMode performance_mode); - - static absl::Span BuildHtpContextConfigs( - const ::qnn::Options& options, - absl::Span configs, - HtpContextConfigs& storage); - // Get resolved function pointers for qnn sdk calls. Nullptr if functions // have not been resolved yet. const QnnApi* Api() const; @@ -127,13 +105,13 @@ class QnnManager { // Create a context handle for compilation. Expected CreateContextHandle( ::qnn::QnnBackend& qnn_backend, - absl::Span configs, + absl::Span configs, ::qnn::Profiling profiling_level); // Create a context handle for inference, from a given bytecode. Expected CreateContextHandle( ::qnn::QnnBackend& qnn_backend, - absl::Span configs, + absl::Span configs, absl::Span bytecode, Qnn_ProfileHandle_t profile_handle); // diff --git a/litert/vendors/qualcomm/qnn_manager_test.cc b/litert/vendors/qualcomm/qnn_manager_test.cc index d43e59b782..d5613fcfee 100644 --- a/litert/vendors/qualcomm/qnn_manager_test.cc +++ b/litert/vendors/qualcomm/qnn_manager_test.cc @@ -17,8 +17,6 @@ #include #include -#include "HTP/QnnHtpContext.h" // from @qairt -#include "QnnContext.h" // from @qairt #include "QnnTypes.h" // from @qairt #include #include @@ -278,39 +276,6 @@ TEST(InitQnnOptionsTest, PropagatesHtpContextInitAcceleration) { EXPECT_TRUE(qnn_options.GetHtpContextInitAcceleration()); } -TEST(QnnManagerTest, BuildHtpContextConfigs) { - ::qnn::Options options; - options.SetGraphPriority(::qnn::GraphPriority::kHigh); - options.SetHtpFileReadMemoryBudgetMB(16); - options.SetHtpContextInitAcceleration(true); - - litert::qnn::HtpContextConfigs storage; - const auto configs = QnnManager::BuildHtpContextConfigs( - options, QnnManager::DefaultContextConfigs(), storage); - - ASSERT_EQ(configs.size(), 4); - EXPECT_EQ(configs[0]->option, QNN_CONTEXT_CONFIG_OPTION_PRIORITY); - EXPECT_EQ(configs[0]->priority, QNN_PRIORITY_HIGH); - EXPECT_EQ(configs[1]->option, QNN_CONTEXT_CONFIG_OPTION_CUSTOM); - EXPECT_EQ(configs[2]->option, QNN_CONTEXT_CONFIG_OPTION_CUSTOM); - EXPECT_EQ(configs[3], nullptr); - - const auto* budget = static_cast( - configs[1]->customConfig); - ASSERT_NE(budget, nullptr); - EXPECT_EQ(budget->option, - QNN_HTP_CONTEXT_CONFIG_OPTION_FILE_READ_MEMORY_BUDGET); - EXPECT_EQ(budget->fileReadMemoryBudgetInMb, 16); - - const auto* init_acceleration = - static_cast( - configs[2]->customConfig); - ASSERT_NE(init_acceleration, nullptr); - EXPECT_EQ(init_acceleration->option, - QNN_HTP_CONTEXT_CONFIG_OPTION_INIT_ACCELERATION); - EXPECT_TRUE(init_acceleration->initAcceleration); -} - TEST(QnnManagerTest, AdspLibraryPathPrecedence) { static constexpr char kAdsp[] = "ADSP_LIBRARY_PATH"; const char* original_adsp_ptr = getenv(kAdsp);