Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion extension/llm/runner/llm_runner_helper.cpp
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -297,7 +298,8 @@ std::unique_ptr<TextLLMRunner> 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.
Expand Down
2 changes: 2 additions & 0 deletions extension/llm/runner/test/BUCK
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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])",
}
)
37 changes: 37 additions & 0 deletions extension/llm/runner/test/test_text_decoder_runner.cpp
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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<int64_t>{7, 8});
auto result = runner.step(tokens, 0);
ASSERT_TRUE(result.ok()) << static_cast<int>(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<float>()[0], 8.0f);
EXPECT_FLOAT_EQ(result->const_data_ptr<float>()[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
67 changes: 62 additions & 5 deletions extension/llm/runner/text_decoder_runner.cpp
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -11,7 +12,9 @@
#include <executorch/extension/llm/runner/text_decoder_runner.h>
#include <executorch/kernels/portable/cpu/util/arange_util.h>

#include <algorithm>
#include <ctime>
#include <limits>

#include <executorch/extension/llm/runner/stats.h>

Expand All @@ -27,12 +30,14 @@ TextDecoderRunner::TextDecoderRunner(
IOManager* io_manager,
std::string method_name,
std::unique_ptr<Sampler> 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
Expand Down Expand Up @@ -93,7 +98,46 @@ ::executorch::runtime::Result<executorch::aten::Tensor> TextDecoderRunner::step(
} else { // no kv cache
(void)start_pos; // unused

std::vector<runtime::EValue> 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<aten::SizesType>(
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<int32_t> padded(input_length, 0);
const auto* data = tokens->const_data_ptr<int64_t>();
for (int64_t i = 0; i < valid_length; ++i) {
ET_CHECK_OR_RETURN_ERROR(
data[i] >= 0 && data[i] <= std::numeric_limits<int32_t>::max(),
InvalidArgument,
"Token ID cannot be represented as int32");
padded[i] = static_cast<int32_t>(data[i]);
}
model_tokens = make_tensor_ptr({1, input_length}, std::move(padded));
} else {
std::vector<int64_t> padded(input_length, 0);
const auto* data = tokens->const_data_ptr<int64_t>();
std::copy(data, data + valid_length, padded.begin());
model_tokens = make_tensor_ptr({1, input_length}, std::move(padded));
}
std::vector<runtime::EValue> inputs{model_tokens};
if (stats_ != nullptr) {
stats_->on_model_execution_begin();
}
Expand All @@ -109,8 +153,21 @@ ::executorch::runtime::Result<executorch::aten::Tensor> 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<aten::SizesType>(logits.size(2));
auto* last_row = static_cast<char*>(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;
}
}

Expand Down
28 changes: 26 additions & 2 deletions extension/llm/runner/text_decoder_runner.h
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -27,7 +28,8 @@ class ET_EXPERIMENTAL TextDecoderRunner {
IOManager* io_manager,
std::string method_name = "forward",
std::unique_ptr<Sampler> sampler = nullptr,
Stats* stats = nullptr);
Stats* stats = nullptr,
bool enable_dynamic_shape = true);

virtual ~TextDecoderRunner() = default;

Expand All @@ -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;
}

/**
Expand Down Expand Up @@ -106,6 +128,8 @@ class ET_EXPERIMENTAL TextDecoderRunner {
std::string method_name_;
std::unique_ptr<Sampler> sampler_;
Stats* stats_;
bool enable_dynamic_shape_;
TensorPtr last_logits_;
};

} // namespace llm
Expand Down
14 changes: 14 additions & 0 deletions test/models/export_program.py
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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__()
Expand Down
6 changes: 6 additions & 0 deletions test/models/targets.bzl
Original file line number Diff line number Diff line change
@@ -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():
Expand Down Expand Up @@ -68,6 +73,7 @@ def define_common_targets():
"ModuleKVCacheInputPos",
"ModuleMultipleEntry",
"ModuleNoKVCache",
"ModuleStaticNoKVCache",
"ModuleIndex",
"ModuleIntBool",
"ModuleDynamicCatUnallocatedIO",
Expand Down
Loading