diff --git a/extension/llm/runner/llm_runner_helper.cpp b/extension/llm/runner/llm_runner_helper.cpp index 105b3f0c9f4..47e8b0f251a 100644 --- a/extension/llm/runner/llm_runner_helper.cpp +++ b/extension/llm/runner/llm_runner_helper.cpp @@ -1,6 +1,7 @@ /* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. + * Copyright 2026 Arm Limited and/or its affiliates. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. @@ -297,7 +298,8 @@ std::unique_ptr create_text_llm_runner( io_manager.get(), prefill_method_name, std::move(sampler), - stats.get()); + stats.get(), + metadata.at(kEnableDynamicShape)); // The decode stage gets its own decoder runner when the PTE exports a // separate decode method; otherwise both stages share text_decoder_runner. diff --git a/extension/llm/runner/test/BUCK b/extension/llm/runner/test/BUCK index 9ed85acadb7..f858e3db6c9 100644 --- a/extension/llm/runner/test/BUCK +++ b/extension/llm/runner/test/BUCK @@ -2,6 +2,7 @@ load("@fbcode_macros//build_defs:build_file_migration.bzl", "fbcode_target", "no oncall("executorch") # Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. +# Copyright 2026 Arm Limited and/or its affiliates. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. @@ -43,5 +44,6 @@ fbcode_target(_kind = runtime.cxx_test, "KVCACHE_CACHE_POS": "$(location fbcode//executorch/test/models:exported_programs[ModuleKVCacheCachePos.pte])", "KVCACHE_INPUT_POS": "$(location fbcode//executorch/test/models:exported_programs[ModuleKVCacheInputPos.pte])", "NO_KVCACHE": "$(location fbcode//executorch/test/models:exported_programs[ModuleNoKVCache.pte])", + "STATIC_NO_KVCACHE": "$(location fbcode//executorch/test/models:exported_programs[ModuleStaticNoKVCache.pte])", } ) diff --git a/extension/llm/runner/test/test_text_decoder_runner.cpp b/extension/llm/runner/test/test_text_decoder_runner.cpp index 1114fe1512f..283e92ae690 100644 --- a/extension/llm/runner/test/test_text_decoder_runner.cpp +++ b/extension/llm/runner/test/test_text_decoder_runner.cpp @@ -1,6 +1,7 @@ /* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. + * Copyright 2026 Arm Limited and/or its affiliates. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. @@ -315,4 +316,40 @@ TEST_F(TextDecoderRunnerTest, StepWithAllModels) { << "No models were tested despite environment variables being set"; } +TEST_F(TextDecoderRunnerTest, StaticNonKVShortPrompt) { + const char* model_path = std::getenv("STATIC_NO_KVCACHE"); + if (!model_path) { + GTEST_SKIP() << "No static non-KV PTE model environment variable set"; + } + + Module module(model_path); + IOManager io_manager(module); + TextDecoderRunner runner( + &module, &io_manager, "forward", nullptr, nullptr, false); + ASSERT_EQ(runner.load(), Error::Ok); + + auto tokens = executorch::extension::make_tensor_ptr( + {1, 2}, std::vector{7, 8}); + auto result = runner.step(tokens, 0); + ASSERT_TRUE(result.ok()) << static_cast(result.error()); + ASSERT_EQ(result->dim(), 2); + ASSERT_EQ(result->size(0), 1); + ASSERT_EQ(result->size(1), 2); + EXPECT_FLOAT_EQ(result->const_data_ptr()[0], 8.0f); + EXPECT_FLOAT_EQ(result->const_data_ptr()[1], 1.0f); +} + +TEST_F(TextDecoderRunnerTest, StaticNonKVRequiresFullLogits) { + const char* model_path = std::getenv("NO_KVCACHE"); + if (!model_path) { + GTEST_SKIP() << "No non-KV PTE model environment variable set"; + } + + Module module(model_path); + IOManager io_manager(module); + TextDecoderRunner runner( + &module, &io_manager, "forward", nullptr, nullptr, false); + EXPECT_EQ(runner.load(), Error::InvalidProgram); +} + } // namespace diff --git a/extension/llm/runner/text_decoder_runner.cpp b/extension/llm/runner/text_decoder_runner.cpp index bb64d79dd2e..2b43a770842 100644 --- a/extension/llm/runner/text_decoder_runner.cpp +++ b/extension/llm/runner/text_decoder_runner.cpp @@ -1,6 +1,7 @@ /* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. + * Copyright 2026 Arm Limited and/or its affiliates. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. @@ -11,7 +12,9 @@ #include #include +#include #include +#include #include @@ -27,12 +30,14 @@ TextDecoderRunner::TextDecoderRunner( IOManager* io_manager, std::string method_name, std::unique_ptr sampler, - Stats* stats) + Stats* stats, + bool enable_dynamic_shape) : module_(module), io_manager_(io_manager), method_name_(std::move(method_name)), sampler_(std::move(sampler)), - stats_(stats) {} + stats_(stats), + enable_dynamic_shape_(enable_dynamic_shape) {} // This function is functional, meaning it shouldn't modify any state of the // input. It should be safe to call multiple times with the same inputs. The @@ -93,7 +98,46 @@ ::executorch::runtime::Result TextDecoderRunner::step( } else { // no kv cache (void)start_pos; // unused - std::vector inputs{tokens}; + auto input_meta = method_meta.input_tensor_meta(0); + ET_CHECK_OK_OR_RETURN_ERROR(input_meta.error()); + const auto sizes = input_meta->sizes(); + ET_CHECK_OR_RETURN_ERROR( + sizes.size() == 2 && sizes[0] == 1 && tokens->dim() == 2 && + tokens->size(0) == 1, + InvalidArgument, + "Non-KV text input must have shape [1, sequence_length]"); + const auto valid_length = tokens->size(1); + const auto input_length = static_cast( + enable_dynamic_shape_ ? valid_length : sizes[1]); + ET_CHECK_OR_RETURN_ERROR( + valid_length > 0 && valid_length <= input_length, + InvalidArgument, + "Token count exceeds the static non-KV input window"); + ET_CHECK_OR_RETURN_ERROR( + tokens->scalar_type() == aten::ScalarType::Long && + (input_meta->scalar_type() == aten::ScalarType::Int || + input_meta->scalar_type() == aten::ScalarType::Long), + InvalidArgument, + "Non-KV text input must use int32 or int64 tokens"); + TensorPtr model_tokens; + if (input_meta->scalar_type() == aten::ScalarType::Int) { + std::vector padded(input_length, 0); + const auto* data = tokens->const_data_ptr(); + for (int64_t i = 0; i < valid_length; ++i) { + ET_CHECK_OR_RETURN_ERROR( + data[i] >= 0 && data[i] <= std::numeric_limits::max(), + InvalidArgument, + "Token ID cannot be represented as int32"); + padded[i] = static_cast(data[i]); + } + model_tokens = make_tensor_ptr({1, input_length}, std::move(padded)); + } else { + std::vector padded(input_length, 0); + const auto* data = tokens->const_data_ptr(); + std::copy(data, data + valid_length, padded.begin()); + model_tokens = make_tensor_ptr({1, input_length}, std::move(padded)); + } + std::vector inputs{model_tokens}; if (stats_ != nullptr) { stats_->on_model_execution_begin(); } @@ -109,8 +153,21 @@ ::executorch::runtime::Result TextDecoderRunner::step( outputs_res.get()[0].isTensor(), "Non Tensor Output returned from executing LLM"); - // Return the logits tensor - return outputs_res.get()[0].toTensor(); + auto logits = outputs_res.get()[0].toTensor(); + if (!enable_dynamic_shape_) { + ET_CHECK_OR_RETURN_ERROR( + logits.dim() == 3 && logits.size(0) == 1 && + logits.size(1) == input_length, + InvalidProgram, + "Static non-KV models need full logits; export with " + "--generate_full_logits"); + const auto vocab_size = static_cast(logits.size(2)); + auto* last_row = static_cast(logits.mutable_data_ptr()) + + (valid_length - 1) * vocab_size * logits.element_size(); + last_logits_ = from_blob(last_row, {1, vocab_size}, logits.scalar_type()); + return *last_logits_; + } + return logits; } } diff --git a/extension/llm/runner/text_decoder_runner.h b/extension/llm/runner/text_decoder_runner.h index 4dbce70a830..ee68a7015d2 100644 --- a/extension/llm/runner/text_decoder_runner.h +++ b/extension/llm/runner/text_decoder_runner.h @@ -1,6 +1,7 @@ /* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. + * Copyright 2026 Arm Limited and/or its affiliates. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. @@ -27,7 +28,8 @@ class ET_EXPERIMENTAL TextDecoderRunner { IOManager* io_manager, std::string method_name = "forward", std::unique_ptr sampler = nullptr, - Stats* stats = nullptr); + Stats* stats = nullptr, + bool enable_dynamic_shape = true); virtual ~TextDecoderRunner() = default; @@ -53,8 +55,28 @@ class ET_EXPERIMENTAL TextDecoderRunner { Error, "Failed to load method '%s'. Check available methods in the model.", method_name_.c_str()); + return err; } - return err; + if (!enable_dynamic_shape_) { + auto meta = module_->method_meta(method_name_); + if (!meta.ok()) { + return meta.error(); + } + if (meta->num_inputs() == 1) { + auto output = meta->output_tensor_meta(0); + if (!output.ok()) { + return output.error(); + } + if (output->sizes().size() != 3) { + ET_LOG( + Error, + "Static non-KV models require full logits. " + "Export with --generate_full_logits."); + return ::executorch::runtime::Error::InvalidProgram; + } + } + } + return ::executorch::runtime::Error::Ok; } /** @@ -106,6 +128,8 @@ class ET_EXPERIMENTAL TextDecoderRunner { std::string method_name_; std::unique_ptr sampler_; Stats* stats_; + bool enable_dynamic_shape_; + TensorPtr last_logits_; }; } // namespace llm diff --git a/test/models/export_program.py b/test/models/export_program.py index a4b08fa2ad6..4b3cce9b575 100644 --- a/test/models/export_program.py +++ b/test/models/export_program.py @@ -1,5 +1,6 @@ # Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. +# Copyright 2026 Arm Limited and/or its affiliates. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. @@ -281,6 +282,19 @@ def get_random_inputs(self): return (torch.randint(100, [1, 3], dtype=torch.long),) +class ModuleStaticNoKVCache(torch.nn.Module): + def forward(self, tokens): + values = tokens.to(torch.float) + positions = torch.arange(4, dtype=torch.float, device=tokens.device).unsqueeze( + 0 + ) + padding_sum = values[:, 2:].sum() + return torch.stack((values, positions + padding_sum), dim=-1) + + def get_random_inputs(self): + return (torch.zeros(1, 4, dtype=torch.int32),) + + class ModuleSharedState(torch.nn.Module): def __init__(self): super().__init__() diff --git a/test/models/targets.bzl b/test/models/targets.bzl index 7deb3f7d6c8..ea6511aa8ba 100644 --- a/test/models/targets.bzl +++ b/test/models/targets.bzl @@ -1,3 +1,8 @@ +# Copyright 2026 Arm Limited and/or its affiliates. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + load("@fbsource//xplat/executorch/build:runtime_wrapper.bzl", "runtime") def define_common_targets(): @@ -68,6 +73,7 @@ def define_common_targets(): "ModuleKVCacheInputPos", "ModuleMultipleEntry", "ModuleNoKVCache", + "ModuleStaticNoKVCache", "ModuleIndex", "ModuleIntBool", "ModuleDynamicCatUnallocatedIO",