diff --git a/examples/models/llama/CMakeLists.txt b/examples/models/llama/CMakeLists.txt index fbd73590905..4d9dc453f14 100644 --- a/examples/models/llama/CMakeLists.txt +++ b/examples/models/llama/CMakeLists.txt @@ -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. @@ -169,6 +170,12 @@ if(TARGET vulkan_backend) executorch_target_link_options_shared_lib(vulkan_backend) endif() +# VGF backend +if(TARGET vgf_backend) + list(APPEND link_libraries vgf_backend) + executorch_target_link_options_shared_lib(vgf_backend) +endif() + # Qnn backend if(TARGET qnn_executorch_backend) list(APPEND link_libraries qnn_executorch_backend) diff --git a/extension/llm/runner/multimodal_decoder_runner.h b/extension/llm/runner/multimodal_decoder_runner.h index b9be142c30d..0399f42ad8a 100644 --- a/extension/llm/runner/multimodal_decoder_runner.h +++ b/extension/llm/runner/multimodal_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. @@ -26,6 +27,15 @@ class ET_EXPERIMENTAL MultimodalDecoderRunner std::move(method_name), std::move(sampler)) {} + inline executorch::runtime::Result + token_input_scalar_type() const override { + auto method_meta = module_->method_meta(kTokenEmbeddingMethod); + ET_CHECK_OK_OR_RETURN_ERROR(method_meta.error()); + auto input_meta = method_meta->input_tensor_meta(0); + ET_CHECK_OK_OR_RETURN_ERROR(input_meta.error()); + return input_meta->scalar_type(); + } + /** * Step the LLM Decoder with the given tokens and start position. * @param tokens The tokens to the LLM. diff --git a/extension/llm/runner/test/CMakeLists.txt b/extension/llm/runner/test/CMakeLists.txt index cd380429601..576e1c338a1 100644 --- a/extension/llm/runner/test/CMakeLists.txt +++ b/extension/llm/runner/test/CMakeLists.txt @@ -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. @@ -70,6 +71,25 @@ et_cxx_test( test_runner SOURCES ${_test_srcs} EXTRA_LIBS executorch extension_llm_runner ) add_dependencies(test_runner generated_model_metadata_test_files) +set(_int32_pte_files + "${CMAKE_CURRENT_BINARY_DIR}/static_int32.pte" + "${CMAKE_CURRENT_BINARY_DIR}/kv_int32.pte" + "${CMAKE_CURRENT_BINARY_DIR}/static_int64.pte" + "${CMAKE_CURRENT_BINARY_DIR}/kv_int64.pte" + "${CMAKE_CURRENT_BINARY_DIR}/multimodal_int32.pte" + "${CMAKE_CURRENT_BINARY_DIR}/multimodal_int64.pte" +) +add_custom_command( + OUTPUT ${_int32_pte_files} + COMMAND + ${PYTHON_EXECUTABLE} + ${CMAKE_CURRENT_SOURCE_DIR}/export_int32_runner_models.py --outdir + ${CMAKE_CURRENT_BINARY_DIR} + WORKING_DIRECTORY ${EXECUTORCH_ROOT} + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/export_int32_runner_models.py +) +add_custom_target(generated_int32_runner_models DEPENDS ${_int32_pte_files}) +add_dependencies(test_runner generated_int32_runner_models) set_property( TEST test_runner PROPERTY @@ -77,6 +97,19 @@ set_property( "ET_MODEL_METADATA_FULL_PATH=${CMAKE_CURRENT_BINARY_DIR}/ModelMetadata_full.pte;ET_MODEL_METADATA_LAST_PATH=${CMAKE_CURRENT_BINARY_DIR}/ModelMetadata_last.pte;ET_MODEL_METADATA_SELECTED_PATH=${CMAKE_CURRENT_BINARY_DIR}/ModelMetadata_selected.pte;ET_MODEL_METADATA_INVALID_CONTEXT_PATH=${CMAKE_CURRENT_BINARY_DIR}/ModelMetadata_invalid_context.pte;ET_MODEL_METADATA_INVALID_PREFILL_PATH=${CMAKE_CURRENT_BINARY_DIR}/ModelMetadata_invalid_prefill.pte;ET_MODEL_METADATA_INVALID_VOCAB_PATH=${CMAKE_CURRENT_BINARY_DIR}/ModelMetadata_invalid_vocab.pte;ET_MODEL_METADATA_MISSING_PATH=${CMAKE_CURRENT_BINARY_DIR}/ModelMetadata_missing.pte;ET_MODEL_METADATA_GEOMETRY_WRONG_TYPE_PATH=${CMAKE_CURRENT_BINARY_DIR}/ModelMetadata_geometry_wrong_type.pte;ET_MODEL_METADATA_GEOMETRY_MISMATCHED_PATH=${CMAKE_CURRENT_BINARY_DIR}/ModelMetadata_geometry_mismatched.pte;ET_MODEL_METADATA_GEOMETRY_INVALID_HEADS_PATH=${CMAKE_CURRENT_BINARY_DIR}/ModelMetadata_geometry_invalid_heads.pte;ET_MODEL_METADATA_GEOMETRY_INVALID_DIMS_PATH=${CMAKE_CURRENT_BINARY_DIR}/ModelMetadata_geometry_invalid_dims.pte;ET_MODEL_METADATA_GEOMETRY_INVALID_WINDOWS_PATH=${CMAKE_CURRENT_BINARY_DIR}/ModelMetadata_geometry_invalid_windows.pte;ET_MODEL_METADATA_GEOMETRY_EMPTY_PATH=${CMAKE_CURRENT_BINARY_DIR}/ModelMetadata_geometry_empty.pte" ) +set_property( + TEST test_runner + APPEND + PROPERTY + ENVIRONMENT + "ET_STATIC_INT32_MODEL=${CMAKE_CURRENT_BINARY_DIR}/static_int32.pte" + "ET_KV_INT32_MODEL=${CMAKE_CURRENT_BINARY_DIR}/kv_int32.pte" + "ET_STATIC_INT64_MODEL=${CMAKE_CURRENT_BINARY_DIR}/static_int64.pte" + "ET_KV_INT64_MODEL=${CMAKE_CURRENT_BINARY_DIR}/kv_int64.pte" + "ET_MULTIMODAL_INT32_MODEL=${CMAKE_CURRENT_BINARY_DIR}/multimodal_int32.pte" + "ET_MULTIMODAL_INT64_MODEL=${CMAKE_CURRENT_BINARY_DIR}/multimodal_int64.pte" +) + # Override sanitizer to this issue: # https://github.com/abseil/abseil-cpp/issues/841 Root issue: # https://github.com/llvm/llvm-project/issues/16778 diff --git a/extension/llm/runner/test/export_int32_runner_models.py b/extension/llm/runner/test/export_int32_runner_models.py new file mode 100644 index 00000000000..92e9e131370 --- /dev/null +++ b/extension/llm/runner/test/export_int32_runner_models.py @@ -0,0 +1,62 @@ +# 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. + +import argparse +from pathlib import Path + +import torch +from executorch.exir import to_edge + + +class StaticTokens(torch.nn.Module): + def forward(self, tokens): + values = tokens.to(torch.float32) + return torch.stack((values, values + 1, values + 2), dim=-1) + + +class TokensAndPosition(torch.nn.Module): + def forward(self, tokens, position): + values = tokens.to(torch.float32) + positions = position.reshape(1, 1).to(torch.float32) + return torch.stack((values, positions, values + positions), dim=-1) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--outdir", type=Path, required=True) + args = parser.parse_args() + args.outdir.mkdir(parents=True, exist_ok=True) + cases = [ + ("static_int32.pte", StaticTokens(), (torch.ones((1, 4), dtype=torch.int32),)), + ( + "kv_int32.pte", + TokensAndPosition(), + (torch.ones((1, 1), dtype=torch.int32), torch.ones(1, dtype=torch.int32)), + ), + ("static_int64.pte", StaticTokens(), (torch.ones((1, 4), dtype=torch.int64),)), + ( + "kv_int64.pte", + TokensAndPosition(), + (torch.ones((1, 1), dtype=torch.int64), torch.ones(1, dtype=torch.int64)), + ), + ] + for name, model, inputs in cases: + program = to_edge(torch.export.export(model, inputs)).to_executorch() + (args.outdir / name).write_bytes(program.buffer) + + for dtype in (torch.int32, torch.int64): + name = f"multimodal_{str(dtype).removeprefix('torch.')}.pte" + model = StaticTokens() + inputs = (torch.ones((1, 1), dtype=dtype),) + program = to_edge( + { + "token_embedding": torch.export.export(model, inputs), + } + ).to_executorch() + (args.outdir / name).write_bytes(program.buffer) + + +if __name__ == "__main__": + main() diff --git a/extension/llm/runner/test/test_text_decoder_runner.cpp b/extension/llm/runner/test/test_text_decoder_runner.cpp index 283e92ae690..11e2779e838 100644 --- a/extension/llm/runner/test/test_text_decoder_runner.cpp +++ b/extension/llm/runner/test/test_text_decoder_runner.cpp @@ -9,6 +9,7 @@ */ #include +#include #include #include #include @@ -16,6 +17,7 @@ #include #include #include +#include using namespace ::testing; using executorch::extension::Module; @@ -30,6 +32,16 @@ class MockModule : public Module { MockModule() : Module("") {} }; +class TokenInputModule : public Module { + public: + explicit TokenInputModule(const std::string& path) : Module(path) {} + MOCK_METHOD( + executorch::runtime::Result>, + execute, + (const std::string&, const std::vector&), + (override)); +}; + class TextDecoderRunnerTest : public Test { protected: void SetUp() override { @@ -50,6 +62,187 @@ TEST_F(TextDecoderRunnerTest, MethodNameDefaultsToForward) { EXPECT_EQ(runner_->method_name(), "forward"); } +TEST_F(TextDecoderRunnerTest, StaticInt32AcceptsTypedPrefixes) { + const char* path = std::getenv("ET_STATIC_INT32_MODEL"); + if (!path) { + GTEST_SKIP() << "Set ET_STATIC_INT32_MODEL to the generated test fixture"; + } + Module module(path); + IOManager io(module); + TextDecoderRunner runner(&module, &io, "forward", nullptr, nullptr, false); + auto dtype = runner.token_input_scalar_type(); + ASSERT_TRUE(dtype.ok()); + EXPECT_EQ(dtype.get(), executorch::aten::ScalarType::Int); + for (int size : {1, 2, 4}) { + auto tokens = executorch::extension::make_tensor_ptr( + {1, size}, std::vector(size, 11)); + auto result = runner.step(tokens, 0); + ASSERT_TRUE(result.ok()); + ASSERT_EQ(result->dim(), 2); + ASSERT_EQ(result->size(1), 3); + const auto* data = result->const_data_ptr(); + EXPECT_EQ(data[0], 11.0f); + EXPECT_EQ(data[1], 12.0f); + EXPECT_EQ(data[2], 13.0f); + } + auto wrong_type = + executorch::extension::make_tensor_ptr({1, 1}, std::vector{11}); + EXPECT_EQ(runner.step(wrong_type, 0).error(), Error::InvalidArgument); + auto too_long = executorch::extension::make_tensor_ptr( + {1, 5}, std::vector(5, 11)); + EXPECT_EQ(runner.step(too_long, 0).error(), Error::InvalidArgument); +} + +TEST_F(TextDecoderRunnerTest, StaticInt64AcceptsTypedPrefixes) { + const char* path = std::getenv("ET_STATIC_INT64_MODEL"); + if (!path) { + GTEST_SKIP() << "Set ET_STATIC_INT64_MODEL to the generated test fixture"; + } + Module module(path); + IOManager io(module); + TextDecoderRunner runner(&module, &io, "forward", nullptr, nullptr, false); + auto dtype = runner.token_input_scalar_type(); + ASSERT_TRUE(dtype.ok()); + EXPECT_EQ(dtype.get(), executorch::aten::ScalarType::Long); + for (int size : {1, 2, 4}) { + auto tokens = executorch::extension::make_tensor_ptr( + {1, size}, std::vector(size, 11)); + auto result = runner.step(tokens, 0); + ASSERT_TRUE(result.ok()); + ASSERT_EQ(result->dim(), 2); + ASSERT_EQ(result->size(1), 3); + const auto* data = result->const_data_ptr(); + EXPECT_EQ(data[0], 11.0f); + EXPECT_EQ(data[1], 12.0f); + EXPECT_EQ(data[2], 13.0f); + } + auto wrong_type = + executorch::extension::make_tensor_ptr({1, 1}, std::vector{11}); + EXPECT_EQ(runner.step(wrong_type, 0).error(), Error::InvalidArgument); +} + +TEST_F(TextDecoderRunnerTest, Int32KvAcceptsTypedTokensAndPositions) { + const char* path = std::getenv("ET_KV_INT32_MODEL"); + if (!path) { + GTEST_SKIP() << "Set ET_KV_INT32_MODEL to the generated test fixture"; + } + Module module(path); + IOManager io(module); + TextDecoderRunner runner(&module, &io); + auto tokens = + executorch::extension::make_tensor_ptr({1, 1}, std::vector{11}); + auto result = runner.step(tokens, 3); + ASSERT_TRUE(result.ok()); + const auto* data = result->const_data_ptr(); + EXPECT_EQ(data[0], 11.0f); + EXPECT_EQ(data[1], 3.0f); + EXPECT_EQ(data[2], 14.0f); + auto int32_tokens = + executorch::extension::make_tensor_ptr({1, 1}, std::vector{12}); + auto int32_result = runner.step(int32_tokens, 4); + ASSERT_TRUE(int32_result.ok()); + data = int32_result->const_data_ptr(); + EXPECT_EQ(data[0], 12.0f); + EXPECT_EQ(data[1], 4.0f); + EXPECT_EQ(data[2], 16.0f); + EXPECT_EQ( + runner + .step( + tokens, + static_cast(std::numeric_limits::max()) + 1) + .error(), + Error::InvalidArgument); + tokens = executorch::extension::make_tensor_ptr( + {1, 1}, + std::vector{ + static_cast(std::numeric_limits::max()) + 1}); + EXPECT_EQ(runner.step(tokens, 0).error(), Error::InvalidArgument); +} + +TEST_F(TextDecoderRunnerTest, Int64KvAcceptsTypedTokensAndPositions) { + const char* path = std::getenv("ET_KV_INT64_MODEL"); + if (!path) { + GTEST_SKIP() << "Set ET_KV_INT64_MODEL to the generated test fixture"; + } + Module module(path); + IOManager io(module); + TextDecoderRunner runner(&module, &io); + auto tokens = + executorch::extension::make_tensor_ptr({1, 1}, std::vector{11}); + auto result = runner.step(tokens, 3); + ASSERT_TRUE(result.ok()); + const auto* data = result->const_data_ptr(); + EXPECT_EQ(data[0], 11.0f); + EXPECT_EQ(data[1], 3.0f); + EXPECT_EQ(data[2], 14.0f); + auto wrong_type = + executorch::extension::make_tensor_ptr({1, 1}, std::vector{11}); + EXPECT_EQ(runner.step(wrong_type, 0).error(), Error::InvalidArgument); +} + +TEST_F(TextDecoderRunnerTest, MultimodalReadsTokenEmbeddingInputType) { + for (bool use_int32 : {false, true}) { + const char* path = std::getenv( + use_int32 ? "ET_MULTIMODAL_INT32_MODEL" : "ET_MULTIMODAL_INT64_MODEL"); + if (!path) { + GTEST_SKIP() << "Generate the multimodal token fixtures"; + } + Module module(path); + IOManager io(module); + executorch::extension::llm::MultimodalDecoderRunner runner(&module, &io); + auto methods = module.method_names(); + ASSERT_TRUE(methods.ok()); + EXPECT_EQ(methods->count("forward"), 0); + auto dtype = runner.token_input_scalar_type(); + ASSERT_TRUE(dtype.ok()); + EXPECT_EQ( + dtype.get(), + use_int32 ? executorch::aten::ScalarType::Int + : executorch::aten::ScalarType::Long); + } +} + +TEST_F(TextDecoderRunnerTest, UnpaddedTokenInputsAreNotCopied) { + for (const char* fixture : + {"ET_KV_INT32_MODEL", + "ET_KV_INT64_MODEL", + "ET_STATIC_INT32_MODEL", + "ET_STATIC_INT64_MODEL"}) { + const char* path = std::getenv(fixture); + if (!path) { + GTEST_SKIP() << "Generate the typed token fixtures"; + } + for (bool dynamic : {false, true}) { + SCOPED_TRACE(fixture); + SCOPED_TRACE(dynamic); + TokenInputModule module(path); + IOManager io(module); + TextDecoderRunner runner( + &module, &io, "forward", nullptr, nullptr, dynamic); + auto meta = module.method_meta("forward"); + ASSERT_TRUE(meta.ok()); + auto input = meta->input_tensor_meta(0); + ASSERT_TRUE(input.ok()); + auto length = input->sizes()[1]; + auto tokens = input->scalar_type() == executorch::aten::ScalarType::Int + ? executorch::extension::make_tensor_ptr( + {1, length}, std::vector(length, 11)) + : executorch::extension::make_tensor_ptr( + {1, length}, std::vector(length, 11)); + EXPECT_CALL(module, execute("forward", _)) + .WillOnce( + [&](const std::string& name, + const std::vector& inputs) { + EXPECT_EQ( + inputs[0].toTensor().const_data_ptr(), + tokens->const_data_ptr()); + return module.Module::execute(name, inputs); + }); + ASSERT_TRUE(runner.step(tokens, 0).ok()); + } + } +} + // Test that method_name can be set to a custom value TEST_F(TextDecoderRunnerTest, MethodNameCustomValue) { auto custom_runner = std::make_unique( @@ -329,7 +522,7 @@ TEST_F(TextDecoderRunnerTest, StaticNonKVShortPrompt) { ASSERT_EQ(runner.load(), Error::Ok); auto tokens = executorch::extension::make_tensor_ptr( - {1, 2}, std::vector{7, 8}); + {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); diff --git a/extension/llm/runner/test/test_text_llm_runner.cpp b/extension/llm/runner/test/test_text_llm_runner.cpp index f6f5137a90f..e1be93dc81e 100644 --- a/extension/llm/runner/test/test_text_llm_runner.cpp +++ b/extension/llm/runner/test/test_text_llm_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. @@ -85,6 +86,11 @@ class MockTextDecoderRunner : public TextDecoderRunner { (executorch::extension::TensorPtr&, int64_t), ()); MOCK_METHOD(bool, is_method_loaded, (), ()); + MOCK_METHOD( + Result, + token_input_scalar_type, + (), + (const, override)); MOCK_METHOD(Result, prefill, (std::vector&, int64_t), ()); MOCK_METHOD(::executorch::runtime::Error, load, (), ()); }; @@ -185,6 +191,11 @@ class RunnerTest : public Test { }); ON_CALL(*text_decoder_runner, is_method_loaded()) .WillByDefault(Return(true)); + ON_CALL(*text_decoder_runner, token_input_scalar_type()) + .WillByDefault([]() { + return Result( + executorch::aten::ScalarType::Long); + }); return text_decoder_runner; } @@ -581,6 +592,119 @@ TEST_F(RunnerTest, NonKvCacheGenerateCompletesSuccessfully) { EXPECT_EQ(step_count, max_new_tokens); } +TEST_F(RunnerTest, Int32TokenInputsPreserveValuesAndStorage) { + for (bool use_kv_cache : {false, true}) { + SCOPED_TRACE(use_kv_cache); + auto tokenizer = createMockTokenizer(); + auto decoder = createMockTextDecoderRunner(); + EXPECT_CALL(*decoder, token_input_scalar_type()).WillOnce([]() { + return Result( + executorch::aten::ScalarType::Int); + }); + int step_count = 0; + const int32_t* storage = nullptr; + EXPECT_CALL(*decoder, step(_, _)) + .Times(20) + .WillRepeatedly([&](executorch::extension::TensorPtr& tokens, + int64_t pos) { + EXPECT_EQ(tokens->scalar_type(), executorch::aten::ScalarType::Int); + EXPECT_EQ(tokens->size(1), use_kv_cache ? 1 : 4 + step_count); + EXPECT_EQ(pos, 4 + step_count); + const auto* data = tokens->const_data_ptr(); + if (storage == nullptr) { + storage = data; + } + EXPECT_EQ(storage, data); + if (use_kv_cache) { + EXPECT_EQ(data[0], step_count == 0 ? 4 : 3); + } else { + for (int index = 0; index < 4; ++index) { + EXPECT_EQ(data[index], index + 1); + } + for (int index = 4; index < tokens->size(1); ++index) { + EXPECT_EQ(data[index], 3); + } + } + ++step_count; + return Result(tensor); + }); + auto eos_ids = std::make_unique>(); + TextTokenGenerator generator( + tokenizer.get(), + decoder.get(), + use_kv_cache, + std::move(eos_ids), + &stats_); + auto result = generator.generate( + {1, 2, 3, 4}, 4, 20, 0.0f, [](const std::string&) {}); + ASSERT_TRUE(result.ok()); + EXPECT_EQ(result.get(), 20); + EXPECT_EQ(step_count, 20); + } +} + +TEST_F(RunnerTest, TokenInputMetadataErrorsPreventExecution) { + for (bool metadata_failure : {false, true}) { + SCOPED_TRACE(metadata_failure); + auto tokenizer = createMockTokenizer(); + auto decoder = createMockTextDecoderRunner(); + EXPECT_CALL(*decoder, token_input_scalar_type()) + .WillOnce([metadata_failure]() { + return metadata_failure + ? Result(Error::InvalidState) + : Result( + executorch::aten::ScalarType::Float); + }); + EXPECT_CALL(*decoder, step(_, _)).Times(0); + auto generator = + createTextTokenGenerator(tokenizer.get(), decoder.get(), &stats_); + auto result = generator->generate({4}, 4, 1); + EXPECT_EQ( + result.error(), + metadata_failure ? Error::InvalidState : Error::InvalidArgument); + } +} + +TEST_F(RunnerTest, Int32TokenInputRejectsOverflow) { + auto tokenizer = createMockTokenizer(); + auto decoder = createMockTextDecoderRunner(); + EXPECT_CALL(*decoder, token_input_scalar_type()).WillOnce([]() { + return Result( + executorch::aten::ScalarType::Int); + }); + EXPECT_CALL(*decoder, step(_, _)).Times(0); + auto generator = + createTextTokenGenerator(tokenizer.get(), decoder.get(), &stats_); + auto result = generator->generate( + {static_cast(std::numeric_limits::max()) + 1}, 4, 1); + EXPECT_EQ(result.error(), Error::InvalidArgument); +} + +TEST_F(RunnerTest, Int64TokenInputsPreserveValuesAboveInt32) { + const uint64_t token = + static_cast(std::numeric_limits::max()) + 1; + for (bool use_kv_cache : {false, true}) { + auto tokenizer = createMockTokenizer(); + auto decoder = createMockTextDecoderRunner(); + EXPECT_CALL(*decoder, step(_, _)) + .WillOnce([&](executorch::extension::TensorPtr& tokens, int64_t) { + EXPECT_EQ(tokens->scalar_type(), executorch::aten::ScalarType::Long); + EXPECT_EQ(tokens->const_data_ptr()[0], token); + return Result(tensor); + }); + TextTokenGenerator generator( + tokenizer.get(), + decoder.get(), + use_kv_cache, + std::make_unique>(), + &stats_); + auto result = + generator.generate({token}, 4, 1, 0.0f, [](const std::string&) {}); + ASSERT_TRUE(result.ok()); + EXPECT_EQ(result.get(), 1); + } +} + // Test that multi-turn generation with seq_len correctly accounts for pos_. // Regression test for a bug where max_context_len was pre-adjusted by pos_, // causing resolve_max_new_tokens to under-count occupied positions when diff --git a/extension/llm/runner/test/test_text_prefiller.cpp b/extension/llm/runner/test/test_text_prefiller.cpp index e859db36346..fbdf2803689 100644 --- a/extension/llm/runner/test/test_text_prefiller.cpp +++ b/extension/llm/runner/test/test_text_prefiller.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. @@ -13,6 +14,8 @@ #include #include #include +#include +#include using namespace ::testing; using executorch::extension::llm::TextDecoderRunner; @@ -32,6 +35,11 @@ class MockTextDecoderRunner : public TextDecoderRunner { (executorch::extension::TensorPtr&, int64_t), ()); MOCK_METHOD(bool, is_method_loaded, (), ()); + MOCK_METHOD( + Result, + token_input_scalar_type, + (), + (const, override)); MOCK_METHOD(Result, prefill, (std::vector&, int64_t), ()); MOCK_METHOD(::executorch::runtime::Error, load, (), ()); }; @@ -44,6 +52,11 @@ class TextPrefillerTest : public Test { // Set up default behavior for the text decoder runner ON_CALL(text_decoder_runner_, is_method_loaded()) .WillByDefault(Return(true)); + ON_CALL(text_decoder_runner_, token_input_scalar_type()) + .WillByDefault([]() { + return Result( + executorch::aten::ScalarType::Long); + }); ON_CALL(text_decoder_runner_, step) .WillByDefault([&](executorch::extension::TensorPtr&, int64_t) { return Result(tensor); @@ -106,6 +119,151 @@ class TextPrefillerTest : public Test { executorch::aten::Tensor tensor = tf.make({1, 4}, return_logits_); }; +TEST_F(TextPrefillerTest, TokenTypesPreserveValuesAndPositions) { + for (auto type : + {executorch::aten::ScalarType::Int, + executorch::aten::ScalarType::Long}) { + for (bool use_kv_cache : {false, true}) { + for (bool parallel : {false, true}) { + SCOPED_TRACE(static_cast(type)); + SCOPED_TRACE(use_kv_cache); + SCOPED_TRACE(parallel); + auto prefiller = createTextPrefiller(8, use_kv_cache, parallel); + std::vector prompt{11, 12, 13}; + int64_t position = 4; + int calls = 0; + const bool sequential = use_kv_cache && !parallel; + EXPECT_CALL(text_decoder_runner_, token_input_scalar_type()) + .WillOnce([type]() { + return Result(type); + }); + EXPECT_CALL(text_decoder_runner_, step(_, _)) + .Times(sequential ? 3 : 1) + .WillRepeatedly([&](executorch::extension::TensorPtr& tokens, + int64_t pos) { + EXPECT_EQ(tokens->scalar_type(), type); + EXPECT_EQ(pos, 4 + (sequential ? calls : 0)); + EXPECT_EQ(tokens->size(1), sequential ? 1 : 3); + for (int i = 0; i < tokens->size(1); ++i) { + const int64_t value = type == executorch::aten::ScalarType::Int + ? tokens->const_data_ptr()[i] + : tokens->const_data_ptr()[i]; + EXPECT_EQ(value, prompt[sequential ? calls : i]); + } + ++calls; + return Result(tensor); + }); + ASSERT_TRUE(prefiller->prefill(prompt, position).ok()); + EXPECT_EQ(position, 7); + Mock::VerifyAndClearExpectations(&text_decoder_runner_); + } + } + } +} + +TEST_F(TextPrefillerTest, TokenMetadataErrorsPreventExecution) { + for (bool metadata_failure : {false, true}) { + for (int chunk_size : {1, 8}) { + SCOPED_TRACE(metadata_failure); + SCOPED_TRACE(chunk_size); + auto prefiller = createTextPrefiller(chunk_size); + std::vector prompt{11, 12, 13}; + int64_t position = 4; + EXPECT_CALL(text_decoder_runner_, token_input_scalar_type()) + .WillOnce([metadata_failure]() { + return metadata_failure + ? Result(Error::InvalidState) + : Result( + executorch::aten::ScalarType::Float); + }); + EXPECT_CALL(text_decoder_runner_, step(_, _)).Times(0); + EXPECT_EQ( + prefiller->prefill(prompt, position).error(), + metadata_failure ? Error::InvalidState : Error::InvalidArgument); + EXPECT_EQ(position, 4); + Mock::VerifyAndClearExpectations(&text_decoder_runner_); + } + } +} + +TEST_F(TextPrefillerTest, ChunkedTokenTypesPreserveValuesAndPositions) { + for (auto type : + {executorch::aten::ScalarType::Int, + executorch::aten::ScalarType::Long}) { + for (bool parallel : {false, true}) { + SCOPED_TRACE(static_cast(type)); + SCOPED_TRACE(parallel); + auto prefiller = createTextPrefiller(2, true, parallel); + const auto max_token = type == executorch::aten::ScalarType::Int + ? static_cast(std::numeric_limits::max()) + : static_cast(std::numeric_limits::max()); + std::vector prompt{11, 12, 13, 14, max_token}; + int64_t position = 4; + int processed = 0; + EXPECT_CALL(text_decoder_runner_, token_input_scalar_type()) + .WillRepeatedly( + [type]() { return Result(type); }); + EXPECT_CALL(text_decoder_runner_, step(_, _)) + .Times(parallel ? 3 : 5) + .WillRepeatedly([&](executorch::extension::TensorPtr& tokens, + int64_t pos) { + const int length = parallel ? std::min(2, 5 - processed) : 1; + EXPECT_EQ(tokens->scalar_type(), type); + EXPECT_EQ(tokens->size(1), length); + EXPECT_EQ(pos, 4 + processed); + for (int i = 0; i < length; ++i) { + const int64_t value = type == executorch::aten::ScalarType::Int + ? tokens->const_data_ptr()[i] + : tokens->const_data_ptr()[i]; + EXPECT_EQ(value, prompt[processed + i]); + } + processed += length; + return Result(tensor); + }); + ASSERT_TRUE(prefiller->prefill(prompt, position).ok()); + EXPECT_EQ(processed, 5); + EXPECT_EQ(position, 9); + Mock::VerifyAndClearExpectations(&text_decoder_runner_); + } + } +} + +TEST_F(TextPrefillerTest, TokenOverflowDoesNotPartiallyUpdateCache) { + for (auto type : + {executorch::aten::ScalarType::Int, + executorch::aten::ScalarType::Long}) { + for (int chunk_size : {1, 3, 8}) { + for (bool parallel : {false, true}) { + for (int invalid_index : {0, 3, 6}) { + SCOPED_TRACE(static_cast(type)); + SCOPED_TRACE(chunk_size); + SCOPED_TRACE(parallel); + SCOPED_TRACE(invalid_index); + auto prefiller = createTextPrefiller(chunk_size, true, parallel); + std::vector prompt{11, 12, 13, 14, 15, 16, 17}; + prompt[invalid_index] = + (type == executorch::aten::ScalarType::Int + ? static_cast(std::numeric_limits::max()) + : static_cast( + std::numeric_limits::max())) + + 1; + int64_t position = 4; + EXPECT_CALL(text_decoder_runner_, token_input_scalar_type()) + .WillRepeatedly([type]() { + return Result(type); + }); + EXPECT_CALL(text_decoder_runner_, step(_, _)).Times(0); + EXPECT_EQ( + prefiller->prefill(prompt, position).error(), + Error::InvalidArgument); + EXPECT_EQ(position, 4); + Mock::VerifyAndClearExpectations(&text_decoder_runner_); + } + } + } + } +} + // Test that prefill() calls prefill_chunk() once when prompt tokens <= // max_seq_len TEST_F(TextPrefillerTest, PrefillCallsPrefillChunkOnceWhenPromptFits) { diff --git a/extension/llm/runner/text_decoder_runner.cpp b/extension/llm/runner/text_decoder_runner.cpp index 2b43a770842..8ea6b54e557 100644 --- a/extension/llm/runner/text_decoder_runner.cpp +++ b/extension/llm/runner/text_decoder_runner.cpp @@ -14,7 +14,6 @@ #include #include -#include #include @@ -39,6 +38,15 @@ TextDecoderRunner::TextDecoderRunner( stats_(stats), enable_dynamic_shape_(enable_dynamic_shape) {} +::executorch::runtime::Result +TextDecoderRunner::token_input_scalar_type() const { + auto method_meta = module_->method_meta(method_name_); + ET_CHECK_OK_OR_RETURN_ERROR(method_meta.error()); + auto input_meta = method_meta->input_tensor_meta(0); + ET_CHECK_OK_OR_RETURN_ERROR(input_meta.error()); + return input_meta->scalar_type(); +} + // 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 // outer loop (call site) is responsible for managing state. @@ -54,6 +62,15 @@ ::executorch::runtime::Result TextDecoderRunner::step( // If only 1 input, we are not using kv cache bool use_kv_cache = method_meta.num_inputs() > 1; + auto token_meta = method_meta.input_tensor_meta(0); + ET_CHECK_OK_OR_RETURN_ERROR(token_meta.error()); + ET_CHECK_OR_RETURN_ERROR( + (tokens->scalar_type() == aten::ScalarType::Int || + tokens->scalar_type() == aten::ScalarType::Long) && + tokens->scalar_type() == token_meta->scalar_type(), + InvalidArgument, + "Token input must match the model's INT32 or INT64 scalar type"); + std::vector cache_positions; if (use_kv_cache) { @@ -113,25 +130,14 @@ ::executorch::runtime::Result TextDecoderRunner::step( 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) { + TensorPtr model_tokens = tokens; + if (valid_length < input_length && + tokens->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]); - } + 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)); - } else { + } else if (valid_length < input_length) { std::vector padded(input_length, 0); const auto* data = tokens->const_data_ptr(); std::copy(data, data + valid_length, padded.begin()); diff --git a/extension/llm/runner/text_decoder_runner.h b/extension/llm/runner/text_decoder_runner.h index ee68a7015d2..de2a9c8e556 100644 --- a/extension/llm/runner/text_decoder_runner.h +++ b/extension/llm/runner/text_decoder_runner.h @@ -35,7 +35,7 @@ class ET_EXPERIMENTAL TextDecoderRunner { /** * Run LLM text decoder with inputs to generate next token. - * @param input The input to the LLM Module. + * @param input Token IDs in the model's INT32 or INT64 input type. * @param start_pos The starting position in KV cache of the input in the LLM * Module. * @return The output of the LLM Module. This will be a tensor of logits. @@ -44,6 +44,10 @@ class ET_EXPERIMENTAL TextDecoderRunner { TensorPtr& input, int64_t start_pos); + /// Return the scalar type of the model's token input (input 0). + virtual ::executorch::runtime::Result + token_input_scalar_type() const; + /** * Load the Module for text decode purpose. * @return The error code. diff --git a/extension/llm/runner/text_prefiller.cpp b/extension/llm/runner/text_prefiller.cpp index a3bfcced4c7..784c8206ed6 100644 --- a/extension/llm/runner/text_prefiller.cpp +++ b/extension/llm/runner/text_prefiller.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,6 +12,7 @@ #include #include +#include namespace executorch { namespace extension { @@ -51,6 +53,24 @@ ::executorch::runtime::Result TextPrefiller::prefill( // If prompt tokens exceed max_seq_len_, we need to chunk them if (num_prompt_tokens > max_seq_len_) { + // Reject invalid tokens before any earlier chunk can mutate the cache. + auto input_type = text_decoder_runner_->token_input_scalar_type(); + ET_CHECK_OK_OR_RETURN_ERROR(input_type.error()); + ET_CHECK_OR_RETURN_ERROR( + input_type.get() == executorch::aten::ScalarType::Int || + input_type.get() == executorch::aten::ScalarType::Long, + InvalidArgument, + "Token inputs must use INT32 or INT64"); + const auto max_token = input_type.get() == executorch::aten::ScalarType::Int + ? static_cast(std::numeric_limits::max()) + : static_cast(std::numeric_limits::max()); + ET_CHECK_OR_RETURN_ERROR( + std::all_of( + prompt_tokens.begin(), + prompt_tokens.end(), + [max_token](uint64_t token) { return token <= max_token; }), + InvalidArgument, + "Token ID does not fit the model's token input type"); uint64_t cur_token = 0; int num_tokens_to_process = 0; @@ -102,6 +122,35 @@ ::executorch::runtime::Result TextPrefiller::prefill_chunk( InvalidArgument, "Temperature must be in [0, 1], got %f", static_cast(temperature)); + ET_CHECK_OR_RETURN_ERROR( + !prompt_tokens.empty(), InvalidArgument, "Prompt cannot be empty"); + auto input_type = text_decoder_runner_->token_input_scalar_type(); + ET_CHECK_OK_OR_RETURN_ERROR(input_type.error()); + switch (input_type.get()) { + case executorch::aten::ScalarType::Int: + return prefill_chunk_impl(prompt_tokens, start_pos, temperature); + case executorch::aten::ScalarType::Long: + return prefill_chunk_impl(prompt_tokens, start_pos, temperature); + default: + ET_LOG(Error, "Token inputs must use INT32 or INT64"); + return ::executorch::runtime::Error::InvalidArgument; + } +} + +template +::executorch::runtime::Result TextPrefiller::prefill_chunk_impl( + const std::vector& prompt_tokens, + int64_t& start_pos, + float temperature) { + std::vector token_data; + token_data.reserve(prompt_tokens.size()); + for (uint64_t token : prompt_tokens) { + ET_CHECK_OR_RETURN_ERROR( + token <= static_cast(std::numeric_limits::max()), + InvalidArgument, + "Token ID does not fit the model's token input type"); + token_data.push_back(static_cast(token)); + } // enable_parallel_prefill_ maybe set even when not using kv cache // When kv cache is not used, start pos is ignored int32_t num_prompt_tokens = prompt_tokens.size(); @@ -111,9 +160,9 @@ ::executorch::runtime::Result TextPrefiller::prefill_chunk( if (enable_parallel_prefill_ || !use_kv_cache_) { // initialize tensor wrappers auto tokens = from_blob( - prompt_tokens.data(), + token_data.data(), {1, num_prompt_tokens}, - executorch::aten::ScalarType::Long); + executorch::runtime::CppTypeToScalarType::value); auto outputs_res = text_decoder_runner_->step(tokens, start_pos); @@ -127,11 +176,13 @@ ::executorch::runtime::Result TextPrefiller::prefill_chunk( } else { // sequential prefill int64_t pos = 0; // position in the sequence // NOLINTNEXTLINE(facebook-hte-ParameterUncheckedArrayBounds) - cur_token = prompt_tokens[0]; + Token input_token = token_data[0]; // initialize tensor wrappers - auto tokens = - from_blob(&cur_token, {1, 1}, executorch::aten::ScalarType::Long); + auto tokens = from_blob( + &input_token, + {1, 1}, + executorch::runtime::CppTypeToScalarType::value); // run the first token and get back logits tensor. Assuming the first token // is bos so don't callback. @@ -147,7 +198,7 @@ ::executorch::runtime::Result TextPrefiller::prefill_chunk( while (pos < num_prompt_tokens) { // Run the model // NOLINTNEXTLINE(facebook-hte-ParameterUncheckedArrayBounds) - cur_token = prompt_tokens[pos]; + input_token = token_data[pos]; auto step_result = text_decoder_runner_->step(tokens, start_pos); if (!step_result.ok()) { diff --git a/extension/llm/runner/text_prefiller.h b/extension/llm/runner/text_prefiller.h index 9f032122349..3a456143d36 100644 --- a/extension/llm/runner/text_prefiller.h +++ b/extension/llm/runner/text_prefiller.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. @@ -87,6 +88,12 @@ class ET_EXPERIMENTAL TextPrefiller { } private: + template + ::executorch::runtime::Result prefill_chunk_impl( + const std::vector& prompt_tokens, + int64_t& start_pos, + float temperature); + /** * Note: TextPrefiller does not own the TextDecoderRunner instance. * The responsibility of managing the lifecycle of TextDecoderRunner diff --git a/extension/llm/runner/text_token_generator.h b/extension/llm/runner/text_token_generator.h index d64927f6559..6899b3ce189 100644 --- a/extension/llm/runner/text_token_generator.h +++ b/extension/llm/runner/text_token_generator.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. @@ -9,7 +10,9 @@ // Generate tokens in a loop. #pragma once +#include #include +#include #include #include @@ -93,36 +96,85 @@ class ET_EXPERIMENTAL TextTokenGenerator { InvalidArgument, "Temperature must be in [0, 1], got %f", static_cast(temperature)); - int64_t pos = start_pos; // position in the sequence + auto input_type = text_decoder_runner_->token_input_scalar_type(); + ET_CHECK_OK_OR_RETURN_ERROR(input_type.error()); + switch (input_type.get()) { + case executorch::aten::ScalarType::Int: + return generate_impl( + tokens, start_pos, max_new_tokens, temperature, token_callback); + case executorch::aten::ScalarType::Long: + return generate_impl( + tokens, start_pos, max_new_tokens, temperature, token_callback); + default: + ET_LOG(Error, "Token inputs must use INT32 or INT64"); + return ::executorch::runtime::Error::InvalidArgument; + } + } + + /** + * Stop the generation loop. + */ + inline void stop() { + should_stop_.store(true, std::memory_order_relaxed); + } + + /** + * Load the necessary resources for TextTokenGenerator. + * This method should be called before using the generate() method. + */ + ::executorch::runtime::Error load() { + return text_decoder_runner_->load(); + } - std::vector token_data; // allocate space for the tokens - std::vector token_shape; + /** + * Check if the TextTokenGenerator has been successfully loaded. + * @return True if the resources are loaded, false otherwise. + */ + bool inline is_loaded() const { + return tokenizer_->is_loaded() && text_decoder_runner_->is_method_loaded(); + } + + private: + template + ::executorch::runtime::Result generate_impl( + const std::vector& tokens, + int64_t start_pos, + int32_t max_new_tokens, + float temperature, + const std::function& token_callback) { + int64_t pos = start_pos; // position in the sequence // Token after prefill uint64_t cur_token = tokens.back(); uint64_t prev_token; - if (use_kv_cache_) { - // hard code these to size 1 as kv cache is locked to static size right - // now. - token_data = {cur_token}; - token_shape = {1, 1}; - } else { - token_data = tokens; - token_shape = {1, static_cast(tokens.size())}; - // Prevent reallocation that would invalidate from_blob's data pointer. - token_data.reserve(token_data.size() + max_new_tokens); + const auto token_count = use_kv_cache_ ? 1 : tokens.size(); + const auto capacity = + use_kv_cache_ ? 1 : token_count + std::max(max_new_tokens, 0); + std::vector token_data; + // Reserve before from_blob so appending tokens cannot invalidate its + // pointer. + token_data.reserve(capacity); + const auto begin = use_kv_cache_ ? tokens.end() - 1 : tokens.begin(); + for (auto it = begin; it != tokens.end(); ++it) { + ET_CHECK_OR_RETURN_ERROR( + *it <= static_cast(std::numeric_limits::max()), + InvalidArgument, + "Token ID does not fit the model's token input type"); + token_data.push_back(static_cast(*it)); } + std::vector token_shape{ + 1, static_cast(token_count)}; // Create tensor wrapper. For non-kv-cache, use max capacity shape so // numel_bound_ is large enough for subsequent resize_tensor_ptr calls, // then resize down to the actual token count. - auto max_shape = use_kv_cache_ - ? token_shape - : std::vector{ - 1, static_cast(tokens.size() + max_new_tokens)}; + std::vector max_shape{ + 1, static_cast(capacity)}; auto tokens_managed = from_blob( - token_data.data(), max_shape, executorch::aten::ScalarType::Long); + token_data.data(), + max_shape, + executorch::runtime::CppTypeToScalarType::value); if (!use_kv_cache_) { ET_CHECK_OK_OR_RETURN_ERROR( resize_tensor_ptr(tokens_managed, token_shape)); @@ -149,13 +201,17 @@ class ET_EXPERIMENTAL TextTokenGenerator { pos++; + ET_CHECK_OR_RETURN_ERROR( + cur_token <= static_cast(std::numeric_limits::max()), + InvalidArgument, + "Token ID does not fit the model's token input type"); if (use_kv_cache_) { // update the token tensor. token_data will not be empty. // NOLINTNEXTLINE(facebook-hte-LocalUncheckedArrayBounds) - token_data[0] = cur_token; + token_data[0] = static_cast(cur_token); } else { // push it to the back - token_data.push_back(cur_token); + token_data.push_back(static_cast(cur_token)); ET_CHECK_OK_OR_RETURN_ERROR(resize_tensor_ptr( tokens_managed, {1, static_cast(token_data.size())})); } @@ -185,31 +241,6 @@ class ET_EXPERIMENTAL TextTokenGenerator { return pos - start_pos; } - /** - * Stop the generation loop. - */ - inline void stop() { - should_stop_.store(true, std::memory_order_relaxed); - } - - /** - * Load the necessary resources for TextTokenGenerator. - * This method should be called before using the generate() method. - */ - ::executorch::runtime::Error load() { - return text_decoder_runner_->load(); - } - - /** - * Check if the TextTokenGenerator has been successfully loaded. - * @return True if the resources are loaded, false otherwise. - */ - bool inline is_loaded() const { - // Implementation to check if resources are loaded - return tokenizer_->is_loaded() && text_decoder_runner_->is_method_loaded(); - } - - private: /** * Note: TextTokenGenerator does not own the tokenizer_ and * text_decoder_runner_. The lifecycle of these objects should be managed diff --git a/extension/llm/runner/util.h b/extension/llm/runner/util.h index 4f7f9eb5142..4c011bc3775 100644 --- a/extension/llm/runner/util.h +++ b/extension/llm/runner/util.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. @@ -15,6 +16,7 @@ #include #include #include +#include #include #include #if defined(__linux__) || defined(__ANDROID__) || defined(__unix__) @@ -293,6 +295,21 @@ inline runtime::Result populate_start_pos_or_cache_position( auto second_input_sizes = second_input_info.sizes(); auto numel = second_input_sizes[0]; + if (second_input_info.scalar_type() == executorch::aten::ScalarType::Int) { + const int count = numel > 1 ? seq_len : 1; + ET_CHECK_OR_RETURN_ERROR( + count > 0 && start_pos >= 0 && + start_pos <= std::numeric_limits::max() - (count - 1), + InvalidArgument, + "Cache positions cannot be represented as int32"); + std::vector positions(count); + for (int i = 0; i < count; ++i) { + positions[i] = static_cast(start_pos + i); + } + return ::executorch::extension::make_tensor_ptr( + {count}, std::move(positions)); + } + TensorPtr start_pos_tensor; if (numel > 1) { // `cache_position` goes from start_pos to start_pos +