From 5fa8c6cf9aa0fa650a0e09f35269f6422bdafa0a Mon Sep 17 00:00:00 2001 From: Digant Desai Date: Mon, 10 Aug 2026 04:08:03 -0700 Subject: [PATCH] Add Muse Glimmer 30B ExecuTorch example Export and runtime support for Muse Glimmer 30B on the CUDA and MLX backends, covering text, vision, DFlash speculative decoding, and OpenAI-compatible serving. Authored with AI assistance (Codex, Claude Code). --- .gitignore | 10 + .lintrunner.toml | 3 + backends/cuda/runtime/cuda_mutable_state.cpp | 15 +- .../runtime/test/test_cuda_mutable_state.cpp | 9 +- examples/models/muse-glimmer/.gitignore | 2 + examples/models/muse-glimmer/CMakeLists.txt | 188 ++ .../models/muse-glimmer/CMakePresets.json | 83 + examples/models/muse-glimmer/README.md | 189 ++ examples/models/muse-glimmer/__init__.py | 13 + .../models/muse-glimmer/export/__init__.py | 5 + examples/models/muse-glimmer/export/common.py | 169 ++ .../muse-glimmer/export/export_dflash.py | 806 +++++++ .../models/muse-glimmer/export/export_solo.py | 692 ++++++ examples/models/muse-glimmer/inference.py | 356 +++ .../models/muse-glimmer/loaders/__init__.py | 5 + .../muse-glimmer/loaders/checkpoint_loader.py | 759 ++++++ .../muse-glimmer/loaders/dflash_loader.py | 203 ++ .../muse-glimmer/loaders/quantize_and_save.py | 199 ++ .../models/muse-glimmer/model/__init__.py | 5 + .../models/muse-glimmer/model/dflash_model.py | 467 ++++ examples/models/muse-glimmer/model/model.py | 955 ++++++++ .../models/muse-glimmer/model/vision_tower.py | 197 ++ .../runtime/engine/dflash_session.cpp | 1317 +++++++++++ .../runtime/engine/dflash_session.h | 71 + .../runtime/engine/dflash_timing.h | 77 + .../runtime/engine/muse_glimmer_engine.cpp | 1635 +++++++++++++ .../runtime/engine/muse_glimmer_engine.h | 213 ++ .../engine/muse_glimmer_vision_runtime.cpp | 459 ++++ .../engine/muse_glimmer_vision_runtime.h | 74 + .../muse-glimmer/runtime/engine/sampling.h | 524 +++++ .../muse-glimmer/runtime/runners/dflash.cpp | 496 ++++ .../runtime/runners/muse_glimmer_worker.cpp | 312 +++ .../muse-glimmer/runtime/runners/solo.cpp | 2059 +++++++++++++++++ .../models/muse-glimmer/serving/__init__.py | 5 + examples/models/muse-glimmer/serving/serve.py | 507 ++++ .../serving/tool_parsers/__init__.py | 11 + .../muse-glimmer/serving/tool_parsers/atem.py | 185 ++ .../source_transformations/__init__.py | 5 + .../source_transformations/cuda.py | 930 ++++++++ .../source_transformations/mlx.py | 563 +++++ .../source_transformations/sampler.py | 39 + .../models/muse-glimmer/tests/__init__.py | 5 + .../tests/data/prompt_golden.json | 378 +++ .../muse-glimmer/tests/dflash_timing_test.cpp | 96 + .../muse-glimmer/tests/gen_prompt_golden.py | 82 + .../muse-glimmer/tests/gen_resize_golden.py | 46 + .../models/muse-glimmer/tests/prompt_cases.py | 193 ++ .../muse-glimmer/tests/sampling_test.cpp | 379 +++ .../tests/scripts/test_multisession.sh | 246 ++ .../tests/scripts/test_multisession_buck.sh | 15 + .../tests/test_atem_tool_parser.py | 404 ++++ .../test_benchmark_dflash_long_context.py | 174 ++ .../muse-glimmer/tests/test_cuda_pipeline.py | 354 +++ .../muse-glimmer/tests/test_export_dflash.py | 51 + .../muse-glimmer/tests/test_mlx_pipeline.py | 216 ++ .../tests/test_ondevice_serving.py | 62 + .../muse-glimmer/tests/test_pipeline.py | 1235 ++++++++++ .../muse-glimmer/tests/test_prompt_tokens.py | 365 +++ .../models/muse-glimmer/tests/test_serve.py | 575 +++++ .../tests/test_vision_precompute.py | 272 +++ .../muse-glimmer/tests/test_vision_tower.py | 235 ++ .../tests/vision_grid_parity_test.cpp | 117 + .../tests/vision_resize_parity_test.cpp | 116 + .../models/muse-glimmer/vision/__init__.py | 5 + .../models/muse-glimmer/vision/precompute.py | 297 +++ .../models/muse-glimmer/vision/preprocess.h | 709 ++++++ examples/models/muse_glimmer | 1 + 67 files changed, 21435 insertions(+), 5 deletions(-) create mode 100644 examples/models/muse-glimmer/.gitignore create mode 100644 examples/models/muse-glimmer/CMakeLists.txt create mode 100644 examples/models/muse-glimmer/CMakePresets.json create mode 100644 examples/models/muse-glimmer/README.md create mode 100644 examples/models/muse-glimmer/__init__.py create mode 100644 examples/models/muse-glimmer/export/__init__.py create mode 100644 examples/models/muse-glimmer/export/common.py create mode 100644 examples/models/muse-glimmer/export/export_dflash.py create mode 100644 examples/models/muse-glimmer/export/export_solo.py create mode 100644 examples/models/muse-glimmer/inference.py create mode 100644 examples/models/muse-glimmer/loaders/__init__.py create mode 100644 examples/models/muse-glimmer/loaders/checkpoint_loader.py create mode 100644 examples/models/muse-glimmer/loaders/dflash_loader.py create mode 100644 examples/models/muse-glimmer/loaders/quantize_and_save.py create mode 100644 examples/models/muse-glimmer/model/__init__.py create mode 100644 examples/models/muse-glimmer/model/dflash_model.py create mode 100644 examples/models/muse-glimmer/model/model.py create mode 100644 examples/models/muse-glimmer/model/vision_tower.py create mode 100644 examples/models/muse-glimmer/runtime/engine/dflash_session.cpp create mode 100644 examples/models/muse-glimmer/runtime/engine/dflash_session.h create mode 100644 examples/models/muse-glimmer/runtime/engine/dflash_timing.h create mode 100644 examples/models/muse-glimmer/runtime/engine/muse_glimmer_engine.cpp create mode 100644 examples/models/muse-glimmer/runtime/engine/muse_glimmer_engine.h create mode 100644 examples/models/muse-glimmer/runtime/engine/muse_glimmer_vision_runtime.cpp create mode 100644 examples/models/muse-glimmer/runtime/engine/muse_glimmer_vision_runtime.h create mode 100644 examples/models/muse-glimmer/runtime/engine/sampling.h create mode 100644 examples/models/muse-glimmer/runtime/runners/dflash.cpp create mode 100644 examples/models/muse-glimmer/runtime/runners/muse_glimmer_worker.cpp create mode 100644 examples/models/muse-glimmer/runtime/runners/solo.cpp create mode 100644 examples/models/muse-glimmer/serving/__init__.py create mode 100644 examples/models/muse-glimmer/serving/serve.py create mode 100644 examples/models/muse-glimmer/serving/tool_parsers/__init__.py create mode 100644 examples/models/muse-glimmer/serving/tool_parsers/atem.py create mode 100644 examples/models/muse-glimmer/source_transformations/__init__.py create mode 100644 examples/models/muse-glimmer/source_transformations/cuda.py create mode 100644 examples/models/muse-glimmer/source_transformations/mlx.py create mode 100644 examples/models/muse-glimmer/source_transformations/sampler.py create mode 100644 examples/models/muse-glimmer/tests/__init__.py create mode 100644 examples/models/muse-glimmer/tests/data/prompt_golden.json create mode 100644 examples/models/muse-glimmer/tests/dflash_timing_test.cpp create mode 100644 examples/models/muse-glimmer/tests/gen_prompt_golden.py create mode 100644 examples/models/muse-glimmer/tests/gen_resize_golden.py create mode 100644 examples/models/muse-glimmer/tests/prompt_cases.py create mode 100644 examples/models/muse-glimmer/tests/sampling_test.cpp create mode 100755 examples/models/muse-glimmer/tests/scripts/test_multisession.sh create mode 100755 examples/models/muse-glimmer/tests/scripts/test_multisession_buck.sh create mode 100644 examples/models/muse-glimmer/tests/test_atem_tool_parser.py create mode 100644 examples/models/muse-glimmer/tests/test_benchmark_dflash_long_context.py create mode 100644 examples/models/muse-glimmer/tests/test_cuda_pipeline.py create mode 100644 examples/models/muse-glimmer/tests/test_export_dflash.py create mode 100644 examples/models/muse-glimmer/tests/test_mlx_pipeline.py create mode 100644 examples/models/muse-glimmer/tests/test_ondevice_serving.py create mode 100644 examples/models/muse-glimmer/tests/test_pipeline.py create mode 100644 examples/models/muse-glimmer/tests/test_prompt_tokens.py create mode 100644 examples/models/muse-glimmer/tests/test_serve.py create mode 100644 examples/models/muse-glimmer/tests/test_vision_precompute.py create mode 100644 examples/models/muse-glimmer/tests/test_vision_tower.py create mode 100644 examples/models/muse-glimmer/tests/vision_grid_parity_test.cpp create mode 100644 examples/models/muse-glimmer/tests/vision_resize_parity_test.cpp create mode 100644 examples/models/muse-glimmer/vision/__init__.py create mode 100644 examples/models/muse-glimmer/vision/precompute.py create mode 100644 examples/models/muse-glimmer/vision/preprocess.h create mode 120000 examples/models/muse_glimmer diff --git a/.gitignore b/.gitignore index 46864c05417..aa28c9663e1 100644 --- a/.gitignore +++ b/.gitignore @@ -24,6 +24,16 @@ build-direct/ dist/ arm-scratch/ executorch.egg-info + +# MLX delegate code generated in-tree from backends/mlx/serialization/schema.fbs +# by generate.py, which the MLX backend runs at build time. +backends/mlx/_generated_inspector.py +backends/mlx/runtime/MLXLoader.cpp +backends/mlx/runtime/MLXLoader.h +backends/mlx/runtime/schema_generated.h +backends/mlx/serialization/_generated/ +backends/mlx/serialization/_generated_serializers.py +backends/mlx/serialization/mlx_graph_schema.py pip-out/ build-profiling/ **/ddr_*_temp diff --git a/.lintrunner.toml b/.lintrunner.toml index 2ca0c0fd394..75713e47f13 100644 --- a/.lintrunner.toml +++ b/.lintrunner.toml @@ -390,6 +390,9 @@ exclude_patterns = [ 'extension/llm/tokenizers', 'extension/llm/tokenizers/**', 'examples/llm_server', + # muse_glimmer is a symlink to this directory; the linter resolves it and + # then fails on a directory. + 'examples/models/muse-glimmer', 'backends/cadence/utils/FACTO', 'examples/cuda', 'examples/qualcomm', diff --git a/backends/cuda/runtime/cuda_mutable_state.cpp b/backends/cuda/runtime/cuda_mutable_state.cpp index 3438bd5b453..dfaef56aabb 100644 --- a/backends/cuda/runtime/cuda_mutable_state.cpp +++ b/backends/cuda/runtime/cuda_mutable_state.cpp @@ -642,10 +642,17 @@ Error mutable_state_rebind_for_execute(CudaDelegateHandle* handle) { return Error::Ok; } auto cit = m.contexts.find(hit->second); - if (cit != m.contexts.end() && - (!cit->second.sessions.empty() || - cit->second.rebound_handles.find(handle) != - cit->second.rebound_handles.end())) { + if (cit != m.contexts.end()) { + const auto desc = cit->second.desc.find(handle); + const bool known_stateless = + desc != cit->second.desc.end() && desc->second.empty(); + const bool requires_active_session = + (!known_stateless && !cit->second.sessions.empty()) || + cit->second.rebound_handles.find(handle) != + cit->second.rebound_handles.end(); + if (!requires_active_session) { + return Error::Ok; + } ET_LOG( Error, "mutable_state: active session is required for this handle"); return Error::InvalidState; diff --git a/backends/cuda/runtime/test/test_cuda_mutable_state.cpp b/backends/cuda/runtime/test/test_cuda_mutable_state.cpp index c7392e5dd55..89ac02dda38 100644 --- a/backends/cuda/runtime/test/test_cuda_mutable_state.cpp +++ b/backends/cuda/runtime/test/test_cuda_mutable_state.cpp @@ -371,11 +371,17 @@ TEST(CudaMutableStateTest, CapturesClonesAndRebindsDeviceBuffer) { container.fqns = {"model.state"}; container.extracted["model.state"] = reinterpret_cast(source_tensor.get()); + FakeContainer stateless_container; cu::CudaDelegateHandle handle = fake_container_handle(&container); + cu::CudaDelegateHandle stateless_handle = + fake_container_handle(&stateless_container); cu::MutableStateContextOwner c; c.register_fqns({"model.state"}); - c.with_load_scope([&] { cu::mutable_state_note_handle(&handle); }); + c.with_load_scope([&] { + cu::mutable_state_note_handle(&handle); + cu::mutable_state_note_handle(&stateless_handle); + }); ASSERT_TRUE(c.available()); EXPECT_EQ(c.bytes_per_session(), 4 * sizeof(float)); @@ -387,6 +393,7 @@ TEST(CudaMutableStateTest, CapturesClonesAndRebindsDeviceBuffer) { auto token = c.create_session(); ASSERT_TRUE(token.ok()); + EXPECT_EQ(cu::mutable_state_rebind_for_execute(&stateless_handle), Error::Ok); EXPECT_EQ(cu::mutable_state_rebind_for_execute(&handle), Error::InvalidState); ASSERT_EQ( diff --git a/examples/models/muse-glimmer/.gitignore b/examples/models/muse-glimmer/.gitignore new file mode 100644 index 00000000000..7a60b85e148 --- /dev/null +++ b/examples/models/muse-glimmer/.gitignore @@ -0,0 +1,2 @@ +__pycache__/ +*.pyc diff --git a/examples/models/muse-glimmer/CMakeLists.txt b/examples/models/muse-glimmer/CMakeLists.txt new file mode 100644 index 00000000000..57562031e56 --- /dev/null +++ b/examples/models/muse-glimmer/CMakeLists.txt @@ -0,0 +1,188 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +cmake_minimum_required(VERSION 3.24) +project(muse_glimmer) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +if(DEFINED ENV{CONDA_PREFIX} AND EXISTS "$ENV{CONDA_PREFIX}/lib") + list(PREPEND CMAKE_BUILD_RPATH "$ENV{CONDA_PREFIX}/lib") +endif() + +set(EXECUTORCH_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../../..) + +include(${EXECUTORCH_ROOT}/tools/cmake/Utils.cmake) + +set(_common_include_directories ${EXECUTORCH_ROOT}/..) +set(_json_include + ${EXECUTORCH_ROOT}/extension/llm/tokenizers/third-party/json/single_include +) + +# gflags +set(gflags_DIR ${EXECUTORCH_ROOT}/cmake-out/third-party/gflags) +find_package(gflags REQUIRED) + +# executorch +list(APPEND CMAKE_FIND_ROOT_PATH ${CMAKE_CURRENT_BINARY_DIR}/../../../..) +find_package(executorch CONFIG REQUIRED FIND_ROOT_PATH_BOTH) +executorch_target_link_options_shared_lib(executorch) + +set(link_libraries executorch gflags) + +# CPU ops (for host-side helpers not delegated to CUDA) +list(APPEND link_libraries optimized_native_cpu_ops_lib cpublas eigen_blas) +executorch_target_link_options_shared_lib(optimized_native_cpu_ops_lib) + +# Extensions +list( + APPEND + link_libraries + extension_llm_runner + extension_module + extension_data_loader + extension_tensor + extension_flat_tensor +) + +# Backend: CUDA or MLX (exactly one required) +if(EXECUTORCH_BUILD_CUDA) + find_package(CUDAToolkit REQUIRED) + list(APPEND link_libraries aoti_cuda_backend) + executorch_target_link_options_shared_lib(aoti_cuda_backend) + add_compile_definitions(EXECUTORCH_BUILD_CUDA) +elseif(TARGET mlxdelegate) + list(APPEND link_libraries mlxdelegate mlx) + executorch_target_link_options_shared_lib(mlxdelegate) + add_compile_definitions(EXECUTORCH_BUILD_MLX) +else() + message(FATAL_ERROR "Set EXECUTORCH_BUILD_CUDA=ON or EXECUTORCH_BUILD_MLX=ON") +endif() + +# Use a supplied or local stb checkout before fetching it. The resize header is +# under deprecated/ in the pinned revision. +if(EXECUTORCH_BUILD_CUDA OR TARGET mlxdelegate) + if(NOT MUSE_GLIMMER_STB_INCLUDE_DIR + AND EXISTS "${EXECUTORCH_ROOT}/third-party/stb/stb_image.h" + ) + set(MUSE_GLIMMER_STB_INCLUDE_DIR "${EXECUTORCH_ROOT}/third-party/stb") + endif() + if(MUSE_GLIMMER_STB_INCLUDE_DIR + AND EXISTS "${MUSE_GLIMMER_STB_INCLUDE_DIR}/stb_image.h" + ) + message( + STATUS "Using local stb headers from: ${MUSE_GLIMMER_STB_INCLUDE_DIR}" + ) + list(APPEND _common_include_directories ${MUSE_GLIMMER_STB_INCLUDE_DIR} + ${MUSE_GLIMMER_STB_INCLUDE_DIR}/deprecated + ) + else() + include(FetchContent) + FetchContent_Declare( + stb + GIT_REPOSITORY https://github.com/nothings/stb.git + GIT_TAG f0569113c93ad095470c54bf34a17b36646bbbb5 + ) + FetchContent_MakeAvailable(stb) + list(APPEND _common_include_directories ${stb_SOURCE_DIR} + ${stb_SOURCE_DIR}/deprecated + ) + endif() +endif() + +# Tokenizer (tiktoken via pytorch/tokenizers) +list(APPEND link_libraries tokenizers::tokenizers) + +add_executable( + solo_runner runtime/runners/solo.cpp runtime/engine/muse_glimmer_engine.cpp + runtime/engine/dflash_session.cpp +) +if(EXECUTORCH_BUILD_CUDA OR TARGET mlxdelegate) + target_sources( + solo_runner PRIVATE runtime/engine/muse_glimmer_vision_runtime.cpp + ) +endif() +target_include_directories( + solo_runner PUBLIC ${_common_include_directories} ${_json_include} +) +target_link_libraries(solo_runner PUBLIC ${link_libraries}) + +# Export symbols required by the dynamically loaded AOTI CUDA blob. +if(EXECUTORCH_BUILD_CUDA + AND NOT APPLE + AND NOT MSVC +) + target_link_options(solo_runner PRIVATE "LINKER:--export-dynamic") +endif() + +add_executable( + dflash_runner + runtime/runners/dflash.cpp runtime/engine/muse_glimmer_engine.cpp + runtime/engine/dflash_session.cpp +) +if(EXECUTORCH_BUILD_CUDA OR TARGET mlxdelegate) + target_sources( + dflash_runner PRIVATE runtime/engine/muse_glimmer_vision_runtime.cpp + ) +endif() +target_include_directories( + dflash_runner PUBLIC ${_common_include_directories} ${_json_include} +) +target_link_libraries(dflash_runner PUBLIC ${link_libraries}) + +add_executable(sampling_test tests/sampling_test.cpp) +target_include_directories(sampling_test PUBLIC ${_common_include_directories}) +target_link_libraries(sampling_test PUBLIC extension_tensor executorch) + +add_executable(dflash_timing_test tests/dflash_timing_test.cpp) +target_include_directories( + dflash_timing_test PUBLIC ${_common_include_directories} +) + +# Worker used by the OpenAI-compatible serving harness. +add_executable( + muse_glimmer_worker + runtime/runners/muse_glimmer_worker.cpp + runtime/engine/muse_glimmer_engine.cpp runtime/engine/dflash_session.cpp +) +if(EXECUTORCH_BUILD_CUDA OR TARGET mlxdelegate) + target_sources( + muse_glimmer_worker PRIVATE runtime/engine/muse_glimmer_vision_runtime.cpp + ) +endif() +target_include_directories( + muse_glimmer_worker PUBLIC ${_common_include_directories} ${_json_include} +) +target_link_libraries(muse_glimmer_worker PUBLIC ${link_libraries}) + +if(EXECUTORCH_BUILD_CUDA + AND NOT APPLE + AND NOT MSVC +) + target_link_options(dflash_runner PRIVATE "LINKER:--export-dynamic") + target_link_options(muse_glimmer_worker PRIVATE "LINKER:--export-dynamic") +endif() + +if(NOT CMAKE_BUILD_TYPE STREQUAL "Debug") + target_link_options_gc_sections(solo_runner) + target_link_options_gc_sections(dflash_runner) + target_link_options_gc_sections(muse_glimmer_worker) + if(NOT APPLE AND NOT MSVC) + # CUDA AOTI blobs resolve symbols from the host executable. + if(NOT EXECUTORCH_BUILD_CUDA) + target_link_options(solo_runner PRIVATE "LINKER:-s") + target_link_options(dflash_runner PRIVATE "LINKER:-s") + target_link_options(muse_glimmer_worker PRIVATE "LINKER:-s") + endif() + endif() +endif() + +if(TARGET mlxdelegate) + executorch_target_copy_mlx_metallib(solo_runner) + executorch_target_copy_mlx_metallib(dflash_runner) + executorch_target_copy_mlx_metallib(muse_glimmer_worker) +endif() diff --git a/examples/models/muse-glimmer/CMakePresets.json b/examples/models/muse-glimmer/CMakePresets.json new file mode 100644 index 00000000000..ab186e6001d --- /dev/null +++ b/examples/models/muse-glimmer/CMakePresets.json @@ -0,0 +1,83 @@ +{ + "version": 6, + "configurePresets": [ + { + "name": "muse-glimmer-base", + "hidden": true, + "binaryDir": "${sourceDir}/../../../cmake-out/examples/models/muse-glimmer", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Release", + "CMAKE_FIND_ROOT_PATH": "${sourceDir}/../../../cmake-out", + "CMAKE_PREFIX_PATH": "${sourceDir}/../../../cmake-out" + } + }, + { + "name": "muse-glimmer-cuda", + "displayName": "Muse Glimmer runner (CUDA)", + "inherits": ["muse-glimmer-base"], + "cacheVariables": { + "EXECUTORCH_BUILD_CUDA": "ON" + }, + "condition": { + "type": "inList", + "string": "${hostSystemName}", + "list": ["Linux", "Windows"] + } + }, + { + "name": "muse-glimmer-mlx", + "displayName": "Muse Glimmer runner (MLX)", + "inherits": ["muse-glimmer-base"], + "cacheVariables": {}, + "condition": { + "type": "equals", + "lhs": "${hostSystemName}", + "rhs": "Darwin" + } + } + ], + "buildPresets": [ + { + "name": "muse-glimmer-cuda", + "displayName": "Build Muse Glimmer runner (CUDA)", + "configurePreset": "muse-glimmer-cuda", + "targets": ["solo_runner", "dflash_runner", "muse_glimmer_worker"] + }, + { + "name": "muse-glimmer-mlx", + "displayName": "Build Muse Glimmer runner (MLX)", + "configurePreset": "muse-glimmer-mlx", + "targets": ["solo_runner", "dflash_runner", "muse_glimmer_worker"] + } + ], + "workflowPresets": [ + { + "name": "muse-glimmer-cuda", + "displayName": "Configure and build Muse Glimmer runner (CUDA)", + "steps": [ + { + "type": "configure", + "name": "muse-glimmer-cuda" + }, + { + "type": "build", + "name": "muse-glimmer-cuda" + } + ] + }, + { + "name": "muse-glimmer-mlx", + "displayName": "Configure and build Muse Glimmer runner (MLX)", + "steps": [ + { + "type": "configure", + "name": "muse-glimmer-mlx" + }, + { + "type": "build", + "name": "muse-glimmer-mlx" + } + ] + } + ] +} diff --git a/examples/models/muse-glimmer/README.md b/examples/models/muse-glimmer/README.md new file mode 100644 index 00000000000..abc9dcfa074 --- /dev/null +++ b/examples/models/muse-glimmer/README.md @@ -0,0 +1,189 @@ +# Muse Glimmer 30B + +ExecuTorch export and runtime support for Muse Glimmer 30B, including text, +vision, DFlash speculative decoding, and OpenAI-compatible serving. Quantized +GGUF checkpoints are the recommended starting point and lower directly to the +selected ExecuTorch backend. + +## Supported backends + +| Backend | Host | Exported artifacts | +|---|---|---| +| CUDA | Linux or Windows | `model.pte` plus `aoti_cuda_blob.ptd` | +| MLX | macOS on Apple silicon | Self-contained `model.pte` | + +CPU export is not supported. For general environment setup, follow the +[ExecuTorch README](../../../README.md) and +[build-from-source guide](../../../docs/source/using-executorch-building-from-source.md). + +## Model assets + +Download the GGUF checkpoints and Hugging Face tokenizer metadata from the +[`meta-models/Muse-Glimmer-30B-GGUF`](https://huggingface.co/meta-models/Muse-Glimmer-30B-GGUF) +and [`meta-models/Muse-Glimmer-30B`](https://huggingface.co/meta-models/Muse-Glimmer-30B), +respectively. Run from the ExecuTorch repository root: + +```bash +GGUF_REPO=meta-models/Muse-Glimmer-30B-GGUF +HF_REPO=meta-models/Muse-Glimmer-30B + +hf download "$GGUF_REPO" \ + --include '*.gguf' \ + --exclude '*[Bb][Ff]16*.gguf' \ + --local-dir assets/quant + +hf download "$HF_REPO" \ + tokenizer.json tokenizer_config.json chat_template.jinja \ + --local-dir assets/hf +``` + +The canonical `chat_template.jinja` must remain beside the tokenizer metadata; +the serving path uses it to render prompts and tools. + +### GGUF checkpoints + +| File | Use | +|---|---| +| `muse-glimmer-30B-kquant-17gb.gguf` | Recommended target checkpoint | +| `muse-glimmer-30B-kquant-dynamic.gguf` | Dynamic K-quant target checkpoint | +| `mmproj-kquant.gguf` | Optional vision projector | +| `dflash-kquant.gguf` | Optional DFlash draft checkpoint | + +Set paths once for the commands below: + +```bash +TARGET="$(find assets/quant -type f -name 'muse-glimmer-30B-kquant-17gb.gguf' -print -quit)" +DRAFT="$(find assets/quant -type f -name 'dflash-kquant.gguf' -print -quit)" +MMPROJ="$(find assets/quant -type f -name 'mmproj-kquant.gguf' -print -quit)" +BACKEND=cuda # use mlx on macOS +``` + +### Prebuilt PTE artifacts + +Ready-to-run exports for Apple silicon and NVIDIA GPUs are published in +[`meta-models/Muse-Glimmer-30B-ExecuTorch-PTE`](https://huggingface.co/meta-models/Muse-Glimmer-30B-ExecuTorch-PTE). +Each subdirectory is one export, named after its quantization, context length, +modalities, decoding mode (`solo` or `dflash`), and target hardware, for example +`muse_glimmer_k_quant_17G_128K_text_solo_metal`. Browse the repository, pick the +subdirectory that matches your setup, and download only that one: + +```bash +EXPORT_DIR= + +hf download meta-models/Muse-Glimmer-30B-ExecuTorch-PTE \ + --include "$EXPORT_DIR/*" \ + --local-dir exports +``` + +The repository holds many exports, so avoid downloading it in full. + +With a prebuilt export, skip the [Export](#export) section and use +`exports/$EXPORT_DIR` as the artifact directory in the sections below. + +## Export + +Run exports from the ExecuTorch repository root. + +Target model: + +```bash +python -m executorch.examples.models.muse_glimmer.export.export_solo \ + --gguf "$TARGET" \ + --backend "$BACKEND" \ + --output-dir exports/solo +``` + +DFlash: + +```bash +python -m executorch.examples.models.muse_glimmer.export.export_dflash \ + --target-gguf "$TARGET" \ + --draft-gguf "$DRAFT" \ + --backend "$BACKEND" \ + --output-dir exports/dflash +``` + +Add `--mmproj "$MMPROJ"` to either command to include the vision encoder. A +vision export also writes `pos_embed.bin` beside `model.pte`. + +The quick download excludes BF16 GGUFs, but they remain supported inputs. For a +custom local quantization, `export_solo` also accepts a consolidated BF16 +checkpoint with `--checkpoint-dir` and a recipe selected by `--quant-recipe`. +Prequantized and MLX-affine checkpoints are available through `--prequantized` +and `--mlx`. Run the export modules with `--help` for the supported recipes and +advanced inputs. + +### Exported methods + +| Export | Backend | Methods | +|---|---|---| +| Target | CUDA | `embed_text`, `forward_from_embeddings`, `decode_from_embedding` | +| Target | MLX | `embed_text`, `forward_from_embeddings` | +| DFlash | CUDA | `target_forward_from_embeddings`, `target_prefill_from_embeddings`, `embed_text`, `draft_forward`, `draft_prefill` | +| DFlash | MLX | `target_forward_from_embeddings`, `embed_text`, `draft_forward` | + +Vision adds `vision_encoder` to each method set. + +## Build the runners + +Use the model-specific CMake workflow preset for the selected backend: + +```bash +# CUDA +(cd examples/models/muse-glimmer && \ + cmake --workflow --preset muse-glimmer-cuda) + +# MLX +(cd examples/models/muse-glimmer && \ + cmake --workflow --preset muse-glimmer-mlx) +``` + +The binaries are written to `cmake-out/examples/models/muse-glimmer/`: + +- `solo_runner` +- `dflash_runner` +- `muse_glimmer_worker` + +Run a binary with `--help` for its model-specific arguments. + +## Serve + +Install the shared server dependencies: + +```bash +pip install -r examples/llm_server/python/requirements.txt +``` + +Serve a CUDA target export: + +```bash +python -m executorch.examples.models.muse_glimmer.serving.serve \ + --model-path exports/solo/model.pte \ + --data-path exports/solo/aoti_cuda_blob.ptd \ + --tokenizer-path assets/hf/tokenizer.json \ + --hf-tokenizer assets/hf \ + --worker-bin cmake-out/examples/models/muse-glimmer/muse_glimmer_worker \ + --model-id muse-glimmer-30B \ + --tool-parser atem \ + --host 127.0.0.1 \ + --port 8000 +``` + +For MLX, use the MLX `model.pte` and omit `--data-path`. For DFlash, replace +`exports/solo` with `exports/dflash` in both artifact paths; the server detects +the exported method contract. For vision, also pass +`--pos-embed-path /pos_embed.bin`. + +Smoke test: + +```bash +curl http://127.0.0.1:8000/v1/chat/completions \ + -H 'Content-Type: application/json' \ + -d '{"model":"muse-glimmer-30B","messages":[{"role":"user","content":"What is the capital of France?"}],"max_tokens":32,"temperature":0}' +``` + +Tool calling is supported with `--tool-parser atem`. The canonical Hugging Face +template renders tool definitions, and the server converts Muse Glimmer 30B ATEM +output into OpenAI-compatible `tool_calls`. See +[`serving/tool_parsers/atem.py`](serving/tool_parsers/atem.py) and +[`tests/test_atem_tool_parser.py`](tests/test_atem_tool_parser.py). diff --git a/examples/models/muse-glimmer/__init__.py b/examples/models/muse-glimmer/__init__.py new file mode 100644 index 00000000000..72d44f40763 --- /dev/null +++ b/examples/models/muse-glimmer/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +from executorch.examples.models.muse_glimmer.model.model import ( + materialize_runtime_buffers, + MuseGlimmerConfig, + MuseGlimmerModel, +) + +__all__ = ["MuseGlimmerConfig", "MuseGlimmerModel", "materialize_runtime_buffers"] diff --git a/examples/models/muse-glimmer/export/__init__.py b/examples/models/muse-glimmer/export/__init__.py new file mode 100644 index 00000000000..2e41cd717f6 --- /dev/null +++ b/examples/models/muse-glimmer/export/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. diff --git a/examples/models/muse-glimmer/export/common.py b/examples/models/muse-glimmer/export/common.py new file mode 100644 index 00000000000..fe87fb6f63b --- /dev/null +++ b/examples/models/muse-glimmer/export/common.py @@ -0,0 +1,169 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""Helpers shared by the solo and DFlash export paths.""" + +import json +import math +import os + +import torch +import torch.nn as nn + + +# CLI choice -> torch dtype for the activation compute path (and, for the MLX +# backend, the KV cache + unquantized weights/buffers). +ACTIVATION_DTYPES: dict[str, torch.dtype] = { + "bfloat16": torch.bfloat16, + "float16": torch.float16, +} + + +class BoundMethodForward: + """Context manager: temporarily set ``model.forward`` to a bound method. + + All exported methods live on the SAME model instance, so exporting each with + ``torch.export.export(model, ...)`` requires shadowing the class ``forward`` + with an instance-attribute bound method for the duration of the export. The + model's class identity never changes, so every ExportedProgram shares + identical mutable-buffer FQNs (``layers.X.self_attn.kv_cache.*``) and the + CUDA backend can unify the prefill/decode KV-cache buffers at runtime. + """ + + def __init__(self, model: nn.Module, bound_method) -> None: + self._model = model + self._bound = bound_method + + def __enter__(self): + self._model.forward = self._bound # instance-attr shadows class method + return self._model + + def __exit__(self, *exc): + try: + del self._model.forward + except AttributeError: + pass + return False + + +def mutable_buffer_metadata(model: nn.Module) -> str: + """JSON list of per-session mutable KV-cache buffer FQNs. + + The serving worker (muse_glimmer_engine) reads this via the ``get_mutable_buffer_metadata`` + constant method to bind each session's own KV cache, so one loaded model can + host multiple isolated conversations. Matches gemma4_31b's filter. + """ + mutable = [name for name, _ in model.named_buffers() if ".kv_cache." in name] + return json.dumps({"version": 1, "mutable_buffers": mutable}) + + +def activation_dtype_tag(dtype: torch.dtype) -> str: + """Canonical string tag recorded in the .pte as ``get_activation_dtype``.""" + return { + torch.bfloat16: "bfloat16", + torch.float16: "float16", + }[dtype] + + +def sample_vision_inputs( + pos_embed_table: torch.Tensor, + vision_config, + grid_side: int = 32, +): + """Build valid sample inputs for tracing ``vision_encoder``. + + Uses a zeros image of ``grid_side*patch`` px so the 9 host-precomputed + tensors have realistic shapes/values (valid permutations and masks) for a + strict-export trace. ``grid_side=32`` -> 1024 patches -> 256 soft tokens. + """ + from executorch.examples.models.muse_glimmer.vision.precompute import ( + precompute_vision_inputs, + ) + + px = grid_side * vision_config.patch_size + image = torch.zeros(3, px, px, dtype=torch.float32) + inputs = precompute_vision_inputs(image, pos_embed_table, vision_config) + return inputs.as_args() + + +def vision_sample_grid_side(max_patches: int, downsample_factor: int) -> int: + side = min(32, math.isqrt(max_patches)) + side -= side % downsample_factor + if side < downsample_factor: + raise ValueError( + "max_vision_patches must fit at least one downsampled patch group" + ) + return side + + +def export_vision_encoder( + vision_model: nn.Module, + pos_embed_table: torch.Tensor, + max_vision_patches: int, +): + """Export ``vision_encoder`` with num_patches dynamic across all 9 inputs. + + The dynamic-shape spec is positional, so it must stay in step with the + tensor order ``sample_vision_inputs`` produces. + """ + from torch.export import Dim, export + + vis_cfg = vision_model.config + ds2 = vis_cfg.downsample_factor**2 + max_groups = max(1, max_vision_patches // ds2) + num_patches = ds2 * Dim("vis_groups", min=1, max=max_groups) + + print(f"Exporting vision_encoder (P in [{ds2}, {ds2 * max_groups}])...") + vis_args = sample_vision_inputs( + pos_embed_table, + vis_cfg, + grid_side=vision_sample_grid_side( + max_vision_patches, vis_cfg.downsample_factor + ), + ) + # Shared dynamic num_patches across all vision inputs (masks use it on + # both the query and key axes). + vis_dynamic = ( + {1: num_patches}, # patches [1,P,1176] + {1: num_patches}, # pos_emb [1,P,1536] + {0: num_patches}, # cos_2d [P,48] + {0: num_patches}, # sin_2d [P,48] + {0: num_patches}, # sparse_perm [P] + {0: num_patches}, # inv_perm [P] + {2: num_patches, 3: num_patches}, # global_mask [1,1,P,P] + {2: num_patches, 3: num_patches}, # sparse_mask [1,1,P,P] + {0: num_patches}, # pixel_perm [P] + ) + with torch.no_grad(): + return export( + vision_model, + vis_args, + dynamic_shapes=vis_dynamic, + strict=True, + ) + + +def save_pte(et_program, output_dir: str, pos_embed_table: torch.Tensor | None) -> None: + """Write ``model.pte``, any ``.ptd`` tensor data, and the vision pos-embed table.""" + os.makedirs(output_dir, exist_ok=True) + pte_path = os.path.join(output_dir, "model.pte") + print(f"Saving to {pte_path}...") + with open(pte_path, "wb") as f: + et_program.write_to_file(f) + print(f" {os.path.getsize(pte_path) / 1024**2:.1f} MB") + + if et_program._tensor_data: + et_program.write_tensor_data_to_file(output_dir) + print(f" Saved tensor data (.ptd) to {output_dir}/") + + if pos_embed_table is not None: + # The 32x32 positional-embedding table is used by the runner for host + # grid_sample interpolation. Written as raw float32 [pos_tokens, latent]. + pe_path = os.path.join(output_dir, "pos_embed.bin") + pe = pos_embed_table.to(torch.float32).contiguous() + with open(pe_path, "wb") as f: + f.write(pe.numpy().tobytes()) + print(f" Saved vision pos-embed table ({tuple(pe.shape)} f32) to {pe_path}") diff --git a/examples/models/muse-glimmer/export/export_dflash.py b/examples/models/muse-glimmer/export/export_dflash.py new file mode 100644 index 00000000000..0a2c08d8689 --- /dev/null +++ b/examples/models/muse-glimmer/export/export_dflash.py @@ -0,0 +1,806 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""Export Muse Glimmer target and DFlash draft models to one ExecuTorch file. + +Target and draft inputs may be GGUF or MLX-affine checkpoints. The export +shares token embeddings and the output head; ``--mmproj`` adds vision. +""" + +from __future__ import annotations + +import argparse +import gc + +import torch + +from executorch.examples.models.muse_glimmer.export import common + + +def validate_dflash_export_options(backend: str) -> None: + if backend not in {"cuda", "mlx"}: + raise ValueError(f"Unsupported DFlash backend: {backend}") + + +def _share_graph_mutable_buffers(backend: str) -> bool: + # CUDA/AOTI lifts state into delegates and shares it by FQN at runtime. + # MLX keeps mutable state at the graph level and needs the shared arena. + return backend != "cuda" + + +def _embed_text_max_len( + backend: str, target_max_len: int, max_target_prefill: int +) -> int: + return max_target_prefill if backend == "cuda" else target_max_len + + +def _max_draft_prefill_len(draft_config, max_target_prefill: int) -> int: + if ( + draft_config.sliding_window + and draft_config.sliding_window_pattern is not None + and all(draft_config.sliding_window_pattern) + ): + return min(draft_config.sliding_window, max_target_prefill) + return max_target_prefill + + +def export_dflash( + output_dir: str, + target_gguf: str | None = None, + target_mlx: str | None = None, + draft_gguf: str | None = None, + draft_mlx: str | None = None, + max_seq_len: int = 131072, + activation_dtype: torch.dtype = torch.bfloat16, + backend: str = "mlx", + mmproj: str | None = None, + max_vision_patches: int = 16384, +) -> None: + """Export DFlash target + draft to one CUDA or MLX .pte. + + The target comes from either a GGUF (``target_gguf``) or an MLX + affine-quantized safetensors dir (``target_mlx``); the draft likewise from a + DFlash GGUF (``draft_gguf``) or an MLX affine-quantized dir (``draft_mlx``, + an mlx_lm.convert output dir). Exactly one of each pair must be given, and + both must already be quantized. Supplying ``mmproj`` reuses the ordinary Muse Glimmer + mmproj loader and vision export contract to add ``vision_encoder``. + """ + validate_dflash_export_options(backend) + + import executorch.extension.llm.export.gguf # noqa: F401 + import executorch.extension.llm.export.int4 # noqa: F401 + from executorch.examples.models.muse_glimmer.loaders.checkpoint_loader import ( + load_gguf_model, + load_mlx_model, + ) + from executorch.examples.models.muse_glimmer.loaders.dflash_loader import ( + load_dflash_gguf, + load_dflash_mlx, + ) + + # -- Load target model -- + print("=" * 60) + print("Loading target model...") + print("=" * 60) + if target_mlx is not None: + target_model, target_config = load_mlx_model( + target_mlx, + backend=backend, + max_seq_len=max_seq_len, + activation_dtype=activation_dtype, + ) + else: + target_model, target_config = load_gguf_model( + target_gguf, + max_seq_len=max_seq_len, + backend=backend, + activation_dtype=activation_dtype, + ) + + # All transformed target entry points cast through this shared contract. + target_model.activation_dtype = activation_dtype + + # -- Load draft model -- + print("=" * 60) + print("Loading draft model...") + print("=" * 60) + if draft_mlx is not None: + draft_model, draft_config = load_dflash_mlx( + draft_mlx, + backend=backend, + max_seq_len=max_seq_len, + activation_dtype=activation_dtype, + ) + else: + draft_model, draft_config = load_dflash_gguf( + draft_gguf, + backend=backend, + max_seq_len=max_seq_len, + activation_dtype=activation_dtype, + ) + + vision_model = None + pos_embed_table = None + if mmproj is not None: + from executorch.examples.models.muse_glimmer.loaders.checkpoint_loader import ( + load_mmproj_vision_model, + ) + + print("=" * 60) + print("Loading vision encoder...") + print("=" * 60) + vision_model, pos_embed_table, _ = load_mmproj_vision_model( + mmproj, + backend=backend, + activation_dtype=activation_dtype, + ) + + backend_export = _export_dflash_mlx if backend == "mlx" else _export_dflash_cuda + backend_export( + target_model, + target_config, + draft_model, + draft_config, + vision_model, + pos_embed_table, + output_dir, + max_seq_len, + activation_dtype, + max_vision_patches, + ) + + +def _dflash_constant_methods( + *, + target_config, + draft_config, + max_prefill: int, + activation_dtype: torch.dtype, + mutable_buffer_metadata: str, + exported_block_size: int, + has_vision: bool, + max_vision_patches: int, +) -> dict[str, object]: + """Constant methods baked into the .pte and read back by the runners. + + ``use_kv_cache`` / ``use_sdpa_with_kv_cache`` / ``enable_dynamic_shape`` / + ``get_vocab_size`` are the standard ExecuTorch LLM metadata keys read by + ``llm::get_llm_metadata``; the rest are muse_glimmer-specific. + """ + constant_methods: dict[str, object] = { + "get_max_seq_len": target_config.max_seq_len, + "get_vocab_size": target_config.vocab_size, + "get_max_prefill_chunk": max_prefill, + "get_activation_dtype": common.activation_dtype_tag(activation_dtype), + "get_mutable_buffer_metadata": mutable_buffer_metadata, + "get_block_size": exported_block_size, + "get_mask_token_id": draft_config.mask_token_id, + "get_n_target_layers": draft_config.n_target_layers, + "get_draft_sliding_window": ( + draft_config.sliding_window or 0 + if draft_config.sliding_window_pattern is not None + and all(draft_config.sliding_window_pattern) + else 0 + ), + "use_kv_cache": True, + "use_sdpa_with_kv_cache": False, + "enable_dynamic_shape": True, + "has_vision_encoder": has_vision, + } + if has_vision: + constant_methods["get_vision_hidden_size"] = target_config.dim + constant_methods["get_max_vision_patches"] = int(max_vision_patches) + return constant_methods + + +def _export_dflash_mlx( + target_model, + target_config, + draft_model, + draft_config, + vision_model, + pos_embed_table, + output_dir: str, + max_seq_len: int, + activation_dtype: torch.dtype, + max_vision_patches: int, +) -> None: + """Export the MLX DFlash contract. + + Always ``embed_text`` + ``target_forward_from_embeddings`` + ``draft_forward``, + with ``vision_encoder`` appended when a vision tower is present. + """ + import executorch.backends.mlx.custom_kernel_ops.gguf.patterns # noqa: F401 + import executorch.backends.mlx.patterns # noqa: F401 + + # Register block-scaled MLX target/draft checkpoint export ops. + import executorch.extension.llm.export.mx # noqa: F401 + import executorch.extension.llm.export.nvfp4 # noqa: F401 + from executorch.backends.mlx import MLXPartitioner + from executorch.backends.mlx.passes import get_default_passes + from executorch.examples.models.muse_glimmer.model.dflash_model import ( + MuseGlimmerWithDFlash, + ) + from executorch.examples.models.muse_glimmer.model.model import ( + materialize_runtime_buffers, + ) + from executorch.examples.models.muse_glimmer.source_transformations.mlx import ( + dflash_mlx_source_transformations, + mlx_source_transformations_dflash_target, + ) + from executorch.exir import ( + EdgeCompileConfig, + ExecutorchBackendConfig, + to_edge_transform_and_lower, + ) + from executorch.exir.passes import MemoryPlanningPass + from executorch.exir.passes.propagate_device_pass import PropagateDeviceConfig + from torch.export import Dim, export + + max_prefill = 512 + + print("Applying target MLX source transforms (with hidden tapping)...") + mlx_source_transformations_dflash_target( + target_model, + target_layer_ids=draft_config.target_layers, + dtype=activation_dtype, + max_write_len=max_prefill, + ) + materialize_runtime_buffers(target_model, dtype=activation_dtype) + + print("Applying draft MLX source transforms...") + draft_model = dflash_mlx_source_transformations( + draft_model, + max_context_length=max_seq_len, + dtype=activation_dtype, + sliding_window=draft_config.sliding_window, + sliding_window_pattern=draft_config.sliding_window_pattern, + max_write_len=max_prefill, + ) + + combined = MuseGlimmerWithDFlash( + target_model, draft_model, target_config, draft_config + ) + + # Normalize every floating param/buffer AND quantized-weight scale to the + # activation dtype (mirrors export_solo.py's terminal ``model.to``). Critical + # for fp16: the MLX draft stores scales as float16 and the target as + # bfloat16, so without this a float16/bfloat16 mix promotes to float32 in MLX + # quantized_matmul -- which surfaces as an SDPA dtype mismatch (query in the + # activation dtype, cached K/V in float32) when exporting draft_forward. + combined.to(activation_dtype) + + # -- Export the target contract -- + target_seq_dim = Dim("target_seq_len", min=1, max=max_prefill) + target_tokens = torch.tensor([[0, 1]], dtype=torch.long) + target_input_pos = torch.arange(target_tokens.size(1), dtype=torch.long) + + print("=" * 60) + print("Exporting target_forward_from_embeddings...") + print("=" * 60) + with common.BoundMethodForward( + combined, combined.target_forward_from_embeddings + ), torch.no_grad(): + target_from_embeddings_ep = export( + combined, + ( + torch.zeros( + (1, target_tokens.size(1), target_config.dim), + dtype=target_model.activation_dtype, + ), + target_input_pos, + ), + dynamic_shapes=({1: target_seq_dim}, {0: target_seq_dim}), + strict=True, + ) + + embed_seq_dim = Dim("embed_seq_len", min=1, max=max_prefill) + print("=" * 60) + print("Exporting embed_text...") + print("=" * 60) + with common.BoundMethodForward(combined, combined.embed_text), torch.no_grad(): + embed_text_ep = export( + combined, + (target_tokens,), + dynamic_shapes=({1: embed_seq_dim},), + strict=True, + ) + + vision_ep = None + if vision_model is not None: + print("=" * 60) + vision_ep = common.export_vision_encoder( + vision_model, pos_embed_table, max_vision_patches + ) + print("=" * 60) + + # -- Export draft method -- + print("=" * 60) + print("Exporting draft_forward...") + print("=" * 60) + exported_block_size = draft_config.block_size + n_target = draft_config.n_target_layers + dim = draft_config.dim + + # Draft block length is dynamic: a single artifact can run any block length + # in [2, block_size] at runtime (min 2 avoids 0/1 specialization; max is the + # native trained block size). target_hidden keeps its dynamic new_ctx_len. + # Both dims feed the RoPE arange over (ctx_start + new_ctx_len + block_len). + block_dim = Dim("block_len", min=2, max=exported_block_size) + new_ctx_dim = Dim("new_ctx_len", min=1, max=max_prefill) + + # input_pos for draft: [ctx_start_pos] — cache write offset + draft_input_pos = torch.tensor([0], dtype=torch.long) + + with common.BoundMethodForward(combined, combined.draft_forward), torch.no_grad(): + draft_ep = export( + combined, + ( + torch.tensor([[0] * exported_block_size], dtype=torch.long), + torch.randn(1, 2, n_target * dim, dtype=activation_dtype), + draft_input_pos, + ), + dynamic_shapes=({1: block_dim}, {1: new_ctx_dim}, None), + strict=True, + ) + + mutable_buffer_metadata = common.mutable_buffer_metadata(combined) + del combined, target_model, draft_model + if vision_model is not None: + del vision_model + gc.collect() + + # -- Lower to ExecuTorch -- + print("=" * 60) + print("Lowering to ExecuTorch with MLX backend...") + print("=" * 60) + methods = { + "target_forward_from_embeddings": target_from_embeddings_ep, + "embed_text": embed_text_ep, + "draft_forward": draft_ep, + } + if vision_ep is not None: + methods["vision_encoder"] = vision_ep + partitioner = {name: [MLXPartitioner()] for name in methods} + + constant_methods = _dflash_constant_methods( + target_config=target_config, + draft_config=draft_config, + max_prefill=max_prefill, + activation_dtype=activation_dtype, + mutable_buffer_metadata=mutable_buffer_metadata, + exported_block_size=exported_block_size, + has_vision=vision_ep is not None, + max_vision_patches=max_vision_patches, + ) + + et_prog = to_edge_transform_and_lower( + methods, + transform_passes=get_default_passes(), + partitioner=partitioner, + compile_config=EdgeCompileConfig( + _check_ir_validity=False, + _skip_dim_order=True, + ), + constant_methods=constant_methods, + ) + + del target_from_embeddings_ep, embed_text_ep, draft_ep, vision_ep + gc.collect() + + et_program = et_prog.to_executorch( + config=ExecutorchBackendConfig( + extract_delegate_segments=True, + do_quant_fusion_and_const_prop=False, + memory_planning_pass=MemoryPlanningPass( + alloc_graph_input=False, + share_mutable_buffers=_share_graph_mutable_buffers("mlx"), + ), + emit_mutable_buffer_names=True, + propagate_device_config=PropagateDeviceConfig(), + ), + ) + + del et_prog + gc.collect() + + common.save_pte(et_program, output_dir, pos_embed_table) + print(f"Done. Methods: {', '.join(methods)}") + + +def _export_dflash_cuda( + target_model, + target_config, + draft_model, + draft_config, + vision_model, + pos_embed_table, + output_dir: str, + max_seq_len: int, + activation_dtype: torch.dtype, + max_vision_patches: int, +) -> None: + """Export the CUDA DFlash contract. + + Text and vision share the embeddings-based target methods. Vision adds + ``vision_encoder`` without changing the text contract. + """ + # Register CUDA quantized tensor linear dispatch before torch.export. + import executorch.backends.cuda.quantize_op_dispatch # noqa: F401 + import torch._inductor.config as inductor_config + from executorch.backends.cuda.cuda_backend import CudaBackend + from executorch.backends.cuda.cuda_partitioner import CudaPartitioner + from executorch.examples.models.gemma4_31b.cuda_packers import ( + convert_quantized_tensors_for_cuda, + ) + from executorch.examples.models.muse_glimmer.model.dflash_model import ( + MuseGlimmerWithDFlash, + ) + from executorch.examples.models.muse_glimmer.source_transformations.cuda import ( + add_dflash_hidden_tapping, + cuda_source_transformations, + dflash_cuda_source_transformations, + materialize_dflash_runtime_buffers, + ) + from executorch.exir import ( + EdgeCompileConfig, + ExecutorchBackendConfig, + to_edge_transform_and_lower, + ) + from executorch.exir.backend.compile_spec_schema import CompileSpec + from executorch.exir.passes import MemoryPlanningPass + from executorch.exir.passes.propagate_device_pass import PropagateDeviceConfig + from torch.export import Dim, export + + max_prefill = 512 + has_vision = vision_model is not None + + print("Applying target CUDA source transforms (with hidden tapping)...") + cuda_source_transformations(target_model) + add_dflash_hidden_tapping(target_model, draft_config.target_layers) + + print("Applying draft CUDA source transforms...") + dflash_cuda_source_transformations(draft_model) + + print("Converting draft quantized tensors for CUDA...") + convert_quantized_tensors_for_cuda(draft_model) + materialize_dflash_runtime_buffers(draft_model, dtype=activation_dtype) + + combined = MuseGlimmerWithDFlash( + target_model, draft_model, target_config, draft_config + ) + max_target_prefill = min( + target_config.max_seq_len - 1, target_model._sliding_window * 2 + ) + + # See _export_dflash_mlx: normalize params/buffers/scales to one dtype + # before export so no mixed-precision promotion leaks into the graph. + combined.to(activation_dtype) + + # -- Export the target contract -- + target_max_len = 4 + target_seq_dim = Dim("target_seq_len", min=1, max=target_max_len) + target_tokens = torch.arange(target_max_len, dtype=torch.long).unsqueeze(0) + target_input_pos = torch.arange(target_tokens.size(1), dtype=torch.long) + print("=" * 60) + print("Exporting target_forward_from_embeddings...") + print("=" * 60) + with common.BoundMethodForward( + combined, combined.target_forward_from_embeddings + ), torch.no_grad(): + target_from_embeddings_ep = export( + combined, + ( + torch.zeros( + (1, target_tokens.size(1), target_config.dim), + dtype=target_model.activation_dtype, + ), + target_input_pos, + ), + dynamic_shapes=({1: target_seq_dim}, {0: target_seq_dim}), + strict=True, + ) + + # ``embed_text`` serves both the fixed-width verifier path and the + # variable-width prefill path, so its input needs the same upper bound as + # ``target_prefill_from_embeddings``. + embed_max_len = _embed_text_max_len("cuda", target_max_len, max_target_prefill) + embed_seq_dim = Dim("embed_seq_len", min=1, max=embed_max_len) + print("=" * 60) + print("Exporting embed_text...") + print("=" * 60) + with common.BoundMethodForward(combined, combined.embed_text), torch.no_grad(): + embed_text_ep = export( + combined, + (target_tokens,), + dynamic_shapes=({1: embed_seq_dim},), + strict=True, + ) + + vision_ep = None + if has_vision: + print("=" * 60) + vision_ep = common.export_vision_encoder( + vision_model, pos_embed_table, max_vision_patches + ) + print("=" * 60) + + # -- Export the prefill contract -- + target_prefill_dim = Dim("target_prefill_seq_len", min=5, max=max_target_prefill) + print("=" * 60) + print( + "Exporting target_prefill_from_embeddings " + f"(T in [5, {max_target_prefill}])..." + ) + print("=" * 60) + with common.BoundMethodForward( + combined, combined.target_prefill_from_embeddings + ), torch.no_grad(): + target_prefill_from_embeddings_ep = export( + combined, + ( + torch.zeros( + (1, max_target_prefill, target_config.dim), + dtype=activation_dtype, + ), + torch.arange(max_target_prefill, dtype=torch.long), + ), + dynamic_shapes=({1: target_prefill_dim}, {0: target_prefill_dim}), + strict=True, + ) + + # -- Export draft methods -- + print("=" * 60) + print("Exporting draft_forward...") + print("=" * 60) + exported_block_size = min(draft_config.block_size, 4) + n_target = draft_config.n_target_layers + dim = draft_config.dim + new_ctx_max = 4 + + block_dim = Dim("block_len", min=2, max=exported_block_size) + draft_input_pos = torch.tensor([0], dtype=torch.long) + + with common.BoundMethodForward(combined, combined.draft_forward), torch.no_grad(): + # Keep every input byte size fixed for CUDA Graph replay. The + # valid-length scalar preserves cache/attention semantics when the + # previous speculative step committed fewer than four positions. + draft_ep = export( + combined, + ( + torch.tensor([[0] * exported_block_size], dtype=torch.long), + torch.randn(1, new_ctx_max, n_target * dim, dtype=activation_dtype), + draft_input_pos, + torch.tensor([2], dtype=torch.long), + ), + dynamic_shapes=({1: block_dim}, None, None, None), + strict=True, + ) + + max_draft_prefill = _max_draft_prefill_len(draft_config, max_target_prefill) + draft_prefill_dim = Dim("draft_prefill_seq_len", min=5, max=max_draft_prefill) + print("=" * 60) + print(f"Exporting draft_prefill (T in [5, {max_draft_prefill}])...") + print("=" * 60) + with common.BoundMethodForward(combined, combined.draft_prefill), torch.no_grad(): + draft_prefill_ep = export( + combined, + ( + torch.tensor([[0] * exported_block_size], dtype=torch.long), + torch.randn( + 1, + max_draft_prefill, + n_target * dim, + dtype=activation_dtype, + ), + draft_input_pos, + ), + dynamic_shapes=( + {1: block_dim}, + {1: draft_prefill_dim}, + None, + ), + strict=True, + ) + + mutable_buffer_metadata = common.mutable_buffer_metadata(combined) + del combined, target_model, draft_model + if vision_model is not None: + del vision_model + gc.collect() + + # -- Lower to ExecuTorch -- + print("=" * 60) + print("Lowering to ExecuTorch with CUDA backend...") + print("=" * 60) + inductor_config.coordinate_descent_tuning = False + inductor_config.aot_inductor.compile_wrapper_opt_level = "O0" + inductor_config.aot_inductor.precompile_headers = False + if hasattr(inductor_config, "cpp_cache_precompile_headers"): + inductor_config.cpp_cache_precompile_headers = False + + def cuda_partitioner(method: str) -> CudaPartitioner: + return CudaPartitioner( + [ + CudaBackend.generate_method_name_compile_spec(method), + CompileSpec("low_memory_mode", b"ON"), + ] + ) + + methods = { + "target_forward_from_embeddings": target_from_embeddings_ep, + "target_prefill_from_embeddings": target_prefill_from_embeddings_ep, + "embed_text": embed_text_ep, + "draft_forward": draft_ep, + "draft_prefill": draft_prefill_ep, + } + if vision_ep is not None: + methods["vision_encoder"] = vision_ep + partitioner = {name: [cuda_partitioner(name)] for name in methods} + + constant_methods = _dflash_constant_methods( + target_config=target_config, + draft_config=draft_config, + max_prefill=max_prefill, + activation_dtype=activation_dtype, + mutable_buffer_metadata=mutable_buffer_metadata, + exported_block_size=exported_block_size, + has_vision=has_vision, + max_vision_patches=max_vision_patches, + ) + constant_methods.update( + { + "get_min_target_prefill_chunk": 5, + "get_max_target_prefill_chunk": max_target_prefill, + "get_min_draft_prefill_chunk": 5, + "get_max_draft_prefill_chunk": max_draft_prefill, + } + ) + + et_prog = to_edge_transform_and_lower( + methods, + transform_passes=None, + partitioner=partitioner, + compile_config=EdgeCompileConfig( + _check_ir_validity=False, + _skip_dim_order=True, + ), + constant_methods=constant_methods, + ) + + del ( + target_prefill_from_embeddings_ep, + target_from_embeddings_ep, + embed_text_ep, + draft_ep, + draft_prefill_ep, + vision_ep, + ) + gc.collect() + + et_program = et_prog.to_executorch( + config=ExecutorchBackendConfig( + extract_delegate_segments=True, + do_quant_fusion_and_const_prop=True, + memory_planning_pass=MemoryPlanningPass( + alloc_graph_input=False, + share_mutable_buffers=_share_graph_mutable_buffers("cuda"), + ), + emit_mutable_buffer_names=True, + propagate_device_config={ + "target_prefill_from_embeddings": PropagateDeviceConfig( + skip_d2h_for_method_outputs=True + ), + "draft_prefill": PropagateDeviceConfig( + skip_d2h_for_method_outputs=True + ), + }, + ), + ) + + del et_prog + gc.collect() + + common.save_pte(et_program, output_dir, pos_embed_table) + print(f"Done. Methods: {', '.join(methods)}") + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Export DFlash (target + draft) to ExecuTorch CUDA or MLX." + ) + target_src = parser.add_mutually_exclusive_group(required=True) + target_src.add_argument( + "--target-gguf", + default=None, + help="Path to target GGUF (e.g. muse-glimmer-30B-kquant-17gb.gguf).", + ) + target_src.add_argument( + "--target-mlx", + default=None, + help="Path to target MLX affine-quantized safetensors dir " + "(e.g. an mlx_lm.convert output dir).", + ) + draft_src = parser.add_mutually_exclusive_group(required=True) + draft_src.add_argument( + "--draft-gguf", + default=None, + help="Path to draft DFlash GGUF (e.g. dflash-kquant.gguf).", + ) + draft_src.add_argument( + "--draft-mlx", + default=None, + help="Path to an MLX affine-quantized DFlash draft dir " + "(e.g. dflash-3l_wind2048-mlx-q5). Already quantized.", + ) + parser.add_argument( + "--backend", + default="mlx", + choices=["cuda", "mlx"], + help="ExecuTorch backend. Defaults to MLX.", + ) + parser.add_argument( + "--output-dir", + default="./dflash_exports_mlx", + help="Output directory for model.pte / model.ptd.", + ) + parser.add_argument( + "--max-seq-len", + type=int, + default=131072, + help="KV cache size for target model.", + ) + parser.add_argument( + "--mmproj", + default=None, + help="Optional Muse Glimmer vision mmproj GGUF; adds vision_encoder.", + ) + parser.add_argument( + "--max-vision-patches", + type=int, + default=16384, + help="Maximum patch count accepted by the exported vision encoder.", + ) + parser.add_argument( + "--activation-dtype", + default=None, + choices=list(common.ACTIVATION_DTYPES), + help="Activation / KV-cache / unquantized-weight dtype. Defaults to " + "float16 for MLX and bfloat16 for CUDA.", + ) + args = parser.parse_args() + + try: + validate_dflash_export_options(args.backend) + except ValueError as error: + parser.error(str(error)) + if args.backend == "cuda" and not torch.cuda.is_available(): + parser.error("CUDA is required for the cuda backend.") + if args.backend == "cuda" and (args.target_mlx or args.draft_mlx): + parser.error("MLX checkpoint directories are only supported by --backend mlx.") + if args.activation_dtype is None: + args.activation_dtype = "float16" if args.backend == "mlx" else "bfloat16" + if args.backend == "cuda" and args.activation_dtype != "bfloat16": + parser.error("The CUDA DFlash path currently requires bfloat16 activations.") + + activation_dtype = common.ACTIVATION_DTYPES[args.activation_dtype] + + export_dflash( + target_gguf=args.target_gguf, + target_mlx=args.target_mlx, + draft_gguf=args.draft_gguf, + draft_mlx=args.draft_mlx, + output_dir=args.output_dir, + max_seq_len=args.max_seq_len, + activation_dtype=activation_dtype, + backend=args.backend, + mmproj=args.mmproj, + max_vision_patches=args.max_vision_patches, + ) + + +if __name__ == "__main__": + main() diff --git a/examples/models/muse-glimmer/export/export_solo.py b/examples/models/muse-glimmer/export/export_solo.py new file mode 100644 index 00000000000..a8d59f855fd --- /dev/null +++ b/examples/models/muse-glimmer/export/export_solo.py @@ -0,0 +1,692 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""Export a Muse Glimmer target checkpoint to ExecuTorch. + +Supports GGUF, consolidated BF16, prequantized, and MLX-affine inputs. Vision +exports add ``vision_encoder`` and write ``pos_embed.bin``. +""" + +import argparse +import gc + +import torch +import torch.nn as nn +from executorch.examples.models.muse_glimmer.export import common +from executorch.examples.models.muse_glimmer.model.model import ( + materialize_runtime_buffers, + MuseGlimmerConfig, + MuseGlimmerModel, +) + +# Smallest CUDA chunk that runs the dynamic ``prefill`` method (shorter tails +# fall back to the static ``decode`` method). +_CUDA_MIN_PREFILL_CHUNK = 5 + + +# Input formats share the loading and backend-packing pipeline in +# ``checkpoint_loader``. + + +def load_prequantized_model( + prequantized_dir: str, + max_seq_len: int = 16384, + backend: str = "cuda", +) -> tuple[MuseGlimmerModel, MuseGlimmerConfig]: + """Load an atomic quantized checkpoint and pack for the target backend.""" + from executorch.examples.models.muse_glimmer.loaders.checkpoint_loader import ( + load_prequantized_model as _load_prequantized_model, + ) + + return _load_prequantized_model(prequantized_dir, max_seq_len, backend) + + +def load_and_quantize( + checkpoint_dir: str, + recipe_name: str, + max_seq_len: int = 16384, + backend: str = "cuda", +) -> tuple[MuseGlimmerModel, MuseGlimmerConfig]: + """Load bf16 checkpoint, quantize, pack — one shot.""" + from executorch.examples.models.muse_glimmer.loaders.checkpoint_loader import ( + load_and_quantize as _load_and_quantize, + ) + from executorch.examples.models.muse_glimmer.loaders.quantize_and_save import ( + build_recipes, + ) + + recipe = build_recipes()[recipe_name] + return _load_and_quantize(checkpoint_dir, recipe, max_seq_len, backend) + + +# Backend dispatch helpers + + +_SUPPORTED_BACKENDS = ("cuda", "mlx") + + +# Export + lower + + +def export_and_lower( + model: MuseGlimmerModel, + config: MuseGlimmerConfig, + output_dir: str, + backend: str = "cuda", + sample: bool = True, + use_turboquant: bool = False, + activation_dtype: torch.dtype = torch.bfloat16, + max_prefill_chunk: int = 512, + vision_model: nn.Module | None = None, + pos_embed_table: torch.Tensor | None = None, + max_vision_patches: int = 16384, + vision_fp32_mm: str = "none", +) -> None: + if backend == "cuda": + _export_cuda( + model, + config, + output_dir, + sample=sample, + use_turboquant=use_turboquant, + vision_model=vision_model, + pos_embed_table=pos_embed_table, + max_vision_patches=max_vision_patches, + vision_fp32_mm=vision_fp32_mm, + ) + elif backend == "mlx": + _export_mlx( + model, + config, + output_dir, + activation_dtype=activation_dtype, + max_prefill_chunk=max_prefill_chunk, + vision_model=vision_model, + pos_embed_table=pos_embed_table, + max_vision_patches=max_vision_patches, + ) + else: + raise ValueError( + f"Unsupported backend: {backend!r}. Supported: {_SUPPORTED_BACKENDS}." + ) + + +def _solo_constant_methods( + *, + config: MuseGlimmerConfig, + max_prefill: int, + activation_dtype: torch.dtype, + mutable_buffer_metadata: str, + has_vision: bool, + max_vision_patches: int, +) -> dict[str, object]: + """Constant methods baked into the .pte and read back by the runners. + + ``use_kv_cache`` / ``use_sdpa_with_kv_cache`` / ``enable_dynamic_shape`` / + ``get_vocab_size`` are the standard ExecuTorch LLM metadata keys read by + ``llm::get_llm_metadata``; the rest are muse_glimmer-specific. CUDA additionally + sets ``get_min_prefill_chunk``, since only it has a separate static + ``decode`` method for short prefill tails. + """ + constant_methods: dict[str, object] = { + "get_max_seq_len": config.max_seq_len, + "get_vocab_size": config.vocab_size, + "get_max_prefill_chunk": max_prefill, + "get_activation_dtype": common.activation_dtype_tag(activation_dtype), + "get_mutable_buffer_metadata": mutable_buffer_metadata, + "use_kv_cache": True, + "use_sdpa_with_kv_cache": False, + "enable_dynamic_shape": True, + "has_vision_encoder": bool(has_vision), + } + if has_vision: + constant_methods["get_vision_hidden_size"] = config.dim + constant_methods["get_max_vision_patches"] = int(max_vision_patches) + return constant_methods + + +def _export_cuda( + model: MuseGlimmerModel, + config: MuseGlimmerConfig, + output_dir: str, + sample: bool = True, + use_turboquant: bool = False, + vision_model: nn.Module | None = None, + pos_embed_table: torch.Tensor | None = None, + max_vision_patches: int = 16384, + vision_fp32_mm: str = "none", +) -> None: + import torch._inductor.config as inductor_config + from executorch.backends.cuda.cuda_backend import CudaBackend + from executorch.backends.cuda.cuda_partitioner import CudaPartitioner + from executorch.exir import ( + EdgeCompileConfig, + ExecutorchBackendConfig, + to_edge_transform_and_lower, + ) + from executorch.exir.backend.compile_spec_schema import CompileSpec + from executorch.exir.passes import MemoryPlanningPass + from executorch.exir.passes.propagate_device_pass import PropagateDeviceConfig + from torch.export import Dim, export + + inductor_config.coordinate_descent_tuning = False + inductor_config.aot_inductor.compile_wrapper_opt_level = "O0" + # Disable precompiled headers: the PCH path shells out to `openssl sha512` + # and does `stdout.split()[-1]`, which raises IndexError when the + # preprocessed header is missing/empty in some environments (flaky). PCH is + # only a compile-time optimization, so turning it off is safe. + inductor_config.aot_inductor.precompile_headers = False + if hasattr(inductor_config, "cpp_cache_precompile_headers"): + inductor_config.cpp_cache_precompile_headers = False + + if vision_fp32_mm == "native": + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + torch.set_float32_matmul_precision("highest") + + import executorch.backends.cuda.quantize_op_dispatch # noqa: F401 + from executorch.examples.models.muse_glimmer.source_transformations.cuda import ( + add_on_device_sampler, + cuda_source_transformations, + vision_cuda_source_transformations, + ) + + # Always applied: bounds global-attention SDPA to the valid context via a + # runtime kv_len (O(context) decode). With use_turboquant=True it also swaps + # the global KV caches for TurboQuant TQ4. + cuda_source_transformations(model, use_turboquant=use_turboquant) + + # Max prefill chunk must fit in the ring buffer (2 * sliding_window) + max_prefill = min(config.max_seq_len - 1, model._sliding_window * 2) + + has_vision = vision_model is not None + programs: dict[str, "torch.export.ExportedProgram"] = {} + + if sample: + add_on_device_sampler(model) + + hidden = config.dim + temp = torch.tensor([1.0], dtype=torch.float32) + et_seq = Dim("embed_seq_len", min=1, max=max_prefill) + print(f"Exporting embed_text (T in [1, {max_prefill}])...") + embed_method = model.embed_text_forward if sample else model.embed_text + with common.BoundMethodForward(model, embed_method), torch.no_grad(): + programs["embed_text"] = export( + model, + (torch.zeros((1, max_prefill), dtype=torch.long),), + dynamic_shapes=({1: et_seq},), + strict=True, + ) + + seq_dim = Dim("seq_len", min=5, max=max_prefill) + print(f"Exporting forward_from_embeddings (T in [5, {max_prefill}], embeds)...") + forward_method = ( + model.forward_from_embeddings if sample else model.prefill_from_embeds + ) + forward_args = ( + torch.zeros((1, max_prefill, hidden), dtype=torch.bfloat16), + torch.arange(max_prefill, dtype=torch.long), + ) + ((temp,) if sample else ()) + forward_dynamic_shapes = ({1: seq_dim}, {0: seq_dim}) + ((None,) if sample else ()) + with common.BoundMethodForward(model, forward_method), torch.no_grad(): + programs["forward_from_embeddings"] = export( + model, + forward_args, + dynamic_shapes=forward_dynamic_shapes, + strict=True, + ) + + print("Exporting decode_from_embedding (T=1, embeds)...") + decode_method = model.decode_from_embedding if sample else model.prefill_from_embeds + decode_args = ( + torch.zeros((1, 1, hidden), dtype=torch.bfloat16), + torch.tensor([0], dtype=torch.long), + ) + ((temp,) if sample else ()) + with common.BoundMethodForward(model, decode_method), torch.no_grad(): + programs["decode_from_embedding"] = export( + model, + decode_args, + strict=True, + ) + + if has_vision: + if vision_fp32_mm != "none": + # CUDA-only: applied as a source transform so vision_tower.py stays + # backend-neutral for the MLX export, which lowers the encoder with + # no transform at all. + vision_cuda_source_transformations( + vision_model, + start=0, + end=34, + use_triton_mm=vision_fp32_mm == "triton", + ) + programs["vision_encoder"] = common.export_vision_encoder( + vision_model, pos_embed_table, max_vision_patches + ) + + mutable_buffer_metadata = common.mutable_buffer_metadata(model) + del model + if has_vision: + del vision_model + gc.collect() + torch.cuda.empty_cache() + + def _partitioner_for(name: str) -> "CudaPartitioner": + return CudaPartitioner( + [ + CudaBackend.generate_method_name_compile_spec(name), + CompileSpec("low_memory_mode", b"ON"), + ] + ) + + constant_methods = _solo_constant_methods( + config=config, + max_prefill=max_prefill, + activation_dtype=torch.bfloat16, + mutable_buffer_metadata=mutable_buffer_metadata, + has_vision=bool(has_vision), + max_vision_patches=max_vision_patches, + ) + constant_methods["get_min_prefill_chunk"] = _CUDA_MIN_PREFILL_CHUNK + constant_methods["use_sampling"] = sample + + print( + f"Lowering {len(programs)} methods to ExecuTorch (CUDA): " + f"{', '.join(programs.keys())}..." + ) + et_prog = to_edge_transform_and_lower( + programs, + partitioner={name: [_partitioner_for(name)] for name in programs}, + compile_config=EdgeCompileConfig( + _check_ir_validity=False, + _skip_dim_order=True, + ), + constant_methods=constant_methods, + ) + del programs + gc.collect() + torch.cuda.empty_cache() + + et_program = et_prog.to_executorch( + config=ExecutorchBackendConfig( + extract_delegate_segments=True, + do_quant_fusion_and_const_prop=True, + memory_planning_pass=MemoryPlanningPass( + alloc_graph_input=False, + ), + emit_mutable_buffer_names=True, + # Keep method outputs device-resident so the CUDA backend does not + # insert a per-step boundary D2H copy. The runner reads the sampled + # token back with its own on-device D2H (solo.cpp read_token). + propagate_device_config=PropagateDeviceConfig( + skip_d2h_for_method_outputs=True, + ), + ), + ) + + del et_prog + gc.collect() + torch.cuda.empty_cache() + + common.save_pte(et_program, output_dir, pos_embed_table if has_vision else None) + + # GPU peak memory marker — emitted on its own line for CI grep. + if torch.cuda.is_available(): + peak_mb = torch.cuda.max_memory_allocated() / (1024**2) + print(f"EXPORT_GPU_PEAK_MEMORY_MB: {peak_mb:.1f}") + print("Done.") + + +def _export_mlx( + model: MuseGlimmerModel, + config: MuseGlimmerConfig, + output_dir: str, + activation_dtype: torch.dtype = torch.bfloat16, + max_prefill_chunk: int = 512, + vision_model: nn.Module | None = None, + pos_embed_table: torch.Tensor | None = None, + max_vision_patches: int = 4096, +) -> None: + """Export to .pte via torch.export + MLX backend. + + MLX exports ``embed_text`` and dynamic ``forward_from_embeddings``. The + latter handles both prefill and single-token decode so one delegated method + owns the KV cache, and returns last-token logits for host-side sampling. + + Vision (``vision_model`` given) is purely additive: it appends a third + ``vision_encoder`` method (the 9-input host-precompute graph). The runner + runs ``vision_encoder`` on host-preprocessed patches, splices the image + soft-tokens into the ``embed_text`` output at ``<|patch|>`` positions, then + runs ``forward_from_embeddings`` on the spliced embeddings. The vision + encoder lowers to MLX with no source transform (LayerNorm, bidirectional + SDPA with a bool mask, GELU, quantized/bf16 Linear and 2D RoPE all have + direct MLX handlers). + + CUDA additionally exports a static ``decode_from_embedding`` method, with + on-device sampling by default. + """ + import gc + + # Register GGUF pattern handlers + custom op so ExportableGGUFTensor weights + # (Q4_K, Q6_K) lower to the MLX GGUF custom kernels. + import executorch.backends.mlx.custom_kernel_ops.gguf.patterns # noqa: F401 + + # Register the Int4 export op + MLX pattern handlers so ExportableInt4Tensor + # weights lower to the MLX quantized matmul. IntxUnpackedToInt8Tensor (int8 + # embedding) already lowers via dequantize_affine -> linear, no import needed. + import executorch.backends.mlx.patterns # noqa: F401 + import executorch.extension.llm.export.gguf # noqa: F401 + import executorch.extension.llm.export.int4 # noqa: F401 + + # Register the NVFP4 / MX export ops so block-scaled MLX checkpoints + # (ExportableNVFP4Tensor / ExportableMXTensor) lower to the MLX + # mode="nvfp4"/"mxfp8" quantized matmul + gather kernels. + import executorch.extension.llm.export.mx # noqa: F401 + import executorch.extension.llm.export.nvfp4 # noqa: F401 + from executorch.backends.mlx import MLXPartitioner + from executorch.backends.mlx.passes import get_default_passes + from executorch.examples.models.muse_glimmer.source_transformations.mlx import ( + mlx_source_transformations, + ) + from executorch.exir import ( + EdgeCompileConfig, + ExecutorchBackendConfig, + to_edge_transform_and_lower, + ) + from executorch.exir.passes import MemoryPlanningPass + from torch.export import Dim, export + + has_vision = vision_model is not None + + max_prefill = max_prefill_chunk + seq_dim = Dim("seq_len", min=1, max=max_prefill) + + # Size sliding-window ring buffers to the prefill chunk (window + + # max_write_len - 1) rather than 2*window, since the runner chunks prefill + # to get_max_prefill_chunk == max_prefill. + mlx_source_transformations(model, dtype=activation_dtype, max_write_len=max_prefill) + materialize_runtime_buffers(model, dtype=activation_dtype) + + # Convert everything to the activation dtype: unquantized floating params + + # buffers (norms, RoPE, softcap) AND the quantized-weight scales. GGUF + # weights are packed with float16 scales; ``model.to`` downcasts them (and + # everything else) to the target dtype. torchao intx tensors convert their + # scale/zero_point while preserving the integer qdata. Keeping scales in the + # activation dtype avoids MLX promoting (e.g. float16 ⊕ bfloat16 → float32) + # in quantized_matmul, which would otherwise feed float32 into the fused + # q5_k/q6_k kernels that are templated on the activation dtype. + model.to(activation_dtype) + mutable_buffer_metadata = common.mutable_buffer_metadata(model) + + programs: dict[str, "torch.export.ExportedProgram"] = {} + + # Unified MLX contract: embed_text + embeds-input forward_from_embeddings, + # with vision_encoder added only when a vision tower is present. Only + # forward_from_embeddings mutates the KV cache (decode reuses it), mirroring + # the gemma4 MLX vision export. + hidden = config.dim + + et_seq = Dim("embed_seq_len", min=1, max=max_prefill) + print(f"Exporting embed_text (T in [1, {max_prefill}])...") + with common.BoundMethodForward(model, model.mlx_embed_text), torch.no_grad(): + programs["embed_text"] = export( + model, + (torch.zeros((1, max_prefill), dtype=torch.long),), + dynamic_shapes=({1: et_seq},), + strict=True, + ) + + print(f"Exporting forward_from_embeddings (T in [1, {max_prefill}], embeds)...") + with common.BoundMethodForward(model, model.mlx_prefill_forward), torch.no_grad(): + programs["forward_from_embeddings"] = export( + model, + ( + torch.zeros((1, max_prefill, hidden), dtype=activation_dtype), + torch.arange(max_prefill, dtype=torch.long), + ), + dynamic_shapes=({1: seq_dim}, {0: seq_dim}), + strict=True, + ) + + if has_vision: + programs["vision_encoder"] = common.export_vision_encoder( + vision_model, pos_embed_table, max_vision_patches + ) + + del model + if has_vision: + del vision_model + gc.collect() + + constant_methods = _solo_constant_methods( + config=config, + max_prefill=max_prefill, + activation_dtype=activation_dtype, + mutable_buffer_metadata=mutable_buffer_metadata, + has_vision=bool(has_vision), + max_vision_patches=max_vision_patches, + ) + constant_methods["use_sampling"] = False + + print( + f"Lowering {len(programs)} method(s) to ExecuTorch (MLX): " + f"{', '.join(programs.keys())}..." + ) + et_prog = to_edge_transform_and_lower( + programs, + transform_passes=get_default_passes(), + partitioner={name: [MLXPartitioner()] for name in programs}, + compile_config=EdgeCompileConfig( + _check_ir_validity=False, + _skip_dim_order=True, + ), + constant_methods=constant_methods, + ) + del programs + gc.collect() + + et_program = et_prog.to_executorch( + config=ExecutorchBackendConfig( + extract_delegate_segments=True, + memory_planning_pass=MemoryPlanningPass( + alloc_graph_input=False, + share_mutable_buffers=True, + ), + emit_mutable_buffer_names=True, + ), + ) + + del et_prog + gc.collect() + + common.save_pte(et_program, output_dir, pos_embed_table if has_vision else None) + print("Done.") + + +def main() -> None: + from executorch.examples.models.muse_glimmer.loaders.quantize_and_save import ( + RECIPE_NAMES, + ) + + parser = argparse.ArgumentParser(description="Export Muse Glimmer to ExecuTorch.") + src = parser.add_mutually_exclusive_group(required=True) + src.add_argument( + "--checkpoint-dir", + default=None, + help="Path to consolidated checkpoint. Triggers load + quantize + export.", + ) + src.add_argument( + "--prequantized", + default=None, + help="Path to a quantized checkpoint directory. Skips quantization.", + ) + src.add_argument( + "--gguf", + default=None, + help="Path to a GGUF file (e.g. muse-glimmer-30B-kquant-17gb.gguf). Streams and " + "converts weights for the target backend, preserving quant bit-widths.", + ) + src.add_argument( + "--mlx", + default=None, + help="Path to an MLX affine-quantized safetensors dir (mlx_lm output, " + "e.g. muse-glimmer-target-mlx-q5-lang). Converts weights to torchao intx " + "and packs for the selected backend.", + ) + parser.add_argument( + "--output-dir", + default="./muse_glimmer_exports", + help="Output directory for model.pte / model.ptd.", + ) + parser.add_argument( + "--max-seq-len", + type=int, + default=131072, + help="KV cache size.", + ) + parser.add_argument( + "--quant-recipe", + default="default", + choices=RECIPE_NAMES, + help="Quantization recipe (only with --checkpoint-dir).", + ) + parser.add_argument( + "--backend", + default="cuda", + choices=list(_SUPPORTED_BACKENDS), + help="Target backend for export.", + ) + parser.add_argument( + "--logits", + action="store_true", + help="Export full logits instead of on-device sampling (for NLL " + "validation). Default samples on-device and returns a token.", + ) + parser.add_argument( + "--turboquant", + action="store_true", + help="Use TurboQuant TQ4 KV cache on global (NoPE) layers (CUDA).", + ) + parser.add_argument( + "--activation-dtype", + default=None, + choices=list(common.ACTIVATION_DTYPES), + help="Activation compute dtype (MLX backend only). Defaults to 'float16' " + "for --backend mlx and 'bfloat16' otherwise. For 'float16' the KV cache " + "and all unquantized weights/buffers are converted to fp16 too.", + ) + parser.add_argument( + "--max-prefill-chunk", + type=int, + default=512, + help="Max prefill chunk size (MLX backend only): the largest number of " + "tokens processed per prefill forward, and the dynamic seq_len upper " + "bound baked into the .pte (get_max_prefill_chunk). Larger values improve " + "prefill GPU utilization/throughput at the cost of more memory. " + "Default 512.", + ) + parser.add_argument( + "--mmproj", + default=None, + help="Optional path to the vision projector GGUF " + "(e.g. mmproj-kquant.gguf). When given (CUDA or " + "MLX backend), a `vision_encoder` method is exported and the runner can " + "take image input. Omit to export the text-only (TITO) model.", + ) + parser.add_argument( + "--max-vision-patches", + type=int, + default=16384, + help="Max input patches to the vision encoder (upper bound on the " + "dynamic num_patches dim before 2x2 downsampling). Default 16384 " + "corresponds to 4096 output image tokens.", + ) + parser.add_argument( + "--vision-fp32-mm", + choices=("triton", "native", "none"), + default="none", + help="Optional FP32-output linear implementation for vision blocks " + "0-34. The default preserves the original all-BF16 encoder.", + ) + args = parser.parse_args() + + if args.backend == "cuda" and not torch.cuda.is_available(): + parser.error("CUDA is required for the cuda backend.") + + if args.activation_dtype is None: + args.activation_dtype = "float16" if args.backend == "mlx" else "bfloat16" + activation_dtype = common.ACTIVATION_DTYPES[args.activation_dtype] + if args.backend != "mlx" and activation_dtype != torch.bfloat16: + parser.error("--activation-dtype is only supported with --backend mlx.") + if args.backend != "mlx" and args.max_prefill_chunk != 512: + parser.error("--max-prefill-chunk is only supported with --backend mlx.") + if args.gguf: + from executorch.examples.models.muse_glimmer.loaders.checkpoint_loader import ( + load_gguf_model, + ) + + model, config = load_gguf_model( + args.gguf, + max_seq_len=args.max_seq_len, + backend=args.backend, + activation_dtype=activation_dtype, + ) + elif args.mlx: + from executorch.examples.models.muse_glimmer.loaders.checkpoint_loader import ( + load_mlx_model, + ) + + model, config = load_mlx_model( + args.mlx, + backend=args.backend, + max_seq_len=args.max_seq_len, + activation_dtype=activation_dtype, + ) + elif args.prequantized: + model, config = load_prequantized_model( + args.prequantized, + max_seq_len=args.max_seq_len, + backend=args.backend, + ) + else: + model, config = load_and_quantize( + args.checkpoint_dir, + args.quant_recipe, + max_seq_len=args.max_seq_len, + backend=args.backend, + ) + + vision_model = None + pos_embed_table = None + if args.mmproj: + from executorch.examples.models.muse_glimmer.loaders.checkpoint_loader import ( + load_mmproj_vision_model, + ) + + vision_model, pos_embed_table, _ = load_mmproj_vision_model( + args.mmproj, + backend=args.backend, + activation_dtype=activation_dtype, + ) + + export_and_lower( + model, + config, + args.output_dir, + backend=args.backend, + sample=not args.logits, + use_turboquant=args.turboquant, + activation_dtype=activation_dtype, + max_prefill_chunk=args.max_prefill_chunk, + vision_model=vision_model, + pos_embed_table=pos_embed_table, + max_vision_patches=args.max_vision_patches, + vision_fp32_mm=args.vision_fp32_mm, + ) + + +if __name__ == "__main__": + main() diff --git a/examples/models/muse-glimmer/inference.py b/examples/models/muse-glimmer/inference.py new file mode 100644 index 00000000000..2eeb6be7c5d --- /dev/null +++ b/examples/models/muse-glimmer/inference.py @@ -0,0 +1,356 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""Eager inference on Muse Glimmer (CUDA + torch.compile). + +Usage: + python inference.py \ + --checkpoint-dir /path/to/consolidated \ + --tokenizer-path /path/to/hf_assets \ + --prompt "The meaning of life is" \ + --max-new-tokens 128 +""" + +import argparse +import time +from pathlib import Path + +import torch +from executorch.examples.models.muse_glimmer.export.export_solo import ( + load_prequantized_model, +) +from executorch.examples.models.muse_glimmer.model.model import ( + materialize_runtime_buffers, + MuseGlimmerModel, +) +from tokenizers import Tokenizer + +BOS_TOKEN_ID = 200000 +EOS_TOKEN_ID = 200001 + + +def load_tokenizer(tokenizer_dir: str) -> Tokenizer: + """Load the Hugging Face tokenizer used by the runners.""" + path = Path(tokenizer_dir) + if path.is_dir(): + path = path / "tokenizer.json" + if not path.exists(): + raise FileNotFoundError(f"Tokenizer file not found at {path}") + return Tokenizer.from_file(str(path)) + + +def _move_to_cuda(model: MuseGlimmerModel) -> None: + """Move weights to CUDA, preserving tensor subclass identity.""" + for name, p in model.named_parameters(): + parts = name.rsplit(".", 1) + parent = model.get_submodule(parts[0]) if len(parts) > 1 else model + setattr( + parent, + parts[-1], + torch.nn.Parameter(p.data.to("cuda"), requires_grad=False), + ) + + for fqn, buf in list(model.named_buffers()): + if buf.device.type != "meta": + parts = fqn.rsplit(".", 1) + parent = model.get_submodule(parts[0]) if len(parts) > 1 else model + parent.register_buffer(parts[-1], buf.to("cuda"), persistent=False) + + materialize_runtime_buffers(model, dtype=torch.bfloat16, device="cuda") + + +def _sample(logits: torch.Tensor, temperature: float) -> int: + if temperature > 0: + probs = torch.nn.functional.softmax(logits / temperature, dim=-1) + return torch.multinomial(probs, 1).item() + return logits.argmax().item() + + +def generate( + model: MuseGlimmerModel, + tokenizer: Tokenizer, + prompt: str, + max_new_tokens: int = 128, + temperature: float = 0.0, + bos_token_id: int = BOS_TOKEN_ID, + eos_token_id: int = EOS_TOKEN_ID, +) -> str: + """Autoregressive generation with chunked multi-token prefill.""" + tokens = [bos_token_id] + tokenizer.encode(prompt, add_special_tokens=False).ids + max_chunk = model._sliding_window * 2 + print(f"Input: {len(tokens)} tokens") + + with torch.no_grad(): + # Chunked prefill: respects ring buffer size limit + pos = 0 + while pos < len(tokens): + chunk_len = min(len(tokens) - pos, max_chunk) + chunk = tokens[pos : pos + chunk_len] + input_ids = torch.tensor([chunk], dtype=torch.long, device="cuda") + input_pos = torch.arange( + pos, pos + chunk_len, dtype=torch.long, device="cuda" + ) + logits = model(input_ids, input_pos) + pos += chunk_len + + next_id = _sample(logits[0, -1].float(), temperature) + generated = [next_id] + + # Decode loop: one token at a time + seq_len = len(tokens) + for step in range(max_new_tokens - 1): + if next_id == eos_token_id: + break + + tok = torch.tensor([[next_id]], dtype=torch.long, device="cuda") + input_pos = torch.tensor([seq_len + step], dtype=torch.long, device="cuda") + logits = model(tok, input_pos) + next_id = _sample(logits[0, -1].float(), temperature) + generated.append(next_id) + + if (step + 1) % 20 == 0: + print(f" Generated {step + 1} tokens...") + + return tokenizer.decode(generated, skip_special_tokens=False) + + +def _load_image_normalized(image_path: str, config) -> torch.Tensor: + """Load an image, resize to the vision grid, normalize to [-1, 1]. + + Returns a ``[3, H, W]`` float tensor where H, W are multiples of + ``patch_size * downsample_factor`` (28), matching the eager preprocessing + (mean/std 0.5). + """ + from executorch.examples.models.muse_glimmer.vision.precompute import ( + compute_grid_size, + ) + from PIL import Image + + img = Image.open(image_path).convert("RGB") + target_h, target_w, _ = compute_grid_size(img.width, img.height, config) + img = img.resize((target_w, target_h), Image.LANCZOS) + buf = torch.frombuffer(bytearray(img.tobytes()), dtype=torch.uint8) + t = buf.reshape(target_h, target_w, 3).permute(2, 0, 1).float() + # Normalize [0,255] -> [-1,1] with mean/std 0.5. + return (t / 255.0 - 0.5) / 0.5 + + +def generate_with_image( + model: MuseGlimmerModel, + vision_model, + pos_embed_table: torch.Tensor, + tokenizer: Tokenizer, + prompt: str, + image_path: str, + max_new_tokens: int = 128, + temperature: float = 0.0, + bos_token_id: int = BOS_TOKEN_ID, + eos_token_id: int = EOS_TOKEN_ID, +) -> str: + """Multimodal generation: encode the image, splice soft tokens, decode. + + Mirrors the C++ runner path: run the vision encoder on host-precomputed + inputs, build ``[BOS] <|image_start|> <|patch|>*N <|image_end|> {prompt}``, + embed the tokens, overwrite the patch rows with vision features, then run + the unified ``prefill_from_embeds`` + per-token decode. + """ + from executorch.examples.models.muse_glimmer.vision.precompute import ( + MuseGlimmerVisionConfig, + precompute_vision_inputs, + ) + + PATCH_ID = tokenizer.token_to_id("<|patch|>") + if PATCH_ID is None: + raise ValueError("Tokenizer has no <|patch|> token") + + vcfg = MuseGlimmerVisionConfig() + # Host precompute runs on CPU (grid_sample needs table + grid co-located); + # move the resulting graph inputs to CUDA afterward. + image = _load_image_normalized(image_path, vcfg) + inputs = precompute_vision_inputs(image, pos_embed_table.cpu(), vcfg) + args = tuple( + a.to("cuda") if isinstance(a, torch.Tensor) else a for a in inputs.as_args() + ) + with torch.no_grad(): + image_embeds = vision_model(*args) # [1, N, hidden] + n_soft = image_embeds.shape[1] + print(f"Vision: {inputs.patches.shape[1]} patches -> {n_soft} soft tokens") + + text_tokens = tokenizer.encode(prompt, add_special_tokens=False).ids + tokens = [bos_token_id] + [PATCH_ID] * n_soft + text_tokens + max_chunk = model._sliding_window * 2 + + with torch.no_grad(): + tok_t = torch.tensor([tokens], dtype=torch.long, device="cuda") + embeds = model.embed_text(tok_t) # [1, T, hidden] + # Splice image rows at <|patch|> positions. + patch_positions = [i for i, t in enumerate(tokens) if t == PATCH_ID] + assert len(patch_positions) == n_soft + for j, i in enumerate(patch_positions): + embeds[0, i] = image_embeds[0, j].to(embeds.dtype) + + pos = 0 + logits = None + while pos < len(tokens): + chunk_len = min(len(tokens) - pos, max_chunk) + chunk = embeds[:, pos : pos + chunk_len] + input_pos = torch.arange( + pos, pos + chunk_len, dtype=torch.long, device="cuda" + ) + logits = model.prefill_from_embeds(chunk, input_pos) + pos += chunk_len + + next_id = _sample(logits[0, -1].float(), temperature) + generated = [next_id] + + seq_len = len(tokens) + for step in range(max_new_tokens - 1): + if next_id == eos_token_id: + break + tok = torch.tensor([[next_id]], dtype=torch.long, device="cuda") + input_pos = torch.tensor([seq_len + step], dtype=torch.long, device="cuda") + logits = model(tok, input_pos) + next_id = _sample(logits[0, -1].float(), temperature) + generated.append(next_id) + + return tokenizer.decode(generated, skip_special_tokens=False) + + +def main() -> None: + parser = argparse.ArgumentParser(description="Eager inference on Muse Glimmer.") + src = parser.add_mutually_exclusive_group(required=True) + src.add_argument( + "--checkpoint-dir", + default=None, + help="Path to consolidated bf16 checkpoint.", + ) + src.add_argument( + "--prequantized", + default=None, + help="Path to a quantized checkpoint directory.", + ) + src.add_argument( + "--gguf", + default=None, + help="Path to a GGUF checkpoint (fused, quantized, packed for CUDA).", + ) + parser.add_argument( + "--tokenizer-path", + required=True, + help="Hugging Face asset directory or tokenizer.json path.", + ) + parser.add_argument("--prompt", default="The meaning of life is") + parser.add_argument("--max-new-tokens", type=int, default=128) + parser.add_argument("--temperature", type=float, default=0.0) + parser.add_argument( + "--max-seq-len", type=int, default=16384, help="KV cache length." + ) + parser.add_argument("--no-compile", action="store_true", help="Skip torch.compile.") + parser.add_argument( + "--mmproj", + default=None, + help="Optional mmproj (clip/muse_glimmer) GGUF for the vision encoder. Enables " + "image input via --image.", + ) + parser.add_argument( + "--image", + default=None, + help="Optional path to an image file. Requires --mmproj.", + ) + parser.add_argument( + "--backend", + default="cuda", + choices=["cuda"], + help="Target backend.", + ) + args = parser.parse_args() + + if not torch.cuda.is_available(): + raise RuntimeError("CUDA is required.") + + if args.image and not args.mmproj: + parser.error("--image requires --mmproj (the vision encoder weights).") + + if args.prequantized: + print(f"Loading prequantized model from {args.prequantized}...") + model, config = load_prequantized_model( + args.prequantized, + max_seq_len=args.max_seq_len, + backend=args.backend, + ) + elif args.gguf: + from executorch.examples.models.muse_glimmer.loaders.checkpoint_loader import ( + load_gguf_model, + ) + + print(f"Loading GGUF model from {args.gguf}...") + model, config = load_gguf_model( + args.gguf, + max_seq_len=args.max_seq_len, + backend=args.backend, + ) + else: + print(f"Loading model from {args.checkpoint_dir}...") + model, config = MuseGlimmerModel.from_checkpoint( + args.checkpoint_dir, max_seq_len=args.max_seq_len + ) + _move_to_cuda(model) + model.eval() + + import executorch.backends.cuda.quantize_op_dispatch # noqa: F401 + + vision_model = None + pos_embed_table = None + if args.mmproj: + from executorch.examples.models.muse_glimmer.loaders.checkpoint_loader import ( + load_mmproj_vision_model, + ) + + print(f"Loading vision encoder from {args.mmproj}...") + vision_model, pos_embed_table, _ = load_mmproj_vision_model(args.mmproj) + _move_to_cuda(vision_model) + vision_model.eval() + + if not args.no_compile: + print("Compiling model with torch.compile...") + model = torch.compile(model, mode="default") + + tokenizer = load_tokenizer(args.tokenizer_path) + + print(f"\nPrompt: {args.prompt}") + if args.image: + print(f"Image: {args.image}") + print("-" * 40) + + t0 = time.perf_counter() + if args.image: + output = generate_with_image( + model, + vision_model, + pos_embed_table, + tokenizer, + args.prompt, + args.image, + max_new_tokens=args.max_new_tokens, + temperature=args.temperature, + ) + else: + output = generate( + model, + tokenizer, + args.prompt, + max_new_tokens=args.max_new_tokens, + temperature=args.temperature, + ) + elapsed = time.perf_counter() - t0 + + print(output) + print("-" * 40) + print(f"Generated in {elapsed:.2f}s") + + +if __name__ == "__main__": + main() diff --git a/examples/models/muse-glimmer/loaders/__init__.py b/examples/models/muse-glimmer/loaders/__init__.py new file mode 100644 index 00000000000..2e41cd717f6 --- /dev/null +++ b/examples/models/muse-glimmer/loaders/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. diff --git a/examples/models/muse-glimmer/loaders/checkpoint_loader.py b/examples/models/muse-glimmer/loaders/checkpoint_loader.py new file mode 100644 index 00000000000..0da3bac7d49 --- /dev/null +++ b/examples/models/muse-glimmer/loaders/checkpoint_loader.py @@ -0,0 +1,759 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""Load Muse Glimmer checkpoints and pack weights for CUDA or MLX. + +Input projections remain unfused until loading so mixed-precision GGUF, +prequantized safetensors, MLX-affine, and consolidated BF16 inputs share the +same backend-packing path. +""" + +from __future__ import annotations + +import os +import re + +import torch + +# GGUF tensor names to atomic Muse Glimmer FQNs. + +_GGUF_KEY_MAP: dict[str, str] = { + "token_embd.weight": "embed_tokens.weight", + "output.weight": "lm_head.weight", + "output_norm.weight": "output_norm.weight", + "blk.{}.attn_q.weight": "layers.{}.self_attn.q_proj.weight", + "blk.{}.attn_k.weight": "layers.{}.self_attn.k_proj.weight", + "blk.{}.attn_v.weight": "layers.{}.self_attn.v_proj.weight", + "blk.{}.attn_output.weight": "layers.{}.self_attn.o_proj.weight", + "blk.{}.attn_output_gate.weight": "layers.{}.self_attn.og_proj.weight", + # The 30B GGUFs renamed the output gate; older checkpoints still ship the + # attn_output_gate spelling, so both names have to resolve. + "blk.{}.attn_gate.weight": "layers.{}.self_attn.og_proj.weight", + "blk.{}.attn_norm.weight": "layers.{}.self_attn.qkv_proj_norm.weight", + "blk.{}.ffn_norm.weight": "layers.{}.mlp.norm.weight", + "blk.{}.post_attention_norm.weight": "layers.{}.post_attn_norm.weight", + "blk.{}.post_ffw_norm.weight": "layers.{}.post_ffn_norm.weight", + "blk.{}.ffn_gate.weight": "layers.{}.mlp.gate_proj.weight", + "blk.{}.ffn_up.weight": "layers.{}.mlp.up_proj.weight", + "blk.{}.ffn_down.weight": "layers.{}.mlp.down_proj.weight", +} + +_GGUF_IGNORED_KEYS = {"rope_freqs.weight"} +# Scaleless QK-norm weights (all-ones); model uses RMSNormNoWeight (no param). +_GGUF_QK_NORM_SUBSTRS = ("attn_q_norm", "attn_k_norm") + + +def _match_key_map(name: str, key_map: dict[str, str]) -> str | None: + """Resolve a checkpoint tensor name through a ``{}``-templated key map.""" + for pat, target in key_map.items(): + if "{}" not in pat: + if name == pat: + return target + continue + prefix, suffix = pat.split("{}") + if name.startswith(prefix) and name.endswith(suffix): + layer = name[len(prefix) : len(name) - len(suffix)] + if layer.isdigit(): + return target.replace("{}", layer) + return None + + +def gguf_to_model_key(gguf_key: str) -> str | None: + """Map a GGUF tensor name to an atomic (unfused) Muse Glimmer FQN, or ``None``.""" + if gguf_key in _GGUF_IGNORED_KEYS: + return None + if any(s in gguf_key for s in _GGUF_QK_NORM_SUBSTRS): + return None + return _match_key_map(gguf_key, _GGUF_KEY_MAP) + + +# MLX Hugging Face tensor names to atomic Muse Glimmer FQNs. +# Norm roles follow the checkpoint decoder; scaleless norms have no weights. +_MLX_HF_KEY_MAP: dict[str, str] = { + "language_model.model.embed_tokens.weight": "embed_tokens.weight", + "language_model.lm_head.weight": "lm_head.weight", + "language_model.model.norm.weight": "output_norm.weight", + "language_model.model.layers.{}.input_layernorm.weight": "layers.{}.self_attn.qkv_proj_norm.weight", + "language_model.model.layers.{}.post_attention_layernorm.weight": "layers.{}.mlp.norm.weight", + "language_model.model.layers.{}.post_attn_norm.weight": "layers.{}.post_attn_norm.weight", + "language_model.model.layers.{}.post_ffn_norm.weight": "layers.{}.post_ffn_norm.weight", + "language_model.model.layers.{}.self_attn.q_proj.weight": "layers.{}.self_attn.q_proj.weight", + "language_model.model.layers.{}.self_attn.k_proj.weight": "layers.{}.self_attn.k_proj.weight", + "language_model.model.layers.{}.self_attn.v_proj.weight": "layers.{}.self_attn.v_proj.weight", + "language_model.model.layers.{}.self_attn.o_proj.weight": "layers.{}.self_attn.o_proj.weight", + "language_model.model.layers.{}.self_attn.output_gate_proj.weight": "layers.{}.self_attn.og_proj.weight", + "language_model.model.layers.{}.mlp.gate_proj.weight": "layers.{}.mlp.gate_proj.weight", + "language_model.model.layers.{}.mlp.up_proj.weight": "layers.{}.mlp.up_proj.weight", + "language_model.model.layers.{}.mlp.down_proj.weight": "layers.{}.mlp.down_proj.weight", +} + + +def mlx_hf_to_model_key(hf_key: str) -> str | None: + """Map an MLX (HF ``MuseGlimmerForCausalLM``) tensor name to an atomic MuseGlimmer FQN.""" + return _match_key_map(hf_key, _MLX_HF_KEY_MAP) + + +# MLX affine-quantized safetensors reader (injected into iter_checkpoint via +# its ``raw_iter`` hook, so the shared loader stays MLX-agnostic). + + +def _mlx_shard_paths(path: str) -> list[str]: + """Resolve the safetensors shard file(s) for an MLX checkpoint dir.""" + import json + + if not os.path.isdir(path): + return [path] + index = os.path.join(path, "model.safetensors.index.json") + if os.path.exists(index): + with open(index, "r") as f: + weight_map = json.load(f)["weight_map"] + return [os.path.join(path, s) for s in sorted(set(weight_map.values()))] + single = os.path.join(path, "model.safetensors") + if os.path.exists(single): + return [single] + raise FileNotFoundError(f"No safetensors checkpoint in {path}") + + +def _mlx_affine_intx(packed, scales, biases, bits, group_size): + """Rebuild an MLX affine-quantized weight as a torchao ``IntxUnpackedToInt8Tensor``. + + ``packed`` is uint32 (``bits`` codes/word, little-endian bit-contiguous); + ``scales`` + optional ``biases`` are per group. Codes are centered to signed + and the affine bias folded into a float zero-point so ``scale * (qdata - + zero_point)`` reproduces MLX exactly (same rewrite as gguf.py for Q4_K/Q5_K). + + NOTE: assumes MLX's little-endian bit-contiguous packing (``group_size * + bits`` is a multiple of 32, so groups stay word-aligned). + """ + import numpy as np + from torchao.quantization import IntxUnpackedToInt8Tensor + + offset = 1 << (bits - 1) + # 6-bit uses an int8 container (like gguf.py's Q6_K); 4/5/8 map directly. + target_dtype = {4: torch.int4, 5: torch.int5, 6: torch.int8, 8: torch.int8}[bits] + + n = int(packed.shape[0]) + k = int(scales.shape[1]) * group_size + + # int32 view avoids torch's limited uint32->numpy support; bit pattern is + # identical. + words = packed.contiguous().cpu() + if words.dtype == torch.uint32: + words = words.view(torch.int32) + byte_view = torch.from_numpy(words.numpy().view(np.uint8)) # [N, 4W] + + # Extract each code by ``bits`` vectorized bit-plane gathers (byte index + + # intra-byte shift precomputed per code) in torch int8. + pos = torch.arange(k, dtype=torch.int64) * bits + pos = pos.unsqueeze(0) + torch.arange(bits, dtype=torch.int64).unsqueeze(1) + byte_idx = pos >> 3 # [bits, k] + byte_sh = (pos & 7).to(torch.uint8) # [bits, k] + qdata = torch.empty((n, k), dtype=torch.int8) + for i in range(0, n, 65536): + blk = byte_view[i : i + 65536] + codes = torch.zeros((blk.shape[0], k), dtype=torch.int8) + for t in range(bits): + codes += (((blk[:, byte_idx[t]] >> byte_sh[t]) & 1) << t).to(torch.int8) + qdata[i : i + 65536] = codes - int(offset) + + scales_f = scales.to(torch.float32) + if biases is not None: + zero = torch.where( + scales_f != 0, + -biases.to(torch.float32) / scales_f, + torch.zeros_like(scales_f), + ) + else: + zero = torch.full_like(scales_f, float(offset)) + + return IntxUnpackedToInt8Tensor( + qdata=qdata, + scale=scales, + zero_point=(zero - offset).to(scales.dtype), + target_dtype=target_dtype, + block_size=(1, group_size), + dtype=scales.dtype, + activation_quantization=None, + ) + + +def _iter_mlx(path: str): + """Yield raw ``(name, tensor)`` pairs from an MLX quantized dir (any format). + + One reader for every mlx_lm quant format. Each weight's *type* is resolved + per-tensor from ``config.json["quantization"]``: a default ``mode`` (absent + => ``affine``) / ``bits`` / ``group_size`` plus per-module override dicts + keyed by the HF module name (no ``.weight`` suffix), e.g. + ``"language_model.model.layers.0.self_attn.v_proj": {"mode": "mxfp8", ...}``. + The safetensors carry no per-tensor metadata, so these config entries are the + per-tensor type source. + + Each quantized weight is a ``X.weight`` (uint32 bit-packed codes) + a + ``X.scales`` pair, plus ``X.biases`` for affine. Dispatch by mode: + + * ``affine`` -> torchao ``IntxUnpackedToInt8Tensor`` (bit-unpacked; affine + bias folded into a float zero-point). + * ``nvfp4`` -> ``ExportableNVFP4Tensor`` (per-tensor scale 1.0 -- these + checkpoints carry no global scale). + * ``mxfp8`` -> ``ExportableMXTensor``. + + nvfp4/mxfp8 keep the MLX-native packed uint32/uint8 verbatim (the MLX kernel + consumes them directly); only affine is bit-unpacked. Unquantized tensors + (norms) pass through. Mixed-format checkpoints are handled per weight. + """ + import contextlib + import json + + from executorch.extension.llm.export.mx import ExportableMXTensor + from executorch.extension.llm.export.nvfp4 import ExportableNVFP4Tensor + from safetensors import safe_open + + with open(os.path.join(path, "config.json"), "r") as f: + quant = json.load(f)["quantization"] + default_mode = quant.get("mode", "affine") + # Per-weight overrides are the dict-valued entries, keyed by HF module name. + overrides = {k: v for k, v in quant.items() if isinstance(v, dict)} + + def _params_for(base: str): + cfg = overrides.get(base, {}) + return ( + cfg.get("mode", default_mode), + int(cfg.get("bits", quant["bits"])), + int(cfg.get("group_size", quant["group_size"])), + ) + + with contextlib.ExitStack() as stack: + handles = [ + stack.enter_context(safe_open(p, framework="pt", device="cpu")) + for p in _mlx_shard_paths(path) + ] + key_to_handle: dict = {} + for handle in handles: + for key in handle.keys(): + key_to_handle[key] = handle + + n_weights = sum(1 for key in key_to_handle if key.endswith(".weight")) + n_done = 0 + for key, handle in key_to_handle.items(): + if key.endswith(".scales") or key.endswith(".biases"): + continue # consumed alongside the paired ``.weight`` + if not key.endswith(".weight"): + yield key, handle.get_tensor(key) + continue + n_done += 1 + if n_done % 25 == 0 or n_done == n_weights: + print(f" MLX unpack: {n_done}/{n_weights} weights...", flush=True) + + base = key[: -len(".weight")] + scales_key = f"{base}.scales" + if scales_key not in key_to_handle: + yield key, handle.get_tensor(key) # unquantized (e.g. a norm) + continue + + qdata = handle.get_tensor(key) # uint32 [N, K*bits/32] + scales = key_to_handle[scales_key].get_tensor(scales_key) # [N, groups] + mode, bits, group_size = _params_for(base) + + if mode == "nvfp4": + pts = torch.tensor(1.0, dtype=torch.float32) + yield ( + key, + ExportableNVFP4Tensor( + qdata, + scales, + pts, + block_size=group_size, + orig_dtype=torch.bfloat16, + ), + ) + elif mode == "mxfp8": + # On disk MLX packs 4 E4M3 codes per uint32 and stores E8M0 + # scales as uint8; reinterpret to the backend-agnostic native + # dtypes ExportableMXTensor holds (the MLX handler repacks). + qdata_fp8 = qdata.view(torch.uint8).view(torch.float8_e4m3fn) + scale_e8m0 = scales.view(torch.uint8).view(torch.float8_e8m0fnu) + yield ( + key, + ExportableMXTensor( + qdata_fp8, + scale_e8m0, + elem_dtype=torch.float8_e4m3fn, + block_size=group_size, + orig_dtype=torch.bfloat16, + ), + ) + elif mode == "affine": + biases_key = f"{base}.biases" + biases = ( + key_to_handle[biases_key].get_tensor(biases_key) + if biases_key in key_to_handle + else None + ) + yield key, _mlx_affine_intx(qdata, scales, biases, bits, group_size) + else: + raise ValueError( + f"Unsupported MLX quantization mode {mode!r} for {key!r}" + ) + + +# Backend fusion groups: fused FQN -> ordered atomic shard FQNs. +# Slice order matches the fused forward in model.py (qko = [Q, K, OG]; +# gate_up = [gate, up]). v_proj stays standalone on CUDA for its own bit-width. + +_FUSION_GROUPS: dict[str, dict[str, list[str]]] = { + "cuda": { + "layers.{}.self_attn.qko_proj.weight": [ + "layers.{}.self_attn.q_proj.weight", + "layers.{}.self_attn.k_proj.weight", + "layers.{}.self_attn.og_proj.weight", + ], + "layers.{}.mlp.gate_up_proj.weight": [ + "layers.{}.mlp.gate_proj.weight", + "layers.{}.mlp.up_proj.weight", + ], + }, + "mlx": { + "layers.{}.mlp.gate_up_proj.weight": [ + "layers.{}.mlp.gate_proj.weight", + "layers.{}.mlp.up_proj.weight", + ], + }, +} + + +def _fuse_state_dict( + atomic_sd: dict, backend: str, n_layers: int +) -> tuple[dict, set[str]]: + """Fuse the atomic shards into the backend's fused projections. + + Returns a state dict keyed by the fused model's FQNs, plus the group templates + that fused successfully. Fused entries use ``fuse_along_output`` + (subclass-aware output-channel concat). A group stays atomic across every + layer if any layer contains incompatible quantization types. + """ + from executorch.extension.llm.export.quant import fuse_along_output + + groups = _FUSION_GROUPS[backend] + consumed: set[str] = set() + fused_sd: dict[str, torch.Tensor] = {} + fused_groups: set[str] = set() + for fused_tmpl, shard_tmpls in groups.items(): + group_sd = {} + group_consumed = set() + try: + for layer in range(n_layers): + fused_fqn = fused_tmpl.format(layer) + shard_fqns = [t.format(layer) for t in shard_tmpls] + if fused_fqn in atomic_sd: + group_sd[fused_fqn] = atomic_sd[fused_fqn] + group_consumed.add(fused_fqn) + continue + group_sd[fused_fqn] = fuse_along_output( + [atomic_sd[f] for f in shard_fqns] + ) + group_consumed.update(shard_fqns) + except ValueError as exc: + print(f"Keeping {fused_tmpl} projections separate: {exc}") + continue + fused_sd.update(group_sd) + consumed.update(group_consumed) + fused_groups.add(fused_tmpl) + for fqn, value in atomic_sd.items(): + if fqn not in consumed: + fused_sd[fqn] = value + return fused_sd, fused_groups + + +# Source heads: produce an atomic (unfused) quantized state dict. + + +def _atomic_sd_from_gguf(gguf_path: str, activation_dtype: torch.dtype) -> dict: + from executorch.extension.llm.export.load import iter_checkpoint + from executorch.extension.llm.export.quant import to_default + + return dict( + iter_checkpoint( + gguf_path, + key_map=gguf_to_model_key, + convert=to_default, + dtype=activation_dtype, + ) + ) + + +def _atomic_sd_from_safetensors( + safetensors_path: str, activation_dtype: torch.dtype +) -> dict: + from executorch.extension.llm.export.load import iter_checkpoint + from executorch.extension.llm.export.quant import to_default + + return dict( + iter_checkpoint(safetensors_path, convert=to_default, dtype=activation_dtype) + ) + + +def _atomic_sd_from_bf16( + checkpoint_dir: str, recipe, max_seq_len: int, activation_dtype: torch.dtype +) -> tuple[dict, object]: + from executorch.examples.models.muse_glimmer.model.model import ( + load_unfused_bf16_state_dict, + ) + from executorch.extension.llm.export.quant import quantize_stream, to_default + + bf16_sd, config = load_unfused_bf16_state_dict(checkpoint_dir, max_seq_len) + # Quantize on the fly, then normalize to the portable form (Int4Tensor -> + # ExportableInt4Tensor) so the downstream fuse/backend pass matches the + # safetensors/GGUF paths exactly. + atomic_sd = { + fqn: to_default(fqn, value) + for fqn, value in quantize_stream( + bf16_sd.items(), recipe, dtype=activation_dtype + ) + } + return atomic_sd, config + + +# Shared tail: fuse -> build fused model -> assign -> backend pass. + + +def _finalize(atomic_sd: dict, backend: str, config, activation_dtype: torch.dtype): + from executorch.examples.models.muse_glimmer.model.model import ( + materialize_runtime_buffers, + MuseGlimmerModel, + ) + from executorch.extension.llm.export.load import assign_state_dict + from executorch.extension.llm.export.quant import identity + + if backend == "cuda" and any( + fqn.endswith(".self_attn.qkv_proj.weight") for fqn in atomic_sd + ): + from executorch.extension.llm.export.int4 import ExportableInt4Tensor + + q_dim = config.n_heads * config.head_dim + kv_dim = config.n_kv_heads * config.head_dim + split_sd = {} + for fqn, value in atomic_sd.items(): + if not fqn.endswith(".self_attn.qkv_proj.weight"): + split_sd[fqn] = value + continue + prefix = fqn[: -len("qkv_proj.weight")] + if isinstance(value, ExportableInt4Tensor): + + def rows(start, end, value=value): + return ExportableInt4Tensor( + value.qdata[start:end], + value.scale[:, start:end], + value.zero_point[:, start:end], + value.group_size, + value.orig_dtype, + ) + + q = rows(0, q_dim) + k = rows(q_dim, q_dim + kv_dim) + v = rows(q_dim + kv_dim, q_dim + 2 * kv_dim) + og = rows(q_dim + 2 * kv_dim, value.shape[0]) + from executorch.extension.llm.export.quant import fuse_along_output + + split_sd[f"{prefix}qko_proj.weight"] = fuse_along_output([q, k, og]) + split_sd[f"{prefix}v_proj.weight"] = v + else: + from executorch.examples.models.muse_glimmer.model.model import ( + _split_fused_qkv_to_qko, + ) + + split_sd.update(_split_fused_qkv_to_qko({fqn: value}, config)) + atomic_sd = split_sd + + fused_sd, fused_groups = _fuse_state_dict(atomic_sd, backend, config.n_layers) + + # Fused runtime layout for the target backend. + config.fuse_qkv = False + config.fuse_qko = "layers.{}.self_attn.qko_proj.weight" in fused_groups + config.fuse_gate_up = "layers.{}.mlp.gate_up_proj.weight" in fused_groups + print("Building fused model on meta device...") + with torch.device("meta"): + model = MuseGlimmerModel(config) + + # Weights are already in portable form; assign directly (convert=identity). + assign_state_dict(model, fused_sd, convert=identity) + + if backend == "cuda": + from executorch.examples.models.gemma4_31b.cuda_packers import ( + convert_quantized_tensors_for_cuda, + ) + + print("Converting quantized tensors for CUDA...") + convert_quantized_tensors_for_cuda(model) + + materialize_runtime_buffers(model, dtype=activation_dtype) + model.eval() + print(f"Model: {config.n_layers} layers, dim={config.dim}") + return model + + +def _validate_backend(backend: str) -> None: + if backend not in ("cuda", "mlx"): + raise ValueError(f"Unsupported backend: {backend!r}. Supported: 'cuda', 'mlx'.") + + +# mmproj (vision encoder) loading. + +_VISION_LAYER_MAP: dict[str, str] = { + "attn_q": "blocks.{}.attn.q_proj", + "attn_k": "blocks.{}.attn.k_proj", + "attn_v": "blocks.{}.attn.v_proj", + "attn_out": "blocks.{}.attn.o_proj", + "ffn_up": "blocks.{}.mlp.c_fc", + "ffn_down": "blocks.{}.mlp.c_proj", + "ln1": "blocks.{}.ln_1", + "ln2": "blocks.{}.ln_2", +} + +_VISION_TOP_MAP: dict[str, str] = { + "v.patch_embd.weight": "conv1_linear.weight", + "v.pre_ln.weight": "ln_pre.weight", + "v.pre_ln.bias": "ln_pre.bias", + "v.post_ln.weight": "ln_post.weight", + "v.post_ln.bias": "ln_post.bias", + "mm.adapter_fc.weight": "adapter_fc.weight", + "mm.adapter_proj.weight": "adapter_proj.weight", + "mm.vision_proj.weight": "vision_proj.weight", + # The 30B mmproj uses numeric projector layer names. + "mm.0.weight": "adapter_fc.weight", + "mm.1.weight": "adapter_proj.weight", + "mm.2.weight": "vision_proj.weight", +} + +_VISION_POS_EMBD_KEY = "v.position_embd.weight" +_VISION_LAYER_RE = re.compile(r"^v\.blk\.(\d+)\.(.+)\.(weight|bias)$") + + +def load_mmproj_vision_model( # noqa: C901 + mmproj_path: str, + config=None, + backend: str = "cuda", + activation_dtype: torch.dtype = torch.bfloat16, +) -> tuple: + """Load an mmproj GGUF into a backend-ready ``MuseGlimmerVisionEncoder``. + + Quantized tensors remain in their native GGUF representation for MLX. CUDA + applies its shared terminal layout conversion, preserving source bit widths + on both backends. + """ + from executorch.examples.models.muse_glimmer.model.vision_tower import ( + MuseGlimmerVisionEncoder, + ) + from executorch.examples.models.muse_glimmer.vision.precompute import ( + MuseGlimmerVisionConfig, + ) + from executorch.extension.llm.export.gguf import ExportableGGUFTensor, iter_gguf + from executorch.extension.llm.export.load import assign_state_dict + from executorch.extension.llm.export.quant import identity + + _validate_backend(backend) + if config is None: + config = MuseGlimmerVisionConfig() + + print("Building vision encoder on meta device...") + with torch.device("meta"): + model = MuseGlimmerVisionEncoder(config) + + pos_embed_table = None + state_dict = {} + + print(f"Streaming mmproj GGUF from {mmproj_path}...") + for name, value in iter_gguf(mmproj_path): + if name == _VISION_POS_EMBD_KEY: + table = ( + value.dequantize(torch.bfloat16) + if isinstance(value, ExportableGGUFTensor) + else value.to(torch.bfloat16) + ) + pos_embed_table = table.contiguous() + continue + + match = _VISION_LAYER_RE.match(name) + if match is not None: + layer, leaf, kind = int(match.group(1)), match.group(2), match.group(3) + fqn_base = _VISION_LAYER_MAP.get(leaf) + if fqn_base is None: + continue + fqn = f"{fqn_base.format(layer)}.{kind}" + else: + fqn = _VISION_TOP_MAP.get(name) + if fqn is None: + continue + + if name == "v.patch_embd.weight" and not isinstance( + value, ExportableGGUFTensor + ): + if value.ndim == 4: + # The 30B GGUF folds the image-only temporal axis into a + # Conv2d weight: W_folded = sum_t W_t. The runner supplies the + # same image patch for every temporal slot, so [W_folded, 0] + # is exactly equivalent while retaining the shared flattened + # patch contract used by both CUDA and MLX. + folded = value.flatten(1) + temporal_padding = config.patch_dim - folded.shape[1] + if temporal_padding < 0: + raise RuntimeError( + f"mmproj patch embedding has {folded.shape[1]} input " + f"features, expected at most {config.patch_dim}" + ) + value = torch.nn.functional.pad( + folded, (0, temporal_padding) + ).contiguous() + if tuple(value.shape) != (config.latent_dim, config.patch_dim): + raise RuntimeError( + f"mmproj patch embedding shape {tuple(value.shape)} does not " + f"match ({config.latent_dim}, {config.patch_dim})" + ) + + if isinstance(value, ExportableGGUFTensor): + if backend == "mlx" and value.orig_dtype != activation_dtype: + value = ExportableGGUFTensor( + value.raw, value.ggml_type, activation_dtype + ) + elif value.dtype.is_floating_point: + value = value.to(activation_dtype) + state_dict[fqn] = value + + if pos_embed_table is None: + raise RuntimeError(f"mmproj {mmproj_path} missing {_VISION_POS_EMBD_KEY!r}") + + assign_state_dict(model, state_dict, convert=identity) + if backend == "cuda": + from executorch.examples.models.gemma4_31b.cuda_packers import ( + convert_quantized_tensors_for_cuda, + ) + + convert_quantized_tensors_for_cuda(model) + model.eval() + + print(f"Vision encoder: {config.n_layers} blocks, latent={config.latent_dim}") + return model, pos_embed_table, config + + +# Public entry points (stable signatures shared with export.py / callers). + + +def load_gguf_model( + gguf_path: str, + backend: str = "cuda", + max_seq_len: int = 131072, + config=None, + activation_dtype: torch.dtype = torch.bfloat16, +) -> tuple: + """Load a GGUF checkpoint into a Muse Glimmer model packed for ``backend``.""" + _validate_backend(backend) + from executorch.examples.models.muse_glimmer.model.model import MuseGlimmerConfig + + if config is None: + config = MuseGlimmerConfig(max_seq_len=max_seq_len) + print(f"Loading GGUF from {gguf_path}...") + atomic_sd = _atomic_sd_from_gguf(gguf_path, activation_dtype) + return _finalize(atomic_sd, backend, config, activation_dtype), config + + +def load_prequantized_model( + prequantized_dir: str, + max_seq_len: int = 16384, + backend: str = "cuda", + activation_dtype: torch.dtype = torch.bfloat16, +) -> tuple: + """Load an atomic quantized safetensors checkpoint, packed for ``backend``.""" + _validate_backend(backend) + from executorch.examples.models.muse_glimmer.model.model import MuseGlimmerConfig + + config = MuseGlimmerConfig.from_json(os.path.join(prequantized_dir, "params.json")) + config.max_seq_len = max_seq_len + safetensors_path = os.path.join(prequantized_dir, "model.safetensors") + print(f"Loading quantized checkpoint from {safetensors_path}...") + atomic_sd = _atomic_sd_from_safetensors(safetensors_path, activation_dtype) + return _finalize(atomic_sd, backend, config, activation_dtype), config + + +def load_and_quantize( + checkpoint_dir: str, + recipe, + max_seq_len: int = 16384, + backend: str = "cuda", + activation_dtype: torch.dtype = torch.bfloat16, +) -> tuple: + """Load a bf16 consolidated checkpoint, quantize, and pack for ``backend``.""" + _validate_backend(backend) + print(f"Loading + quantizing checkpoint from {checkpoint_dir}...") + atomic_sd, config = _atomic_sd_from_bf16( + checkpoint_dir, recipe, max_seq_len, activation_dtype + ) + return _finalize(atomic_sd, backend, config, activation_dtype), config + + +# Muse Glimmer ET ``RMSNorm`` applies its weight as an absolute gain, but the HF +# ``MuseGlimmerRMSNorm`` stores these norms as a delta from 1.0 (``rms_norm(x) * (1 + +# weight)``). Fold the delta by adding 1.0 on load -- same suffixes/offset as the +# consolidated ``.pt`` loader. ``output_norm`` is a direct-gain norm (excluded). +_MLX_DELTA_NORM_SUFFIXES = ( + ".qkv_proj_norm.weight", + ".mlp.norm.weight", + ".post_attn_norm.weight", + ".post_ffn_norm.weight", +) + + +def _mlx_target_convert(fqn: str, w: torch.Tensor) -> torch.Tensor: + """Weight convert for the MLX *target* load. + + Applies the standard portable conversion, then folds the HF ``MuseGlimmerRMSNorm`` + delta convention into muse_glimmer's ET ``RMSNorm``: the HF model stores those norm + weights as ``gain - 1`` (forward does ``rms_norm(x) * (1 + weight)``) while ET + applies the weight as an absolute gain, so add 1.0 -- the same suffixes and + offset the consolidated ``.pt`` loader uses (``model._load_and_remap_checkpoint``). + The final ``output_norm`` is a direct-gain norm and is intentionally excluded. + """ + from executorch.extension.llm.export.quant import to_default + + w = to_default(fqn, w) + if fqn.endswith(_MLX_DELTA_NORM_SUFFIXES): + w = w + 1.0 + return w + + +def load_mlx_model( + mlx_dir: str, + backend: str = "mlx", + max_seq_len: int = 131072, + config=None, + activation_dtype: torch.dtype = torch.bfloat16, +) -> tuple: + """Load an MLX-quantized safetensors checkpoint (e.g. mlx_lm output). + + The directory carries HF ``MuseGlimmerForCausalLM`` tensor names and a ``config.json`` + ``quantization`` block. ``_iter_mlx`` reads that block per weight (default + + per-module overrides) and builds the right representation for each tensor's + ``mode``: ``affine`` -> torchao intx, ``nvfp4`` -> ``ExportableNVFP4Tensor``, + ``mxfp8`` -> ``ExportableMXTensor`` (mixed-format checkpoints are handled + per weight). ``mlx_hf_to_model_key`` remaps the HF names to atomic Muse Glimmer FQNs + and ``_mlx_target_convert`` folds the HF RMSNorm delta into an absolute gain; + the standard fuse (gate/up) + backend pass then finalizes the model. + """ + _validate_backend(backend) + from executorch.examples.models.muse_glimmer.model.model import MuseGlimmerConfig + from executorch.extension.llm.export.load import iter_checkpoint + + if config is None: + config = MuseGlimmerConfig(max_seq_len=max_seq_len) + print(f"Loading MLX checkpoint from {mlx_dir}...") + atomic_sd = dict( + iter_checkpoint( + mlx_dir, + raw_iter=_iter_mlx, + key_map=mlx_hf_to_model_key, + convert=_mlx_target_convert, + dtype=activation_dtype, + ) + ) + return _finalize(atomic_sd, backend, config, activation_dtype), config diff --git a/examples/models/muse-glimmer/loaders/dflash_loader.py b/examples/models/muse-glimmer/loaders/dflash_loader.py new file mode 100644 index 00000000000..677d3ba8fcc --- /dev/null +++ b/examples/models/muse-glimmer/loaders/dflash_loader.py @@ -0,0 +1,203 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""Load a GGUF or MLX-affine DFlash draft checkpoint. + +Token embeddings and the output head are shared with the target model at +export time. +""" + +from __future__ import annotations + +from typing import Optional + +import torch +import torch.nn as nn + + +# GGUF pattern → model FQN pattern. ``{}`` is the layer index. +_KEY_MAP = { + "fc.weight": "fc.weight", + "enc.output_norm.weight": "hidden_norm.weight", + "output_norm.weight": "norm.weight", + "blk.{}.attn_q.weight": "layers.{}.self_attn.q_proj.weight", + "blk.{}.attn_k.weight": "layers.{}.self_attn.k_proj.weight", + "blk.{}.attn_v.weight": "layers.{}.self_attn.v_proj.weight", + "blk.{}.attn_output.weight": "layers.{}.self_attn.o_proj.weight", + "blk.{}.attn_norm.weight": "layers.{}.input_layernorm.weight", + "blk.{}.ffn_norm.weight": "layers.{}.post_attention_layernorm.weight", + "blk.{}.attn_q_norm.weight": "layers.{}.self_attn.q_norm.weight", + "blk.{}.attn_k_norm.weight": "layers.{}.self_attn.k_norm.weight", + "blk.{}.ffn_gate.weight": "layers.{}.mlp.gate_proj.weight", + "blk.{}.ffn_up.weight": "layers.{}.mlp.up_proj.weight", + "blk.{}.ffn_down.weight": "layers.{}.mlp.down_proj.weight", +} + +_IGNORED_KEYS = { + "rope_freqs.weight", +} + + +def dflash_gguf_to_model_key(gguf_key: str) -> Optional[str]: + """Map a DFlash GGUF tensor name to a model FQN, or ``None`` to skip.""" + if gguf_key in _IGNORED_KEYS: + return None + + for gguf_pat, model_pat in _KEY_MAP.items(): + if "{}" not in gguf_pat: + if gguf_key == gguf_pat: + return model_pat + continue + prefix, suffix = gguf_pat.split("{}") + if gguf_key.startswith(prefix) and gguf_key.endswith(suffix): + layer_str = gguf_key[len(prefix) : len(gguf_key) - len(suffix)] + if layer_str.isdigit(): + return model_pat.replace("{}", layer_str) + + return None + + +def _validate_no_meta(model: nn.Module) -> None: + """Ensure all parameters have been loaded.""" + for fqn, p in model.named_parameters(): + if p.device.type == "meta": + raise RuntimeError( + f"Weight '{fqn}' not found in DFlash GGUF file " + f"(model/checkpoint version mismatch?)" + ) + for p in model.parameters(): + p.requires_grad_(False) + + +def load_dflash_gguf( + gguf_path: str, + backend: str = "mlx", + max_seq_len: int = 131072, + activation_dtype: torch.dtype = torch.bfloat16, +) -> tuple: + """Load a DFlash draft GGUF, remap keys, and return (model, config). + + Streams weights through ``load_checkpoint`` with a DFlash key remap. The + caller applies backend-specific packing after loading. + + Returns ``(model, config)`` where config is a ``DFlashConfig``. + """ + from executorch.examples.models.muse_glimmer.model.dflash_model import ( + DFlashConfig, + DFlashDraftModel, + ) + from executorch.extension.llm.export.load import load_checkpoint + from executorch.extension.llm.export.quant import to_default + + # Read metadata from GGUF to build config + from gguf import GGUFReader, GGUFValueType + + reader = GGUFReader(gguf_path) + metadata = {} + for key, field in reader.fields.items(): + if field.types and field.types[0] == GGUFValueType.ARRAY: + # Array field: data values are in parts[field.data] + metadata[key] = [field.parts[i].tolist()[0] for i in field.data] + else: + # Scalar field + data = field.parts[-1] + if hasattr(data, "tolist"): + val = data.tolist() + metadata[key] = val[0] if len(val) == 1 else val + else: + metadata[key] = data + del reader + + config = DFlashConfig.from_gguf_metadata(metadata) + print( + f"DFlash config: {config.n_layers} layers, dim={config.dim}, " + f"block_size={config.block_size}, target_layers={config.target_layers}" + ) + + print("Building draft model on meta device...") + with torch.device("meta"): + model = DFlashDraftModel(config, max_context_length=max_seq_len) + + print(f"Loading DFlash draft from {gguf_path}...") + load_checkpoint( + gguf_path, + model, + key_map=dflash_gguf_to_model_key, + convert=to_default, + dtype=activation_dtype, + ) + _validate_no_meta(model) + model.eval() + + print(f"Loaded DFlash draft: {config.n_layers} layers, dim={config.dim}") + return model, config + + +def load_dflash_mlx( + mlx_dir: str, + backend: str = "mlx", + max_seq_len: int = 131072, + activation_dtype: torch.dtype = torch.bfloat16, +) -> tuple: + """Load an MLX affine-quantized DFlash draft (e.g. dflash-3l_wind2048-mlx-q5). + + The MLX draft's tensor names already match the ``DFlashDraftModel`` FQNs + (``fc``, ``hidden_norm``, ``norm``, per-layer ``self_attn`` / ``mlp`` / + layernorms / ``q_norm`` / ``k_norm``), so no key remap is needed: + ``iter_checkpoint`` auto-detects the MLX layout, ``_iter_mlx`` rebuilds each + ``(weight, scales, biases)`` triplet as a torchao intx tensor, and the draft + is already quantized. ``DFlashConfig`` is built + from the checkpoint's HF-style ``config.json``. Returns ``(model, config)``. + """ + import json + import os + + from executorch.examples.models.muse_glimmer.loaders.checkpoint_loader import ( + _iter_mlx, + ) + from executorch.examples.models.muse_glimmer.model.dflash_model import ( + DFlashConfig, + DFlashDraftModel, + ) + from executorch.extension.llm.export.load import load_checkpoint + from executorch.extension.llm.export.quant import to_default + + with open(os.path.join(mlx_dir, "config.json"), "r") as f: + c = json.load(f) + layer_types = c.get("layer_types", []) + config = DFlashConfig( + dim=c["hidden_size"], + n_layers=c["num_hidden_layers"], + n_heads=c["num_attention_heads"], + n_kv_heads=c["num_key_value_heads"], + head_dim=c["head_dim"], + ffn_dim=c["intermediate_size"], + vocab_size=c["vocab_size"], + block_size=c["block_size"], + target_layers=c["target_layer_ids"], + rope_theta=c["rope_theta"], + norm_eps=c["rms_norm_eps"], + mask_token_id=c["mask_token_id"], + max_seq_len=max_seq_len, + sliding_window=c.get("sliding_window"), + sliding_window_pattern=( + [lt == "sliding_attention" for lt in layer_types] if layer_types else None + ), + ) + + print("Building DFlash draft model on meta device...") + with torch.device("meta"): + model = DFlashDraftModel(config) + + print(f"Loading MLX DFlash draft from {mlx_dir}...") + load_checkpoint( + mlx_dir, model, raw_iter=_iter_mlx, convert=to_default, dtype=activation_dtype + ) + _validate_no_meta(model) + model.eval() + + print(f"Loaded DFlash draft: {config.n_layers} layers, dim={config.dim}") + return model, config diff --git a/examples/models/muse-glimmer/loaders/quantize_and_save.py b/examples/models/muse-glimmer/loaders/quantize_and_save.py new file mode 100644 index 00000000000..c30cee0653b --- /dev/null +++ b/examples/models/muse-glimmer/loaders/quantize_and_save.py @@ -0,0 +1,199 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""Quantize Muse Glimmer into an unfused, backend-independent checkpoint. + +Weights are streamed and quantized individually; backend projection fusion +happens when the checkpoint is loaded. +""" + +import argparse +import gc +import os +import shutil + +import torch +from executorch.examples.models.muse_glimmer.model.model import ( + load_unfused_bf16_state_dict, +) +from executorch.extension.llm.export.quant import ( + QuantConfig, + quantize_stream, + QuantRecipe, + QuantRule, +) + +# Quantization recipes keep norms unquantized and use wider weights for the +# sensitive projections. Atomic weights allow per-projection bit widths. + +_INT4 = QuantConfig(bits=4, group_size=32, symmetric=False, method="min_max") +_INT4_HQQ = QuantConfig(bits=4, group_size=32, symmetric=False, method="hqq") +_INT8 = QuantConfig(bits=8, group_size=32, symmetric=True, method="min_max") +_INT8_PER_AXIS = QuantConfig(bits=8, group_size=6656, symmetric=True, method="min_max") +_INT6 = QuantConfig(bits=6, group_size=32, symmetric=True, method="min_max") +_INT8_GS128 = QuantConfig(bits=8, group_size=128, symmetric=True, method="min_max") +_INT4_GS64 = QuantConfig(bits=4, group_size=64, symmetric=False, method="min_max") +_INT4_GS128 = QuantConfig(bits=4, group_size=128, symmetric=False, method="min_max") +_INT6_GS64 = QuantConfig(bits=6, group_size=64, symmetric=True, method="min_max") +_INT6_GS128 = QuantConfig(bits=6, group_size=128, symmetric=True, method="min_max") +_EDGE_LAYERS = set(range(13)) | set(range(39, 52)) + +RECIPE_NAMES = ( + "default", + "sensitive", + "int4", + "gguf", + "gguf_int8", + "gguf_int6_gs64", + "gguf_int6_gs128", + "gguf_int6only_gs128", +) + + +def build_recipes(use_int6: bool = False) -> dict[str, QuantRecipe]: + """Build the Muse Glimmer quant recipes. + + When ``use_int6`` is set, the weights that are otherwise int8 (the + embedding and the edge-layer o_proj/down_proj) are quantized to 6-bit at + group_size 32 instead. MLX backend only. ``use_int6`` does not affect the + 'gguf' recipe, which specifies its int6 layers explicitly. + """ + embed_cfg = _INT6 if use_int6 else _INT8_PER_AXIS + wide_cfg = _INT6 if use_int6 else _INT8 + + default = QuantRecipe( + rules=[ + QuantRule(r"embed_tokens\.weight", embed_cfg), + QuantRule(r".*norm\.weight", None), + QuantRule(r".*\.weight", _INT4), + ] + ) + sensitive = QuantRecipe( + rules=[ + QuantRule(r"embed_tokens\.weight", embed_cfg), + QuantRule(r".*norm\.weight", None), + QuantRule(r".*\.(o_proj|down_proj)\.weight", wide_cfg, layers=_EDGE_LAYERS), + QuantRule(r".*\.weight", _INT4_HQQ), + ] + ) + + # Mixed recipes keep v_proj, down_proj, and lm_head at higher precision. + def _gguf_style( + wide_cfg: QuantConfig, narrow_cfg: QuantConfig = _INT4 + ) -> QuantRecipe: + return QuantRecipe( + rules=[ + QuantRule(r"embed_tokens\.weight", narrow_cfg), + QuantRule(r".*norm\.weight", None), + QuantRule(r".*\.v_proj\.weight", wide_cfg), + QuantRule(r".*\.down_proj\.weight", wide_cfg), + QuantRule(r"lm_head\.weight", wide_cfg), + QuantRule(r".*\.weight", narrow_cfg), + ] + ) + + # All quantizable weights at int4 (including the embedding); norms + # unquantized. MLX-only (int4 embedding is not supported by the CUDA + # embedding packer). + int4 = QuantRecipe( + rules=[ + QuantRule(r".*norm\.weight", None), + QuantRule(r".*\.weight", _INT4), + ] + ) + + return { + "default": default, + "sensitive": sensitive, + "int4": int4, + "gguf": _gguf_style(_INT6), + "gguf_int8": _gguf_style(_INT8_GS128), + "gguf_int6_gs64": _gguf_style(_INT6_GS64, narrow_cfg=_INT4_GS64), + "gguf_int6_gs128": _gguf_style(_INT6_GS128, narrow_cfg=_INT4_GS128), + # int6 wide layers at gs128, int4 narrow layers stay at gs32. + "gguf_int6only_gs128": _gguf_style(_INT6_GS128), + } + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Quantize Muse Glimmer and save as an atomic quantized checkpoint." + ) + parser.add_argument( + "--checkpoint-dir", + required=True, + help="Path to consolidated Muse Glimmer checkpoint.", + ) + parser.add_argument( + "--output", + default="./muse_glimmer_int4", + help="Output directory.", + ) + parser.add_argument( + "--quant-recipe", + default="default", + choices=RECIPE_NAMES, + help="'default': int4 min_max linears + int8 per-axis embedding. " + "'sensitive': int8 for edge-layer o_proj/down_proj, int4 hqq elsewhere. " + "'int4': int4 everywhere incl. embedding (MLX-only). " + "'gguf': int6 v_proj/down_proj/lm_head, int4 elsewhere. " + "'gguf_int8': same but int8 gs128 on those layers. " + "'gguf_int6_gs128': like gguf but groupsize 128 for both int4 and int6.", + ) + parser.add_argument( + "--int6", + action="store_true", + help="Quantize the otherwise-int8 weights (embedding + edge-layer " + "o_proj/down_proj) to 6-bit at group_size 32 instead. MLX backend only.", + ) + args = parser.parse_args() + + recipe = build_recipes(args.int6)[args.quant_recipe] + + # Load the checkpoint as a fully-unfused (atomic) bf16 state dict. The full + # model is never instantiated; the weights stay mmap-backed so peak memory is + # the quantized output plus a small working set. + print("Loading checkpoint (atomic, unfused)...") + state_dict, _config = load_unfused_bf16_state_dict(args.checkpoint_dir) + + print(f"Quantizing (model-free) with recipe '{args.quant_recipe}'...") + quantized: dict[str, torch.Tensor] = {} + for fqn, value in quantize_stream(state_dict.items(), recipe, dtype=torch.bfloat16): + quantized[fqn] = value + print(f" Quantized: {fqn}", end="\r") + print() + del state_dict + gc.collect() + + os.makedirs(args.output, exist_ok=True) + safetensors_path = os.path.join(args.output, "model.safetensors") + print("Saving atomic quantized checkpoint...") + from safetensors.torch import save_file + from torchao.prototype.safetensors.safetensors_support import ( + flatten_tensor_state_dict, + ) + + tensors_data, metadata = flatten_tensor_state_dict(quantized) + # flatten_tensor_state_dict clones every quantized tensor, so drop the + # originals before writing. + n_tensors = len(quantized) + del quantized + gc.collect() + save_file(tensors_data, safetensors_path, metadata=metadata) + + # The checkpoint is atomic / backend-agnostic: no fusion layout is recorded + # (fusion is decided at load time per backend). Copy params.json verbatim. + params_src = os.path.join(args.checkpoint_dir, "params.json") + if os.path.exists(params_src): + shutil.copy2(params_src, os.path.join(args.output, "params.json")) + + size_mb = os.path.getsize(safetensors_path) / (1024 * 1024) + print(f"Saved {n_tensors} tensors ({size_mb:.1f} MB) to {args.output}/") + print(f"Done. Use with: python export.py --prequantized {args.output}") + + +if __name__ == "__main__": + main() diff --git a/examples/models/muse-glimmer/model/__init__.py b/examples/models/muse-glimmer/model/__init__.py new file mode 100644 index 00000000000..2e41cd717f6 --- /dev/null +++ b/examples/models/muse-glimmer/model/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. diff --git a/examples/models/muse-glimmer/model/dflash_model.py b/examples/models/muse-glimmer/model/dflash_model.py new file mode 100644 index 00000000000..d11958c068c --- /dev/null +++ b/examples/models/muse-glimmer/model/dflash_model.py @@ -0,0 +1,467 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""DFlash draft model for Muse Glimmer speculative decoding. + +The draft uses target hidden states as injected attention context and shares +the target token embeddings and output head. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass, field + +import torch +import torch.nn as nn +import torch.nn.functional as F +from executorch.examples.models.muse_glimmer.model.model import ( + FlatKVCache, + RingKVCache, + RMSNorm, + ROPE_SAFE_DTYPES, +) + + +def rotate_half( + x: torch.Tensor, + cos: torch.Tensor, + sin: torch.Tensor, + *, + allow_low_precision: bool = False, +) -> torch.Tensor: + """Apply half-split rotary embeddings to ``[B, H, T, D]`` input. + + Draft GGUF tensors use the NEOX layout while target tensors remain + interleaved, so the two models require different rotations. + """ + if allow_low_precision and x.dtype in ROPE_SAFE_DTYPES: + compute_dtype = x.dtype + else: + compute_dtype = torch.float32 + xc = x.to(compute_dtype) + cos = cos.to(compute_dtype) + sin = sin.to(compute_dtype) + half = xc.shape[-1] // 2 + x1 = xc[..., :half] + x2 = xc[..., half:] + return torch.cat([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1).to(x.dtype) + + +@dataclass +class DFlashConfig: + dim: int = 6656 + n_layers: int = 5 + n_heads: int = 32 + n_kv_heads: int = 8 + head_dim: int = 128 + ffn_dim: int = 19968 + vocab_size: int = 202048 + block_size: int = 16 + target_layers: list[int] = field(default_factory=lambda: [2, 14, 26, 38, 50]) + rope_theta: float = 500000.0 + norm_eps: float = 1e-5 + mask_token_id: int = 201818 + max_seq_len: int = 131072 + sliding_window: int | None = None + sliding_window_pattern: list[bool] | None = None + + @property + def n_target_layers(self) -> int: + return len(self.target_layers) + + @staticmethod + def from_gguf_metadata(metadata: dict) -> DFlashConfig: + return DFlashConfig( + dim=metadata.get("dflash.embedding_length", 6656), + n_layers=metadata.get("dflash.block_count", 5), + n_heads=metadata.get("dflash.attention.head_count", 32), + n_kv_heads=metadata.get("dflash.attention.head_count_kv", 8), + head_dim=metadata.get("dflash.attention.key_length", 128), + ffn_dim=metadata.get("dflash.feed_forward_length", 19968), + block_size=metadata.get("dflash.block_size", 16), + target_layers=metadata.get("dflash.target_layers", [2, 14, 26, 38, 50]), + rope_theta=metadata.get("dflash.rope.freq_base", 500000.0), + norm_eps=metadata.get("dflash.attention.layer_norm_rms_epsilon", 1e-5), + mask_token_id=metadata.get("tokenizer.ggml.mask_token_id", 201818), + max_seq_len=metadata.get("dflash.context_length", 131072), + sliding_window=metadata.get("dflash.attention.sliding_window", None), + sliding_window_pattern=metadata.get( + "dflash.attention.sliding_window_pattern", None + ), + ) + + +def build_dflash_swa_mask( + total_ctx: int, + block_len: int, + buf_size: int, + window_size: int, +) -> torch.Tensor: + """Build boolean validity mask for ring-buffer context + block K/V. + + The SWA ring buffer evicts entries beyond ``window_size``. This mask + marks which ring slots are filled — uniform for all Q positions (the + draft model's cross-attention is non-causal). Block entries are always + valid. + + Returns [1, 1, 1, buf_size + block_len] boolean mask (True = attend). + """ + slots = torch.arange(buf_size, dtype=torch.long) + ring_pos = slots + ((total_ctx - 1 - slots) // buf_size) * buf_size + valid = (ring_pos >= 0) & (ring_pos >= total_ctx - window_size) + blk_valid = torch.ones(block_len, dtype=torch.bool) + return torch.cat([valid, blk_valid]).unsqueeze(0).unsqueeze(0).unsqueeze(0) + + +class DFlashAttention(nn.Module): + """Non-causal cross-attention via KV injection with context KV cache. + + Q comes from the block tokens only. K/V are the concatenation of + cached context (from projected target hidden states) and block tokens — + the same k_proj/v_proj weights are used for both. + + Context K/V are cached: only new target hidden states are projected each + call. The cache is populated incrementally via ``input_pos[0]`` which + gives the write offset (ctx_start_pos). + """ + + def __init__( + self, + config: DFlashConfig, + max_context_length: int = 4096, + is_sliding: bool = False, + window_size: int | None = None, + ): + super().__init__() + self.n_heads = config.n_heads + self.n_kv_heads = config.n_kv_heads + self.head_dim = config.head_dim + q_dim = self.n_heads * self.head_dim + kv_dim = self.n_kv_heads * self.head_dim + + self.q_proj = nn.Linear(config.dim, q_dim, bias=False) + self.k_proj = nn.Linear(config.dim, kv_dim, bias=False) + self.v_proj = nn.Linear(config.dim, kv_dim, bias=False) + self.o_proj = nn.Linear(q_dim, config.dim, bias=False) + + self.q_norm = RMSNorm(self.head_dim, config.norm_eps) + self.k_norm = RMSNorm(self.head_dim, config.norm_eps) + + self.attn_scale = 1.0 / math.sqrt(self.head_dim) + self.rope_theta = config.rope_theta + self.is_sliding = is_sliding + self.window_size = window_size + + if is_sliding: + self.kv_cache = RingKVCache( + max_batch_size=1, + window_size=window_size, + num_kv_heads=self.n_kv_heads, + head_dim=self.head_dim, + ) + else: + self.kv_cache = FlatKVCache( + max_batch_size=1, + max_seq_len=max_context_length, + num_kv_heads=self.n_kv_heads, + head_dim=self.head_dim, + ) + + def forward( + self, + x: torch.Tensor, + target_hidden: torch.Tensor, + cos: torch.Tensor, + sin: torch.Tensor, + ctx_start: int, + total_ctx: int, + ) -> torch.Tensor: + """ + Args: + x: block token hidden states [B, T, D] + target_hidden: NEW projected target hidden [B, n_new, D] + cos, sin: RoPE frequencies [1, 1, total_ctx+T, head_dim//2] + ctx_start: cache write offset (number of already-cached positions) + total_ctx: total context length after adding new (ctx_start + n_new) + """ + B, T, _ = x.shape + n_new = target_hidden.shape[1] + + # Project new context K/V, apply k_norm, RoPE, then cache + k_new = self.k_proj(target_hidden).view( + B, n_new, self.n_kv_heads, self.head_dim + ) + v_new = self.v_proj(target_hidden).view( + B, n_new, self.n_kv_heads, self.head_dim + ) + k_new = self.k_norm(k_new) + k_new = k_new.transpose(1, 2) + v_new = v_new.transpose(1, 2) + k_new = rotate_half( + k_new, + cos[:, :, ctx_start:total_ctx, :], + sin[:, :, ctx_start:total_ctx, :], + ) + positions = torch.arange(ctx_start, total_ctx, device=k_new.device) + k_cached, v_cached = self.kv_cache.update(positions, k_new, v_new) + + if self.is_sliding: + attn_mask = build_dflash_swa_mask( + total_ctx, + T, + self.kv_cache.buf_size, + self.window_size, + ) + k_ctx = k_cached + v_ctx = v_cached + else: + k_ctx = k_cached[:, :, :total_ctx, :] + v_ctx = v_cached[:, :, :total_ctx, :] + attn_mask = None + + # Block K/V — computed fresh each call + k_blk = self.k_proj(x).view(B, T, self.n_kv_heads, self.head_dim) + v_blk = self.v_proj(x).view(B, T, self.n_kv_heads, self.head_dim) + k_blk = self.k_norm(k_blk) + k_blk = k_blk.transpose(1, 2) + v_blk = v_blk.transpose(1, 2) + k_blk = rotate_half( + k_blk, + cos[:, :, total_ctx : total_ctx + T, :], + sin[:, :, total_ctx : total_ctx + T, :], + ) + + # Q from block tokens + xq = self.q_proj(x).view(B, T, self.n_heads, self.head_dim) + xq = self.q_norm(xq) + xq = xq.transpose(1, 2) + xq = rotate_half( + xq, + cos[:, :, total_ctx : total_ctx + T, :], + sin[:, :, total_ctx : total_ctx + T, :], + ) + + # SDPA over cached context + block + k = torch.cat([k_ctx, k_blk], dim=2) + v = torch.cat([v_ctx, v_blk], dim=2) + + y = F.scaled_dot_product_attention( + xq, + k, + v, + attn_mask=attn_mask, + is_causal=False, + enable_gqa=True, + scale=self.attn_scale, + ) + y = y.transpose(1, 2).contiguous().reshape(B, T, -1) + return self.o_proj(y) + + +class DFlashMLP(nn.Module): + """SwiGLU MLP with separate gate/up projections.""" + + def __init__(self, config: DFlashConfig): + super().__init__() + self.gate_proj = nn.Linear(config.dim, config.ffn_dim, bias=False) + self.up_proj = nn.Linear(config.dim, config.ffn_dim, bias=False) + self.down_proj = nn.Linear(config.ffn_dim, config.dim, bias=False) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x)) + + +class DFlashDecoderLayer(nn.Module): + """DFlash decoder layer: pre-norm attention + pre-norm MLP.""" + + def __init__( + self, + config: DFlashConfig, + max_context_length: int = 4096, + is_sliding: bool = False, + window_size: int | None = None, + ): + super().__init__() + self.input_layernorm = RMSNorm(config.dim, config.norm_eps) + self.self_attn = DFlashAttention( + config, max_context_length, is_sliding, window_size + ) + self.post_attention_layernorm = RMSNorm(config.dim, config.norm_eps) + self.mlp = DFlashMLP(config) + + def forward( + self, + x: torch.Tensor, + target_hidden: torch.Tensor, + cos: torch.Tensor, + sin: torch.Tensor, + ctx_start: int, + total_ctx: int, + ) -> torch.Tensor: + x = x + self.self_attn( + self.input_layernorm(x), target_hidden, cos, sin, ctx_start, total_ctx + ) + x = x + self.mlp(self.post_attention_layernorm(x)) + return x + + +class DFlashDraftModel(nn.Module): + """DFlash draft model for block-parallel speculative decoding. + + Generates block_size tokens in a single forward pass. Does NOT own + embed_tokens or lm_head — those are shared from the target model. + + Each layer has a per-layer KV cache for context (projected target hidden + states). Only new target hidden states are projected each call. + + Forward: + noise_embedding: [B, T, D] — embedded [anchor, MASK, ..., MASK] + target_hidden: [B, n_new, N*D] — NEW target hidden states only + input_pos: [1] — ctx_start_pos (cache write offset) + Returns: + hidden: [B, T, D] — pass through target's lm_head to get logits + """ + + def __init__(self, config: DFlashConfig, max_context_length: int = 4096): + super().__init__() + self.config = config + + self.fc = nn.Linear(config.n_target_layers * config.dim, config.dim, bias=False) + self.hidden_norm = RMSNorm(config.dim, config.norm_eps) + + self.layers = nn.ModuleList( + [ + DFlashDecoderLayer( + config, + max_context_length, + is_sliding=( + config.sliding_window_pattern[i] + if config.sliding_window_pattern is not None + else False + ), + window_size=config.sliding_window, + ) + for i in range(config.n_layers) + ] + ) + + self.norm = RMSNorm(config.dim, config.norm_eps) + + self.rope_theta = config.rope_theta + self.head_dim = config.head_dim + + def forward( + self, + noise_embedding: torch.Tensor, + target_hidden: torch.Tensor, + input_pos: torch.Tensor, + ) -> torch.Tensor: + ctx = self.hidden_norm(self.fc(target_hidden)) + n_new = ctx.shape[1] + T = noise_embedding.shape[1] + ctx_start = input_pos[0].item() + total_ctx = ctx_start + n_new + + # RoPE frequencies for total_ctx + T positions + total_len = total_ctx + T + inv_freq = 1.0 / ( + self.rope_theta + ** ( + torch.arange( + 0, + self.head_dim, + 2, + device=input_pos.device, + dtype=torch.float32, + ) + / self.head_dim + ) + ) + freqs = torch.outer( + torch.arange(total_len, device=input_pos.device, dtype=torch.float32), + inv_freq, + ) + cos = torch.cos(freqs).unsqueeze(0).unsqueeze(0) + sin = torch.sin(freqs).unsqueeze(0).unsqueeze(0) + + x = noise_embedding + for layer in self.layers: + x = layer(x, ctx, cos, sin, ctx_start, total_ctx) + + return self.norm(x) + + +class MuseGlimmerWithDFlash(nn.Module): + """Wrapper combining target and draft models with shared weights. + + The target's embed_tokens and lm_head are shared with the draft. The ET + emitter deduplicates them by content hash when both methods are exported. + """ + + def __init__( + self, target: nn.Module, draft: nn.Module, target_config, draft_config + ): + super().__init__() + self.target = target + self.draft = draft + self.target_config = target_config + self.draft_config = draft_config + + def embed_text(self, tokens: torch.Tensor) -> torch.Tensor: + """Embed target tokens using the backend-transformed target contract.""" + return self.target.embed_text(tokens) + + def target_forward_from_embeddings( + self, inputs_embeds: torch.Tensor, input_pos: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor]: + """Run the hidden-tapped target from precomputed text/image embeddings.""" + return self.target.target_forward_from_embeddings(inputs_embeds, input_pos) + + def target_prefill_from_embeddings( + self, inputs_embeds: torch.Tensor, input_pos: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor]: + """Run long hidden-tapped target prefill from text/image embeddings.""" + return self.target.target_prefill_from_embeddings(inputs_embeds, input_pos) + + def target_forward( + self, tokens: torch.Tensor, input_pos: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor]: + """Backward-compatible token-input hidden-tapped target forward.""" + return self.target(tokens, input_pos) + + def draft_forward( + self, + draft_tokens: torch.Tensor, + target_hidden: torch.Tensor, + input_pos: torch.Tensor, + valid_ctx_len: torch.Tensor | None = None, + ) -> torch.Tensor: + noise_embedding = self.target.embed_tokens(draft_tokens).to( + self.target.activation_dtype + ) + + # valid_ctx_len is a CUDA-graph-only signal (fixed-shape padded context + + # a runtime valid length); the CUDA draft forward accepts it, while the + # eager reference and MLX forwards keep the 3-arg signature. + if valid_ctx_len is None: + h = self.draft(noise_embedding, target_hidden, input_pos) + else: + h = self.draft(noise_embedding, target_hidden, input_pos, valid_ctx_len) + + return self.target.lm_head(h).float() + + def draft_prefill( + self, + draft_tokens: torch.Tensor, + target_hidden: torch.Tensor, + input_pos: torch.Tensor, + ) -> torch.Tensor: + """Populate the Draft context cache without projecting logits.""" + noise_embedding = self.target.embed_tokens(draft_tokens).to( + self.target.activation_dtype + ) + return self.draft(noise_embedding, target_hidden, input_pos) diff --git a/examples/models/muse-glimmer/model/model.py b/examples/models/muse-glimmer/model/model.py new file mode 100644 index 00000000000..1a73d0e18cb --- /dev/null +++ b/examples/models/muse-glimmer/model/model.py @@ -0,0 +1,955 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""Backend-independent Muse Glimmer text model for ExecuTorch export. + +CUDA and MLX adaptations are applied by their source-transformation modules. +""" + +import json +import math +import os +import re +from dataclasses import dataclass +from typing import Optional + +import torch +import torch.nn as nn +from torch.nn import functional as F + + +# Config + + +@dataclass +class MuseGlimmerConfig: + dim: int = 6656 + n_layers: int = 52 + n_heads: int = 32 + n_kv_heads: int = 2 + head_dim: int = 128 + ffn_dim_multiplier: float = 3.0 + vocab_size: int = 202048 + norm_eps: float = 1e-5 + rope_theta: float = 500_000.0 + use_qk_norm: bool = True + use_attn_o_gate: bool = True + fuse_qkv: bool = True + # CUDA GGUF layout: fuse Q/K/output-gate into one projection but keep V + # separate so it can carry its own per-layer quant bit-width. Takes + # precedence over ``fuse_qkv`` when True. + fuse_qko: bool = False + fuse_gate_up: bool = True + output_soft_cap_temp: float = 20.0 + global_attn_cfg: str = "[2048,2048,2048,0]" + every_n_layers_nope: int = 4 + normalize_tok_embeddings: bool = True + output_multiplier: float = 0.19611613513 + post_norm_eps: float = 1e-8 + max_seq_len: int = 16384 + + @property + def ffn_dim(self) -> int: + return int(self.ffn_dim_multiplier * self.dim) + + @property + def attn_pattern(self) -> list[int]: + s = self.global_attn_cfg.strip("[]") + return [int(x) for x in s.split(",")] + + def layer_use_rope(self, layer_idx: int) -> bool: + return (self.n_layers - layer_idx - 1) % self.every_n_layers_nope != 0 + + def layer_window_size(self, layer_idx: int) -> int: + """Return window size for layer (0 = global attention).""" + nope_freq = self.every_n_layers_nope + count_backward = layer_idx + nope_freq - self.n_layers % nope_freq + pattern = self.attn_pattern + return pattern[count_backward % len(pattern)] + + @staticmethod + def from_json(path: str) -> "MuseGlimmerConfig": + with open(path) as f: + d = json.load(f) + return MuseGlimmerConfig( + **{ + k: v + for k, v in d.items() + if k in MuseGlimmerConfig.__dataclass_fields__ + } + ) + + +# Norms +# +# Norms are expressed canonically with ``F.rms_norm`` (a single op). The MLX +# backend consumes this directly (fused via ``FuseRMSNormPass``); the CUDA +# backend rewrites it to the decomposed elementwise form in +# ``cuda_source_transformations``. + + +class RMSNorm(nn.Module): + """RMSNorm with a learnable scale, expressed via ``F.rms_norm``.""" + + def __init__(self, dim: int, eps: float = 1e-5): + super().__init__() + self.dim = dim + self.eps = eps + self.weight = nn.Parameter(torch.ones(dim)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return F.rms_norm(x, (self.dim,), self.weight, self.eps) + + +class RMSNormNoWeight(nn.Module): + """Scaleless RMSNorm (QK-norm, embedding norm), expressed via ``F.rms_norm``.""" + + def __init__(self, dim: int, eps: float = 1e-5): + super().__init__() + self.dim = dim + self.eps = eps + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return F.rms_norm(x, (self.dim,), None, self.eps) + + +# Rotary Position Embeddings (interleaved cos/sin — no complex tensors) + + +# Dtypes whose mantissa preserves RoPE phase well enough to rotate in place, +# used only when a caller opts in via ``allow_low_precision`` (see +# rotate_interleaved). fp16 has a 10-bit mantissa (~1e-3); bf16 is deliberately +# absent because its 8-bit mantissa quantizes cos/sin too coarsely. +ROPE_SAFE_DTYPES: frozenset[torch.dtype] = frozenset({torch.float32, torch.float16}) + + +def rotate_interleaved( + x: torch.Tensor, + cos: torch.Tensor, + sin: torch.Tensor, + *, + allow_low_precision: bool = False, +) -> torch.Tensor: + """Apply interleaved (adjacent-pair) rotary embeddings. x: [B, H, T, D]. + + Pairs dims (2i, 2i+1) — matches ggml GGML_ROPE_TYPE_NORMAL / MLX + traditional=True. cos, sin: [..., T, D//2]. + + By default the rotation runs in fp32 (cast in, cast back) regardless of x's + dtype, matching the eager complex reference. A caller whose positions are + small and whose cos/sin are precomputed in fp32 -- the vision tower, on a + 32x32 grid -- may pass ``allow_low_precision=True`` to rotate natively when + x is in ``ROPE_SAFE_DTYPES`` (fp16/fp32), which drops the surrounding casts. + The decoder does not opt in: its long context makes the fp16 phase error + unverified, so it stays on fp32. + """ + if allow_low_precision and x.dtype in ROPE_SAFE_DTYPES: + compute_dtype = x.dtype + else: + compute_dtype = torch.float32 + xc = x.to(compute_dtype) + cos = cos.to(compute_dtype) + sin = sin.to(compute_dtype) + x1 = xc[..., 0::2] + x2 = xc[..., 1::2] + rx1 = x1 * cos - x2 * sin + rx2 = x1 * sin + x2 * cos + return torch.stack([rx1, rx2], dim=-1).flatten(-2).to(x.dtype) + + +def apply_rotary_emb( + q: torch.Tensor, + k: torch.Tensor, + cos: torch.Tensor, + sin: torch.Tensor, +) -> tuple[torch.Tensor, torch.Tensor]: + """Apply interleaved rotary embeddings to a q/k pair. q, k: [B, H, T, D].""" + return rotate_interleaved(q, cos, sin), rotate_interleaved(k, cos, sin) + + +# KV Caches + + +class RingKVCache(nn.Module): + """Ring-buffer KV cache for sliding window attention. + + Sized to ``window_size * 2`` to avoid index_copy_ collisions when + prefill chunks approach the window size. The C++ runner must chunk + prefill to not exceed buf_size. + """ + + def __init__( + self, + max_batch_size: int, + window_size: int, + num_kv_heads: int, + head_dim: int, + ): + super().__init__() + self.window_size = window_size + self.buf_size = window_size * 2 + cache_shape = (max_batch_size, num_kv_heads, self.buf_size, head_dim) + self.register_buffer("k_cache", torch.zeros(cache_shape), persistent=False) + self.register_buffer("v_cache", torch.zeros(cache_shape), persistent=False) + + def update( + self, + input_pos: torch.Tensor, + k_val: torch.Tensor, + v_val: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor]: + wrapped = input_pos % self.buf_size + self.k_cache.index_copy_(2, wrapped, k_val) + self.v_cache.index_copy_(2, wrapped, v_val) + return self.k_cache, self.v_cache + + +class FlatKVCache(nn.Module): + """Flat KV cache for global (non-sliding) attention layers.""" + + def __init__( + self, + max_batch_size: int, + max_seq_len: int, + num_kv_heads: int, + head_dim: int, + ): + super().__init__() + cache_shape = (max_batch_size, num_kv_heads, max_seq_len, head_dim) + self.register_buffer("k_cache", torch.zeros(cache_shape), persistent=False) + self.register_buffer("v_cache", torch.zeros(cache_shape), persistent=False) + + def update( + self, + input_pos: torch.Tensor, + k_val: torch.Tensor, + v_val: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor]: + self.k_cache.index_copy_(2, input_pos, k_val) + self.v_cache.index_copy_(2, input_pos, v_val) + return self.k_cache, self.v_cache + + +# Attention + + +class MuseGlimmerAttention(nn.Module): + """Muse Glimmer attention with fused QKV+OG, scaleless QK-norm, iRoPE, and GQA. + + Each layer is either sliding-window+RoPE or global+NoPE, determined at + init by the config's iRoPE and attention pattern. The same class handles + both; torch.export traces a fixed path per layer. + """ + + def __init__(self, config: MuseGlimmerConfig, layer_idx: int): + super().__init__() + self.layer_idx = layer_idx + self.n_heads = config.n_heads + self.n_kv_heads = config.n_kv_heads + self.head_dim = config.head_dim + + self.use_rope = config.layer_use_rope(layer_idx) + window = config.layer_window_size(layer_idx) + self.is_sliding = window > 0 + self.window_size = window + + self.use_o_gate = config.use_attn_o_gate + q_dim = self.n_heads * self.head_dim + kv_dim = self.n_kv_heads * self.head_dim + og_dim = q_dim if self.use_o_gate else 0 + self.q_dim = q_dim + self.kv_dim = kv_dim + self.fuse_qkv = config.fuse_qkv + self.fuse_qko = config.fuse_qko + + # Attention input pre-norm, shared by the projections below. + self.qkv_proj_norm = RMSNorm(config.dim, config.norm_eps) + # Three projection layouts (all mathematically equivalent): + # * fuse_qko (CUDA GGUF): Q/K/output-gate fused into ``qko_proj`` (all + # Q4_K) plus a standalone ``v_proj`` so V can carry its own per-layer + # quant bit-width (the GGUF stores attn_v at Q6_K on some layers, + # Q4_K on others, which a single fused qkv weight cannot express). + # * fuse_qkv (default): one fused ``qkv_proj`` (Q+K+V+OG), one matmul. + # * else: separate q/k/v/og projections (quantized independently). + if self.fuse_qko: + self.qko_proj = nn.Linear(config.dim, q_dim + kv_dim + og_dim, bias=False) + self.v_proj = nn.Linear(config.dim, kv_dim, bias=False) + elif self.fuse_qkv: + self.qkv_proj = nn.Linear( + config.dim, q_dim + 2 * kv_dim + og_dim, bias=False + ) + else: + self.q_proj = nn.Linear(config.dim, q_dim, bias=False) + self.k_proj = nn.Linear(config.dim, kv_dim, bias=False) + self.v_proj = nn.Linear(config.dim, kv_dim, bias=False) + if self.use_o_gate: + self.og_proj = nn.Linear(config.dim, og_dim, bias=False) + self.o_proj = nn.Linear(q_dim, config.dim, bias=False) + + # Attention scale passed to SDPA. Absorbs both the QK-norm query + # scaling (43.78.../sqrt(head_dim)) and SDPA's default 1/sqrt(head_dim), + # avoiding a separate tensor multiply that creates a convert_element_type + # op during AOTI constant folding. + self.attn_scale = (43.7840518911 / math.sqrt(config.head_dim)) / math.sqrt( + self.head_dim + ) + if config.use_qk_norm: + self.q_norm = RMSNormNoWeight(self.head_dim, config.norm_eps) + self.k_norm = RMSNormNoWeight(self.head_dim, config.norm_eps) + else: + self.q_norm = None + self.k_norm = None + + # RoPE inv_freq (only for RoPE layers) + self.rope_theta = config.rope_theta + if self.use_rope: + self.register_buffer("inv_freq", self._compute_inv_freq(), persistent=False) + + # KV cache: ring buffer for SWA, flat for global + if self.is_sliding: + self.kv_cache = RingKVCache( + max_batch_size=1, + window_size=self.window_size, + num_kv_heads=self.n_kv_heads, + head_dim=self.head_dim, + ) + else: + self.kv_cache = FlatKVCache( + max_batch_size=1, + max_seq_len=config.max_seq_len, + num_kv_heads=self.n_kv_heads, + head_dim=self.head_dim, + ) + + def _compute_inv_freq(self, device: torch.device | None = None) -> torch.Tensor: + """Compute RoPE inverse-frequency table for this layer.""" + return 1.0 / ( + self.rope_theta + ** ( + torch.arange(0, self.head_dim, 2, device=device, dtype=torch.float32) + / self.head_dim + ) + ) + + def forward( + self, + x: torch.Tensor, + input_pos: torch.Tensor, + attn_mask: torch.Tensor, + ) -> torch.Tensor: + B, T, _ = x.shape + + # Pre-norm shared by all projection layouts. + h = self.qkv_proj_norm(x) + if self.fuse_qko: + # Fused Q/K/output-gate projection, plus a separate V projection. + # Slice with [..., start:end] (decomposes to aten::slice, not + # aten::split_copy which lacks an AOTI fallback). qko: [Q | K | OG]. + qko = self.qko_proj(h) + q_end = self.q_dim + k_end = q_end + self.kv_dim + xq = qko[..., :q_end] + xk = qko[..., q_end:k_end] + og = qko[..., k_end:] if self.use_o_gate else None + xv = self.v_proj(h) + elif self.fuse_qkv: + qkv = self.qkv_proj(h) + # Slice Q, K, V, and optionally output gate from the fused + # projection. Uses [..., start:end] slicing (decomposes to + # aten::slice, not aten::split_copy which lacks an AOTI fallback). + q_end = self.q_dim + k_end = q_end + self.kv_dim + v_end = k_end + self.kv_dim + xq = qkv[..., :q_end] + xk = qkv[..., q_end:k_end] + xv = qkv[..., k_end:v_end] + og = qkv[..., v_end:] if self.use_o_gate else None + else: + xq = self.q_proj(h) + xk = self.k_proj(h) + xv = self.v_proj(h) + og = self.og_proj(h) if self.use_o_gate else None + + xq = xq.view(B, T, self.n_heads, self.head_dim) + xk = xk.view(B, T, self.n_kv_heads, self.head_dim) + xv = xv.view(B, T, self.n_kv_heads, self.head_dim) + + # QK-norm (scaleless, no query scaling — absorbed into SDPA scale) + if self.q_norm is not None: + xq = self.q_norm(xq) + xk = self.k_norm(xk) + + # Transpose to [B, H, T, D] for SDPA + xq = xq.transpose(1, 2) + xk = xk.transpose(1, 2) + xv = xv.transpose(1, 2) + + # RoPE (interleaved cos/sin) + if self.use_rope: + freqs = torch.outer(input_pos.float(), self.inv_freq) + cos = torch.cos(freqs).unsqueeze(0).unsqueeze(0) + sin = torch.sin(freqs).unsqueeze(0).unsqueeze(0) + xq, xk = apply_rotary_emb(xq, xk, cos, sin) + + # Update KV cache and read back full cache + k, v = self.kv_cache.update(input_pos, xk, xv) + + # SDPA with GQA. attn_scale absorbs both the muP query scaling + # and the standard 1/sqrt(head_dim), matching the standalone's + # (norm(Q) * scale_query_by) @ K^T / sqrt(head_dim). + y = F.scaled_dot_product_attention( + xq, + k, + v, + attn_mask=attn_mask, + is_causal=False, + enable_gqa=True, + scale=self.attn_scale, + ) + y = y.transpose(1, 2).contiguous() + + # Output gate: sigmoid(OG) * attn_output + if self.use_o_gate and og is not None: + og = og.view(B, T, self.n_heads, self.head_dim) + y = torch.sigmoid(og) * y + + y = y.reshape(B, T, -1) + return self.o_proj(y) + + +# MLP (SwiGLU) + + +class MuseGlimmerMLP(nn.Module): + """SwiGLU MLP with pre-norm. Gate+up can be fused or separate.""" + + def __init__(self, config: MuseGlimmerConfig): + super().__init__() + self.intermediate_size = config.ffn_dim + self.fuse_gate_up = config.fuse_gate_up + self.norm = RMSNorm(config.dim, config.norm_eps) + if self.fuse_gate_up: + self.gate_up_proj = nn.Linear(config.dim, 2 * config.ffn_dim, bias=False) + else: + self.gate_proj = nn.Linear(config.dim, config.ffn_dim, bias=False) + self.up_proj = nn.Linear(config.dim, config.ffn_dim, bias=False) + self.down_proj = nn.Linear(config.ffn_dim, config.dim, bias=False) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + h = self.norm(x) + if self.fuse_gate_up: + h = self.gate_up_proj(h) + gate = h[..., : self.intermediate_size] + up = h[..., self.intermediate_size :] + else: + gate = self.gate_proj(h) + up = self.up_proj(h) + return self.down_proj(F.silu(gate) * up) + + +# Decoder block + + +class MuseGlimmerDecoderLayer(nn.Module): + def __init__(self, config: MuseGlimmerConfig, layer_idx: int): + super().__init__() + self.self_attn = MuseGlimmerAttention(config, layer_idx) + self.mlp = MuseGlimmerMLP(config) + self.post_attn_norm = RMSNorm(config.dim, config.post_norm_eps) + self.post_ffn_norm = RMSNorm(config.dim, config.post_norm_eps) + self.is_sliding = self.self_attn.is_sliding + + def forward( + self, + x: torch.Tensor, + input_pos: torch.Tensor, + sliding_mask: torch.Tensor, + global_mask: torch.Tensor, + ) -> torch.Tensor: + attn_mask = sliding_mask if self.is_sliding else global_mask + + attn_out = self.self_attn(x, input_pos, attn_mask) + x = x + self.post_attn_norm(attn_out) + + ffn_out = self.mlp(x) + x = x + self.post_ffn_norm(ffn_out) + + return x + + +# Top-level model + + +class MuseGlimmerModel(nn.Module): + def __init__(self, config: MuseGlimmerConfig): + super().__init__() + self.config = config + self.normalize_tok_embeddings = config.normalize_tok_embeddings + + self.embed_tokens = nn.Embedding(config.vocab_size, config.dim) + if config.normalize_tok_embeddings: + self.tok_norm = RMSNormNoWeight(config.dim, config.norm_eps) + + self.layers = nn.ModuleList( + [MuseGlimmerDecoderLayer(config, i) for i in range(config.n_layers)] + ) + + self.output_norm = RMSNorm(config.dim, config.norm_eps) + self.lm_head = nn.Linear(config.dim, config.vocab_size, bias=False) + + # Sliding window size for mask building (from config pattern) + self._sliding_window = max(config.attn_pattern) + + # Constants as buffers so they move with .to(device) + self.register_buffer( + "output_multiplier", + torch.tensor(config.output_multiplier), + persistent=False, + ) + self.register_buffer( + "logit_softcap", + torch.tensor(config.output_soft_cap_temp), + persistent=False, + ) + self.register_buffer( + "cache_positions", + torch.arange(config.max_seq_len, dtype=torch.long), + persistent=False, + ) + + def _build_masks( + self, input_pos: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor]: + """Build boolean (1, 1, T_q, T_kv) masks for global and sliding attention. + + True = attend. Built once per forward, shared across layers of the + same type. + """ + # Global (causal) mask: (1, 1, T_q, max_seq_len) + cache_pos = self.cache_positions + q_pos = input_pos.unsqueeze(1) + causal = q_pos >= cache_pos.unsqueeze(0) + global_mask = causal.unsqueeze(0).unsqueeze(0) + + # Sliding window mask over ring buffer: (1, 1, T_q, buf_size) + window_size = self._sliding_window + buf_size = window_size * 2 + seq_len = input_pos.shape[0] + total_written = input_pos[0] + seq_len + j = torch.arange(buf_size, dtype=torch.long, device=input_pos.device) + ring_pos = j + ((total_written - 1 - j) // buf_size) * buf_size + delta = q_pos - ring_pos.unsqueeze(0) + sliding = (ring_pos >= 0) & (delta >= 0) & (delta < window_size) + sliding_mask = sliding.unsqueeze(0).unsqueeze(0) + + return sliding_mask, global_mask + + def _soft_cap(self, logits: torch.Tensor) -> torch.Tensor: + """Output soft-capping: cap * tanh(logits * multiplier / cap).""" + mult = self.output_multiplier.float() + cap = self.logit_softcap.float() + return torch.tanh(logits.float() * mult / cap) * cap + + def embed_text(self, tokens: torch.LongTensor) -> torch.Tensor: + """Token embedding lookup + (optional) scaleless norm, cast to bf16. + + This is the exported ``embed_text`` method and the first stage of the + multimodal prefill: the runner calls it to get ``inputs_embeds``, then + (for image input) overwrites the rows at ``patch_token_id`` positions + with vision features before calling ``prefill_from_embeds``. Numerically + identical to the embedding stage of the original text-only ``forward``. + + Args: + tokens: (B, T) token IDs. + + Returns: + (B, T, dim) bfloat16 embeddings. + """ + x = self.embed_tokens(tokens) + if self.normalize_tok_embeddings: + x = self.tok_norm(x) + return x.to(torch.bfloat16) + + def _run_blocks( + self, + x: torch.Tensor, + input_pos: torch.LongTensor, + ) -> torch.Tensor: + """Run the 52 decoder layers over pre-embedded (bf16) hidden states. + + ``x`` is the layer-0 input (already ``embed_text``-scaled bf16). Shared + by ``prefill_from_embeds`` and ``decode_forward`` so all entry points + run the identical decoder stack. + """ + sliding_mask, global_mask = self._build_masks(input_pos) + for layer in self.layers: + x = layer(x, input_pos, sliding_mask, global_mask) + return x + + def prefill_from_embeds( + self, + inputs_embeds: torch.Tensor, + input_pos: torch.LongTensor, + ) -> torch.Tensor: + """Run the model on PRE-COMPUTED embeddings (unified prefill). + + This is the exported ``prefill`` entry: the runner builds + ``inputs_embeds`` via ``embed_text`` (+ image splice for multimodal) and + passes it here. Used for BOTH text-only and image+text. + + Args: + inputs_embeds: (B, T, dim) bfloat16 embeddings. + input_pos: (T,) absolute positions for RoPE / KV cache. + + Returns: + (B, T, V) float32 soft-capped logits. + """ + x = self._run_blocks(inputs_embeds, input_pos) + x = self.output_norm(x) + return self._soft_cap(self.lm_head(x)) + + def forward( + self, + tokens: torch.LongTensor, + input_pos: torch.LongTensor, + ) -> torch.Tensor: + """Run the model on tokens (text-only / NLL path). + + Equivalent to ``prefill_from_embeds(embed_text(tokens), input_pos)`` — a + numerically-identical decomposition of the original text-only forward. + Retained as the token-input entry for the ``--logits`` NLL export path. + + Args: + tokens: (B, T) token IDs. + input_pos: (T,) absolute positions for RoPE / KV cache. + + Returns: + (B, T, V) float32 soft-capped logits. Sampling is performed by the + caller (host) or a backend source transform, not in the model. + """ + return self.prefill_from_embeds(self.embed_text(tokens), input_pos) + + # Checkpoint loading + + @staticmethod + def from_checkpoint( + checkpoint_dir: str, + max_seq_len: int = 16384, + fuse_qkv: Optional[bool] = None, + ) -> tuple["MuseGlimmerModel", MuseGlimmerConfig]: + """Load a consolidated Muse Glimmer checkpoint (mp_1/ format). + + Expects ``checkpoint_dir/params.json`` and ``checkpoint_dir/mp_1/model_0.pt``. + + ``fuse_qkv`` overrides the value from ``params.json`` (default fused). When + false, the checkpoint's fused ``qkv_proj.weight`` is split by rows into + separate q/k/v/og projections so they can be quantized independently. + When ``config.fuse_qko`` is set, it is instead split into ``qko_proj`` + ([Q|K|OG]) + ``v_proj`` ([V]) for the CUDA per-layer-bit-width layout. + """ + config = MuseGlimmerConfig.from_json( + os.path.join(checkpoint_dir, "params.json") + ) + config.max_seq_len = max_seq_len + if fuse_qkv is not None: + config.fuse_qkv = fuse_qkv + + with torch.device("meta"): + model = MuseGlimmerModel(config) + + state_dict = _load_and_remap_checkpoint(checkpoint_dir) + if config.fuse_qko: + state_dict = _split_fused_qkv_to_qko(state_dict, config) + elif not config.fuse_qkv: + state_dict = _split_fused_qkv(state_dict, config) + + missing, unexpected = model.load_state_dict( + state_dict, strict=False, assign=True + ) + del state_dict + + runtime_prefixes = ( + ".kv_cache.", + ".inv_freq", + "output_multiplier", + "logit_softcap", + "cache_positions", + ) + actual_missing = set(missing) + expected = {k for k in actual_missing if any(p in k for p in runtime_prefixes)} + extra = actual_missing - expected + if extra: + raise RuntimeError(f"Missing weight keys: {sorted(extra)[:10]}") + if unexpected: + raise RuntimeError(f"Unexpected keys: {sorted(unexpected)[:10]}") + + return model, config + + +# Weight loading utilities + + +_IGNORED_PREFIXES = ( + "vision_projection.", + "perception_emb_norm.", +) + +# Checkpoint key → model key. ``{}`` = layer index placeholder. +_CKPT_KEY_MAP = { + # Embeddings + "tok_embeddings.weight": "embed_tokens.weight", + # Output + "output_norm.weight": "output_norm.weight", + "output.weight": "lm_head.weight", + # Per-layer attention. The consolidated checkpoint fuses Q/K/V/OG into one + # ``qkv_proj`` weight. It is mapped directly here; for the split (fuse_qkv= + # False) or CUDA qko (fuse_qko=True) layouts it is post-split in + # ``from_checkpoint`` via ``_split_fused_qkv`` / ``_split_fused_qkv_to_qko``. + "layers.{}.attention.qkv_proj_norm.weight": "layers.{}.self_attn.qkv_proj_norm.weight", + "layers.{}.attention.qkv_proj.weight": "layers.{}.self_attn.qkv_proj.weight", + "layers.{}.attention.o_proj.weight": "layers.{}.self_attn.o_proj.weight", + # Per-layer MLP + "layers.{}.feed_forward.norm.weight": "layers.{}.mlp.norm.weight", + "layers.{}.feed_forward.fc1_weight": "layers.{}.mlp.gate_up_proj.weight", + "layers.{}.feed_forward.fc2_weight": "layers.{}.mlp.down_proj.weight", + # Per-layer post-norms (same name in both) + "layers.{}.post_attn_norm.weight": "layers.{}.post_attn_norm.weight", + "layers.{}.post_ffn_norm.weight": "layers.{}.post_ffn_norm.weight", +} + +# Pre-remapping: raw checkpoint keys have variant naming for some norms. +_RAW_KEY_FIXES = [ + (".attention.qkv_proj.norm_weight", ".attention.qkv_proj_norm.weight"), + (".attention.qkv_proj.norm.weight", ".attention.qkv_proj_norm.weight"), + (".feed_forward.norm_weight", ".feed_forward.norm.weight"), + ("output.norm_weight", "output_norm.weight"), + ("output.norm.weight", "output_norm.weight"), +] + + +def _fix_raw_key(key: str) -> str: + for old, new in _RAW_KEY_FIXES: + key = key.replace(old, new) + return key + + +def _ckpt_to_model_key(key: str) -> Optional[str]: + if key.startswith(_IGNORED_PREFIXES): + return None + + for ckpt_pat, model_pat in _CKPT_KEY_MAP.items(): + if "{}" not in ckpt_pat: + if key == ckpt_pat: + return model_pat + continue + regex = re.escape(ckpt_pat).replace(r"\{\}", r"(\d+)") + m = re.fullmatch(regex, key) + if m: + return model_pat.replace("{}", m.group(1), 1) + return None + + +def _load_and_remap_checkpoint(checkpoint_dir: str) -> dict[str, torch.Tensor]: + """Load mp_1/model_0.pt and remap keys to model state_dict keys.""" + ckpt_path = os.path.join(checkpoint_dir, "mp_1", "model_0.pt") + if not os.path.exists(ckpt_path): + available = os.listdir(checkpoint_dir) if os.path.isdir(checkpoint_dir) else [] + raise FileNotFoundError( + f"Checkpoint not found at {ckpt_path}. " + f"Available: {available}. " + f"Re-run consolidation with --produce_mp_sizes 1." + ) + + # mmap=True keeps the (~56 GB bf16) weights file-backed instead of loading + # them all into anonymous RAM. quantize_model then pages in one tensor at a + # time and the OS can evict the clean pages, so peak memory is the quantized + # output (~15-20 GB) plus a small working set rather than the whole model + + # output (~75 GB, which OOMs a 64 GB machine). The checkpoint is already + # bf16, so .to(bf16) below is a no-op and preserves the mmap views. + raw = torch.load(ckpt_path, map_location="cpu", weights_only=True, mmap=True) + + # Gemma-family checkpoints store norm weights as deltas from 1.0. + # Fold +1.0 so the model can use standard RMSNorm (weight used directly). + _MUSE_GLIMMER_NORM_SUFFIXES = ( + ".qkv_proj_norm.weight", + ".mlp.norm.weight", + ".post_attn_norm.weight", + ".post_ffn_norm.weight", + ) + + state_dict: dict[str, torch.Tensor] = {} + skipped = 0 + for raw_key, value in raw.items(): + fixed_key = _fix_raw_key(raw_key) + model_key = _ckpt_to_model_key(fixed_key) + if model_key is None: + skipped += 1 + continue + value = value.to(dtype=torch.bfloat16) + if any(model_key.endswith(s) for s in _MUSE_GLIMMER_NORM_SUFFIXES): + value = value + 1.0 + state_dict[model_key] = value + del raw + + return state_dict + + +def _split_fused_qkv( + state_dict: dict[str, torch.Tensor], config: MuseGlimmerConfig +) -> dict[str, torch.Tensor]: + """Split each fused ``self_attn.qkv_proj.weight`` into q/k/v/og projections. + + The fused weight has output rows laid out as [Q | K | V | OG] with sizes + ``q_dim``, ``kv_dim``, ``kv_dim``, ``og_dim``. Used when the model is built + with ``fuse_qkv=False`` so q/k/v/og can be quantized independently. + """ + q_dim = config.n_heads * config.head_dim + kv_dim = config.n_kv_heads * config.head_dim + use_o_gate = config.use_attn_o_gate + + out: dict[str, torch.Tensor] = {} + for key, value in state_dict.items(): + if not key.endswith(".self_attn.qkv_proj.weight"): + out[key] = value + continue + prefix = key[: -len("qkv_proj.weight")] + q_end = q_dim + k_end = q_end + kv_dim + v_end = k_end + kv_dim + out[f"{prefix}q_proj.weight"] = value[:q_end] + out[f"{prefix}k_proj.weight"] = value[q_end:k_end] + out[f"{prefix}v_proj.weight"] = value[k_end:v_end] + if use_o_gate: + out[f"{prefix}og_proj.weight"] = value[v_end:] + return out + + +def _split_fused_qkv_to_qko( + state_dict: dict[str, torch.Tensor], config: MuseGlimmerConfig +) -> dict[str, torch.Tensor]: + """Split each fused ``self_attn.qkv_proj.weight`` into ``qko_proj`` + ``v_proj``. + + The fused weight rows are laid out ``[Q | K | V | OG]``. This produces + ``qko_proj`` = ``[Q | K | OG]`` (V removed from the middle) plus a standalone + ``v_proj`` = ``[V]``, matching the CUDA ``fuse_qko`` layout so V can carry its + own per-layer quant bit-width. + """ + q_dim = config.n_heads * config.head_dim + kv_dim = config.n_kv_heads * config.head_dim + use_o_gate = config.use_attn_o_gate + + out: dict[str, torch.Tensor] = {} + for key, value in state_dict.items(): + if not key.endswith(".self_attn.qkv_proj.weight"): + out[key] = value + continue + prefix = key[: -len("qkv_proj.weight")] + q_end = q_dim + k_end = q_end + kv_dim + v_end = k_end + kv_dim + q = value[:q_end] + k = value[q_end:k_end] + v = value[k_end:v_end] + parts = [q, k] + if use_o_gate: + parts.append(value[v_end:]) + out[f"{prefix}qko_proj.weight"] = torch.cat(parts, dim=0) + out[f"{prefix}v_proj.weight"] = v + return out + + +def _split_gate_up( + state_dict: dict[str, torch.Tensor], config: MuseGlimmerConfig +) -> dict[str, torch.Tensor]: + """Split each fused ``mlp.gate_up_proj.weight`` into gate/up projections. + + The fused weight has output rows laid out as [gate | up], each of size + ``ffn_dim``. Splitting yields the atomic (unfused) layout so gate and up are + stored as independent weights; fusion back into ``gate_up_proj`` is then a + load-time concern (see ``checkpoint_loader``). + """ + ffn_dim = config.ffn_dim + out: dict[str, torch.Tensor] = {} + for key, value in state_dict.items(): + if not key.endswith(".mlp.gate_up_proj.weight"): + out[key] = value + continue + prefix = key[: -len("gate_up_proj.weight")] + out[f"{prefix}gate_proj.weight"] = value[:ffn_dim] + out[f"{prefix}up_proj.weight"] = value[ffn_dim:] + return out + + +def load_unfused_bf16_state_dict( + checkpoint_dir: str, max_seq_len: int = 16384 +) -> tuple[dict[str, torch.Tensor], MuseGlimmerConfig]: + """Load a consolidated Muse Glimmer checkpoint as a fully-unfused bf16 state dict. + + Returns ``(state_dict, config)`` with the consolidated checkpoint's fused + ``qkv_proj`` split into q/k/v/og and fused ``gate_up_proj`` split into + gate/up -- the atomic, backend-agnostic layout. Quantization and per-backend + fusion both operate on this canonical form downstream (``quantize_and_save`` + and ``checkpoint_loader``), so no fusion layout is baked into the checkpoint. + """ + config = MuseGlimmerConfig.from_json(os.path.join(checkpoint_dir, "params.json")) + config.max_seq_len = max_seq_len + state_dict = _load_and_remap_checkpoint(checkpoint_dir) + state_dict = _split_fused_qkv(state_dict, config) + state_dict = _split_gate_up(state_dict, config) + return state_dict, config + + +# Runtime buffer materialization + + +def materialize_runtime_buffers( + model: MuseGlimmerModel, + dtype: torch.dtype, + device: str = "cpu", +) -> None: + """Replace meta-device buffers with real tensors. + + Called after weight loading to fill in KV caches (zeros), RoPE tables, + and scalar constants. Only touches buffers still on the meta device. + """ + config = model.config + + for fqn, buf in list(model.named_buffers()): + if buf.device.type != "meta": + continue + parts = fqn.rsplit(".", 1) + parent = model.get_submodule(parts[0]) if len(parts) > 1 else model + is_kv = ".kv_cache." in fqn + target_dtype = dtype if is_kv else torch.float32 + parent.register_buffer( + parts[-1], + torch.zeros(buf.shape, dtype=target_dtype, device=device), + persistent=False, + ) + + # Recompute inv_freq (zero-fill above is wrong for RoPE frequencies) + for layer in model.layers: + attn = layer.self_attn + if attn.use_rope and hasattr(attn, "_compute_inv_freq"): + attn.register_buffer( + "inv_freq", attn._compute_inv_freq(device=device), persistent=False + ) + + model.register_buffer( + "output_multiplier", + torch.tensor(config.output_multiplier, device=device), + persistent=False, + ) + model.register_buffer( + "logit_softcap", + torch.tensor(config.output_soft_cap_temp, device=device), + persistent=False, + ) + model.register_buffer( + "cache_positions", + torch.arange(config.max_seq_len, dtype=torch.long, device=device), + persistent=False, + ) diff --git a/examples/models/muse-glimmer/model/vision_tower.py b/examples/models/muse-glimmer/model/vision_tower.py new file mode 100644 index 00000000000..8f3fb5a1795 --- /dev/null +++ b/examples/models/muse-glimmer/model/vision_tower.py @@ -0,0 +1,197 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""Exportable Muse Glimmer vision encoder. + +Data-dependent preprocessing runs on the host, leaving only ``num_patches`` +dynamic in the device graph. +""" + +from __future__ import annotations + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from executorch.examples.models.muse_glimmer.model.model import ( + RMSNormNoWeight, + rotate_interleaved, +) +from executorch.examples.models.muse_glimmer.vision.precompute import ( + MuseGlimmerVisionConfig, +) + + +# Attention / MLP / block + + +class MuseGlimmerVisionAttention(nn.Module): + """Bidirectional multi-head attention with 2D RoPE (bias-ful projections).""" + + def __init__(self, config: MuseGlimmerVisionConfig): + super().__init__() + self.n_heads = config.n_heads + self.head_dim = config.head_dim + dim = config.latent_dim + qkv_dim = self.n_heads * self.head_dim + self.q_proj = nn.Linear(dim, qkv_dim, bias=True) + self.k_proj = nn.Linear(dim, qkv_dim, bias=True) + self.v_proj = nn.Linear(dim, qkv_dim, bias=True) + self.o_proj = nn.Linear(qkv_dim, dim, bias=True) + + def forward( + self, + x: torch.Tensor, # [1, P, dim] + cos: torch.Tensor, # [1, P, 1, head_dim//2] + sin: torch.Tensor, # [1, P, 1, head_dim//2] + attn_mask: torch.Tensor, # [1, 1, P, P] bool + ) -> torch.Tensor: + B, P, _ = x.shape + q = self.q_proj(x).view(B, P, self.n_heads, self.head_dim) + k = self.k_proj(x).view(B, P, self.n_heads, self.head_dim) + v = self.v_proj(x).view(B, P, self.n_heads, self.head_dim) + + # 2D RoPE (real interleaved form). Small grid positions + fp32-precomputed + # cos/sin make fp16 rotation safe, so opt into native-dtype rotation. + q = rotate_interleaved(q, cos, sin, allow_low_precision=True) + k = rotate_interleaved(k, cos, sin, allow_low_precision=True) + + q = q.transpose(1, 2) # [B, H, P, head_dim] + k = k.transpose(1, 2) + v = v.transpose(1, 2) + + # Default SDPA scale (1/sqrt(head_dim)) matches the eager encoder. + out = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask) + out = out.transpose(1, 2).contiguous().view(B, P, self.n_heads * self.head_dim) + return self.o_proj(out) + + +class MuseGlimmerVisionMLP(nn.Module): + """Bias-enabled feed-forward block used by the vision encoder.""" + + def __init__(self, config: MuseGlimmerVisionConfig): + super().__init__() + self.c_fc = nn.Linear(config.latent_dim, config.mlp_hidden, bias=True) + self.c_proj = nn.Linear(config.mlp_hidden, config.latent_dim, bias=True) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.c_proj(F.gelu(self.c_fc(x))) + + +class MuseGlimmerVisionBlock(nn.Module): + """Pre-LayerNorm vision transformer block.""" + + def __init__(self, config: MuseGlimmerVisionConfig): + super().__init__() + self.ln_1 = nn.LayerNorm(config.latent_dim) + self.attn = MuseGlimmerVisionAttention(config) + self.ln_2 = nn.LayerNorm(config.latent_dim) + self.mlp = MuseGlimmerVisionMLP(config) + + def forward( + self, + x: torch.Tensor, + cos: torch.Tensor, + sin: torch.Tensor, + attn_mask: torch.Tensor, + ) -> torch.Tensor: + x = x + self.attn(self.ln_1(x), cos, sin, attn_mask) + x = x + self.mlp(self.ln_2(x)) + return x + + +# Top-level encoder (encoder + adapter + projection + perception norm) + + +class MuseGlimmerVisionEncoder(nn.Module): + """End-to-end image branch: host-precomputed patch inputs -> text-space embeds. + + Submodule names match the mmproj GGUF mapping. The positional-embedding + table is loaded separately for host preprocessing. + """ + + def __init__(self, config: MuseGlimmerVisionConfig | None = None): + super().__init__() + if config is None: + config = MuseGlimmerVisionConfig() + self.config = config + self.downsample_factor = config.downsample_factor + + self.conv1_linear = nn.Linear(config.patch_dim, config.latent_dim, bias=False) + self.ln_pre = nn.LayerNorm(config.latent_dim) + self.blocks = nn.ModuleList( + [MuseGlimmerVisionBlock(config) for _ in range(config.n_layers)] + ) + self.ln_post = nn.LayerNorm(config.latent_dim) + + self.adapter_fc = nn.Linear( + config.encoder_output_dim, config.adapter_dim, bias=False + ) + self.adapter_proj = nn.Linear( + config.adapter_dim, config.adapter_dim, bias=False + ) + self.vision_proj = nn.Linear(config.adapter_dim, config.hidden_size, bias=False) + self.perception_emb_norm = RMSNormNoWeight( + config.hidden_size, config.rms_norm_eps + ) + + # Static per-layer routing (global vs sparse attention), resolved at + # trace time. + self._is_global = [config.layer_is_global(i) for i in range(config.n_layers)] + + def forward( + self, + patches: torch.Tensor, # [1, P, patch_dim] f32 + pos_emb: torch.Tensor, # [1, P, latent] bf16 + cos_2d: torch.Tensor, # [P, head_dim//2] f32 + sin_2d: torch.Tensor, # [P, head_dim//2] f32 + sparse_perm: torch.Tensor, # [P] i64 + inv_perm: torch.Tensor, # [P] i64 + global_mask: torch.Tensor, # [1, 1, P, P] bool + sparse_mask: torch.Tensor, # [1, 1, P, P] bool + pixel_perm: torch.Tensor, # [P] i64 + ) -> torch.Tensor: # [1, P//f^2, hidden_size] activation dtype + w_dtype = self.conv1_linear.weight.dtype + + # Patch embed + host-interpolated positional embedding + pre-norm. + x = self.conv1_linear(patches.to(w_dtype)) + x = x + pos_emb.to(w_dtype) + x = self.ln_pre(x) + + # Sparse tiling: reorder tokens (and RoPE) so each 32x32 block is + # contiguous; global layers see all tokens, sparse layers see one block. + x = x.index_select(1, sparse_perm) + cos_p = cos_2d.index_select(0, sparse_perm) + sin_p = sin_2d.index_select(0, sparse_perm) + # [P, head_dim//2] -> [1, P, 1, head_dim//2] for rotate_interleaved. + cos_b = cos_p.unsqueeze(0).unsqueeze(2) + sin_b = sin_p.unsqueeze(0).unsqueeze(2) + + for i, block in enumerate(self.blocks): + mask = global_mask if self._is_global[i] else sparse_mask + x = block(x, cos_b, sin_b, mask) + + # Undo the sparse permutation, then final norm. + x = x.index_select(1, inv_perm) + x = self.ln_post(x) + + # Pixel-shuffle 2x downsample: gather then (n_out, f*f, d)->(n_out, d*f*f). + f = self.downsample_factor + d = self.config.latent_dim + x_flat = x[0].index_select(0, pixel_perm) # [P, d] + x_ds = ( + x_flat.view(-1, f * f, d) + .permute(0, 2, 1) + .contiguous() + .view(1, -1, d * f * f) + ) # [1, P//f^2, d*f^2] + + # Adapter -> projection into text space -> perception norm. + x_ds = F.gelu(self.adapter_fc(x_ds)) + x_ds = F.gelu(self.adapter_proj(x_ds)) + x_ds = self.vision_proj(x_ds) + x_ds = self.perception_emb_norm(x_ds) + return x_ds.to(w_dtype) diff --git a/examples/models/muse-glimmer/runtime/engine/dflash_session.cpp b/examples/models/muse-glimmer/runtime/engine/dflash_session.cpp new file mode 100644 index 00000000000..50a84452115 --- /dev/null +++ b/examples/models/muse-glimmer/runtime/engine/dflash_session.cpp @@ -0,0 +1,1317 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef EXECUTORCH_BUILD_CUDA +#include +#endif + +namespace executorch::extension::llm { +namespace { + +using ::executorch::extension::from_blob; +using ::executorch::runtime::Error; +using ::executorch::runtime::EValue; +using ::executorch::runtime::Result; +using SizesType = executorch::aten::SizesType; +using Clock = std::chrono::steady_clock; + +constexpr const char* kTargetForwardFromEmbeddings = + "target_forward_from_embeddings"; +constexpr const char* kTargetPrefillFromEmbeddings = + "target_prefill_from_embeddings"; +constexpr const char* kEmbedText = "embed_text"; +constexpr const char* kDraftForward = "draft_forward"; +constexpr const char* kDraftPrefill = "draft_prefill"; +constexpr const char* kMaxContextLen = "get_max_seq_len"; + +bool valid_temperature(float temperature) { + return temperature == -1.0f || (temperature >= 0.0f && temperature <= 2.0f); +} + +bool valid_top_p(float top_p) { + return top_p > 0.0f && top_p <= 1.0f; +} + +bool same_sampling(const SamplingConfig& lhs, const SamplingConfig& rhs) { + return lhs.temperature == rhs.temperature && lhs.top_p == rhs.top_p && + lhs.top_k == rhs.top_k && lhs.seed == rhs.seed; +} + +double elapsed_ms(Clock::time_point start, Clock::time_point end) { + return std::chrono::duration(end - start).count(); +} + +class ProbabilityWorkers { + public: + explicit ProbabilityWorkers(int64_t worker_count) { + workers_.reserve(worker_count); + for (int64_t worker_index = 0; worker_index < worker_count; + ++worker_index) { + auto worker = std::make_unique(); + worker->thread = std::thread([this, worker_index, worker = worker.get()] { + run_worker(worker_index, worker->workspace); + }); + workers_.push_back(std::move(worker)); + } + } + + ~ProbabilityWorkers() { + { + std::lock_guard guard(mutex_); + stopping_ = true; + ++generation_; + } + start_.notify_all(); + for (auto& worker : workers_) { + worker->thread.join(); + } + } + + ProbabilityWorkers(const ProbabilityWorkers&) = delete; + ProbabilityWorkers& operator=(const ProbabilityWorkers&) = delete; + + void fill( + const executorch::aten::Tensor& logits, + int64_t row_count, + int64_t logits_row_offset, + int64_t probabilities_row_offset, + double temperature, + int32_t top_k, + double top_p, + std::vector>& probabilities) { + const int64_t vocab_size = logits.size(logits.dim() - 1); + { + std::lock_guard guard(mutex_); + logits_ = static_cast(logits.const_data_ptr()); + vocab_size_ = vocab_size; + row_count_ = row_count; + logits_row_offset_ = logits_row_offset; + probabilities_row_offset_ = probabilities_row_offset; + temperature_ = temperature; + top_k_ = top_k; + top_p_ = top_p; + probabilities_ = &probabilities; + row_stride_ = workers_.size() + (row_count > workers_.size() ? 1 : 0); + completed_ = 0; + ++generation_; + } + start_.notify_all(); + if (row_count > static_cast(workers_.size())) { + for (int64_t row = workers_.size(); row < row_count; row += row_stride_) { + muse_glimmer::fill_sampling_probabilities( + logits_ + (logits_row_offset + row) * vocab_size, + vocab_size, + temperature, + top_k, + top_p, + probabilities[probabilities_row_offset + row], + caller_workspace_); + } + } + std::unique_lock lock(mutex_); + done_.wait(lock, [this] { return completed_ == workers_.size(); }); + } + + private: + struct Worker { + muse_glimmer::SamplingWorkspace workspace; + std::thread thread; + }; + + void run_worker( + int64_t worker_index, + muse_glimmer::SamplingWorkspace& workspace) { + uint64_t observed_generation = 0; + while (true) { + const float* logits = nullptr; + int64_t vocab_size = 0; + int64_t row_count = 0; + int64_t logits_row_offset = 0; + int64_t probabilities_row_offset = 0; + int64_t row_stride = 0; + double temperature = 0.0; + int32_t top_k = 0; + double top_p = 1.0; + std::vector>* probabilities = nullptr; + { + std::unique_lock lock(mutex_); + start_.wait(lock, [this, &observed_generation] { + return stopping_ || generation_ != observed_generation; + }); + if (stopping_) { + return; + } + observed_generation = generation_; + logits = logits_; + vocab_size = vocab_size_; + row_count = row_count_; + logits_row_offset = logits_row_offset_; + probabilities_row_offset = probabilities_row_offset_; + row_stride = row_stride_; + temperature = temperature_; + top_k = top_k_; + top_p = top_p_; + probabilities = probabilities_; + } + + for (int64_t row = worker_index; row < row_count; row += row_stride) { + muse_glimmer::fill_sampling_probabilities( + logits + (logits_row_offset + row) * vocab_size, + vocab_size, + temperature, + top_k, + top_p, + (*probabilities)[probabilities_row_offset + row], + workspace); + } + + { + std::lock_guard guard(mutex_); + ++completed_; + if (completed_ == workers_.size()) { + done_.notify_one(); + } + } + } + } + + std::vector> workers_; + std::mutex mutex_; + std::condition_variable start_; + std::condition_variable done_; + bool stopping_ = false; + uint64_t generation_ = 0; + size_t completed_ = 0; + const float* logits_ = nullptr; + int64_t vocab_size_ = 0; + int64_t row_count_ = 0; + int64_t logits_row_offset_ = 0; + int64_t probabilities_row_offset_ = 0; + int64_t row_stride_ = 0; + double temperature_ = 0.0; + int32_t top_k_ = 0; + double top_p_ = 1.0; + std::vector>* probabilities_ = nullptr; + muse_glimmer::SamplingWorkspace caller_workspace_; +}; + +class DFlashSession final : public LLMSession, public DFlashMultimodalSession { + public: + explicit DFlashSession(DFlashSessionConfig config) + : config_(std::move(config)), + block_length_( + config_.block_length > 0 ? config_.block_length + : config_.block_size), + n_draft_(config_.n_draft > 0 ? config_.n_draft : block_length_ - 1), + hidden_dtype_( + config_.activation_dtype == "bfloat16" + ? executorch::aten::ScalarType::BFloat16 + : executorch::aten::ScalarType::Half), + rng_(std::random_device{}()) {} + + ~DFlashSession() override { + probability_workers_.reset(); + if (config_.mutable_state != nullptr && + config_.session_token != kMuseGlimmerNoMutableSession) { + config_.mutable_state->destroy_session(config_.session_token); + } + if (config_.live_sessions != nullptr) { + config_.live_sessions->fetch_sub(1); + } + } + + Error prefill_tokens( + const std::vector& tokens, + const SamplingConfig* initial_sampling) override { + // Moving the staged value up front makes image staging one-shot on every + // prefill exit path, including validation failures. + std::optional image = std::move(staged_image_); + staged_image_.reset(); + preserve_staged_image_on_next_reset_ = false; + + if (poisoned_) { + ET_LOG(Error, "DFlashSession is poisoned; reset before prefill"); + return Error::InvalidState; + } + if (tokens.empty()) { + ET_LOG(Error, "DFlash prefill requires at least one token"); + return Error::InvalidArgument; + } + + int64_t next_image_row = 0; + if (image.has_value()) { + ET_CHECK_OR_RETURN_ERROR( + target_pos_ == 0 && logical_pos_ == 0 && cached_ctx_len_ == 0 && + hidden_.empty(), + InvalidState, + "DFlash image prefill requires a freshly reset session"); + ET_CHECK_OK_OR_RETURN_ERROR(validate_staged_image(tokens, *image)); + } + + SamplingConfig sampling = sampling_; + if (initial_sampling != nullptr) { + sampling = *initial_sampling; + } + ET_CHECK_OK_OR_RETURN_ERROR(validate_sampling(sampling)); + sampling_ = sampling; + sampling_initialized_ = true; + seed_rng(sampling_); + if (effective_temperature() > 0.0 && n_draft_ > 1 && + probability_workers_ == nullptr) { + probability_workers_ = std::make_unique(n_draft_); + } + stop_.store(false, std::memory_order_relaxed); + + const int64_t token_count = static_cast(tokens.size()); + const int64_t max_context = max_context_len(); + if (max_context > 0 && logical_pos_ + token_count >= max_context) { + ET_LOG(Error, "DFlash prefill would leave no room to generate"); + return Error::InvalidArgument; + } + + // A request may end while verified lookahead is still queued. The worker's + // suffix starts at logical_pos_, so retain only target hidden state through + // that caller-visible boundary and overwrite speculative cache slots there. + ET_CHECK_OK_OR_RETURN_ERROR(discard_unreturned_lookahead()); + + int64_t offset = 0; +#ifdef EXECUTORCH_BUILD_CUDA + const int64_t retained_hidden_start = config_.draft_sliding_window > 0 + ? std::max( + logical_pos_, + logical_pos_ + token_count - config_.draft_sliding_window) + : logical_pos_; + if (retained_hidden_start > logical_pos_) { + hidden_.clear(); + cached_ctx_len_ = retained_hidden_start; + } +#endif + while (offset < token_count) { + int64_t chunk = token_count - offset; +#ifndef EXECUTORCH_BUILD_CUDA + chunk = std::min( + chunk, + config_.max_prefill_chunk > 0 ? config_.max_prefill_chunk : chunk); +#endif + bool use_target_prefill = false; +#ifdef EXECUTORCH_BUILD_CUDA + if (config_.max_target_prefill_chunk > 0 && + chunk >= config_.min_target_prefill_chunk) { + chunk = std::min(chunk, config_.max_target_prefill_chunk); + const int64_t tail = token_count - offset - chunk; + if (tail > 0 && tail < config_.min_target_prefill_chunk) { + chunk -= config_.min_target_prefill_chunk - tail; + } + use_target_prefill = chunk >= config_.min_target_prefill_chunk; + } else { + chunk = std::min(chunk, kCudaDFlashHiddenRows); + } +#endif + const bool is_final_chunk = offset + chunk == token_count; +#ifdef EXECUTORCH_BUILD_CUDA + const int64_t retain_from_row = std::min( + chunk, std::max(0, retained_hidden_start - logical_pos_)); +#else + const int64_t retain_from_row = 0; +#endif + auto result = run_target_from_embeddings( + tokens.data() + offset, + chunk, + target_pos_, + sampling_, + /*sample_last=*/is_final_chunk, + image.has_value() ? &*image : nullptr, + image.has_value() ? &next_image_row : nullptr, + /*timing=*/nullptr, + use_target_prefill, + retain_from_row); + if (result.error() != Error::Ok) { + poisoned_ = true; + return result.error(); + } + if (is_final_chunk) { + pending_token_ = result->sampled_token; + } + append_hidden(result->hidden); + target_pos_ += chunk; + logical_pos_ += chunk; + offset += chunk; + } + + ET_CHECK_OR_RETURN_ERROR( + !image.has_value() || next_image_row == image->num_soft_tokens, + InvalidState, + "DFlash image prefill did not consume every image embedding row"); + prev_decode_token_ = tokens.back(); + trim_hidden_window(); + const Error prime_error = prime_draft_cache(); + if (prime_error != Error::Ok) { + poisoned_ = true; + return prime_error; + } + return Error::Ok; + } + + Result decode_one(const SamplingConfig& sampling) override { + if (poisoned_) { + ET_LOG(Error, "DFlashSession is poisoned; reset before decode"); + return Error::InvalidState; + } + ET_CHECK_OK_OR_RETURN_ERROR(validate_sampling(sampling)); + if (sampling_initialized_ && !same_sampling(sampling_, sampling)) { + ET_LOG( + Error, + "Cannot change DFlash sampling after prefill; prefill a suffix first"); + return Error::InvalidState; + } + if (!sampling_initialized_) { + sampling_ = sampling; + seed_rng(sampling_); + sampling_initialized_ = true; + } + + if (stop_.load(std::memory_order_relaxed)) { + return DecodeResult{0, "", /*is_eos=*/false, /*is_terminal=*/true}; + } + if (!pending_token_.has_value() && ready_tokens_.empty()) { + ET_LOG(Error, "DFlash decode requires prefill"); + return Error::InvalidState; + } + + if (ready_tokens_.empty()) { + if (is_eos(*pending_token_)) { + const uint64_t eos = *pending_token_; + pending_token_.reset(); + return terminal_result(eos); + } + const Error cycle_error = run_decode_cycle(); + if (cycle_error != Error::Ok) { + poisoned_ = true; + return cycle_error; + } + } + + if (ready_tokens_.empty()) { + poisoned_ = true; + ET_LOG(Error, "DFlash cycle produced no committed token"); + return Error::InvalidState; + } + const uint64_t token = ready_tokens_.front(); + ready_tokens_.pop_front(); + auto decoded = decode_piece(token); + if (decoded.error() != Error::Ok) { + poisoned_ = true; + return decoded.error(); + } + ++logical_pos_; + prev_decode_token_ = token; + return DecodeResult{ + token, + std::move(decoded.get()), + /*is_eos=*/false, + /*is_terminal=*/false}; + } + + int64_t position() const override { + return logical_pos_; + } + + Error reset() override { + ready_tokens_.clear(); + pending_token_.reset(); + hidden_.clear(); + hidden_dim_ = 0; + cached_ctx_len_ = 0; + target_pos_ = 0; + logical_pos_ = 0; + prev_decode_token_.reset(); + sampling_initialized_ = false; + poisoned_ = false; + if (preserve_staged_image_on_next_reset_) { + // Staging may precede the worker's full-request reset. Preserve only + // across that single reset; any later reset clears the one-shot value. + preserve_staged_image_on_next_reset_ = false; + } else { + staged_image_.reset(); + } + if (config_.timing != nullptr) { + config_.timing->reset(); + } + stop_.store(false, std::memory_order_relaxed); + return Error::Ok; + } + + void stop() override { + stop_.store(true, std::memory_order_relaxed); + } + + void stage_image_for_next_prefill(PreparedMuseGlimmerImage image) override { + staged_image_ = std::move(image); + preserve_staged_image_on_next_reset_ = true; + } + + void clear_staged_image() override { + staged_image_.reset(); + preserve_staged_image_on_next_reset_ = false; + } + + private: + struct TargetResult { + uint64_t sampled_token = 0; + std::vector hidden; + }; + + Error validate_staged_image( + const std::vector& tokens, + const PreparedMuseGlimmerImage& image) const { + ET_CHECK_OR_RETURN_ERROR( + image.num_soft_tokens > 0 && image.hidden_dim > 0, + InvalidArgument, + "DFlash staged image dimensions must be positive"); + ET_CHECK_OR_RETURN_ERROR( + image.embeddings.size() % image.num_soft_tokens == 0 && + image.embeddings.size() / image.num_soft_tokens == image.hidden_dim, + InvalidArgument, + "DFlash staged image data size does not match its dimensions"); + + // A contiguous run of <|patch|> tokens identifies the image span. + std::optional first; + int64_t last = -1; + int64_t patch_count = 0; + for (int64_t i = 0; i < static_cast(tokens.size()); ++i) { + if (tokens[i] == kMuseGlimmerImagePatchTokenId) { + if (!first.has_value()) { + first = i; + } + last = i; + ++patch_count; + } + } + ET_CHECK_OR_RETURN_ERROR( + patch_count == image.num_soft_tokens, + InvalidArgument, + "DFlash image span patch count does not match staged embeddings"); + ET_CHECK_OR_RETURN_ERROR( + first.has_value() && last - *first + 1 == patch_count, + InvalidArgument, + "DFlash image span must be one contiguous run of patch tokens"); + return Error::Ok; + } + + Error validate_sampling(const SamplingConfig& sampling) const { + if (!valid_temperature(sampling.temperature) || + !valid_top_p(sampling.top_p) || sampling.top_k < 0) { + ET_LOG(Error, "Invalid DFlash sampling configuration"); + return Error::InvalidArgument; + } + return Error::Ok; + } + + void seed_rng(const SamplingConfig& sampling) { + if (sampling.seed == 0) { + std::random_device random; + std::seed_seq seed{random(), random()}; + rng_.seed(seed); + return; + } + std::seed_seq seed{ + static_cast(sampling.seed), + static_cast(sampling.seed >> 32)}; + rng_.seed(seed); + } + + int64_t max_context_len() const { + const auto it = config_.metadata.find(kMaxContextLen); + return it == config_.metadata.end() ? 0 : it->second; + } + + bool is_eos(uint64_t token) const { + return !config_.ignore_eos && + config_.eos_ids.find(token) != config_.eos_ids.end(); + } + + Result decode_piece(uint64_t token) { + const uint64_t previous = prev_decode_token_.value_or(token); + auto decoded = config_.tokenizer->decode(previous, token); + if (!decoded.ok()) { + ET_LOG(Error, "DFlash tokenizer decode failed"); + return Error::InvalidArgument; + } + return std::move(*decoded); + } + + Result terminal_result(uint64_t token) { + auto decoded = decode_piece(token); + ET_CHECK_OK_OR_RETURN_ERROR(decoded.error()); + return DecodeResult{ + token, + std::move(decoded.get()), + /*is_eos=*/true, + /*is_terminal=*/true}; + } + + Error discard_unreturned_lookahead() { + ET_CHECK_OR_RETURN_ERROR( + logical_pos_ >= cached_ctx_len_, + InvalidState, + "DFlash logical position precedes draft cache cursor"); + const int64_t retained_rows = logical_pos_ - cached_ctx_len_; + ET_CHECK_OR_RETURN_ERROR( + retained_rows <= hidden_rows(), + InvalidState, + "DFlash hidden backlog does not cover logical position"); + if (hidden_dim_ > 0) { + hidden_.resize(retained_rows * hidden_dim_); + } + target_pos_ = logical_pos_; + ready_tokens_.clear(); + pending_token_.reset(); + return Error::Ok; + } + + int64_t hidden_rows() const { + return hidden_dim_ == 0 + ? 0 + : static_cast(hidden_.size()) / hidden_dim_; + } + + void append_hidden(const std::vector& values) { + hidden_.insert(hidden_.end(), values.begin(), values.end()); + trim_hidden_window(); + } + + void trim_hidden_window() { + if (config_.draft_sliding_window <= 0 || hidden_dim_ == 0 || + hidden_rows() <= config_.draft_sliding_window) { + return; + } + const int64_t drop = hidden_rows() - config_.draft_sliding_window; + hidden_.erase(hidden_.begin(), hidden_.begin() + drop * hidden_dim_); + cached_ctx_len_ += drop; + } + + Error prime_draft_cache() { +#ifdef EXECUTORCH_BUILD_CUDA + if (config_.has_draft_prefill) { + while (hidden_rows() - kCudaDFlashHiddenRows >= + config_.min_draft_prefill_chunk) { + const int64_t rows_to_feed = std::min( + hidden_rows() - kCudaDFlashHiddenRows, + config_.max_draft_prefill_chunk); + ET_CHECK_OK_OR_RETURN_ERROR(run_draft_prefill(rows_to_feed)); + hidden_.erase( + hidden_.begin(), hidden_.begin() + rows_to_feed * hidden_dim_); + cached_ctx_len_ += rows_to_feed; + } + } + constexpr int64_t prime_chunk = kCudaDFlashHiddenRows; +#else + const int64_t prime_chunk = config_.max_prefill_chunk; +#endif + ET_CHECK_OR_RETURN_ERROR( + prime_chunk > 0, InvalidProgram, "Invalid DFlash prime chunk"); + while (hidden_rows() > prime_chunk) { + ET_CHECK_OK_OR_RETURN_ERROR( + run_draft(/*discard_output=*/true, prime_chunk).error()); + const int64_t consumed = std::min(hidden_rows(), prime_chunk); + hidden_.erase(hidden_.begin(), hidden_.begin() + consumed * hidden_dim_); + cached_ctx_len_ += consumed; + } + return Error::Ok; + } + + Error run_draft_prefill(int64_t rows_to_feed) { + ET_CHECK_OR_RETURN_ERROR( + pending_token_.has_value() && hidden_dim_ > 0 && + rows_to_feed >= config_.min_draft_prefill_chunk && + rows_to_feed <= config_.max_draft_prefill_chunk && + rows_to_feed <= hidden_rows(), + InvalidState, + "Invalid DFlash prefill hidden rows"); + std::vector draft_tokens(block_length_, config_.mask_token_id); + draft_tokens[0] = static_cast(*pending_token_); + std::vector draft_position = {cached_ctx_len_}; + auto token_tensor = from_blob( + draft_tokens.data(), + {1, static_cast(block_length_)}, + executorch::aten::ScalarType::Long); + auto hidden_tensor = from_blob( + hidden_.data(), + {1, + static_cast(rows_to_feed), + static_cast(hidden_dim_)}, + hidden_dtype_); + auto position_tensor = from_blob( + draft_position.data(), {1}, executorch::aten::ScalarType::Long); + std::vector inputs = { + EValue(token_tensor), EValue(hidden_tensor), EValue(position_tensor)}; + std::lock_guard guard(*config_.exec_mutex); + auto outputs = execute_active(kDraftPrefill, inputs); + ET_CHECK_OK_OR_RETURN_ERROR(outputs.error()); + ET_CHECK_OR_RETURN_ERROR( + !outputs->empty() && (*outputs)[0].isTensor(), + InvalidProgram, + "draft_prefill must return a tensor"); + return Error::Ok; + } + + Error run_decode_cycle() { + ET_CHECK_OR_RETURN_ERROR( + pending_token_.has_value(), + InvalidState, + "DFlash cycle requires a pending token"); + const int64_t room = + max_context_len() > 0 ? max_context_len() - target_pos_ : block_length_; + ET_CHECK_OR_RETURN_ERROR( + room > 0, InvalidArgument, "DFlash context capacity exhausted"); +#ifdef EXECUTORCH_BUILD_CUDA + if (room < n_draft_ + 1) { + return run_target_only_cycle(); + } +#else + if (room == 1) { + return run_target_only_cycle(); + } +#endif + + DFlashCycleTiming cycle_timing; + DFlashCycleTiming* const timing = + config_.timing == nullptr ? nullptr : &cycle_timing; + const auto cycle_start = + timing == nullptr ? Clock::time_point{} : Clock::now(); + + auto draft_logits = + run_draft(/*discard_output=*/false, hidden_rows(), timing); + ET_CHECK_OK_OR_RETURN_ERROR(draft_logits.error()); + const int64_t verify_len = std::min(n_draft_ + 1, room); + std::vector candidates(verify_len); + candidates[0] = *pending_token_; + if (draft_probs_.size() < verify_len) { + draft_probs_.resize(verify_len); + } + const bool stochastic = effective_temperature() > 0.0; + const bool draft_argmax = stochastic && config_.draft_argmax; + const auto draft_sampling_start = + timing == nullptr ? Clock::time_point{} : Clock::now(); + if (draft_argmax) { + const auto& logits = *draft_logits.get(); + const int64_t vocab_size = logits.size(logits.dim() - 1); + const float* logits_data = + static_cast(logits.const_data_ptr()); + for (int64_t i = 1; i < verify_len; ++i) { + candidates[i] = muse_glimmer::argmax_index( + logits_data + i * vocab_size, vocab_size); + } + } else if (stochastic && probability_workers_ != nullptr) { + probability_workers_->fill( + *draft_logits.get(), + verify_len - 1, + /*logits_row_offset=*/1, + /*probabilities_row_offset=*/1, + effective_temperature(), + sampling_.top_k, + sampling_.top_p, + draft_probs_); + const auto& logits = *draft_logits.get(); + const int64_t vocab_size = logits.size(logits.dim() - 1); + for (int64_t i = 1; i < verify_len; ++i) { + candidates[i] = muse_glimmer::categorical_sample( + rng_, draft_probs_[i].data(), vocab_size); + } + } else { + for (int64_t i = 1; i < verify_len; ++i) { + candidates[i] = muse_glimmer::sample_token( + rng_, + *draft_logits.get(), + i, + effective_temperature(), + sampling_.top_k, + sampling_.top_p, + stochastic ? &draft_probs_[i] : nullptr, + /*probs_only=*/false, + &sampling_workspace_); + } + } + if (timing != nullptr) { + timing->draft_sampling_ms += + elapsed_ms(draft_sampling_start, Clock::now()); + } + + auto verify = run_target( + candidates.data(), + verify_len, + target_pos_, + sampling_, + /*sample_last=*/false, + timing); + ET_CHECK_OK_OR_RETURN_ERROR(verify.error()); + const auto& verify_logits = *last_logits_tensor_; + + int64_t committed = verify_len; + uint64_t correction = 0; + bool rejected = false; + const auto accept_start = + timing == nullptr ? Clock::time_point{} : Clock::now(); + if (stochastic) { + if (target_probs_.size() < verify_len) { + target_probs_.resize(verify_len); + } + if (probability_workers_ != nullptr) { + probability_workers_->fill( + verify_logits, + verify_len, + /*logits_row_offset=*/0, + /*probabilities_row_offset=*/0, + effective_temperature(), + sampling_.top_k, + sampling_.top_p, + target_probs_); + } + } + for (int64_t i = 0; i < verify_len - 1; ++i) { + bool accepted = false; + if (!stochastic) { + const uint64_t target_pick = muse_glimmer::sample_token( + rng_, verify_logits, i, 0.0, sampling_.top_k, sampling_.top_p); + accepted = target_pick == candidates[i + 1]; + if (!accepted) { + committed = i + 1; + correction = target_pick; + } + } else { + if (probability_workers_ == nullptr) { + muse_glimmer::sample_token( + rng_, + verify_logits, + i, + effective_temperature(), + sampling_.top_k, + sampling_.top_p, + &target_probs_[i], + /*probs_only=*/true, + &sampling_workspace_); + } + const uint64_t token = candidates[i + 1]; + const float p = target_probs_[i][token]; + const float q = draft_argmax ? 1.0f : draft_probs_[i + 1][token]; + const float accept_probability = + q > 0.0f ? std::min(1.0f, p / q) : 1.0f; + accepted = + muse_glimmer::accept_with_probability(rng_, accept_probability); + if (!accepted) { + committed = i + 1; + correction = draft_argmax + ? muse_glimmer::sample_excluding_token_in_place( + rng_, target_probs_[i], token) + : muse_glimmer::sample_from_residual_in_place( + rng_, target_probs_[i], draft_probs_[i + 1]); + } + } + if (timing != nullptr) { + if (timing->draft_attempts_by_row.size() <= static_cast(i)) { + timing->draft_attempts_by_row.resize(i + 1); + timing->draft_accepts_by_row.resize(i + 1); + } + ++timing->draft_attempts_by_row[i]; + if (accepted) { + ++timing->draft_accepts_by_row[i]; + } + } + if (!accepted) { + rejected = true; + break; + } + } + if (!rejected) { + if (stochastic && probability_workers_ != nullptr) { + const int64_t vocab_size = verify_logits.size(verify_logits.dim() - 1); + correction = muse_glimmer::categorical_sample( + rng_, target_probs_[verify_len - 1].data(), vocab_size); + } else { + correction = muse_glimmer::sample_token( + rng_, + verify_logits, + verify_len - 1, + effective_temperature(), + sampling_.top_k, + sampling_.top_p, + /*out_probs=*/nullptr, + /*probs_only=*/false, + &sampling_workspace_); + } + } + if (timing != nullptr) { + timing->accept_correction_ms += elapsed_ms(accept_start, Clock::now()); + } + + const auto commit_start = + timing == nullptr ? Clock::time_point{} : Clock::now(); + const int64_t old_hidden_rows = hidden_rows(); + cached_ctx_len_ += old_hidden_rows; + hidden_ = std::move(verify->hidden); + hidden_.resize(committed * hidden_dim_); + + int64_t nonterminal_committed = committed; + std::optional terminal; + for (int64_t i = 0; i < committed; ++i) { + if (is_eos(candidates[i])) { + nonterminal_committed = i; + terminal = candidates[i]; + break; + } + ready_tokens_.push_back(candidates[i]); + } + if (nonterminal_committed != committed) { + hidden_.resize(nonterminal_committed * hidden_dim_); + correction = *terminal; + } + target_pos_ += nonterminal_committed; + pending_token_ = correction; + if (timing != nullptr) { + timing->state_commit_ms += elapsed_ms(commit_start, Clock::now()); + timing->total_cycle_ms += elapsed_ms(cycle_start, Clock::now()); + config_.timing->record(*timing); + } + return Error::Ok; + } + + Error run_target_only_cycle() { + DFlashCycleTiming cycle_timing; + DFlashCycleTiming* const timing = + config_.timing == nullptr ? nullptr : &cycle_timing; + const auto cycle_start = + timing == nullptr ? Clock::time_point{} : Clock::now(); + const uint64_t anchor = *pending_token_; + auto result = run_target( + &anchor, + 1, + target_pos_, + sampling_, + /*sample_last=*/true, + timing); + ET_CHECK_OK_OR_RETURN_ERROR(result.error()); + const auto commit_start = + timing == nullptr ? Clock::time_point{} : Clock::now(); + append_hidden(result->hidden); + ready_tokens_.push_back(anchor); + pending_token_ = result->sampled_token; + ++target_pos_; + if (timing != nullptr) { + timing->state_commit_ms += elapsed_ms(commit_start, Clock::now()); + timing->total_cycle_ms += elapsed_ms(cycle_start, Clock::now()); + timing->target_only = true; + config_.timing->record(*timing); + } + return Error::Ok; + } + + double effective_temperature() const { + return sampling_.temperature < 0.0f ? 0.0 : sampling_.temperature; + } + + Result run_target( + const uint64_t* tokens, + int64_t count, + int64_t start_pos, + const SamplingConfig& sampling, + bool sample_last, + DFlashCycleTiming* timing = nullptr, + bool use_target_prefill = false, + int64_t retain_from_row = 0) { + return run_target_from_embeddings( + tokens, + count, + start_pos, + sampling, + sample_last, + /*image=*/nullptr, + /*next_image_row=*/nullptr, + timing, + use_target_prefill, + retain_from_row); + } + + Result run_target_from_embeddings( + const uint64_t* tokens, + int64_t count, + int64_t start_pos, + const SamplingConfig& sampling, + bool sample_last, + const PreparedMuseGlimmerImage* image, + int64_t* next_image_row, + DFlashCycleTiming* timing = nullptr, + bool use_target_prefill = false, + int64_t retain_from_row = 0) { + std::vector token_data(tokens, tokens + count); + std::vector positions(count); + std::iota(positions.begin(), positions.end(), start_pos); + auto token_tensor = from_blob( + token_data.data(), + {1, static_cast(count)}, + executorch::aten::ScalarType::Long); + auto position_tensor = from_blob( + positions.data(), + {static_cast(count)}, + executorch::aten::ScalarType::Long); + + const auto execute_start = + timing == nullptr ? Clock::time_point{} : Clock::now(); + std::lock_guard guard(*config_.exec_mutex); + auto embed_outputs = execute_active(kEmbedText, {EValue(token_tensor)}); + ET_CHECK_OK_OR_RETURN_ERROR(embed_outputs.error()); + ET_CHECK_OR_RETURN_ERROR( + embed_outputs->size() == 1 && (*embed_outputs)[0].isTensor(), + InvalidProgram, + "embed_text must return one tensor"); + const auto& embed_tensor = (*embed_outputs)[0].toTensor(); + ET_CHECK_OR_RETURN_ERROR( + embed_tensor.dim() == 3 && embed_tensor.size(0) == 1 && + embed_tensor.size(1) == count && + embed_tensor.scalar_type() == hidden_dtype_, + InvalidProgram, + "embed_text must return [1, T, H] in the activation dtype"); + const int64_t embed_dim = embed_tensor.size(2); + ET_CHECK_OR_RETURN_ERROR( + embed_dim > 0 && (image == nullptr || embed_dim == image->hidden_dim), + InvalidArgument, + "embed_text hidden dimension does not match the staged image"); + + std::vector embeddings; + TensorPtr embeddings_tensor; + std::vector target_inputs; + if (image != nullptr) { + ET_CHECK_OR_RETURN_ERROR( + next_image_row != nullptr, + InvalidState, + "DFlash image splice requires an image row cursor"); + embeddings.resize(count * embed_dim); + ET_CHECK_OK_OR_RETURN_ERROR(copy_bytes_to_host( + embeddings.data(), + embed_tensor.const_data_ptr(), + embeddings.size() * sizeof(uint16_t))); + for (int64_t row = 0; row < count; ++row) { + if (tokens[row] != kMuseGlimmerImagePatchTokenId) { + continue; + } + ET_CHECK_OR_RETURN_ERROR( + *next_image_row < image->num_soft_tokens, + InvalidArgument, + "DFlash prefill has more patch tokens than image rows"); + std::memcpy( + embeddings.data() + row * embed_dim, + image->embeddings.data() + *next_image_row * embed_dim, + embed_dim * sizeof(uint16_t)); + ++*next_image_row; + } + embeddings_tensor = from_blob( + embeddings.data(), + {1, static_cast(count), static_cast(embed_dim)}, + hidden_dtype_); + target_inputs = {EValue(embeddings_tensor), EValue(position_tensor)}; + } else { + target_inputs = {(*embed_outputs)[0], EValue(position_tensor)}; + } + + auto outputs = execute_active( + use_target_prefill ? kTargetPrefillFromEmbeddings + : kTargetForwardFromEmbeddings, + target_inputs); + if (timing != nullptr) { + timing->target_execute_ms += elapsed_ms(execute_start, Clock::now()); + } + ET_CHECK_OK_OR_RETURN_ERROR(outputs.error()); + return process_target_outputs( + *outputs, + count, + sampling, + sample_last, + timing, + use_target_prefill, + retain_from_row); + } + + Result process_target_outputs( + const std::vector& outputs, + int64_t count, + const SamplingConfig& sampling, + bool sample_last, + DFlashCycleTiming* timing, + bool use_target_prefill, + int64_t retain_from_row) { + ET_CHECK_OR_RETURN_ERROR( + outputs.size() >= 2 && outputs[0].isTensor() && outputs[1].isTensor(), + InvalidProgram, + "DFlash target must return logits and hidden tensors"); + + const auto logits_copy_start = + timing == nullptr ? Clock::time_point{} : Clock::now(); + auto logits = + copy_float_tensor_to_host(outputs[0].toTensor(), last_logits_storage_); + ET_CHECK_OK_OR_RETURN_ERROR(logits.error()); + last_logits_tensor_ = std::move(logits.get()); + if (timing != nullptr) { + timing->target_logits_copy_ms += + elapsed_ms(logits_copy_start, Clock::now()); + } + uint64_t sampled = 0; + if (sample_last) { + const auto sampling_start = + timing == nullptr ? Clock::time_point{} : Clock::now(); + sampled = muse_glimmer::sample_token( + rng_, + *last_logits_tensor_, + use_target_prefill ? 0 : count - 1, + sampling.temperature < 0.0f ? 0.0 : sampling.temperature, + sampling.top_k, + sampling.top_p, + /*out_probs=*/nullptr, + /*probs_only=*/false, + &sampling_workspace_); + if (timing != nullptr) { + timing->accept_correction_ms += + elapsed_ms(sampling_start, Clock::now()); + } + } + + const auto& hidden_tensor = outputs[1].toTensor(); + ET_CHECK_OR_RETURN_ERROR( + hidden_tensor.dim() == 3 && hidden_tensor.size(0) == 1 && + hidden_tensor.size(1) == count && + hidden_tensor.scalar_type() == hidden_dtype_, + InvalidProgram, + "DFlash target hidden must be [1, T, H] in the activation dtype"); + if (hidden_dim_ == 0) { + hidden_dim_ = hidden_tensor.size(2); + } + ET_CHECK_OR_RETURN_ERROR( + hidden_tensor.size(2) == hidden_dim_, + InvalidProgram, + "DFlash target hidden dimension changed"); + ET_CHECK_OR_RETURN_ERROR( + retain_from_row >= 0 && retain_from_row <= count, + InvalidArgument, + "Invalid retained target hidden row offset"); + const int64_t retained_rows = count - retain_from_row; + std::vector hidden(retained_rows * hidden_dim_); + const auto hidden_copy_start = + timing == nullptr ? Clock::time_point{} : Clock::now(); + ET_CHECK_OK_OR_RETURN_ERROR(copy_bytes_to_host( + hidden.data(), + static_cast(hidden_tensor.const_data_ptr()) + + retain_from_row * hidden_dim_, + hidden.size() * sizeof(uint16_t))); + if (timing != nullptr) { + timing->target_hidden_copy_ms += + elapsed_ms(hidden_copy_start, Clock::now()); + } + return TargetResult{sampled, std::move(hidden)}; + } + + Result copy_float_tensor_to_host( + const executorch::aten::Tensor& source, + std::vector& storage) { + ET_CHECK_OR_RETURN_ERROR( + source.scalar_type() == executorch::aten::ScalarType::Float, + InvalidProgram, + "DFlash logits must be float32"); + storage.resize(source.numel()); + ET_CHECK_OK_OR_RETURN_ERROR(copy_bytes_to_host( + storage.data(), + source.const_data_ptr(), + storage.size() * sizeof(float))); + std::vector sizes(source.dim()); + for (int32_t i = 0; i < source.dim(); ++i) { + sizes[i] = source.size(i); + } + return from_blob( + storage.data(), sizes, executorch::aten::ScalarType::Float); + } + + Error + copy_bytes_to_host(void* destination, const void* source, size_t bytes) { +#ifdef EXECUTORCH_BUILD_CUDA + cudaPointerAttributes attributes{}; + const bool on_device = + cudaPointerGetAttributes(&attributes, source) == cudaSuccess && + attributes.type == cudaMemoryTypeDevice; + if (on_device) { + return cudaMemcpy(destination, source, bytes, cudaMemcpyDeviceToHost) == + cudaSuccess + ? Error::Ok + : Error::Internal; + } +#endif + std::memcpy(destination, source, bytes); + return Error::Ok; + } + + Result run_draft( + bool discard_output, + int64_t rows_to_feed, + DFlashCycleTiming* timing = nullptr) { + ET_CHECK_OR_RETURN_ERROR( + pending_token_.has_value() && hidden_dim_ > 0 && hidden_rows() > 0 && + rows_to_feed > 0 && rows_to_feed <= hidden_rows(), + InvalidState, + "DFlash draft requires pending token and target hidden state"); + const int64_t draft_len = block_length_; + std::vector draft_tokens(draft_len, config_.mask_token_id); + draft_tokens[0] = static_cast(*pending_token_); + std::vector draft_position = {cached_ctx_len_}; + + const uint16_t* hidden_data = hidden_.data(); + int64_t hidden_input_rows = rows_to_feed; +#ifdef EXECUTORCH_BUILD_CUDA + std::vector padded_hidden(kCudaDFlashHiddenRows * hidden_dim_, 0); + ET_CHECK_OR_RETURN_ERROR( + hidden_input_rows <= kCudaDFlashHiddenRows, + InvalidState, + "CUDA DFlash hidden backlog exceeds %" PRId64 " rows", + kCudaDFlashHiddenRows); + std::memcpy( + padded_hidden.data(), + hidden_data, + rows_to_feed * hidden_dim_ * sizeof(uint16_t)); + hidden_data = padded_hidden.data(); + hidden_input_rows = kCudaDFlashHiddenRows; +#endif + auto token_tensor = from_blob( + draft_tokens.data(), + {1, static_cast(draft_len)}, + executorch::aten::ScalarType::Long); + auto hidden_tensor = from_blob( + const_cast(hidden_data), + {1, + static_cast(hidden_input_rows), + static_cast(hidden_dim_)}, + hidden_dtype_); + auto position_tensor = from_blob( + draft_position.data(), {1}, executorch::aten::ScalarType::Long); + std::vector inputs = { + EValue(token_tensor), EValue(hidden_tensor), EValue(position_tensor)}; +#ifdef EXECUTORCH_BUILD_CUDA + std::vector valid_length = {rows_to_feed}; + auto valid_length_tensor = + from_blob(valid_length.data(), {1}, executorch::aten::ScalarType::Long); + inputs.push_back(EValue(valid_length_tensor)); +#endif + const auto execute_start = + timing == nullptr ? Clock::time_point{} : Clock::now(); + std::lock_guard guard(*config_.exec_mutex); + auto outputs = execute_active(kDraftForward, inputs); + if (timing != nullptr) { + timing->draft_execute_ms += elapsed_ms(execute_start, Clock::now()); + } + ET_CHECK_OK_OR_RETURN_ERROR(outputs.error()); + ET_CHECK_OR_RETURN_ERROR( + !outputs->empty() && (*outputs)[0].isTensor(), + InvalidProgram, + "draft_forward must return logits"); + if (discard_output) { + return TensorPtr{}; + } + const auto logits_copy_start = + timing == nullptr ? Clock::time_point{} : Clock::now(); + auto host_logits = copy_float_tensor_to_host( + (*outputs)[0].toTensor(), draft_logits_storage_); + ET_CHECK_OK_OR_RETURN_ERROR(host_logits.error()); + draft_logits_tensor_ = std::move(host_logits.get()); + if (timing != nullptr) { + timing->draft_logits_copy_ms += + elapsed_ms(logits_copy_start, Clock::now()); + } + return draft_logits_tensor_; + } + + Result> execute_active( + const char* method, + const std::vector& inputs) { + return config_.mutable_state != nullptr + ? config_.mutable_state->with_active_session( + config_.session_token, + [&]() { return config_.module->execute(method, inputs); }) + : config_.module->execute(method, inputs); + } + + DFlashSessionConfig config_; + int64_t block_length_; + int64_t n_draft_; + executorch::aten::ScalarType hidden_dtype_; + std::mt19937 rng_; + SamplingConfig sampling_; + bool sampling_initialized_ = false; + bool poisoned_ = false; + bool preserve_staged_image_on_next_reset_ = false; + std::optional staged_image_; + std::atomic stop_{false}; + + int64_t logical_pos_ = 0; + int64_t target_pos_ = 0; + int64_t cached_ctx_len_ = 0; + int64_t hidden_dim_ = 0; + std::vector hidden_; + std::deque ready_tokens_; + std::optional pending_token_; + std::optional prev_decode_token_; + + std::vector last_logits_storage_; + TensorPtr last_logits_tensor_; + std::vector draft_logits_storage_; + TensorPtr draft_logits_tensor_; + std::vector> draft_probs_; + std::vector> target_probs_; + muse_glimmer::SamplingWorkspace sampling_workspace_; + std::unique_ptr probability_workers_; +}; + +} // namespace + +Result> create_dflash_session( + DFlashSessionConfig config) { + ET_CHECK_OR_RETURN_ERROR( + config.module != nullptr && config.exec_mutex != nullptr && + config.live_sessions != nullptr && config.tokenizer != nullptr, + InvalidArgument, + "DFlash session requires module, mutex, live-session counter, and tokenizer"); + ET_CHECK_OR_RETURN_ERROR( + config.block_size >= 2 && config.block_length >= 2 && + config.block_length <= config.block_size && config.n_draft > 0 && + config.n_draft < config.block_length, + InvalidArgument, + "Invalid DFlash block configuration"); + ET_CHECK_OR_RETURN_ERROR( + config.activation_dtype == "bfloat16" || + config.activation_dtype == "float16", + InvalidProgram, + "DFlash hidden dtype must be bfloat16 or float16"); + return std::unique_ptr(new DFlashSession(std::move(config))); +} + +} // namespace executorch::extension::llm diff --git a/examples/models/muse-glimmer/runtime/engine/dflash_session.h b/examples/models/muse-glimmer/runtime/engine/dflash_session.h new file mode 100644 index 00000000000..4b30803f952 --- /dev/null +++ b/examples/models/muse-glimmer/runtime/engine/dflash_session.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace executorch::extension::llm { + +// The CUDA draft_forward artifact takes a fixed-size hidden-state input, so the +// hidden backlog carried into a draft call (n_draft + 1 rows after a decode +// cycle) must fit within this many rows. +inline constexpr int64_t kCudaDFlashHiddenRows = 4; + +using DFlashMultimodalSession = MuseGlimmerMultimodalSession; + +inline DFlashMultimodalSession* as_dflash_multimodal_session( + LLMSession* session) { + return as_muse_glimmer_multimodal_session(session); +} + +struct DFlashSessionConfig { + Module* module = nullptr; + std::mutex* exec_mutex = nullptr; + std::atomic* live_sessions = nullptr; + ::tokenizers::Tokenizer* tokenizer = nullptr; + std::unordered_map metadata; + std::unordered_set eos_ids; + MuseGlimmerMutableStateContextOwner* mutable_state = nullptr; + int session_token = kMuseGlimmerNoMutableSession; + int64_t max_prefill_chunk = 0; + int64_t block_size = 0; + int64_t block_length = 0; + int64_t n_draft = 0; + int64_t mask_token_id = 0; + int64_t n_target_layers = 0; + int64_t draft_sliding_window = 0; + int64_t min_target_prefill_chunk = 0; + int64_t max_target_prefill_chunk = 0; + int64_t min_draft_prefill_chunk = 0; + int64_t max_draft_prefill_chunk = 0; + bool has_draft_prefill = false; + std::string activation_dtype; + bool draft_argmax = true; + bool ignore_eos = false; + DFlashDecodeTiming* timing = nullptr; +}; + +::executorch::runtime::Result> +create_dflash_session(DFlashSessionConfig config); + +} // namespace executorch::extension::llm diff --git a/examples/models/muse-glimmer/runtime/engine/dflash_timing.h b/examples/models/muse-glimmer/runtime/engine/dflash_timing.h new file mode 100644 index 00000000000..26aa5ed564b --- /dev/null +++ b/examples/models/muse-glimmer/runtime/engine/dflash_timing.h @@ -0,0 +1,77 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#pragma once + +#include +#include +#include + +namespace executorch::extension::llm { + +struct DFlashCycleTiming { + double draft_execute_ms = 0.0; + double draft_logits_copy_ms = 0.0; + double draft_sampling_ms = 0.0; + double target_execute_ms = 0.0; + double target_logits_copy_ms = 0.0; + double target_hidden_copy_ms = 0.0; + double accept_correction_ms = 0.0; + double state_commit_ms = 0.0; + double total_cycle_ms = 0.0; + std::vector draft_attempts_by_row; + std::vector draft_accepts_by_row; + bool target_only = false; +}; + +struct DFlashDecodeTiming { + int64_t cycles = 0; + int64_t speculative_cycles = 0; + int64_t target_only_cycles = 0; + double draft_execute_ms = 0.0; + double draft_logits_copy_ms = 0.0; + double draft_sampling_ms = 0.0; + double target_execute_ms = 0.0; + double target_logits_copy_ms = 0.0; + double target_hidden_copy_ms = 0.0; + double accept_correction_ms = 0.0; + double state_commit_ms = 0.0; + double total_cycle_ms = 0.0; + std::vector draft_attempts_by_row; + std::vector draft_accepts_by_row; + + void record(const DFlashCycleTiming& timing) { + ++cycles; + if (timing.target_only) { + ++target_only_cycles; + } else { + ++speculative_cycles; + } + draft_execute_ms += timing.draft_execute_ms; + draft_logits_copy_ms += timing.draft_logits_copy_ms; + draft_sampling_ms += timing.draft_sampling_ms; + target_execute_ms += timing.target_execute_ms; + target_logits_copy_ms += timing.target_logits_copy_ms; + target_hidden_copy_ms += timing.target_hidden_copy_ms; + accept_correction_ms += timing.accept_correction_ms; + state_commit_ms += timing.state_commit_ms; + total_cycle_ms += timing.total_cycle_ms; + if (draft_attempts_by_row.size() < timing.draft_attempts_by_row.size()) { + draft_attempts_by_row.resize(timing.draft_attempts_by_row.size()); + draft_accepts_by_row.resize(timing.draft_accepts_by_row.size()); + } + for (size_t row = 0; row < timing.draft_attempts_by_row.size(); ++row) { + draft_attempts_by_row[row] += timing.draft_attempts_by_row[row]; + draft_accepts_by_row[row] += timing.draft_accepts_by_row[row]; + } + } + + void reset() { + *this = DFlashDecodeTiming{}; + } +}; + +} // namespace executorch::extension::llm diff --git a/examples/models/muse-glimmer/runtime/engine/muse_glimmer_engine.cpp b/examples/models/muse-glimmer/runtime/engine/muse_glimmer_engine.cpp new file mode 100644 index 00000000000..8ffd20aa82e --- /dev/null +++ b/examples/models/muse-glimmer/runtime/engine/muse_glimmer_engine.cpp @@ -0,0 +1,1635 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#ifdef EXECUTORCH_BUILD_CUDA +#include +#include +#else +#include +#endif + +namespace executorch::extension::llm { + +using ::executorch::extension::clone_tensor_ptr_to; +using ::executorch::extension::from_blob; +using ::executorch::extension::Module; +using ::executorch::extension::TensorPtr; +using ::executorch::runtime::Error; +using ::executorch::runtime::EValue; +using ::executorch::runtime::Result; +using SizesType = executorch::aten::SizesType; + +::tokenizers::Result> tokenize_muse_glimmer_prompt( + const ::tokenizers::Tokenizer& tokenizer, + const std::string& prompt, + uint64_t bos_id, + std::optional image_tokens) { + std::vector tokens{bos_id}; + if (!image_tokens.has_value()) { + auto encoded = tokenizer.encode(prompt, /*bos=*/0, /*eos=*/0); + if (!encoded.ok()) { + return encoded.error(); + } + tokens.insert(tokens.end(), encoded->begin(), encoded->end()); + return tokens; + } + + if (*image_tokens <= 0) { + return ::tokenizers::Error::EncodeFailure; + } + const std::string placeholder = kMuseGlimmerImagePlaceholder; + const size_t marker = prompt.find(placeholder); + if (marker == std::string::npos || + prompt.find(placeholder, marker + placeholder.size()) != + std::string::npos) { + return ::tokenizers::Error::EncodeFailure; + } + + auto before = + tokenizer.encode(prompt.substr(0, marker), /*bos=*/0, /*eos=*/0); + if (!before.ok()) { + return before.error(); + } + auto after = tokenizer.encode( + prompt.substr(marker + placeholder.size()), /*bos=*/0, /*eos=*/0); + if (!after.ok()) { + return after.error(); + } + tokens.insert(tokens.end(), before->begin(), before->end()); + tokens.insert( + tokens.end(), + static_cast(*image_tokens), + kMuseGlimmerImagePatchTokenId); + tokens.insert(tokens.end(), after->begin(), after->end()); + return tokens; +} + +namespace { + +constexpr const char* kForwardFromEmbeddingsMethod = "forward_from_embeddings"; +constexpr const char* kDecodeFromEmbeddingMethod = "decode_from_embedding"; + +constexpr const char* kMaxPrefillChunk = "get_max_prefill_chunk"; +constexpr const char* kMinPrefillChunk = "get_min_prefill_chunk"; +constexpr const char* kUseSampling = "use_sampling"; +constexpr const char* kTargetForwardFromEmbeddingsMethod = + "target_forward_from_embeddings"; +constexpr const char* kTargetPrefillFromEmbeddingsMethod = + "target_prefill_from_embeddings"; +constexpr const char* kEmbedTextMethod = "embed_text"; +constexpr const char* kMuseGlimmerVisionEncoderMethod = "vision_encoder"; +constexpr const char* kDraftForwardMethod = "draft_forward"; +constexpr const char* kDraftPrefillMethod = "draft_prefill"; +constexpr const char* kDFlashBlockSize = "get_block_size"; +constexpr const char* kDFlashMaskTokenId = "get_mask_token_id"; +constexpr const char* kDFlashTargetLayers = "get_n_target_layers"; +constexpr const char* kDFlashSlidingWindow = "get_draft_sliding_window"; +constexpr const char* kDFlashMinTargetPrefillChunk = + "get_min_target_prefill_chunk"; +constexpr const char* kDFlashMaxTargetPrefillChunk = + "get_max_target_prefill_chunk"; +constexpr const char* kDFlashMinDraftPrefillChunk = + "get_min_draft_prefill_chunk"; +constexpr const char* kDFlashMaxDraftPrefillChunk = + "get_max_draft_prefill_chunk"; +constexpr const char* kActivationDtype = "get_activation_dtype"; +constexpr const char* kVisionHiddenSize = "get_vision_hidden_size"; +constexpr const char* kMaxVisionPatches = "get_max_vision_patches"; +constexpr int64_t kVisionDownsampleArea = 4; + +const char* artifact_mode_name(MuseGlimmerArtifactMode mode) { + switch (mode) { + case MuseGlimmerArtifactMode::Auto: + return "auto"; + case MuseGlimmerArtifactMode::Autoregressive: + return "autoregressive"; + case MuseGlimmerArtifactMode::DFlash: + return "dflash"; + } + return "unknown"; +} + +Result resolve_artifact_mode( + Module* module, + MuseGlimmerArtifactMode requested_mode) { + auto method_names_result = module->method_names(); + ET_CHECK_OK_OR_RETURN_ERROR(method_names_result.error()); + const auto& methods = method_names_result.get(); + const bool has_embeddings_method = + methods.count(kTargetForwardFromEmbeddingsMethod) != 0; + const bool has_embed_text_method = methods.count(kEmbedTextMethod) != 0; + const bool has_vision_method = + methods.count(kMuseGlimmerVisionEncoderMethod) != 0; + const bool has_any_embeddings_target = + has_embeddings_method || has_embed_text_method || has_vision_method; + const bool has_embeddings_target = + has_embeddings_method && has_embed_text_method; + const bool has_draft = methods.count(kDraftForwardMethod) != 0; + ET_CHECK_OR_RETURN_ERROR( + !has_draft || !has_any_embeddings_target || has_embeddings_target, + InvalidProgram, + "DFlash artifact must expose target_forward_from_embeddings and " + "embed_text together, plus vision_encoder when multimodal"); + const bool has_dflash = has_embeddings_target && has_draft; +#ifdef EXECUTORCH_BUILD_MLX + const bool has_autoregressive = has_embed_text_method && + methods.count(kForwardFromEmbeddingsMethod) != 0 && !has_draft; +#else + const bool has_autoregressive = has_embed_text_method && + methods.count(kForwardFromEmbeddingsMethod) != 0 && + methods.count(kDecodeFromEmbeddingMethod) != 0 && !has_draft; +#endif + ET_CHECK_OR_RETURN_ERROR( + has_autoregressive || has_dflash, + InvalidProgram, +#ifdef EXECUTORCH_BUILD_MLX + "Invalid Muse Glimmer artifact. MLX Solo expects embed_text and " + "forward_from_embeddings. DFlash expects " + "target_forward_from_embeddings, embed_text, and draft_forward. " + "Re-export it."); +#else + "Invalid Muse Glimmer artifact. Solo expects embed_text, " + "forward_from_embeddings, and decode_from_embedding. DFlash expects a " + "target_forward_from_embeddings, embed_text, and draft_forward. " + "Re-export it."); +#endif + + ET_CHECK_OR_RETURN_ERROR( + has_dflash != has_autoregressive, + InvalidProgram, + "Muse Glimmer artifact must expose exactly one complete execution contract: " + "autoregressive=%d dflash=%d", + static_cast(has_autoregressive), + static_cast(has_dflash)); + const MuseGlimmerArtifactMode detected = has_dflash + ? MuseGlimmerArtifactMode::DFlash + : MuseGlimmerArtifactMode::Autoregressive; + ET_CHECK_OR_RETURN_ERROR( + requested_mode == MuseGlimmerArtifactMode::Auto || + requested_mode == detected, + InvalidArgument, + "Requested Muse Glimmer artifact mode %s does not match detected mode %s", + artifact_mode_name(requested_mode), + artifact_mode_name(detected)); + return detected; +} + +Result get_required_int_metadata(Module* module, const char* name) { + auto value = module->get(name); + ET_CHECK_OK_OR_RETURN_ERROR(value.error()); + ET_CHECK_OR_RETURN_ERROR( + value->isScalar(), InvalidProgram, "%s must return a scalar", name); + return value->toScalar().to(); +} + +Result get_required_string_metadata( + Module* module, + const char* name) { + auto value = module->get(name); + ET_CHECK_OK_OR_RETURN_ERROR(value.error()); + ET_CHECK_OR_RETURN_ERROR( + value->isString(), InvalidProgram, "%s must return a string", name); + return std::string(value->toString()); +} + +Result read_sampled_token( + const executorch::aten::Tensor& output, + float temperature, + bool use_sampling) { +#ifdef EXECUTORCH_BUILD_CUDA + (void)temperature; + (void)use_sampling; + const void* ptr = output.const_data_ptr(); + cudaPointerAttributes attrs{}; + const bool on_device = cudaPointerGetAttributes(&attrs, ptr) == cudaSuccess && + attrs.type == cudaMemoryTypeDevice; + + auto copy_scalar = [&](void* dst, size_t nbytes) -> Error { + if (on_device) { + if (cudaMemcpy(dst, ptr, nbytes, cudaMemcpyDeviceToHost) != cudaSuccess) { + return Error::Internal; + } + } else { + std::memcpy(dst, ptr, nbytes); + } + return Error::Ok; + }; + + if (output.scalar_type() == executorch::aten::ScalarType::Long) { + int64_t val = 0; + if (copy_scalar(&val, sizeof(val)) != Error::Ok) { + ET_LOG(Error, "read_sampled_token: cudaMemcpy D2H failed"); + return Error::Internal; + } + return static_cast(val); + } + if (output.scalar_type() == executorch::aten::ScalarType::Float) { + float val = 0.0f; + if (copy_scalar(&val, sizeof(val)) != Error::Ok) { + ET_LOG(Error, "read_sampled_token: cudaMemcpy D2H failed"); + return Error::Internal; + } + return static_cast(llrintf(val)); + } + ET_LOG( + Error, + "read_sampled_token: expected Long or Float scalar output, got %d", + static_cast(output.scalar_type())); + return Error::InvalidArgument; +#else + if (use_sampling) { + ET_CHECK_OR_RETURN_ERROR( + output.scalar_type() == executorch::aten::ScalarType::Long, + InvalidProgram, + "read_sampled_token: use_sampling set but forward output is not Long"); + return static_cast(output.const_data_ptr()[0]); + } + return static_cast( + logits_to_token(output, temperature < 0.0f ? 0.0f : temperature)); +#endif +} + +Result> build_muse_glimmer_module( + const MuseGlimmerConfig& config, + MuseGlimmerArtifactMode artifact_mode, + bool has_vision, + bool multi_session) { + std::vector data_files; + if (!config.data_path.empty()) { + data_files.push_back(config.data_path); + } + bool share_memory_arenas = true; +#ifdef EXECUTORCH_BUILD_CUDA + share_memory_arenas = false; +#endif + auto module = std::make_unique( + config.model_path, + data_files, + Module::LoadMode::MmapUseMlockIgnoreErrors, + /*event_tracer=*/nullptr, + /*memory_allocator=*/nullptr, + /*temp_allocator=*/nullptr, + /*share_memory_arenas=*/share_memory_arenas); + +#ifdef EXECUTORCH_BUILD_CUDA + executorch::runtime::BackendOptions<3> cuda_opts; + ET_CHECK_OK_OR_RETURN_ERROR( + cuda_opts.set_option("use_shared_cuda_stream", true)); + ET_CHECK_OK_OR_RETURN_ERROR( + cuda_opts.set_option("weight_sharing_across_methods", true)); + if (config.enable_cuda_graph) { + const char* graph_methods = artifact_mode == MuseGlimmerArtifactMode::DFlash + ? "target_forward_from_embeddings,draft_forward" + : kDecodeFromEmbeddingMethod; + ET_CHECK_OK_OR_RETURN_ERROR( + cuda_opts.set_option("enable_cuda_graph_for_method", graph_methods)); + ET_LOG(Info, "MuseGlimmerEngine: CUDA graph enabled for %s", graph_methods); + } + ET_CHECK_OK_OR_RETURN_ERROR( + executorch::runtime::set_option("CudaBackend", cuda_opts.view())); +#endif + + const executorch::runtime::LoadBackendOptionsMap* load_options = nullptr; +#ifdef EXECUTORCH_BUILD_MLX + // Per-model MLX runtime specs, delivered to MLXBackend::init(). Must outlive + // the load_method calls below (they read it during init). + executorch::runtime::BackendOptions<2> mlx_opts; + executorch::runtime::LoadBackendOptionsMap mlx_options_map; + // Release MLX's cached buffer pool every N forward calls to bound memory + // growth during long sessions. + constexpr int kMLXClearCacheInterval = 1; + ET_CHECK_OK_OR_RETURN_ERROR(mlx_opts.set_option( + ::executorch::backends::mlx::kClearCacheIntervalKey, + kMLXClearCacheInterval)); + ET_LOG( + Info, + "MuseGlimmerEngine: MLX clear_cache_interval=%d", + kMLXClearCacheInterval); + // skip_mutable_buffer_init must match the multi-session owner: it is only + // safe when a load scope is active (the caller passes multi_session = "owner + // exists"), since per-session buffers are then allocated by + // mlx_mutable_state. The backend also defensively rejects the flag without an + // active owner. + if (multi_session) { + ET_CHECK_OK_OR_RETURN_ERROR(mlx_opts.set_option( + ::executorch::backends::mlx::kSkipMutableBufferInitKey, true)); + ET_LOG(Info, "MuseGlimmerEngine: MLX skip_mutable_buffer_init=true"); + } + ET_CHECK_OK_OR_RETURN_ERROR(mlx_options_map.set_options( + ::executorch::backends::mlx::kMLXBackendId, mlx_opts.view())); + load_options = &mlx_options_map; +#endif + + if (artifact_mode == MuseGlimmerArtifactMode::DFlash) { +#ifdef EXECUTORCH_BUILD_CUDA + auto method_names_result = module->method_names(); + ET_CHECK_OK_OR_RETURN_ERROR(method_names_result.error()); + if (method_names_result.get().count(kTargetPrefillFromEmbeddingsMethod) != + 0) { + ET_CHECK_OK_OR_RETURN_ERROR(module->load_method( + kTargetPrefillFromEmbeddingsMethod, nullptr, nullptr, load_options)); + } + if (method_names_result.get().count(kDraftPrefillMethod) != 0) { + ET_CHECK_OK_OR_RETURN_ERROR(module->load_method( + kDraftPrefillMethod, nullptr, nullptr, load_options)); + } +#endif + ET_CHECK_OK_OR_RETURN_ERROR(module->load_method( + kTargetForwardFromEmbeddingsMethod, nullptr, nullptr, load_options)); + ET_CHECK_OK_OR_RETURN_ERROR( + module->load_method(kEmbedTextMethod, nullptr, nullptr, load_options)); + if (has_vision) { + ET_CHECK_OK_OR_RETURN_ERROR(module->load_method( + kMuseGlimmerVisionEncoderMethod, nullptr, nullptr, load_options)); + } + ET_CHECK_OK_OR_RETURN_ERROR(module->load_method( + kDraftForwardMethod, nullptr, nullptr, load_options)); + } else { + ET_CHECK_OK_OR_RETURN_ERROR( + module->load_method(kEmbedTextMethod, nullptr, nullptr, load_options)); + ET_CHECK_OK_OR_RETURN_ERROR(module->load_method( + kForwardFromEmbeddingsMethod, nullptr, nullptr, load_options)); +#ifndef EXECUTORCH_BUILD_MLX + ET_CHECK_OK_OR_RETURN_ERROR(module->load_method( + kDecodeFromEmbeddingMethod, nullptr, nullptr, load_options)); +#endif + if (has_vision) { + ET_CHECK_OK_OR_RETURN_ERROR(module->load_method( + kMuseGlimmerVisionEncoderMethod, nullptr, nullptr, load_options)); + } + } + return module; +} + +std::string default_pos_embed_path(const std::string& model_path) { + const auto separator = model_path.find_last_of("/\\"); + const std::string directory = + separator == std::string::npos ? "." : model_path.substr(0, separator); + return directory + "/pos_embed.bin"; +} + +void add_token_piece( + ::tokenizers::Tokenizer* tokenizer, + std::unordered_set& ids, + const char* piece) { + if (auto id = tokenizer->piece_to_id(piece); id.ok()) { + ids.insert(*id); + } +} + +#ifdef EXECUTORCH_BUILD_CUDA +Error register_mutable_fqns( + Module* module, + ::executorch::backends::cuda::MutableStateContextOwner& mutable_state) { + auto res = module->execute("get_mutable_buffer_metadata"); + if (res.error() != Error::Ok) { + ET_LOG( + Info, + "MuseGlimmerEngine: model has no get_mutable_buffer_metadata; " + "multi-session disabled"); + return res.error(); + } + const auto& outs = res.get(); + if (outs.empty() || !outs[0].isString()) { + ET_LOG(Error, "get_mutable_buffer_metadata did not return a string"); + return Error::InvalidProgram; + } + std::string json_str(outs[0].toString()); + auto j = nlohmann::json::parse(json_str, nullptr, /*allow_exceptions=*/false); + if (j.is_discarded() || !j.is_object()) { + ET_LOG(Error, "get_mutable_buffer_metadata is not a valid JSON object"); + return Error::InvalidProgram; + } + if (!j.contains("version") || !j["version"].is_number_integer() || + j["version"].get() != 1) { + ET_LOG(Error, "get_mutable_buffer_metadata: unsupported/missing version"); + return Error::InvalidProgram; + } + if (!j.contains("mutable_buffers") || !j["mutable_buffers"].is_array() || + j["mutable_buffers"].empty()) { + ET_LOG( + Error, + "get_mutable_buffer_metadata: mutable_buffers must be a non-empty array"); + return Error::InvalidProgram; + } + std::vector fqns; + for (const auto& f : j["mutable_buffers"]) { + if (!f.is_string() || f.get().empty()) { + ET_LOG( + Error, + "get_mutable_buffer_metadata: every mutable_buffers entry must be a " + "non-empty string"); + return Error::InvalidProgram; + } + fqns.push_back(f.get()); + } + mutable_state.register_fqns(fqns); + return Error::Ok; +} + +TensorPtr build_decode_pos_table( + const std::unordered_map& metadata) { + auto ctx_it = metadata.find(kMaxContextLen); + if (ctx_it == metadata.end() || ctx_it->second <= 0) { + return nullptr; + } + std::vector pos_data(ctx_it->second); + for (int64_t i = 0; i < ctx_it->second; ++i) { + pos_data[i] = i; + } + return clone_tensor_ptr_to( + from_blob( + pos_data.data(), + {static_cast(pos_data.size())}, + executorch::aten::ScalarType::Long), + executorch::aten::Device(executorch::aten::DeviceType::CUDA, 0)); +} +#endif + +class MuseGlimmerSession : public LLMSession, + public MuseGlimmerMultimodalSession { + public: + MuseGlimmerSession( + Module* module, + std::mutex* exec_mutex, + std::atomic* live_sessions, + ::tokenizers::Tokenizer* tokenizer, + std::unordered_map metadata, + std::unordered_set eos_ids, + int64_t max_prefill_chunk, + int64_t min_prefill_chunk, + TensorPtr decode_pos_table_dev, + MuseGlimmerMutableStateContextOwner* mutable_state, + int session_token) + : module_(module), + exec_mutex_(exec_mutex), + live_sessions_(live_sessions), + tokenizer_(tokenizer), + metadata_(std::move(metadata)), + eos_ids_(std::move(eos_ids)), + max_prefill_chunk_(max_prefill_chunk), + min_prefill_chunk_(min_prefill_chunk), +#ifdef EXECUTORCH_BUILD_CUDA + decode_pos_table_dev_(std::move(decode_pos_table_dev)), +#endif + mutable_state_(mutable_state), + session_token_(session_token) { + if (auto it = metadata_.find(kUseSampling); it != metadata_.end()) { + use_sampling_ = it->second != 0; + } + decode_tokens_ = from_blob( + decode_token_data_, {1, 1}, executorch::aten::ScalarType::Long); + decode_pos_ = + from_blob(decode_pos_data_, {1}, executorch::aten::ScalarType::Long); +#ifdef EXECUTORCH_BUILD_CUDA + decode_tokens_dev_ = clone_tensor_ptr_to(decode_tokens_, cuda_device_); + decode_pos_dev_ = clone_tensor_ptr_to(decode_pos_, cuda_device_); + auto temp_host = + from_blob(&temp_val_, {1}, executorch::aten::ScalarType::Float); + temp_tensor_dev_ = clone_tensor_ptr_to(temp_host, cuda_device_); +#endif +#ifdef EXECUTORCH_BUILD_MLX + temp_tensor_mlx_ = + from_blob(&temp_val_mlx_, {}, executorch::aten::ScalarType::Float); + top_k_tensor_ = + from_blob(&top_k_val_, {}, executorch::aten::ScalarType::Long); + top_p_tensor_ = + from_blob(&top_p_val_, {}, executorch::aten::ScalarType::Float); + seed_tensor_ = + from_blob(&seed_val_, {}, executorch::aten::ScalarType::Long); +#endif + } + + ~MuseGlimmerSession() override { + if (mutable_state_ != nullptr && + session_token_ != kMuseGlimmerNoMutableSession) { + mutable_state_->destroy_session(session_token_); + } + if (live_sessions_ != nullptr) { + live_sessions_->fetch_sub(1); + } + } + + Error prefill_tokens( + const std::vector& tokens, + const SamplingConfig* initial_sampling) override { + std::optional image = std::move(staged_image_); + staged_image_.reset(); + preserve_staged_image_on_next_reset_ = false; + if (tokens.empty()) { + ET_LOG(Error, "prefill_tokens: empty token list"); + return Error::InvalidArgument; + } + int64_t next_image_row = 0; + if (image.has_value()) { + ET_CHECK_OR_RETURN_ERROR( + pos_ == 0, + InvalidState, + "Image prefill requires a freshly reset Muse Glimmer session"); + ET_CHECK_OK_OR_RETURN_ERROR(validate_staged_image(tokens, *image)); + } + float first_token_temp = temperature_; + if (initial_sampling != nullptr) { + if (!use_sampling_ && + (initial_sampling->top_k != 0 || initial_sampling->top_p != 1.0f || + initial_sampling->seed != 0)) { + ET_LOG( + Error, + "prefill_tokens: top_k/top_p/seed require a sampling model " + "(export with --sample); only temperature is supported otherwise"); + return Error::NotSupported; + } + first_token_temp = initial_sampling->temperature; + if (use_sampling_) { + if (!valid_top_p(initial_sampling->top_p)) { + ET_LOG(Error, "prefill_tokens: top_p must be in (0, 1]"); + return Error::InvalidArgument; + } + top_k_ = initial_sampling->top_k; + top_p_ = initial_sampling->top_p; + seed_ = initial_sampling->seed; + } + } + if (!valid_temperature(first_token_temp)) { + ET_LOG(Error, "prefill_tokens: temperature must be -1 or in [0, 2]"); + return Error::InvalidArgument; + } + + const int64_t T = static_cast(tokens.size()); + const auto ctx_it = metadata_.find(kMaxContextLen); + if (ctx_it != metadata_.end() && pos_ + T >= ctx_it->second) { + ET_LOG( + Error, + "prefill_tokens would leave no room to generate (pos %" PRId64 + " + %" PRId64 " >= max_context %" PRId64 ")", + pos_, + T, + ctx_it->second); + return Error::InvalidArgument; + } + + stop_.store(false, std::memory_order_relaxed); + int64_t offset = 0; + while (offset < T) { + int64_t chunk = T - offset; + if (max_prefill_chunk_ > 0) { + chunk = std::min(chunk, max_prefill_chunk_); + } +#ifdef EXECUTORCH_BUILD_CUDA + if (chunk > 1 && chunk < min_prefill_chunk_) { + chunk = 1; + } +#endif + auto sampled = run_prefill_chunk( + tokens.data() + offset, + chunk, + first_token_temp, + image.has_value() ? &*image : nullptr, + image.has_value() ? &next_image_row : nullptr); + ET_CHECK_OK_OR_RETURN_ERROR(sampled.error()); + pending_ = sampled.get(); + pos_ += chunk; + offset += chunk; + } + ET_CHECK_OR_RETURN_ERROR( + !image.has_value() || next_image_row == image->num_soft_tokens, + InvalidState, + "Image prefill did not consume every image embedding row"); + prev_decode_token_ = tokens.back(); +#ifdef EXECUTORCH_BUILD_MLX + if (use_sampling_) { + seed_ += 1; + } +#endif + return Error::Ok; + } + + Result decode_one(const SamplingConfig& sampling) override { + if (!use_sampling_ && + (sampling.top_k != 0 || sampling.top_p != 1.0f || sampling.seed != 0)) { + ET_LOG( + Error, + "MuseGlimmerSession: top_k/top_p/seed require a sampling model " + "(export with --sample); only temperature is supported otherwise"); + return Error::NotSupported; + } + if (!valid_temperature(sampling.temperature)) { + ET_LOG(Error, "decode_one: temperature must be -1 or in [0, 2]"); + return Error::InvalidArgument; + } + ET_CHECK_OR_RETURN_ERROR( + pending_.has_value(), + InvalidState, + "decode_one requires a pending token; call prefill_tokens() first"); + temperature_ = sampling.temperature; + if (use_sampling_) { + if (!valid_top_p(sampling.top_p)) { + ET_LOG(Error, "decode_one: top_p must be in (0, 1]"); + return Error::InvalidArgument; + } + top_k_ = sampling.top_k; + top_p_ = sampling.top_p; + } + + if (stop_.load(std::memory_order_relaxed)) { + return DecodeResult{0, "", /*is_eos=*/false, /*is_terminal=*/true}; + } + + const uint64_t token = pending_.value(); + const bool is_eos = eos_ids_.find(token) != eos_ids_.end(); + const uint64_t prev = prev_decode_token_.value_or(token); + auto dec = tokenizer_->decode(prev, token); + if (!dec.ok()) { + ET_LOG( + Error, + "Tokenizers error code %d", + static_cast(dec.error())); + return Error::InvalidArgument; + } + std::string text_piece = std::move(*dec); + + if (is_eos) { + pending_.reset(); + return DecodeResult{ + token, std::move(text_piece), is_eos, /*is_terminal=*/true}; + } + + const auto ctx_it = metadata_.find(kMaxContextLen); + if (ctx_it != metadata_.end()) { + ET_CHECK_OR_RETURN_ERROR( + pos_ < ctx_it->second, + InvalidArgument, + "decode_one would exceed context capacity: pos_ %" PRId64 + " >= max_context %" PRId64, + pos_, + ctx_it->second); + } + + decode_token_data_[0] = static_cast(token); + decode_pos_data_[0] = pos_; + std::vector inputs; +#ifdef EXECUTORCH_BUILD_CUDA + ET_CHECK_OK_OR_RETURN_ERROR(update_decode_pos_on_cuda()); + ET_CHECK_OK_OR_RETURN_ERROR(set_temperature(temperature_)); + inputs.push_back(EValue(decode_tokens_dev_)); + inputs.push_back(EValue(decode_pos_dev_)); + inputs.push_back(EValue(temp_tensor_dev_)); +#else + inputs.push_back(EValue(decode_tokens_)); + inputs.push_back(EValue(decode_pos_)); +#ifdef EXECUTORCH_BUILD_MLX + if (use_sampling_) { + set_sampling_inputs(temperature_, top_k_, top_p_, seed_); + inputs.push_back(EValue(temp_tensor_mlx_)); + inputs.push_back(EValue(top_k_tensor_)); + inputs.push_back(EValue(top_p_tensor_)); + inputs.push_back(EValue(seed_tensor_)); + } +#endif +#endif + // MLX must reuse the dynamic prefill method so decode observes the KV + // cache written by prefill. Separate delegated methods do not share MLX + // mutable state reliably even when their ExecuTorch arenas are shared. +#ifdef EXECUTORCH_BUILD_MLX + constexpr const char* kDecodeMethod = kForwardFromEmbeddingsMethod; +#else + constexpr const char* kDecodeMethod = kDecodeFromEmbeddingMethod; +#endif + auto sampled = run_locked( + kDecodeMethod, + inputs, + temperature_, + /*sync_after=*/false, + /*token_ids=*/nullptr, + 1, + /*image=*/nullptr, + /*next_image_row=*/nullptr); + ET_CHECK_OK_OR_RETURN_ERROR(sampled.error()); + pending_ = sampled.get(); + prev_decode_token_ = token; + pos_ += 1; +#ifdef EXECUTORCH_BUILD_MLX + if (use_sampling_) { + seed_ += 1; + } +#endif + return DecodeResult{ + token, std::move(text_piece), /*is_eos=*/false, /*is_terminal=*/false}; + } + + int64_t position() const override { + return pos_; + } + + Error reset() override { + pos_ = 0; + pending_.reset(); + prev_decode_token_.reset(); + if (preserve_staged_image_on_next_reset_) { + preserve_staged_image_on_next_reset_ = false; + } else { + staged_image_.reset(); + } + stop_.store(false, std::memory_order_relaxed); + return Error::Ok; + } + + void stop() override { + stop_.store(true, std::memory_order_relaxed); + } + + void stage_image_for_next_prefill(PreparedMuseGlimmerImage image) override { + staged_image_ = std::move(image); + preserve_staged_image_on_next_reset_ = true; + } + + void clear_staged_image() override { + staged_image_.reset(); + preserve_staged_image_on_next_reset_ = false; + } + + private: + Error validate_staged_image( + const std::vector& tokens, + const PreparedMuseGlimmerImage& image) const { + ET_CHECK_OR_RETURN_ERROR( + image.num_soft_tokens > 0 && image.hidden_dim > 0 && + image.embeddings.size() == + static_cast(image.num_soft_tokens * image.hidden_dim), + InvalidArgument, + "Staged image data does not match its dimensions"); + + // A contiguous run of <|patch|> tokens identifies the image span. + std::optional first; + int64_t last = -1; + int64_t patch_count = 0; + for (int64_t i = 0; i < static_cast(tokens.size()); ++i) { + if (tokens[i] == kMuseGlimmerImagePatchTokenId) { + if (!first.has_value()) { + first = i; + } + last = i; + ++patch_count; + } + } + ET_CHECK_OR_RETURN_ERROR( + patch_count == image.num_soft_tokens, + InvalidArgument, + "Image span patch count does not match staged embeddings"); + ET_CHECK_OR_RETURN_ERROR( + first.has_value() && last - *first + 1 == patch_count, + InvalidArgument, + "Image span must be one contiguous run of patch tokens"); + return Error::Ok; + } + + Error + copy_bytes_to_host(void* destination, const void* source, size_t bytes) { +#ifdef EXECUTORCH_BUILD_CUDA + cudaPointerAttributes attributes{}; + const bool on_device = + cudaPointerGetAttributes(&attributes, source) == cudaSuccess && + attributes.type == cudaMemoryTypeDevice; + if (on_device) { + return cudaMemcpy(destination, source, bytes, cudaMemcpyDeviceToHost) == + cudaSuccess + ? Error::Ok + : Error::Internal; + } +#endif + std::memcpy(destination, source, bytes); + return Error::Ok; + } + + static bool valid_temperature(float temperature) { + return temperature == -1.0f || (temperature >= 0.0f && temperature <= 2.0f); + } + + static bool valid_top_p(float top_p) { + return top_p > 0.0f && top_p <= 1.0f; + } + +#ifdef EXECUTORCH_BUILD_MLX + void + set_sampling_inputs(float temp, int64_t top_k, float top_p, uint64_t seed) { + temp_val_mlx_ = (temp < 0.0f) ? 0.0f : temp; + top_k_val_ = (top_k <= 0) ? INT64_MAX : top_k; // 0/neg = keep all + top_p_val_ = top_p; + seed_val_ = static_cast(seed); + } +#endif + + Result run_prefill_chunk( + const uint64_t* tokens, + int64_t T, + float temperature, + const PreparedMuseGlimmerImage* image, + int64_t* next_image_row) { + std::vector token_data(tokens, tokens + T); + std::vector pos_data(T); + for (int64_t i = 0; i < T; ++i) { + pos_data[i] = pos_ + i; + } + auto tokens_tensor = from_blob( + token_data.data(), + {1, static_cast(T)}, + executorch::aten::ScalarType::Long); + auto pos_tensor = from_blob( + pos_data.data(), + {static_cast(T)}, + executorch::aten::ScalarType::Long); + std::vector inputs; + TensorPtr token_input = tokens_tensor; + TensorPtr pos_input = pos_tensor; +#ifdef EXECUTORCH_BUILD_CUDA + std::vector device_inputs; + token_input = to_cuda(token_input, device_inputs); + pos_input = to_cuda(pos_input, device_inputs); + ET_CHECK_OK_OR_RETURN_ERROR(set_temperature(temperature)); +#endif + inputs.push_back(EValue(token_input)); + inputs.push_back(EValue(pos_input)); +#ifdef EXECUTORCH_BUILD_CUDA + inputs.push_back(EValue(temp_tensor_dev_)); +#endif +#ifdef EXECUTORCH_BUILD_MLX + constexpr const char* method = kForwardFromEmbeddingsMethod; +#else + const char* method = T >= min_prefill_chunk_ ? kForwardFromEmbeddingsMethod + : kDecodeFromEmbeddingMethod; +#endif +#ifdef EXECUTORCH_BUILD_MLX + if (use_sampling_) { + set_sampling_inputs(temperature, top_k_, top_p_, seed_); + inputs.push_back(EValue(temp_tensor_mlx_)); + inputs.push_back(EValue(top_k_tensor_)); + inputs.push_back(EValue(top_p_tensor_)); + inputs.push_back(EValue(seed_tensor_)); + } +#endif + return run_locked( + method, + inputs, + temperature, + /*sync_after=*/true, + tokens, + T, + image, + next_image_row); + } + +#ifdef EXECUTORCH_BUILD_CUDA + TensorPtr to_cuda(TensorPtr tensor, std::vector& keep_alive) { + keep_alive.push_back(clone_tensor_ptr_to(tensor, cuda_device_)); + return keep_alive.back(); + } + + Error set_temperature(float temperature) { + if (!valid_temperature(temperature)) { + return Error::InvalidArgument; + } + temp_val_ = (temperature <= 0.0f) ? 1e-6f : temperature; + if (cudaMemcpy( + temp_tensor_dev_->mutable_data_ptr(), + &temp_val_, + sizeof(float), + cudaMemcpyHostToDevice) != cudaSuccess) { + ET_LOG(Error, "set_temperature: cudaMemcpy H2D failed"); + return Error::Internal; + } + return Error::Ok; + } + + Error copy_decode_token_to_cuda(uint64_t token) { + const int64_t token_value = static_cast(token); + if (cudaMemcpy( + decode_tokens_dev_->mutable_data_ptr(), + &token_value, + sizeof(int64_t), + cudaMemcpyHostToDevice) != cudaSuccess) { + ET_LOG(Error, "copy_decode_token_to_cuda: token H2D failed"); + return Error::Internal; + } + return Error::Ok; + } + + Error stage_next_decode_token_on_cuda( + const executorch::aten::Tensor& out_tensor, + uint64_t token) { + if (out_tensor.scalar_type() == executorch::aten::ScalarType::Long) { + const void* ptr = out_tensor.const_data_ptr(); + cudaPointerAttributes attrs{}; + const bool on_device = + cudaPointerGetAttributes(&attrs, ptr) == cudaSuccess && + attrs.type == cudaMemoryTypeDevice; + if (cudaMemcpy( + decode_tokens_dev_->mutable_data_ptr(), + ptr, + sizeof(int64_t), + on_device ? cudaMemcpyDeviceToDevice : cudaMemcpyHostToDevice) != + cudaSuccess) { + ET_LOG(Error, "stage_next_decode_token_on_cuda: token copy failed"); + return Error::Internal; + } + return Error::Ok; + } + return copy_decode_token_to_cuda(token); + } + + Error update_decode_pos_on_cuda() { + if (decode_pos_table_dev_ != nullptr) { + auto* pos_table = + static_cast(decode_pos_table_dev_->mutable_data_ptr()); + auto* pos_slot = + static_cast(decode_pos_dev_->mutable_data_ptr()); + if (cudaMemcpy( + pos_slot, + pos_table + pos_, + sizeof(int64_t), + cudaMemcpyDeviceToDevice) != cudaSuccess) { + ET_LOG(Error, "update_decode_pos_on_cuda: position D2D failed"); + return Error::Internal; + } + return Error::Ok; + } + if (cudaMemcpy( + decode_pos_dev_->mutable_data_ptr(), + decode_pos_data_, + sizeof(int64_t), + cudaMemcpyHostToDevice) != cudaSuccess) { + ET_LOG(Error, "update_decode_pos_on_cuda: position H2D failed"); + return Error::Internal; + } + return Error::Ok; + } +#endif + + Result run_locked( + const char* method, + std::vector& inputs, + float temperature, + bool sync_after, + const uint64_t* token_ids, + int64_t token_count, + const PreparedMuseGlimmerImage* image, + int64_t* next_image_row) { + std::lock_guard guard(*exec_mutex_); + auto execute_contract = [&]() -> Result> { + auto embed_outputs = module_->execute(kEmbedTextMethod, {inputs[0]}); + ET_CHECK_OK_OR_RETURN_ERROR(embed_outputs.error()); + ET_CHECK_OR_RETURN_ERROR( + embed_outputs->size() == 1 && (*embed_outputs)[0].isTensor(), + InvalidProgram, + "embed_text must return one tensor"); + const auto& embed_tensor = (*embed_outputs)[0].toTensor(); + ET_CHECK_OR_RETURN_ERROR( + embed_tensor.dim() == 3 && embed_tensor.size(0) == 1 && + embed_tensor.size(1) == token_count && + (embed_tensor.scalar_type() == + executorch::aten::ScalarType::BFloat16 || + embed_tensor.scalar_type() == + executorch::aten::ScalarType::Half), + InvalidProgram, + "embed_text must return [1, T, H] in the activation dtype"); + + std::vector spliced_embeddings; + TensorPtr spliced_tensor; + std::vector forward_inputs = inputs; + if (image != nullptr) { + ET_CHECK_OR_RETURN_ERROR( + token_ids != nullptr && next_image_row != nullptr && + embed_tensor.size(2) == image->hidden_dim, + InvalidArgument, + "Image embedding dimension does not match embed_text"); + const int64_t hidden_dim = embed_tensor.size(2); + spliced_embeddings.resize(token_count * hidden_dim); + ET_CHECK_OK_OR_RETURN_ERROR(copy_bytes_to_host( + spliced_embeddings.data(), + embed_tensor.const_data_ptr(), + spliced_embeddings.size() * sizeof(uint16_t))); + for (int64_t row = 0; row < token_count; ++row) { + if (token_ids[row] != kMuseGlimmerImagePatchTokenId) { + continue; + } + ET_CHECK_OR_RETURN_ERROR( + *next_image_row < image->num_soft_tokens, + InvalidArgument, + "Image prefill has more patch tokens than image rows"); + std::memcpy( + spliced_embeddings.data() + row * hidden_dim, + image->embeddings.data() + *next_image_row * hidden_dim, + hidden_dim * sizeof(uint16_t)); + ++*next_image_row; + } + spliced_tensor = from_blob( + spliced_embeddings.data(), + {1, + static_cast(token_count), + static_cast(hidden_dim)}, + embed_tensor.scalar_type()); + forward_inputs[0] = EValue(spliced_tensor); + } else { + forward_inputs[0] = (*embed_outputs)[0]; + } + return module_->execute(method, forward_inputs); + }; + auto res = mutable_state_ != nullptr + ? mutable_state_->with_active_session(session_token_, execute_contract) + : execute_contract(); + ET_CHECK_OK_OR_RETURN_ERROR(res.error()); + const auto& out_tensor = res.get()[0].toTensor(); + auto sampled = read_sampled_token(out_tensor, temperature, use_sampling_); + ET_CHECK_OK_OR_RETURN_ERROR(sampled.error()); +#ifdef EXECUTORCH_BUILD_CUDA + ET_CHECK_OK_OR_RETURN_ERROR( + stage_next_decode_token_on_cuda(out_tensor, sampled.get())); +#endif +#ifdef EXECUTORCH_BUILD_CUDA + if (sync_after && cudaDeviceSynchronize() != cudaSuccess) { + ET_LOG(Error, "run_locked: cudaDeviceSynchronize failed"); + return Error::Internal; + } +#else + (void)sync_after; +#endif + return sampled.get(); + } + + Module* module_; + std::mutex* exec_mutex_; + std::atomic* live_sessions_; + ::tokenizers::Tokenizer* tokenizer_; + std::unordered_map metadata_; + std::unordered_set eos_ids_; + int64_t max_prefill_chunk_; + int64_t min_prefill_chunk_; + + int64_t pos_ = 0; + std::optional pending_; + std::optional prev_decode_token_; + float temperature_ = -1.0f; + std::atomic stop_{false}; + std::optional staged_image_; + bool preserve_staged_image_on_next_reset_ = false; + + bool use_sampling_ = false; + int64_t top_k_ = 0; // 0 = off (keep all); mapped to INT64_MAX on-device + float top_p_ = 1.0f; + uint64_t seed_ = 0; + + int64_t decode_token_data_[1] = {0}; + int64_t decode_pos_data_[1] = {0}; + TensorPtr decode_tokens_; + TensorPtr decode_pos_; +#ifdef EXECUTORCH_BUILD_CUDA + TensorPtr decode_pos_table_dev_; +#endif + MuseGlimmerMutableStateContextOwner* mutable_state_ = nullptr; + int session_token_ = kMuseGlimmerNoMutableSession; +#ifdef EXECUTORCH_BUILD_CUDA + float temp_val_ = 1e-6f; + executorch::aten::Device cuda_device_ = + executorch::aten::Device(executorch::aten::DeviceType::CUDA, 0); + TensorPtr decode_tokens_dev_; + TensorPtr decode_pos_dev_; + TensorPtr temp_tensor_dev_; +#endif +#ifdef EXECUTORCH_BUILD_MLX + float temp_val_mlx_ = 0.0f; + int64_t top_k_val_ = INT64_MAX; + float top_p_val_ = 1.0f; + int64_t seed_val_ = 0; + TensorPtr temp_tensor_mlx_; + TensorPtr top_k_tensor_; + TensorPtr top_p_tensor_; + TensorPtr seed_tensor_; +#endif +}; + +} // namespace + +Result> MuseGlimmerEngine::create( + const MuseGlimmerConfig& config) { + if (config.model_path.empty() || config.tokenizer_path.empty()) { + ET_LOG( + Error, "MuseGlimmerEngine: model_path and tokenizer_path are required"); + return Error::InvalidArgument; + } + + auto tokenizer = std::make_unique<::tokenizers::HFTokenizer>(); + if (tokenizer->load(config.tokenizer_path) != ::tokenizers::Error::Ok) { + ET_LOG(Error, "MuseGlimmerEngine: failed to load tokenizer"); + return Error::InvalidArgument; + } + + std::vector data_files; + if (!config.data_path.empty()) { + data_files.push_back(config.data_path); + } + auto meta_module = std::make_unique( + config.model_path, data_files, Module::LoadMode::File); + auto artifact_mode_result = + resolve_artifact_mode(meta_module.get(), config.artifact_mode); + if (artifact_mode_result.error() != Error::Ok) { + ET_LOG(Error, "MuseGlimmerEngine: failed to resolve artifact mode"); + return artifact_mode_result.error(); + } + const MuseGlimmerArtifactMode artifact_mode = artifact_mode_result.get(); + ET_LOG( + Info, + "MuseGlimmerEngine: detected %s artifact", + artifact_mode_name(artifact_mode)); + + auto method_names_result = meta_module->method_names(); + ET_CHECK_OK_OR_RETURN_ERROR(method_names_result.error()); + const auto& method_names = method_names_result.get(); + const bool has_vision = + method_names.count(kMuseGlimmerVisionEncoderMethod) != 0; +#ifdef EXECUTORCH_BUILD_CUDA + const bool has_dflash_target_prefill = + artifact_mode == MuseGlimmerArtifactMode::DFlash && + method_names.count(kTargetPrefillFromEmbeddingsMethod) != 0; +#endif + if (has_vision && artifact_mode == MuseGlimmerArtifactMode::DFlash) { + ET_CHECK_OR_RETURN_ERROR( + method_names.count(kEmbedTextMethod) != 0 && + method_names.count(kTargetForwardFromEmbeddingsMethod) != 0, + InvalidProgram, + "Vision DFlash artifact must expose embed_text and " + "target_forward_from_embeddings"); + } +#ifdef EXECUTORCH_BUILD_CUDA + ET_CHECK_OR_RETURN_ERROR( + artifact_mode != MuseGlimmerArtifactMode::DFlash || + has_dflash_target_prefill, + InvalidProgram, + "CUDA DFlash artifact must expose target_prefill_from_embeddings"); +#endif + + auto metadata_result = get_llm_metadata(tokenizer.get(), meta_module.get()); + if (metadata_result.error() != Error::Ok) { + ET_LOG(Error, "MuseGlimmerEngine: failed to read metadata"); + return metadata_result.error(); + } + + // Validate the patch token only for vision artifacts; text-only tokenizers + // may omit it. + if (has_vision) { + auto patch_id = tokenizer->piece_to_id("<|patch|>"); + ET_CHECK_OR_RETURN_ERROR( + patch_id.ok(), + InvalidArgument, + "Vision artifact needs a tokenizer with a <|patch|> token"); + ET_CHECK_OR_RETURN_ERROR( + *patch_id == kMuseGlimmerImagePatchTokenId, + InvalidArgument, + "Tokenizer maps <|patch|> to %" PRIu64 ", expected %" PRIu64, + static_cast(*patch_id), + kMuseGlimmerImagePatchTokenId); + } + + auto eos_ids = get_eos_ids(tokenizer.get(), meta_module.get()); + eos_ids.insert(static_cast(config.eos_id)); + // <|eom|> continues the assistant turn. Add only turn-ending Harmony tokens + // here so a reasoning message can precede a tool call. + add_token_piece(tokenizer.get(), eos_ids, "<|eot|>"); + add_token_piece(tokenizer.get(), eos_ids, "<|end_of_text|>"); + + auto metadata = metadata_result.get(); + int64_t max_prefill_chunk = 1; + auto max_ctx_it = metadata.find(kMaxContextLen); + if (max_ctx_it != metadata.end() && max_ctx_it->second > 1) { + max_prefill_chunk = max_ctx_it->second - 1; + } + if (auto get_result = meta_module->get(kMaxPrefillChunk); get_result.ok()) { + max_prefill_chunk = get_result->toScalar().to(); + metadata[kMaxPrefillChunk] = max_prefill_chunk; + } + + if (auto get_result = meta_module->get(kUseSampling); get_result.ok()) { + metadata[kUseSampling] = get_result->toScalar().to(); + } + + int64_t min_prefill_chunk = 1; +#ifdef EXECUTORCH_BUILD_CUDA + if (artifact_mode == MuseGlimmerArtifactMode::Autoregressive) { + min_prefill_chunk = 5; + if (auto get_result = meta_module->get(kMinPrefillChunk); get_result.ok()) { + min_prefill_chunk = get_result->toScalar().to(); + } + metadata[kMinPrefillChunk] = min_prefill_chunk; + } +#endif + + int64_t dflash_block_size = 0; + int64_t dflash_mask_token_id = 0; + int64_t dflash_n_target_layers = 0; + int64_t dflash_sliding_window = 0; + int64_t dflash_min_target_prefill_chunk = 0; + int64_t dflash_max_target_prefill_chunk = 0; + int64_t dflash_min_draft_prefill_chunk = 0; + int64_t dflash_max_draft_prefill_chunk = 0; + int64_t vision_hidden_size = 0; + int64_t max_vision_patches = 0; + auto activation_dtype_result = + get_required_string_metadata(meta_module.get(), kActivationDtype); + ET_CHECK_OK_OR_RETURN_ERROR(activation_dtype_result.error()); + std::string activation_dtype = std::move(activation_dtype_result.get()); + ET_CHECK_OR_RETURN_ERROR( + activation_dtype == "bfloat16" || activation_dtype == "float16" || + activation_dtype == "float32", + InvalidProgram, + "Unsupported Muse Glimmer activation dtype %s", + activation_dtype.c_str()); + ET_CHECK_OR_RETURN_ERROR( + (!has_vision && artifact_mode != MuseGlimmerArtifactMode::DFlash) || + activation_dtype != "float32", + InvalidProgram, + "Vision and DFlash require bfloat16 or float16 activations"); + if (artifact_mode == MuseGlimmerArtifactMode::DFlash) { + auto block_size = + get_required_int_metadata(meta_module.get(), kDFlashBlockSize); + auto mask_token = + get_required_int_metadata(meta_module.get(), kDFlashMaskTokenId); + auto target_layers = + get_required_int_metadata(meta_module.get(), kDFlashTargetLayers); + auto sliding_window = + get_required_int_metadata(meta_module.get(), kDFlashSlidingWindow); + ET_CHECK_OK_OR_RETURN_ERROR(block_size.error()); + ET_CHECK_OK_OR_RETURN_ERROR(mask_token.error()); + ET_CHECK_OK_OR_RETURN_ERROR(target_layers.error()); + ET_CHECK_OK_OR_RETURN_ERROR(sliding_window.error()); + dflash_block_size = block_size.get(); + dflash_mask_token_id = mask_token.get(); + dflash_n_target_layers = target_layers.get(); + dflash_sliding_window = sliding_window.get(); +#ifdef EXECUTORCH_BUILD_CUDA + if (has_dflash_target_prefill) { + auto min_target_prefill_chunk = get_required_int_metadata( + meta_module.get(), kDFlashMinTargetPrefillChunk); + auto max_target_prefill_chunk = get_required_int_metadata( + meta_module.get(), kDFlashMaxTargetPrefillChunk); + ET_CHECK_OK_OR_RETURN_ERROR(min_target_prefill_chunk.error()); + ET_CHECK_OK_OR_RETURN_ERROR(max_target_prefill_chunk.error()); + dflash_min_target_prefill_chunk = min_target_prefill_chunk.get(); + dflash_max_target_prefill_chunk = max_target_prefill_chunk.get(); + ET_CHECK_OR_RETURN_ERROR( + dflash_min_target_prefill_chunk > kCudaDFlashHiddenRows && + dflash_max_target_prefill_chunk >= + dflash_min_target_prefill_chunk, + InvalidProgram, + "Invalid DFlash target prefill chunk interval [%" PRId64 ", %" PRId64 + "]", + dflash_min_target_prefill_chunk, + dflash_max_target_prefill_chunk); + } + const bool has_draft_prefill = method_names.count(kDraftPrefillMethod) != 0; + if (has_draft_prefill) { + auto min_draft_prefill_chunk = get_required_int_metadata( + meta_module.get(), kDFlashMinDraftPrefillChunk); + auto max_draft_prefill_chunk = get_required_int_metadata( + meta_module.get(), kDFlashMaxDraftPrefillChunk); + ET_CHECK_OK_OR_RETURN_ERROR(min_draft_prefill_chunk.error()); + ET_CHECK_OK_OR_RETURN_ERROR(max_draft_prefill_chunk.error()); + dflash_min_draft_prefill_chunk = min_draft_prefill_chunk.get(); + dflash_max_draft_prefill_chunk = max_draft_prefill_chunk.get(); + ET_CHECK_OR_RETURN_ERROR( + dflash_min_draft_prefill_chunk > kCudaDFlashHiddenRows && + dflash_max_draft_prefill_chunk >= dflash_min_draft_prefill_chunk, + InvalidProgram, + "Invalid DFlash draft prefill chunk interval [%" PRId64 ", %" PRId64 + "]", + dflash_min_draft_prefill_chunk, + dflash_max_draft_prefill_chunk); + } +#endif + ET_CHECK_OR_RETURN_ERROR( + dflash_block_size >= 2, + InvalidProgram, + "DFlash block size must be at least 2, got %" PRId64, + dflash_block_size); + ET_CHECK_OR_RETURN_ERROR( + config.dflash_block_length == 0 || + (config.dflash_block_length >= 2 && + config.dflash_block_length <= dflash_block_size), + InvalidArgument, + "DFlash block length must be in [2, %" PRId64 "]", + dflash_block_size); + const int64_t block_length = config.dflash_block_length > 0 + ? config.dflash_block_length + : dflash_block_size; + ET_CHECK_OR_RETURN_ERROR( + config.dflash_n_draft == 0 || + (config.dflash_n_draft > 0 && config.dflash_n_draft < block_length), + InvalidArgument, + "DFlash n_draft must be in [1, block_length - 1]"); +#ifdef EXECUTORCH_BUILD_CUDA + // A decode cycle retains up to n_draft + 1 hidden rows, which the next + // draft call must feed into the fixed-size CUDA hidden input. + const int64_t n_draft = + config.dflash_n_draft > 0 ? config.dflash_n_draft : block_length - 1; + ET_CHECK_OR_RETURN_ERROR( + n_draft + 1 <= kCudaDFlashHiddenRows, + InvalidArgument, + "CUDA DFlash n_draft must be at most %" PRId64 ", got %" PRId64, + kCudaDFlashHiddenRows - 1, + n_draft); +#endif + metadata[kDFlashBlockSize] = dflash_block_size; + metadata[kDFlashMaskTokenId] = dflash_mask_token_id; + metadata[kDFlashTargetLayers] = dflash_n_target_layers; + metadata[kDFlashSlidingWindow] = dflash_sliding_window; +#ifdef EXECUTORCH_BUILD_CUDA + metadata[kDFlashMinTargetPrefillChunk] = dflash_min_target_prefill_chunk; + metadata[kDFlashMaxTargetPrefillChunk] = dflash_max_target_prefill_chunk; + metadata[kDFlashMinDraftPrefillChunk] = dflash_min_draft_prefill_chunk; + metadata[kDFlashMaxDraftPrefillChunk] = dflash_max_draft_prefill_chunk; +#endif + } + if (has_vision) { + auto hidden_size = + get_required_int_metadata(meta_module.get(), kVisionHiddenSize); + auto patch_limit = + get_required_int_metadata(meta_module.get(), kMaxVisionPatches); + ET_CHECK_OK_OR_RETURN_ERROR(hidden_size.error()); + ET_CHECK_OK_OR_RETURN_ERROR(patch_limit.error()); + vision_hidden_size = hidden_size.get(); + max_vision_patches = patch_limit.get(); + ET_CHECK_OR_RETURN_ERROR( + vision_hidden_size > 0, + InvalidProgram, + "Vision hidden size must be positive"); + ET_CHECK_OR_RETURN_ERROR( + max_vision_patches > 0 && + max_vision_patches % kVisionDownsampleArea == 0, + InvalidProgram, + "Max vision patches must be positive and divisible by %" PRId64, + kVisionDownsampleArea); + metadata[kVisionHiddenSize] = vision_hidden_size; + metadata[kMaxVisionPatches] = max_vision_patches; + } + + std::unique_ptr mutable_state; +#ifdef EXECUTORCH_BUILD_CUDA + if (config.enable_cuda_graph) { + ET_LOG( + Info, + "MuseGlimmerEngine: CUDA graph requested; per-session rebinding " + "disabled and serving capacity clamped to 1 session."); + } else { + auto candidate = std::make_unique(); + if (Error e = register_mutable_fqns(meta_module.get(), *candidate); + e == Error::Ok) { + mutable_state = std::move(candidate); + } else { + ET_LOG( + Info, + "MuseGlimmerEngine: mutable-buffer metadata unavailable or invalid; " + "serving capacity clamped to 1 session."); + } + } +#elif defined(EXECUTORCH_BUILD_MLX) + // Only enable the per-session mutable-buffer path when actually serving more + // than one session. For a single session (the CLI runner) the rebind would + // allocate a second copy of the KV-cache buffers on top of the program's + // default buffers — doubling KV-cache memory and adding a one-time + // session-buffer allocation during the first prefill — for no isolation + // benefit. Leaving mutable_state null keeps the program's default buffers. + if (config.max_sessions > 1) { + mutable_state = std::make_unique(); + } +#endif + + // Pass whether a multi-session owner exists as the single source of truth for + // skip_mutable_buffer_init, so the skip flag can never diverge from the + // owner. + const bool multi_session = mutable_state != nullptr; + auto module_res = multi_session + ? mutable_state->with_load_scope([&]() { + return build_muse_glimmer_module( + config, artifact_mode, has_vision, multi_session); + }) + : build_muse_glimmer_module( + config, artifact_mode, has_vision, multi_session); + if (module_res.error() != Error::Ok) { + return module_res.error(); + } + std::unique_ptr shared_module = std::move(module_res.get()); + + bool rebind_available = false; + rebind_available = mutable_state != nullptr && mutable_state->available(); + if (rebind_available && mutable_state->validate_coverage() != Error::Ok) { + ET_LOG( + Error, + "MuseGlimmerEngine: mutable-buffer coverage check failed; disabling " + "multi-session (capacity clamped to 1)."); + rebind_available = false; + } + if (!rebind_available) { + ET_LOG( + Info, + "MuseGlimmerEngine: per-session rebinding unavailable; serving capacity " + "clamped to 1 session."); + } + + TensorPtr decode_pos_table_dev; +#ifdef EXECUTORCH_BUILD_CUDA + decode_pos_table_dev = build_decode_pos_table(metadata); +#endif + + ET_CHECK_OR_RETURN_ERROR( + !has_vision || config.max_image_bytes > 0, + InvalidArgument, + "max_image_bytes must be positive"); + const auto vision_activation_dtype = activation_dtype == "bfloat16" + ? executorch::aten::ScalarType::BFloat16 + : executorch::aten::ScalarType::Half; + auto engine = std::unique_ptr(new MuseGlimmerEngine( + config, + std::move(tokenizer), + std::move(metadata), + std::move(eos_ids), + std::move(shared_module), + artifact_mode, + max_prefill_chunk, + min_prefill_chunk, + dflash_block_size, + dflash_mask_token_id, + dflash_n_target_layers, + dflash_sliding_window, + dflash_min_target_prefill_chunk, + dflash_max_target_prefill_chunk, + std::move(activation_dtype), + std::move(decode_pos_table_dev), + /*vision_runtime=*/nullptr, + rebind_available, + std::move(mutable_state))); + if (has_vision) { + MuseGlimmerVisionRuntimeConfig vision_config; + vision_config.module = engine->shared_module_.get(); + vision_config.execution_mutex = &engine->exec_mutex_; + vision_config.pos_embed_path = config.pos_embed_path.empty() + ? default_pos_embed_path(config.model_path) + : config.pos_embed_path; + vision_config.activation_dtype = vision_activation_dtype; + vision_config.expected_hidden_dim = vision_hidden_size; + vision_config.max_image_tokens = max_vision_patches / kVisionDownsampleArea; + vision_config.max_encoded_bytes = config.max_image_bytes; + try { + engine->vision_runtime_ = + std::make_unique(std::move(vision_config)); + } catch (const std::exception& exception) { + ET_LOG( + Error, + "MuseGlimmerEngine: failed to initialize vision runtime: %s", + exception.what()); + return Error::InvalidExternalData; + } + } + return engine; +} + +MuseGlimmerEngine::~MuseGlimmerEngine() = default; + +Result MuseGlimmerEngine::prepare_image_from_file( + const std::string& image_path) const { + ET_CHECK_OR_RETURN_ERROR( + vision_runtime_ != nullptr, + NotSupported, + "Muse Glimmer artifact does not support image input"); + return vision_runtime_->prepare_image_from_file(image_path); +} + +Result MuseGlimmerEngine::prepare_image_from_bytes( + ::executorch::runtime::Span encoded_image) const { + ET_CHECK_OR_RETURN_ERROR( + vision_runtime_ != nullptr, + NotSupported, + "Muse Glimmer artifact does not support image input"); + return vision_runtime_->prepare_image_from_bytes(encoded_image); +} + +Result> MuseGlimmerEngine::create_session() { + const int cap = + serving_capacity().max_physical_sessions_without_weight_duplication; + { + std::lock_guard g(exec_mutex_); + if (live_sessions_.load() >= cap) { + ET_LOG( + Error, + "MuseGlimmerEngine: at session capacity (%d); refusing create_session", + cap); + return Error::InvalidState; + } + live_sessions_.fetch_add(1); + } + + int token = -1; + if (rebind_available_) { + auto t = mutable_state_->create_session(); + if (t.error() != Error::Ok) { + live_sessions_.fetch_sub(1); + return t.error(); + } + token = t.get(); + } + + if (artifact_mode_ == MuseGlimmerArtifactMode::DFlash) { + const int64_t block_length = config_.dflash_block_length > 0 + ? config_.dflash_block_length + : dflash_block_size_; + const int64_t n_draft = + config_.dflash_n_draft > 0 ? config_.dflash_n_draft : block_length - 1; + DFlashSessionConfig session_config; + session_config.module = shared_module_.get(); + session_config.exec_mutex = &exec_mutex_; + session_config.live_sessions = &live_sessions_; + session_config.tokenizer = tokenizer_.get(); + session_config.metadata = metadata_; + session_config.eos_ids = eos_ids_; + session_config.mutable_state = + rebind_available_ ? mutable_state_.get() : nullptr; + session_config.session_token = token; + session_config.max_prefill_chunk = max_prefill_chunk_; + session_config.block_size = dflash_block_size_; + session_config.block_length = block_length; + session_config.n_draft = n_draft; + session_config.mask_token_id = dflash_mask_token_id_; + session_config.n_target_layers = dflash_n_target_layers_; + session_config.draft_sliding_window = dflash_sliding_window_; + session_config.min_target_prefill_chunk = dflash_min_target_prefill_chunk_; + session_config.max_target_prefill_chunk = dflash_max_target_prefill_chunk_; + session_config.min_draft_prefill_chunk = + metadata_.count(kDFlashMinDraftPrefillChunk) != 0 + ? metadata_.at(kDFlashMinDraftPrefillChunk) + : 0; + session_config.max_draft_prefill_chunk = + metadata_.count(kDFlashMaxDraftPrefillChunk) != 0 + ? metadata_.at(kDFlashMaxDraftPrefillChunk) + : 0; + session_config.has_draft_prefill = + session_config.min_draft_prefill_chunk > 0; + session_config.activation_dtype = activation_dtype_; + session_config.draft_argmax = config_.dflash_draft_argmax; + session_config.ignore_eos = config_.dflash_ignore_eos; + session_config.timing = config_.dflash_timing; + auto session = create_dflash_session(std::move(session_config)); + if (session.error() != Error::Ok) { + if (rebind_available_) { + mutable_state_->destroy_session(token); + } + live_sessions_.fetch_sub(1); + } + return session; + } + + return std::unique_ptr(new MuseGlimmerSession( + shared_module_.get(), + &exec_mutex_, + &live_sessions_, + tokenizer_.get(), + metadata_, + eos_ids_, + max_prefill_chunk_, + min_prefill_chunk_, + decode_pos_table_dev_, + rebind_available_ ? mutable_state_.get() : nullptr, + token)); +} + +LLMServingCapacity MuseGlimmerEngine::serving_capacity() const { + LLMServingCapacity cap; + if (rebind_available_) { + cap.max_physical_sessions_without_weight_duplication = + config_.max_sessions > 1 ? config_.max_sessions : 1; + cap.estimated_bytes_per_session = mutable_state_->bytes_per_session(); + } + return cap; +} + +} // namespace executorch::extension::llm diff --git a/examples/models/muse-glimmer/runtime/engine/muse_glimmer_engine.h b/examples/models/muse-glimmer/runtime/engine/muse_glimmer_engine.h new file mode 100644 index 00000000000..06709f5c0bb --- /dev/null +++ b/examples/models/muse-glimmer/runtime/engine/muse_glimmer_engine.h @@ -0,0 +1,213 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +// Engine/Session adapter for the shared embeddings-input Muse Glimmer contract. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#ifdef EXECUTORCH_BUILD_CUDA +#include +#elif defined(EXECUTORCH_BUILD_MLX) +#include +#include +#else +#error \ + "MuseGlimmerEngine requires EXECUTORCH_BUILD_CUDA or EXECUTORCH_BUILD_MLX" +#endif + +namespace executorch::extension::llm { + +// <|patch|>. One row of image soft tokens is spliced over each occurrence. +// MuseGlimmerEngine::create checks this against the loaded tokenizer, so a +// model whose vocabulary disagrees fails at load rather than generating +// nonsense. +inline constexpr uint64_t kMuseGlimmerImagePatchTokenId = 200092; +inline constexpr char kMuseGlimmerImagePlaceholder[] = ""; + +::tokenizers::Result> tokenize_muse_glimmer_prompt( + const ::tokenizers::Tokenizer& tokenizer, + const std::string& prompt, + uint64_t bos_id, + std::optional image_tokens = std::nullopt); + +enum class MuseGlimmerArtifactMode { + Auto, + Autoregressive, + DFlash, +}; + +#if defined(EXECUTORCH_BUILD_CUDA) +using MuseGlimmerMutableStateContextOwner = + ::executorch::backends::cuda::MutableStateContextOwner; +constexpr int kMuseGlimmerNoMutableSession = + ::executorch::backends::cuda::kNoMutableSession; +#elif defined(EXECUTORCH_BUILD_MLX) +using MuseGlimmerMutableStateContextOwner = + ::executorch::backends::mlx::MutableStateContextOwner; +constexpr int kMuseGlimmerNoMutableSession = + ::executorch::backends::mlx::kNoMutableSession; +#endif + +struct MuseGlimmerConfig { + std::string model_path; + std::string data_path; + std::string tokenizer_path; + std::string pos_embed_path; + size_t max_image_bytes = 20 * 1024 * 1024; + int32_t max_sessions = 1; + int64_t eos_id = 200001; + bool enable_cuda_graph = false; + MuseGlimmerArtifactMode artifact_mode = MuseGlimmerArtifactMode::Auto; + int32_t dflash_block_length = 0; + int32_t dflash_n_draft = 0; + bool dflash_draft_argmax = true; + bool dflash_ignore_eos = false; + DFlashDecodeTiming* dflash_timing = nullptr; +}; + +class MuseGlimmerMultimodalSession { + public: + virtual ~MuseGlimmerMultimodalSession() = default; + + virtual void stage_image_for_next_prefill(PreparedMuseGlimmerImage image) = 0; + virtual void clear_staged_image() = 0; +}; + +inline MuseGlimmerMultimodalSession* as_muse_glimmer_multimodal_session( + LLMSession* session) { + return dynamic_cast(session); +} + +class ET_EXPERIMENTAL MuseGlimmerEngine : public LLMEngine { + public: + static ::executorch::runtime::Result> + create(const MuseGlimmerConfig& config); + + ~MuseGlimmerEngine() override; + + ::executorch::runtime::Result> create_session() + override; + + LLMServingCapacity serving_capacity() const override; + + const std::unordered_map& metadata() const override { + return metadata_; + } + + ::tokenizers::Tokenizer* tokenizer() const { + return tokenizer_.get(); + } + + bool has_vision() const { + return vision_runtime_ != nullptr; + } + + ::executorch::runtime::Result + prepare_image_from_file(const std::string& image_path) const; + + ::executorch::runtime::Result + prepare_image_from_bytes( + ::executorch::runtime::Span encoded_image) const; + + ::executorch::runtime::Result + prepare_image_from_bytes(const std::vector& encoded_image) const { + return prepare_image_from_bytes(::executorch::runtime::Span( + encoded_image.data(), encoded_image.size())); + } + + MuseGlimmerArtifactMode artifact_mode() const { + return artifact_mode_; + } + + MuseGlimmerEngine(const MuseGlimmerEngine&) = delete; + MuseGlimmerEngine& operator=(const MuseGlimmerEngine&) = delete; + + private: + MuseGlimmerEngine( + MuseGlimmerConfig config, + std::unique_ptr<::tokenizers::Tokenizer> tokenizer, + std::unordered_map metadata, + std::unordered_set eos_ids, + std::unique_ptr shared_module, + MuseGlimmerArtifactMode artifact_mode, + int64_t max_prefill_chunk, + int64_t min_prefill_chunk, + int64_t dflash_block_size, + int64_t dflash_mask_token_id, + int64_t dflash_n_target_layers, + int64_t dflash_sliding_window, + int64_t dflash_min_target_prefill_chunk, + int64_t dflash_max_target_prefill_chunk, + std::string activation_dtype, + ::executorch::extension::TensorPtr decode_pos_table_dev, + std::unique_ptr vision_runtime, + bool rebind_available, + std::unique_ptr mutable_state) + : config_(std::move(config)), + tokenizer_(std::move(tokenizer)), + metadata_(std::move(metadata)), + eos_ids_(std::move(eos_ids)), + shared_module_(std::move(shared_module)), + artifact_mode_(artifact_mode), + max_prefill_chunk_(max_prefill_chunk), + min_prefill_chunk_(min_prefill_chunk), + dflash_block_size_(dflash_block_size), + dflash_mask_token_id_(dflash_mask_token_id), + dflash_n_target_layers_(dflash_n_target_layers), + dflash_sliding_window_(dflash_sliding_window), + dflash_min_target_prefill_chunk_(dflash_min_target_prefill_chunk), + dflash_max_target_prefill_chunk_(dflash_max_target_prefill_chunk), + activation_dtype_(std::move(activation_dtype)), + decode_pos_table_dev_(std::move(decode_pos_table_dev)), + vision_runtime_(std::move(vision_runtime)), + rebind_available_(rebind_available), + mutable_state_(std::move(mutable_state)) {} + + MuseGlimmerConfig config_; + std::unique_ptr<::tokenizers::Tokenizer> tokenizer_; + std::unordered_map metadata_; + std::unordered_set eos_ids_; + std::unique_ptr shared_module_; + std::mutex exec_mutex_; + MuseGlimmerArtifactMode artifact_mode_ = + MuseGlimmerArtifactMode::Autoregressive; + int64_t max_prefill_chunk_ = 0; + int64_t min_prefill_chunk_ = 1; + int64_t dflash_block_size_ = 0; + int64_t dflash_mask_token_id_ = 0; + int64_t dflash_n_target_layers_ = 0; + int64_t dflash_sliding_window_ = 0; + int64_t dflash_min_target_prefill_chunk_ = 0; + int64_t dflash_max_target_prefill_chunk_ = 0; + std::string activation_dtype_; + ::executorch::extension::TensorPtr decode_pos_table_dev_; + std::unique_ptr vision_runtime_; + bool rebind_available_ = false; + std::unique_ptr mutable_state_; + std::atomic live_sessions_{0}; +}; + +} // namespace executorch::extension::llm diff --git a/examples/models/muse-glimmer/runtime/engine/muse_glimmer_vision_runtime.cpp b/examples/models/muse-glimmer/runtime/engine/muse_glimmer_vision_runtime.cpp new file mode 100644 index 00000000000..8c187c138ae --- /dev/null +++ b/examples/models/muse-glimmer/runtime/engine/muse_glimmer_vision_runtime.cpp @@ -0,0 +1,459 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#ifdef EXECUTORCH_BUILD_CUDA +#include +#endif + +#define STBI_ONLY_JPEG +#define STBI_ONLY_PNG +#define STBI_NO_HDR +#define STBI_NO_LINEAR +#define STB_IMAGE_IMPLEMENTATION +#include + +#define STB_IMAGE_RESIZE_IMPLEMENTATION +#include + +namespace executorch::extension::llm { +namespace { + +using ::executorch::runtime::Error; +using ::executorch::runtime::EValue; +using ::executorch::runtime::Result; +using ::executorch::runtime::Span; +namespace muse_glimmer_vision = ::executorch::examples::muse_glimmer_vision; + +constexpr size_t kPngSignatureSize = 8; +constexpr uint8_t kPngSignature[kPngSignatureSize] = + {0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a}; + +bool has_jpeg_signature(Span bytes) { + return bytes.size() >= 3 && bytes[0] == 0xff && bytes[1] == 0xd8 && + bytes[2] == 0xff; +} + +bool has_png_signature(Span bytes) { + return bytes.size() >= kPngSignatureSize && + std::equal( + kPngSignature, kPngSignature + kPngSignatureSize, bytes.data()); +} + +bool validate_image_dimensions( + int width, + int height, + const MuseGlimmerVisionRuntimeConfig& config) { + if (width <= 0 || height <= 0) { + ET_LOG(Error, "Muse Glimmer image dimensions must be positive"); + return false; + } + if (width > config.max_image_dimension || + height > config.max_image_dimension) { + ET_LOG( + Error, + "Muse Glimmer image dimensions %dx%d exceed the limit of %d", + width, + height, + config.max_image_dimension); + return false; + } + if (config.max_image_pixels <= 0 || + static_cast(width) > config.max_image_pixels / height) { + ET_LOG( + Error, + "Muse Glimmer image dimensions %dx%d exceed the pixel limit", + width, + height); + return false; + } + return true; +} + +Error copy_tensor_to_host( + const executorch::aten::Tensor& tensor, + void* destination, + size_t num_bytes) { +#ifdef EXECUTORCH_BUILD_CUDA + cudaPointerAttributes attributes{}; + const bool on_device = + cudaPointerGetAttributes(&attributes, tensor.const_data_ptr()) == + cudaSuccess && + attributes.type == cudaMemoryTypeDevice; + if (on_device) { + return cudaMemcpy( + destination, + tensor.const_data_ptr(), + num_bytes, + cudaMemcpyDeviceToHost) == cudaSuccess + ? Error::Ok + : Error::Internal; + } +#endif + std::memcpy(destination, tensor.const_data_ptr(), num_bytes); + return Error::Ok; +} + +int decode_base64_character(char character) { + if (character >= 'A' && character <= 'Z') { + return character - 'A'; + } + if (character >= 'a' && character <= 'z') { + return character - 'a' + 26; + } + if (character >= '0' && character <= '9') { + return character - '0' + 52; + } + if (character == '+') { + return 62; + } + if (character == '/') { + return 63; + } + return -1; +} + +Result> read_file_signature_with_limit( + const std::string& path, + size_t max_bytes) { + std::ifstream file(path, std::ios::binary | std::ios::ate); + if (!file.is_open()) { + ET_LOG(Error, "Cannot open Muse Glimmer image: %s", path.c_str()); + return Error::AccessFailed; + } + const std::streamoff file_size = file.tellg(); + if (file_size <= 0) { + ET_LOG( + Error, + "Muse Glimmer image file is empty or unreadable: %s", + path.c_str()); + return Error::InvalidExternalData; + } + if (static_cast(file_size) > max_bytes) { + ET_LOG( + Error, + "Muse Glimmer image file exceeds the encoded byte limit: %s", + path.c_str()); + return Error::InvalidArgument; + } + std::vector signature(kPngSignatureSize); + file.seekg(0, std::ios::beg); + file.read( + reinterpret_cast(signature.data()), + static_cast(signature.size())); + signature.resize(static_cast(file.gcount())); + return signature; +} + +} // namespace + +MuseGlimmerVisionRuntime::MuseGlimmerVisionRuntime( + MuseGlimmerVisionRuntimeConfig config) + : config_(std::move(config)) { + if (config_.module == nullptr || config_.execution_mutex == nullptr) { + throw std::invalid_argument( + "MuseGlimmerVisionRuntime requires a module and execution mutex"); + } + if (config_.pos_embed_path.empty()) { + throw std::invalid_argument( + "MuseGlimmerVisionRuntime requires an explicit pos_embed_path"); + } + if (config_.activation_dtype != executorch::aten::ScalarType::BFloat16 && + config_.activation_dtype != executorch::aten::ScalarType::Half) { + throw std::invalid_argument( + "MuseGlimmerVisionRuntime activation dtype must be bfloat16 or float16"); + } + if (config_.expected_hidden_dim <= 0 || config_.max_image_tokens <= 0 || + config_.max_encoded_bytes == 0 || config_.max_image_dimension <= 0 || + config_.max_image_pixels <= 0) { + throw std::invalid_argument( + "MuseGlimmerVisionRuntime limits must be positive"); + } + pos_embed_table_ = + muse_glimmer_vision::load_pos_embed_table(config_.pos_embed_path); +} + +Result +MuseGlimmerVisionRuntime::prepare_image_from_file( + const std::string& image_path) const { + auto signature = + read_file_signature_with_limit(image_path, config_.max_encoded_bytes); + if (!signature.ok()) { + return signature.error(); + } + const Span signature_span( + signature->data(), signature->size()); + if (!has_jpeg_signature(signature_span) && + !has_png_signature(signature_span)) { + ET_LOG(Error, "Muse Glimmer image must have a JPEG or PNG signature"); + return Error::InvalidExternalData; + } + + int width = 0; + int height = 0; + int channels = 0; + if (stbi_info(image_path.c_str(), &width, &height, &channels) == 0) { + ET_LOG( + Error, + "Muse Glimmer image metadata decode failed: %s", + stbi_failure_reason()); + return Error::InvalidExternalData; + } + if (!validate_image_dimensions(width, height, config_)) { + return Error::InvalidArgument; + } + + using StbiImage = std::unique_ptr; + StbiImage rgb( + stbi_load(image_path.c_str(), &width, &height, &channels, 3), + &stbi_image_free); + if (rgb == nullptr) { + ET_LOG( + Error, "Muse Glimmer image decode failed: %s", stbi_failure_reason()); + return Error::InvalidExternalData; + } + if (!validate_image_dimensions(width, height, config_)) { + return Error::InvalidExternalData; + } + return prepare_decoded_image(rgb.get(), width, height); +} + +Result +MuseGlimmerVisionRuntime::prepare_image_from_bytes( + Span encoded_image) const { + if (encoded_image.empty()) { + ET_LOG(Error, "Muse Glimmer encoded image is empty"); + return Error::InvalidArgument; + } + if (encoded_image.size() > config_.max_encoded_bytes || + encoded_image.size() > + static_cast(std::numeric_limits::max())) { + ET_LOG(Error, "Muse Glimmer encoded image exceeds the byte limit"); + return Error::InvalidArgument; + } + if (!has_jpeg_signature(encoded_image) && !has_png_signature(encoded_image)) { + ET_LOG(Error, "Muse Glimmer image must have a JPEG or PNG signature"); + return Error::InvalidExternalData; + } + + int width = 0; + int height = 0; + int channels = 0; + const int encoded_size = static_cast(encoded_image.size()); + if (stbi_info_from_memory( + encoded_image.data(), encoded_size, &width, &height, &channels) == + 0) { + ET_LOG( + Error, + "Muse Glimmer image metadata decode failed: %s", + stbi_failure_reason()); + return Error::InvalidExternalData; + } + if (!validate_image_dimensions(width, height, config_)) { + return Error::InvalidArgument; + } + + using StbiImage = std::unique_ptr; + StbiImage rgb( + stbi_load_from_memory( + encoded_image.data(), encoded_size, &width, &height, &channels, 3), + &stbi_image_free); + if (rgb == nullptr) { + ET_LOG( + Error, "Muse Glimmer image decode failed: %s", stbi_failure_reason()); + return Error::InvalidExternalData; + } + if (!validate_image_dimensions(width, height, config_)) { + return Error::InvalidExternalData; + } + return prepare_decoded_image(rgb.get(), width, height); +} + +Result +MuseGlimmerVisionRuntime::prepare_decoded_image( + const uint8_t* rgb, + int32_t width, + int32_t height) const { + muse_glimmer_vision::VisionInputs inputs; + try { + inputs = muse_glimmer_vision::preprocess_image( + rgb, width, height, pos_embed_table_, config_.max_image_tokens); + } catch (const std::exception& exception) { + ET_LOG( + Error, + "Muse Glimmer vision preprocessing failed: %s", + exception.what()); + return Error::InvalidExternalData; + } + + std::vector encoder_inputs; + encoder_inputs.reserve(9); +#ifdef EXECUTORCH_BUILD_CUDA + std::vector<::executorch::extension::TensorPtr> device_inputs; + device_inputs.reserve(9); + const executorch::aten::Device cuda_device( + executorch::aten::DeviceType::CUDA, 0); + const auto stage_input = [&](const auto& input) { + device_inputs.push_back( + ::executorch::extension::clone_tensor_ptr_to(input, cuda_device)); + encoder_inputs.emplace_back(device_inputs.back()); + }; + stage_input(inputs.patches); + stage_input(inputs.pos_emb); + stage_input(inputs.cos_2d); + stage_input(inputs.sin_2d); + stage_input(inputs.sparse_perm); + stage_input(inputs.inv_perm); + stage_input(inputs.global_mask); + stage_input(inputs.sparse_mask); + stage_input(inputs.pixel_perm); +#else + encoder_inputs.emplace_back(inputs.patches); + encoder_inputs.emplace_back(inputs.pos_emb); + encoder_inputs.emplace_back(inputs.cos_2d); + encoder_inputs.emplace_back(inputs.sin_2d); + encoder_inputs.emplace_back(inputs.sparse_perm); + encoder_inputs.emplace_back(inputs.inv_perm); + encoder_inputs.emplace_back(inputs.global_mask); + encoder_inputs.emplace_back(inputs.sparse_mask); + encoder_inputs.emplace_back(inputs.pixel_perm); +#endif + + std::lock_guard guard(*config_.execution_mutex); + const auto encoder_start = std::chrono::steady_clock::now(); + auto outputs = config_.module->execute("vision_encoder", encoder_inputs); + if (!outputs.ok()) { + ET_LOG(Error, "Muse Glimmer vision_encoder execution failed"); + return outputs.error(); + } + const double vision_encoder_ms = + std::chrono::duration( + std::chrono::steady_clock::now() - encoder_start) + .count(); + if (outputs->size() != 1 || !(*outputs)[0].isTensor()) { + ET_LOG(Error, "Muse Glimmer vision_encoder must return exactly one tensor"); + return Error::InvalidProgram; + } + + const auto& embeddings = (*outputs)[0].toTensor(); + if (embeddings.dim() != 3 || embeddings.size(0) != 1 || + embeddings.size(1) != inputs.num_soft_tokens || + embeddings.size(2) != config_.expected_hidden_dim) { + ET_LOG( + Error, + "Muse Glimmer vision_encoder output must be [1, %lld, %lld]", + static_cast(inputs.num_soft_tokens), + static_cast(config_.expected_hidden_dim)); + return Error::InvalidProgram; + } + if (embeddings.scalar_type() != config_.activation_dtype || + (embeddings.scalar_type() != executorch::aten::ScalarType::BFloat16 && + embeddings.scalar_type() != executorch::aten::ScalarType::Half)) { + ET_LOG( + Error, + "Muse Glimmer vision_encoder returned an unexpected activation dtype"); + return Error::InvalidProgram; + } + + const int64_t num_values = + inputs.num_soft_tokens * config_.expected_hidden_dim; + if (num_values <= 0 || + static_cast(num_values) > + std::numeric_limits::max() / sizeof(uint16_t)) { + ET_LOG(Error, "Muse Glimmer vision_encoder output size is invalid"); + return Error::InvalidProgram; + } + PreparedMuseGlimmerImage prepared; + prepared.num_soft_tokens = inputs.num_soft_tokens; + prepared.hidden_dim = config_.expected_hidden_dim; + prepared.vision_encoder_ms = vision_encoder_ms; + prepared.embeddings.resize(static_cast(num_values)); + ET_CHECK_OK_OR_RETURN_ERROR(copy_tensor_to_host( + embeddings, + prepared.embeddings.data(), + prepared.embeddings.size() * sizeof(uint16_t))); + return prepared; +} + +Result> decode_muse_glimmer_base64_strict( + std::string_view encoded, + size_t max_decoded_bytes) { + if (encoded.empty()) { + return std::vector{}; + } + if (encoded.size() % 4 != 0) { + ET_LOG(Error, "Muse Glimmer base64 length must be a multiple of four"); + return Error::InvalidArgument; + } + + size_t padding = 0; + if (encoded.back() == '=') { + padding = 1; + if (encoded.size() >= 2 && encoded[encoded.size() - 2] == '=') { + padding = 2; + } + } + const size_t quartet_count = encoded.size() / 4; + if (quartet_count > (std::numeric_limits::max() - 2) / 3) { + return Error::OutOfResources; + } + const size_t decoded_size = quartet_count * 3 - padding; + if (decoded_size > max_decoded_bytes) { + ET_LOG(Error, "Muse Glimmer base64 payload exceeds the decoded byte limit"); + return Error::InvalidArgument; + } + + std::vector decoded; + decoded.reserve(decoded_size); + for (size_t offset = 0; offset < encoded.size(); offset += 4) { + const bool final_quartet = offset + 4 == encoded.size(); + const char c0 = encoded[offset]; + const char c1 = encoded[offset + 1]; + const char c2 = encoded[offset + 2]; + const char c3 = encoded[offset + 3]; + const int v0 = decode_base64_character(c0); + const int v1 = decode_base64_character(c1); + const int v2 = c2 == '=' ? 0 : decode_base64_character(c2); + const int v3 = c3 == '=' ? 0 : decode_base64_character(c3); + if (v0 < 0 || v1 < 0 || v2 < 0 || v3 < 0 || + (!final_quartet && (c2 == '=' || c3 == '=')) || + (c2 == '=' && c3 != '=') || (c2 == '=' && (v1 & 0x0f) != 0) || + (c3 == '=' && c2 != '=' && (v2 & 0x03) != 0)) { + ET_LOG( + Error, "Muse Glimmer base64 payload has invalid alphabet or padding"); + return Error::InvalidArgument; + } + decoded.push_back(static_cast((v0 << 2) | (v1 >> 4))); + if (c2 != '=') { + decoded.push_back(static_cast((v1 << 4) | (v2 >> 2))); + } + if (c3 != '=') { + decoded.push_back(static_cast((v2 << 6) | v3)); + } + } + if (decoded.size() != decoded_size) { + return Error::Internal; + } + return decoded; +} + +} // namespace executorch::extension::llm diff --git a/examples/models/muse-glimmer/runtime/engine/muse_glimmer_vision_runtime.h b/examples/models/muse-glimmer/runtime/engine/muse_glimmer_vision_runtime.h new file mode 100644 index 00000000000..a4074b1cd13 --- /dev/null +++ b/examples/models/muse-glimmer/runtime/engine/muse_glimmer_vision_runtime.h @@ -0,0 +1,74 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace executorch::extension::llm { + +struct PreparedMuseGlimmerImage { + std::vector embeddings; + int64_t num_soft_tokens = 0; + int64_t hidden_dim = 0; + double vision_encoder_ms = 0.0; +}; + +struct MuseGlimmerVisionRuntimeConfig { + Module* module = nullptr; + std::mutex* execution_mutex = nullptr; + std::string pos_embed_path; + executorch::aten::ScalarType activation_dtype = + executorch::aten::ScalarType::BFloat16; + int64_t expected_hidden_dim = 0; + int64_t max_image_tokens = 4096; + size_t max_encoded_bytes = 32 * 1024 * 1024; + int32_t max_image_dimension = 32768; + int64_t max_image_pixels = 64 * 1024 * 1024; +}; + +class MuseGlimmerVisionRuntime final { + public: + explicit MuseGlimmerVisionRuntime(MuseGlimmerVisionRuntimeConfig config); + + ::executorch::runtime::Result + prepare_image_from_file(const std::string& image_path) const; + + ::executorch::runtime::Result + prepare_image_from_bytes( + ::executorch::runtime::Span encoded_image) const; + + ::executorch::runtime::Result + prepare_image_from_bytes(const std::vector& encoded_image) const { + return prepare_image_from_bytes(::executorch::runtime::Span( + encoded_image.data(), encoded_image.size())); + } + + private: + ::executorch::runtime::Result prepare_decoded_image( + const uint8_t* rgb, + int32_t width, + int32_t height) const; + + MuseGlimmerVisionRuntimeConfig config_; + std::vector pos_embed_table_; +}; + +::executorch::runtime::Result> +decode_muse_glimmer_base64_strict( + std::string_view encoded, + size_t max_decoded_bytes); + +} // namespace executorch::extension::llm diff --git a/examples/models/muse-glimmer/runtime/engine/sampling.h b/examples/models/muse-glimmer/runtime/engine/sampling.h new file mode 100644 index 00000000000..4afa43b6447 --- /dev/null +++ b/examples/models/muse-glimmer/runtime/engine/sampling.h @@ -0,0 +1,524 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +// Shared sampling utilities for speculative decoding runners (DFlash). + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__aarch64__) || defined(_M_ARM64) +#include +#endif + +#include + +namespace muse_glimmer { +namespace detail { + +inline uint64_t argmax_index(const float* values, int64_t size) { +#if defined(__aarch64__) || defined(_M_ARM64) + int64_t offset = 0; + float32x4_t best_values = + vdupq_n_f32(-std::numeric_limits::infinity()); + uint32x4_t best_indices = vdupq_n_u32(0); + uint32x4_t indices = {0, 1, 2, 3}; + const uint32x4_t stride = vdupq_n_u32(4); + for (; offset + 4 <= size; offset += 4) { + const float32x4_t current = vld1q_f32(values + offset); + const uint32x4_t better = vcgtq_f32(current, best_values); + best_values = vbslq_f32(better, current, best_values); + best_indices = vbslq_u32(better, indices, best_indices); + indices = vaddq_u32(indices, stride); + } + + float lane_values[4]; + uint32_t lane_indices[4]; + vst1q_f32(lane_values, best_values); + vst1q_u32(lane_indices, best_indices); + float best_value = lane_values[0]; + uint64_t best_index = lane_indices[0]; + for (int lane = 1; lane < 4; ++lane) { + if (lane_values[lane] > best_value || + (lane_values[lane] == best_value && lane_indices[lane] < best_index)) { + best_value = lane_values[lane]; + best_index = lane_indices[lane]; + } + } + for (; offset < size; ++offset) { + if (values[offset] > best_value) { + best_value = values[offset]; + best_index = offset; + } + } + return best_index; +#else + return static_cast( + std::distance(values, std::max_element(values, values + size))); +#endif +} + +inline float max_value(const float* values, int64_t size) { +#if defined(__aarch64__) || defined(_M_ARM64) + int64_t offset = 0; + float32x4_t maximum = vdupq_n_f32(-std::numeric_limits::infinity()); + for (; offset + 4 <= size; offset += 4) { + maximum = vmaxq_f32(maximum, vld1q_f32(values + offset)); + } + float result = vmaxvq_f32(maximum); + for (; offset < size; ++offset) { + result = std::max(result, values[offset]); + } + return result; +#else + return *std::max_element(values, values + size); +#endif +} + +inline void +normalize_probabilities(float* probabilities, int64_t size, float sum) { +#if defined(__aarch64__) || defined(_M_ARM64) + int64_t offset = 0; + const float32x4_t denominator = vdupq_n_f32(sum); + for (; offset + 4 <= size; offset += 4) { + vst1q_f32( + probabilities + offset, + vdivq_f32(vld1q_f32(probabilities + offset), denominator)); + } + for (; offset < size; ++offset) { + probabilities[offset] /= sum; + } +#else + for (int64_t offset = 0; offset < size; ++offset) { + probabilities[offset] /= sum; + } +#endif +} + +} // namespace detail + +inline uint64_t argmax_index(const float* values, int64_t size) { + return detail::argmax_index(values, size); +} + +inline float max_value(const float* values, int64_t size) { + return detail::max_value(values, size); +} + +inline void +normalize_probabilities(float* probabilities, int64_t size, float sum) { + detail::normalize_probabilities(probabilities, size, sum); +} + +inline uint64_t +categorical_sample(std::mt19937& rng, const float* probs, int64_t n) { + std::uniform_real_distribution dist(0.0f, 1.0f); + float r = dist(rng); + float cumsum = 0.0f; + for (int64_t i = 0; i < n; i++) { + cumsum += probs[i]; + if (cumsum >= r) { + return static_cast(i); + } + } + return static_cast(n - 1); +} + +struct SamplingWorkspace { + std::vector probabilities; + std::vector candidates; + std::vector radix_keys; + std::vector radix_scratch; + std::array radix_counts{}; +}; + +namespace detail { + +inline uint32_t float_to_descending_radix_key(float value) { + static_assert(sizeof(float) == sizeof(uint32_t)); + uint32_t bits; + std::memcpy(&bits, &value, sizeof(bits)); + if ((bits & 0x7fffffffu) == 0) { + bits = 0; + } + const uint32_t ascending_key = + bits ^ ((bits & 0x80000000u) != 0 ? 0xffffffffu : 0x80000000u); + return ~ascending_key; +} + +inline void stable_radix_sort_indices( + const float* logits, + int64_t vocab_size, + SamplingWorkspace& workspace) { + auto& candidates = workspace.candidates; + auto& keys = workspace.radix_keys; + auto& scratch = workspace.radix_scratch; + auto& counts = workspace.radix_counts; + + candidates.resize(vocab_size); + std::iota(candidates.begin(), candidates.end(), int32_t{0}); + keys.resize(vocab_size); + scratch.resize(vocab_size); + for (int64_t token = 0; token < vocab_size; ++token) { + keys[token] = float_to_descending_radix_key(logits[token]); + } + + auto* source = &candidates; + auto* destination = &scratch; + for (uint32_t shift = 0; shift < 32; shift += 8) { + counts.fill(0); + for (const int32_t token : *source) { + ++counts[(keys[token] >> shift) & 0xffu]; + } + + int64_t offset = 0; + for (int64_t& count : counts) { + const int64_t bucket_size = count; + count = offset; + offset += bucket_size; + } + for (const int32_t token : *source) { + const uint32_t bucket = (keys[token] >> shift) & 0xffu; + (*destination)[counts[bucket]++] = token; + } + std::swap(source, destination); + } + ET_CHECK(source == &candidates); +} + +inline double fill_dense_weights( + const float* logits, + int64_t vocab_size, + double temperature, + std::vector& probabilities) { + probabilities.resize(vocab_size); + const float maximum = max_value(logits, vocab_size); + double sum = 0.0; + for (int64_t token = 0; token < vocab_size; ++token) { + probabilities[token] = + std::exp((logits[token] - maximum) / static_cast(temperature)); + sum += probabilities[token]; + } + return sum; +} + +inline double fill_top_k_weights( + const float* logits, + int64_t vocab_size, + double temperature, + int32_t top_k, + SamplingWorkspace& workspace) { + auto& probabilities = workspace.probabilities; + auto& candidates = workspace.candidates; + probabilities.assign(vocab_size, 0.0f); + candidates.resize(vocab_size); + std::iota(candidates.begin(), candidates.end(), int32_t{0}); + const auto higher_logit = [logits](int32_t lhs, int32_t rhs) { + if (logits[lhs] != logits[rhs]) { + return logits[lhs] > logits[rhs]; + } + return lhs < rhs; + }; + std::nth_element( + candidates.begin(), + candidates.begin() + top_k, + candidates.end(), + higher_logit); + candidates.resize(top_k); + + const auto max_it = std::max_element( + candidates.begin(), candidates.end(), [logits](int32_t lhs, int32_t rhs) { + return logits[lhs] < logits[rhs]; + }); + const float maximum = logits[*max_it]; + double sum = 0.0; + for (const int32_t token : candidates) { + probabilities[token] = + std::exp((logits[token] - maximum) / static_cast(temperature)); + sum += probabilities[token]; + } + return sum; +} + +inline void normalize_candidates( + std::vector& probabilities, + const std::vector& candidates, + size_t selected_begin, + size_t selected_end, + double sum) { + for (size_t index = selected_begin; index < selected_end; ++index) { + probabilities[candidates[index]] /= static_cast(sum); + } +} + +inline void apply_top_p_radix( + const float* logits, + int64_t vocab_size, + double top_p, + double sum, + SamplingWorkspace& workspace) { + stable_radix_sort_indices(logits, vocab_size, workspace); + auto& probabilities = workspace.probabilities; + const auto& candidates = workspace.candidates; + const double nucleus_target = top_p * sum; + double nucleus_sum = 0.0; + size_t selected_count = 0; + while (selected_count < candidates.size() && nucleus_sum < nucleus_target) { + nucleus_sum += probabilities[candidates[selected_count]]; + ++selected_count; + } + for (size_t index = selected_count; index < candidates.size(); ++index) { + probabilities[candidates[index]] = 0.0f; + } + normalize_candidates( + probabilities, candidates, 0, selected_count, nucleus_sum); +} + +inline void apply_top_p_heap( + const float* logits, + double top_p, + double sum, + SamplingWorkspace& workspace) { + auto& probabilities = workspace.probabilities; + auto& candidates = workspace.candidates; + const auto lower_logit = [logits](int32_t lhs, int32_t rhs) { + if (logits[lhs] != logits[rhs]) { + return logits[lhs] < logits[rhs]; + } + return lhs > rhs; + }; + std::make_heap(candidates.begin(), candidates.end(), lower_logit); + auto heap_end = candidates.end(); + const double nucleus_target = top_p * sum; + double nucleus_sum = 0.0; + while (heap_end != candidates.begin() && nucleus_sum < nucleus_target) { + std::pop_heap(candidates.begin(), heap_end, lower_logit); + --heap_end; + nucleus_sum += probabilities[*heap_end]; + } + for (auto it = candidates.begin(); it != heap_end; ++it) { + probabilities[*it] = 0.0f; + } + normalize_candidates( + probabilities, + candidates, + static_cast(std::distance(candidates.begin(), heap_end)), + candidates.size(), + nucleus_sum); +} + +inline void fill_sampling_probabilities( + const float* logits, + int64_t vocab_size, + double temperature, + int32_t top_k, + double top_p, + SamplingWorkspace& workspace) { + const bool use_top_k = top_k > 0 && top_k < vocab_size; + const bool use_top_p = top_p > 0.0 && top_p < 1.0; + auto& probabilities = workspace.probabilities; + + if (!use_top_k) { + const double sum = + fill_dense_weights(logits, vocab_size, temperature, probabilities); + if (use_top_p) { + ET_CHECK_MSG( + vocab_size <= std::numeric_limits::max(), + "Sampling vocabulary exceeds 32-bit candidate index range"); + apply_top_p_radix(logits, vocab_size, top_p, sum, workspace); + } else { + normalize_probabilities( + probabilities.data(), vocab_size, static_cast(sum)); + } + return; + } + + const double sum = + fill_top_k_weights(logits, vocab_size, temperature, top_k, workspace); + if (use_top_p) { + apply_top_p_heap(logits, top_p, sum, workspace); + } else { + normalize_candidates( + probabilities, + workspace.candidates, + 0, + workspace.candidates.size(), + sum); + } +} + +} // namespace detail + +inline void fill_sampling_probabilities( + const float* logits, + int64_t vocab_size, + double temperature, + int32_t top_k, + double top_p, + SamplingWorkspace& workspace) { + detail::fill_sampling_probabilities( + logits, vocab_size, temperature, top_k, top_p, workspace); +} + +inline void fill_sampling_probabilities( + const float* logits, + int64_t vocab_size, + double temperature, + int32_t top_k, + double top_p, + std::vector& probabilities, + SamplingWorkspace& workspace) { + if (&probabilities == &workspace.probabilities) { + fill_sampling_probabilities( + logits, vocab_size, temperature, top_k, top_p, workspace); + return; + } + + probabilities.swap(workspace.probabilities); + fill_sampling_probabilities( + logits, vocab_size, temperature, top_k, top_p, workspace); + probabilities.swap(workspace.probabilities); +} + +inline void fill_sampling_probabilities( + const float* logits, + int64_t vocab_size, + double temperature, + int32_t top_k, + double top_p, + std::vector& probabilities, + std::vector& candidates) { + SamplingWorkspace workspace; + probabilities.swap(workspace.probabilities); + candidates.swap(workspace.candidates); + fill_sampling_probabilities( + logits, vocab_size, temperature, top_k, top_p, workspace); + probabilities.swap(workspace.probabilities); + candidates.swap(workspace.candidates); +} + +inline std::vector sampling_probabilities( + const float* logits, + int64_t vocab_size, + double temperature, + int32_t top_k, + double top_p) { + SamplingWorkspace workspace; + fill_sampling_probabilities( + logits, + vocab_size, + temperature, + top_k, + top_p, + workspace.probabilities, + workspace); + return std::move(workspace.probabilities); +} + +inline uint64_t sample_token( + std::mt19937& rng, + const executorch::aten::Tensor& logits, + int64_t seq_pos, + double temperature, + int32_t top_k = 0, + double top_p = 1.0, + std::vector* out_probs = nullptr, + bool probs_only = false, + SamplingWorkspace* workspace = nullptr) { + int64_t vocab_size = logits.size(logits.dim() - 1); + const float* src = + static_cast(logits.const_data_ptr()) + seq_pos * vocab_size; + + if (temperature <= 0.0) { + return argmax_index(src, vocab_size); + } + + SamplingWorkspace local_workspace; + SamplingWorkspace& scratch = + workspace == nullptr ? local_workspace : *workspace; + std::vector& probs = + out_probs == nullptr ? scratch.probabilities : *out_probs; + fill_sampling_probabilities( + src, vocab_size, temperature, top_k, top_p, probs, scratch); + if (out_probs && probs_only) { + return 0; + } + return categorical_sample(rng, probs.data(), vocab_size); +} + +inline bool accept_with_probability(std::mt19937& rng, float probability) { + std::uniform_real_distribution uniform(0.0f, 1.0f); + return uniform(rng) < probability; +} + +inline uint64_t sample_excluding_token_in_place( + std::mt19937& rng, + std::vector& probabilities, + uint64_t excluded_token) { + ET_CHECK(excluded_token < probabilities.size()); + probabilities[excluded_token] = 0.0f; + double sum = 0.0; + for (const float probability : probabilities) { + sum += probability; + } + ET_CHECK_MSG(sum > 0.0, "Cannot sample after excluding all probability mass"); + normalize_probabilities( + probabilities.data(), probabilities.size(), static_cast(sum)); + + std::uniform_real_distribution uniform(0.0f, 1.0f); + const float sample = uniform(rng); + float cumulative = 0.0f; + uint64_t last_supported_token = 0; + for (uint64_t token = 0; token < probabilities.size(); ++token) { + const float probability = probabilities[token]; + if (probability == 0.0f) { + continue; + } + last_supported_token = token; + cumulative += probability; + if (sample < cumulative) { + return token; + } + } + return last_supported_token; +} + +inline uint64_t sample_from_residual_in_place( + std::mt19937& rng, + std::vector& p, + const std::vector& q) { + int64_t n = static_cast(p.size()); + double sum = 0.0; + for (int64_t i = 0; i < n; i++) { + sum += std::max(0.0f, p[i] - q[i]); + } + if (sum <= 0.0) { + return categorical_sample(rng, p.data(), n); + } + for (int64_t i = 0; i < n; i++) { + p[i] = std::max(0.0f, p[i] - q[i]) / static_cast(sum); + } + return categorical_sample(rng, p.data(), n); +} + +inline uint64_t sample_from_residual( + std::mt19937& rng, + const std::vector& p, + const std::vector& q) { + std::vector residual = p; + return sample_from_residual_in_place(rng, residual, q); +} + +} // namespace muse_glimmer diff --git a/examples/models/muse-glimmer/runtime/runners/dflash.cpp b/examples/models/muse-glimmer/runtime/runners/dflash.cpp new file mode 100644 index 00000000000..70c0aa45531 --- /dev/null +++ b/examples/models/muse-glimmer/runtime/runners/dflash.cpp @@ -0,0 +1,496 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +// Standalone DFlash CLI backed by the same MuseGlimmerEngine / LLMSession +// implementation used by muse_glimmer_worker. + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +DEFINE_string(model_path, "", "DFlash model .pte file path."); +DEFINE_string(data_path, "", "Data file (.ptd), if the export produced one."); +DEFINE_string(tokenizer_path, "", "Hugging Face tokenizer.json path."); +DEFINE_string( + image_path, + "", + "Optional local JPEG/PNG image path; the prompt must contain one " + "marker at which to splice its soft tokens."); +DEFINE_string( + pos_embed_path, + "", + "Optional pos_embed.bin path; defaults beside model.pte."); +DEFINE_string(prompt, "The meaning of life is", "Prompt text."); +DEFINE_string( + prompt_file, + "", + "Path to file containing prompt text (overrides --prompt)."); +#ifdef EXECUTORCH_BUILD_CUDA +DEFINE_string( + prompt_tokens_file, + "", + "Little-endian int64 prompt IDs; bypasses tokenizer encoding."); +DEFINE_bool( + tokens_have_bos, + false, + "The prompt token file already includes BOS."); +DEFINE_string( + generated_tokens_file, + "", + "Optional path for generated little-endian int64 token IDs."); +#endif +DEFINE_double(temperature, 0.0, "Sampling temperature (0 = greedy)."); +DEFINE_int32(top_k, 0, "Top-K sampling (0 = disabled)."); +DEFINE_double(top_p, 1.0, "Top-P (nucleus) sampling (1.0 = disabled)."); +DEFINE_int64( + seed, + -1, + "RNG seed (-1 = fresh random stream; otherwise positive)."); +DEFINE_bool( + draft_argmax, + true, + "Use exact deterministic argmax proposals for stochastic DFlash drafting."); +DEFINE_int32(max_new_tokens, 128, "Maximum visible tokens to generate."); +DEFINE_bool( + ignore_eos, + false, + "Ignore EOS and emit exactly max_new_tokens tokens for benchmarking."); +DEFINE_int32(bos_id, 200000, "BOS token id to prepend."); +DEFINE_int32(eos_id, 200001, "EOS token id."); +DEFINE_int32( + n_draft, + 3, + "Draft positions per call (0 = block_length - 1). On CUDA this must be at " + "most 3."); +DEFINE_int32( + block_length, + 4, + "Draft block length per call (0 = artifact maximum; otherwise must be in " + "[2, block_size])."); +#ifdef EXECUTORCH_BUILD_CUDA +DEFINE_bool( + cuda_graph, + true, + "Enable CUDA graph capture for DFlash target and draft methods."); +#else +DEFINE_bool(cuda_graph, false, "CUDA only."); +#endif + +extern "C" void et_pal_emit_log_message( + ET_UNUSED et_timestamp_t timestamp, + et_pal_log_level_t level, + const char* filename, + ET_UNUSED const char* function, + size_t line, + const char* message, + ET_UNUSED size_t length) { + if (level == 'D' || level == 'I') { + return; + } + fprintf(stderr, "%c [%s:%zu] %s\n", (char)level, filename, line, message); +} + +namespace { +namespace llm = ::executorch::extension::llm; +using ::executorch::runtime::Error; + +bool validate_flags() { + if (FLAGS_model_path.empty() || FLAGS_tokenizer_path.empty()) { + ET_LOG(Error, "--model_path and --tokenizer_path are required"); + return false; + } + if (FLAGS_max_new_tokens <= 0) { + ET_LOG(Error, "--max_new_tokens must be positive"); + return false; + } + if (!std::isfinite(FLAGS_temperature) || FLAGS_temperature < 0.0 || + FLAGS_temperature > 2.0) { + ET_LOG(Error, "--temperature must be finite and in [0, 2]"); + return false; + } + if (!std::isfinite(FLAGS_top_p) || FLAGS_top_p <= 0.0 || FLAGS_top_p > 1.0) { + ET_LOG(Error, "--top_p must be finite and in (0, 1]"); + return false; + } + if (FLAGS_top_k < 0) { + ET_LOG(Error, "--top_k must be nonnegative"); + return false; + } + if (FLAGS_seed != -1 && FLAGS_seed <= 0) { + ET_LOG(Error, "--seed must be -1 or positive"); + return false; + } + if (FLAGS_bos_id < 0 || FLAGS_eos_id < 0) { + ET_LOG(Error, "--bos_id and --eos_id must be nonnegative"); + return false; + } + if (FLAGS_block_length < 0 || FLAGS_n_draft < 0) { + ET_LOG(Error, "--block_length and --n_draft must be nonnegative"); + return false; + } + return true; +} + +bool read_prompt(std::string& prompt) { + prompt = FLAGS_prompt; + if (FLAGS_prompt_file.empty()) { + return true; + } + + std::ifstream input(FLAGS_prompt_file); + if (!input.is_open()) { + ET_LOG(Error, "Failed to open prompt file: %s", FLAGS_prompt_file.c_str()); + return false; + } + prompt.assign( + std::istreambuf_iterator(input), std::istreambuf_iterator()); + return true; +} + +#ifdef EXECUTORCH_BUILD_CUDA +bool read_prompt_tokens(std::vector& tokens) { + std::ifstream input( + FLAGS_prompt_tokens_file, std::ios::binary | std::ios::ate); + if (!input.is_open()) { + ET_LOG(Error, "Cannot open --prompt_tokens_file"); + return false; + } + const std::streamsize size = input.tellg(); + if (size <= 0 || size % sizeof(int64_t) != 0) { + ET_LOG(Error, "Prompt token file must contain little-endian int64 values"); + return false; + } + input.seekg(0, std::ios::beg); + std::vector values(size / sizeof(int64_t)); + if (!input.read(reinterpret_cast(values.data()), size)) { + ET_LOG(Error, "Failed to read --prompt_tokens_file"); + return false; + } + for (const int64_t value : values) { + if (value < 0) { + ET_LOG(Error, "Prompt token IDs must be nonnegative"); + return false; + } + tokens.push_back(static_cast(value)); + } + if (!FLAGS_tokens_have_bos) { + tokens.insert(tokens.begin(), static_cast(FLAGS_bos_id)); + } + return true; +} + +bool write_generated_tokens(const std::vector& tokens) { + if (FLAGS_generated_tokens_file.empty()) { + return true; + } + std::ofstream output(FLAGS_generated_tokens_file, std::ios::binary); + output.write( + reinterpret_cast(tokens.data()), + tokens.size() * sizeof(int64_t)); + if (!output) { + ET_LOG(Error, "Failed to write --generated_tokens_file"); + return false; + } + return true; +} +#endif + +void print_rate(const char* label, int64_t tokens, long start_ms, long end_ms) { + const double elapsed_ms = static_cast(end_ms - start_ms); + const double tokens_per_second = + elapsed_ms > 0.0 ? tokens * 1000.0 / elapsed_ms : 0.0; + printf( + "%s: %" PRId64 " tokens in %.1f ms (%.1f tok/s)\n", + label, + tokens, + elapsed_ms, + tokens_per_second); +} + +void print_int64_array(const std::vector& values) { + std::putchar('['); + for (size_t index = 0; index < values.size(); ++index) { + if (index > 0) { + std::putchar(','); + } + std::printf("%" PRId64, values[index]); + } + std::putchar(']'); +} + +void print_dflash_timing(const llm::DFlashDecodeTiming& timing) { + const double speculative_denominator = + timing.speculative_cycles > 0 ? timing.speculative_cycles : 1; + const double cycle_denominator = timing.cycles > 0 ? timing.cycles : 1; + const double accounted_ms = timing.draft_execute_ms + + timing.draft_logits_copy_ms + timing.draft_sampling_ms + + timing.target_execute_ms + timing.target_logits_copy_ms + + timing.target_hidden_copy_ms + timing.accept_correction_ms + + timing.state_commit_ms; + const double accounted_percent = timing.total_cycle_ms > 0.0 + ? accounted_ms * 100.0 / timing.total_cycle_ms + : 0.0; + printf( + "DFlashDecodeTiming {\"cycles\":%" PRId64 + ",\"speculative_cycles\":%" PRId64 ",\"target_only_cycles\":%" PRId64 + ",\"total_cycle_ms\":%.3f" + ",\"avg_cycle_ms\":%.3f" + ",\"draft_execute_ms\":%.3f" + ",\"avg_draft_execute_ms\":%.3f" + ",\"draft_logits_copy_ms\":%.3f" + ",\"avg_draft_logits_copy_ms\":%.3f" + ",\"draft_sampling_ms\":%.3f" + ",\"avg_draft_sampling_ms\":%.3f" + ",\"target_execute_ms\":%.3f" + ",\"avg_target_execute_ms\":%.3f" + ",\"target_logits_copy_ms\":%.3f" + ",\"avg_target_logits_copy_ms\":%.3f" + ",\"target_hidden_copy_ms\":%.3f" + ",\"avg_target_hidden_copy_ms\":%.3f" + ",\"accept_correction_ms\":%.3f" + ",\"avg_accept_correction_ms\":%.3f" + ",\"state_commit_ms\":%.3f" + ",\"avg_state_commit_ms\":%.3f" + ",\"accounted_percent\":%.1f", + timing.cycles, + timing.speculative_cycles, + timing.target_only_cycles, + timing.total_cycle_ms, + timing.total_cycle_ms / cycle_denominator, + timing.draft_execute_ms, + timing.draft_execute_ms / speculative_denominator, + timing.draft_logits_copy_ms, + timing.draft_logits_copy_ms / speculative_denominator, + timing.draft_sampling_ms, + timing.draft_sampling_ms / speculative_denominator, + timing.target_execute_ms, + timing.target_execute_ms / cycle_denominator, + timing.target_logits_copy_ms, + timing.target_logits_copy_ms / cycle_denominator, + timing.target_hidden_copy_ms, + timing.target_hidden_copy_ms / cycle_denominator, + timing.accept_correction_ms, + timing.accept_correction_ms / cycle_denominator, + timing.state_commit_ms, + timing.state_commit_ms / cycle_denominator, + accounted_percent); + std::printf(",\"draft_attempts_by_row\":"); + print_int64_array(timing.draft_attempts_by_row); + std::printf(",\"draft_accepts_by_row\":"); + print_int64_array(timing.draft_accepts_by_row); + std::printf("}\n"); +} + +} // namespace + +int main(int argc, char** argv) { + gflags::ParseCommandLineFlags(&argc, &argv, true); + if (!validate_flags()) { + return 1; + } +#ifndef EXECUTORCH_BUILD_CUDA + if (FLAGS_cuda_graph) { + ET_LOG(Info, "--cuda_graph ignored on non-CUDA build"); + } +#endif + + llm::Stats stats; + stats.model_load_start_ms = llm::time_in_ms(); + + llm::MuseGlimmerConfig config; + config.model_path = FLAGS_model_path; + config.data_path = FLAGS_data_path; + config.tokenizer_path = FLAGS_tokenizer_path; + config.pos_embed_path = FLAGS_pos_embed_path; + config.max_sessions = 1; + config.eos_id = FLAGS_eos_id; + config.enable_cuda_graph = FLAGS_cuda_graph; + config.artifact_mode = llm::MuseGlimmerArtifactMode::DFlash; + config.dflash_block_length = FLAGS_block_length; + config.dflash_n_draft = FLAGS_n_draft; + config.dflash_draft_argmax = FLAGS_draft_argmax; + config.dflash_ignore_eos = FLAGS_ignore_eos; + + llm::DFlashDecodeTiming dflash_timing; + config.dflash_timing = &dflash_timing; + + auto engine_result = llm::MuseGlimmerEngine::create(config); + if (engine_result.error() != Error::Ok) { + ET_LOG(Error, "Failed to create DFlash MuseGlimmerEngine"); + return 1; + } + auto engine = std::move(engine_result.get()); + stats.model_load_end_ms = llm::time_in_ms(); + + auto session_result = engine->create_session(); + if (session_result.error() != Error::Ok) { + ET_LOG(Error, "Failed to create DFlash LLMSession"); + return 1; + } + auto session = std::move(session_result.get()); + + const bool has_image = !FLAGS_image_path.empty(); + std::optional prepared_image; + llm::DFlashMultimodalSession* multimodal = nullptr; + int64_t image_tokens = 0; + if (has_image) { + auto prepared = engine->prepare_image_from_file(FLAGS_image_path); + if (prepared.error() != Error::Ok) { + ET_LOG(Error, "Failed to prepare image for DFlash prefill"); + return 1; + } + multimodal = llm::as_dflash_multimodal_session(session.get()); + if (multimodal == nullptr) { + ET_LOG(Error, "DFlash session does not support image input"); + return 1; + } + image_tokens = prepared->num_soft_tokens; + prepared_image.emplace(std::move(prepared.get())); + } + + std::vector prompt_tokens; +#ifdef EXECUTORCH_BUILD_CUDA + if (!FLAGS_prompt_tokens_file.empty()) { + if (!read_prompt_tokens(prompt_tokens)) { + return 1; + } + if (has_image) { + const auto image_patches = std::count( + prompt_tokens.begin(), + prompt_tokens.end(), + llm::kMuseGlimmerImagePatchTokenId); + if (image_patches != image_tokens) { + ET_LOG( + Error, + "Pre-tokenized image prompt has %td patch tokens; expected " + "%" PRId64 " at the image position", + image_patches, + image_tokens); + return 1; + } + } + stats.inference_start_ms = llm::time_in_ms(); + } else +#endif + { + std::string prompt_text; + if (!read_prompt(prompt_text)) { + return 1; + } + auto tokenized = llm::tokenize_muse_glimmer_prompt( + *engine->tokenizer(), + prompt_text, + static_cast(FLAGS_bos_id), + has_image ? std::optional(image_tokens) : std::nullopt); + if (!tokenized.ok()) { + ET_LOG( + Error, + "Failed to tokenize prompt; --image_path requires exactly one " + " marker"); + return 1; + } + prompt_tokens = std::move(*tokenized); + // Tokenization is excluded from the prefill timer, matching solo.cpp. + // Timing it here made the reported prefill rate depend on prompt text + // length, and made DFlash look slower than solo for the same work. + stats.inference_start_ms = llm::time_in_ms(); + } + if (has_image) { + multimodal->stage_image_for_next_prefill(std::move(*prepared_image)); + } + stats.token_encode_end_ms = llm::time_in_ms(); + stats.num_prompt_tokens = static_cast(prompt_tokens.size()); + + llm::SamplingConfig sampling; + sampling.temperature = static_cast(FLAGS_temperature); + sampling.top_p = static_cast(FLAGS_top_p); + sampling.top_k = FLAGS_top_k; + sampling.seed = FLAGS_seed < 0 ? 0 : static_cast(FLAGS_seed); + + if (session->prefill_tokens(prompt_tokens, &sampling) != Error::Ok) { + if (auto* multimodal = llm::as_dflash_multimodal_session(session.get())) { + multimodal->clear_staged_image(); + } + ET_LOG(Error, "DFlash prefill failed"); + return 1; + } + stats.prompt_eval_end_ms = llm::time_in_ms(); + print_rate( + "Prefill", + stats.num_prompt_tokens, + stats.inference_start_ms, + stats.prompt_eval_end_ms); + + std::vector generated_tokens; + generated_tokens.reserve(FLAGS_max_new_tokens); + for (int32_t step = 0; step < FLAGS_max_new_tokens; ++step) { + auto decode_result = session->decode_one(sampling); + if (decode_result.error() != Error::Ok) { + ET_LOG(Error, "DFlash decode failed at step %d", step); + return 1; + } + const auto& decoded = decode_result.get(); + if (decoded.is_terminal) { + break; + } + if (generated_tokens.empty()) { + stats.first_token_ms = llm::time_in_ms(); + } + if (!decoded.text_piece.empty()) { + fwrite(decoded.text_piece.data(), 1, decoded.text_piece.size(), stdout); + fflush(stdout); + } + generated_tokens.push_back(static_cast(decoded.token_id)); + } + + stats.inference_end_ms = llm::time_in_ms(); + if (FLAGS_ignore_eos && + generated_tokens.size() != static_cast(FLAGS_max_new_tokens)) { + ET_LOG( + Error, + "Exact-output mode emitted %zu tokens, expected %d", + generated_tokens.size(), + FLAGS_max_new_tokens); + return 1; + } +#ifdef EXECUTORCH_BUILD_CUDA + if (!write_generated_tokens(generated_tokens)) { + return 1; + } +#endif + + stats.num_generated_tokens = static_cast(generated_tokens.size()); + printf("\n"); + print_rate( + "Decode", + static_cast(generated_tokens.size()), + stats.prompt_eval_end_ms, + stats.inference_end_ms); + printf("Prompt tokens: %" PRId64 "\n", stats.num_prompt_tokens); + llm::print_report(stats); + print_dflash_timing(dflash_timing); + return 0; +} diff --git a/examples/models/muse-glimmer/runtime/runners/muse_glimmer_worker.cpp b/examples/models/muse-glimmer/runtime/runners/muse_glimmer_worker.cpp new file mode 100644 index 00000000000..188cad33506 --- /dev/null +++ b/examples/models/muse-glimmer/runtime/runners/muse_glimmer_worker.cpp @@ -0,0 +1,312 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +// Muse Glimmer worker for the shared LLM server. Image requests add one +// attachment segment before normal generation. + +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +DEFINE_string(model_path, "", "Model .pte file path."); +DEFINE_string(tokenizer_path, "", "Hugging Face tokenizer.json path."); +DEFINE_string(data_path, "", "Data file (.ptd) for delegated weights."); +DEFINE_string( + pos_embed_path, + "", + "Optional pos_embed.bin path; defaults beside model.pte."); +DEFINE_int64( + max_image_bytes, + 20 * 1024 * 1024, + "Maximum decoded JPEG/PNG byte count accepted from the control plane."); +DEFINE_int32( + max_sessions, + 1, + "Max physical sessions to host on one weight allocation. Clamped to 1 if " + "the backend cannot isolate per-session mutable state."); +DEFINE_bool( + warm_resume, + true, + "Warm append-only resume for named sessions when the engine supports them."); +DEFINE_int32( + bos_id, + 200000, + "BOS token id to prepend to server-rendered prompts."); +DEFINE_int32(eos_id, 200001, "EOS token id (MuseGlimmer convention: 200001)."); +DEFINE_string( + artifact_mode, + "auto", + "Artifact execution mode: auto, autoregressive, or dflash."); +DEFINE_int32( + dflash_block_length, + 4, + "DFlash block length. Zero uses the artifact's exported maximum."); +DEFINE_int32( + dflash_n_draft, + 3, + "DFlash candidates per iteration. Zero uses block_length - 1. On CUDA this " + "must be at most 3."); +DEFINE_bool( + dflash_draft_argmax, + true, + "Use exact deterministic argmax proposals for stochastic DFlash drafting."); +DEFINE_bool( + cuda_graph, + false, + "Capture CUDA graphs for supported methods. Disables CUDA multi-session " + "state rebinding."); + +namespace { +namespace llm = ::executorch::extension::llm; +using ::executorch::runtime::Error; +using Json = nlohmann::json; + +llm::MuseGlimmerArtifactMode parse_artifact_mode(const std::string& value) { + if (value == "auto") { + return llm::MuseGlimmerArtifactMode::Auto; + } + if (value == "autoregressive") { + return llm::MuseGlimmerArtifactMode::Autoregressive; + } + if (value == "dflash") { + return llm::MuseGlimmerArtifactMode::DFlash; + } + ET_LOG( + Error, + "muse_glimmer_worker: invalid --artifact_mode=%s; expected auto, " + "autoregressive, or dflash", + value.c_str()); + return llm::MuseGlimmerArtifactMode::Auto; +} + +struct ImageAttachment { + std::string base64_data; + size_t segment_index; +}; + +std::optional extract_image_attachment(Json& request) { + if (!request.contains("prompt_segments")) { + return std::nullopt; + } + std::optional attachment; + size_t segment_index = 0; + for (const auto& segment : request.at("prompt_segments")) { + if (!segment.contains("image")) { + ++segment_index; + continue; + } + if (attachment.has_value() || segment.size() != 1 || + !segment.at("image").is_object()) { + throw std::runtime_error("exactly one valid image segment is supported"); + } + const auto& image = segment.at("image"); + if (image.value("encoding", std::string{}) != "base64") { + throw std::runtime_error("image segment encoding must be base64"); + } + const std::string mime_type = image.value("mime_type", std::string{}); + if (mime_type != "image/jpeg" && mime_type != "image/png") { + throw std::runtime_error("image segment must be JPEG or PNG"); + } + attachment = + ImageAttachment{image.at("data").get(), segment_index}; + ++segment_index; + } + return attachment; +} + +void replace_image_segment_with_ids( + Json& request, + const ImageAttachment& attachment, + int64_t num_soft_tokens) { + const std::vector image_ids( + static_cast(num_soft_tokens), llm::kMuseGlimmerImagePatchTokenId); + request["prompt_segments"][attachment.segment_index] = {{"ids", image_ids}}; +} + +void handle_session_operation( + llm::WorkerSessions& sessions, + const Json& request) { + const std::string op = request.value("op", std::string{}); + const std::string id = request.at("session_id").get(); + if (id.empty()) { + throw std::runtime_error("session_id required for op"); + } + if (op == "close") { + sessions.close_named(id); + llm::worker_emit({{"closed", true}, {"session_id", id}}); + return; + } + if (op == "reset") { + if (sessions.reset_named(id) != Error::Ok) { + llm::worker_emit({{"error", "session reset failed"}, {"session_id", id}}); + } else { + llm::worker_emit({{"reset", true}, {"session_id", id}}); + } + return; + } + std::string code; + if (sessions.open_named(id, code) == nullptr) { + llm::worker_emit( + {{"error", "cannot open session"}, {"code", code}, {"session_id", id}}); + } else { + llm::worker_emit({{"opened", true}, {"session_id", id}}); + } +} + +int run_muse_glimmer_worker_loop(llm::MuseGlimmerEngine& engine) { + llm::WorkerSessions sessions(engine); + llm::worker_emit( + {{"ready", true}, + {"max_sessions", + engine.serving_capacity() + .max_physical_sessions_without_weight_duplication}, + {"max_named_sessions", sessions.max_named()}, + {"supports_image", engine.has_vision()}}); + + std::string line; + while (std::getline(std::cin, line)) { + if (line.empty()) { + continue; + } + try { + Json request = Json::parse(line); + const std::string op = request.value("op", std::string{}); + if (op == "open" || op == "close" || op == "reset") { + handle_session_operation(sessions, request); + continue; + } + + const std::string id = request.value("session_id", std::string{}); + llm::WorkerSessionState* state = nullptr; + bool warm = false; + if (id.empty()) { + state = sessions.scratch(); + } else { + std::string code; + state = sessions.open_named(id, code); + if (state == nullptr) { + llm::worker_emit( + {{"error", "cannot open session"}, + {"code", code}, + {"session_id", id}}); + continue; + } + warm = FLAGS_warm_resume; + } + + std::vector prefix = {static_cast(FLAGS_bos_id)}; + Json additional_terminal_stats = Json::object(); + auto attachment = extract_image_attachment(request); + llm::MuseGlimmerMultimodalSession* multimodal = nullptr; + if (attachment.has_value()) { + if (!engine.has_vision()) { + throw std::runtime_error( + "Muse Glimmer artifact does not support image input"); + } + multimodal = + llm::as_muse_glimmer_multimodal_session(state->session.get()); + if (multimodal == nullptr) { + throw std::runtime_error( + "image input requires a Muse Glimmer session"); + } + auto decoded = llm::decode_muse_glimmer_base64_strict( + attachment->base64_data, + static_cast(FLAGS_max_image_bytes)); + if (decoded.error() != Error::Ok) { + throw std::runtime_error("invalid base64 image payload"); + } + auto prepared = engine.prepare_image_from_bytes(decoded.get()); + if (prepared.error() != Error::Ok) { + throw std::runtime_error("image decode or vision encoding failed"); + } + replace_image_segment_with_ids( + request, *attachment, prepared->num_soft_tokens); + additional_terminal_stats["vision_encoder_ms"] = + prepared->vision_encoder_ms; + multimodal->stage_image_for_next_prefill(std::move(prepared.get())); + warm = false; + } + + try { + llm::worker_handle_request( + *state, + warm, + *engine.tokenizer(), + engine.metadata(), + request, + prefix, + additional_terminal_stats); + } catch (...) { + if (multimodal != nullptr) { + multimodal->clear_staged_image(); + } + throw; + } + if (multimodal != nullptr) { + multimodal->clear_staged_image(); + } + } catch (const std::exception& exception) { + llm::worker_emit({{"error", std::string(exception.what())}}); + } + } + return 0; +} + +} // namespace + +int main(int argc, char** argv) { + gflags::ParseCommandLineFlags(&argc, &argv, true); + if (FLAGS_model_path.empty() || FLAGS_tokenizer_path.empty()) { + ET_LOG( + Error, + "muse_glimmer_worker: --model_path and --tokenizer_path required"); + return 1; + } + if (FLAGS_artifact_mode != "auto" && + FLAGS_artifact_mode != "autoregressive" && + FLAGS_artifact_mode != "dflash") { + parse_artifact_mode(FLAGS_artifact_mode); + return 1; + } + if (FLAGS_max_image_bytes <= 0) { + ET_LOG(Error, "muse_glimmer_worker: --max_image_bytes must be positive"); + return 1; + } + + llm::MuseGlimmerConfig config; + config.model_path = FLAGS_model_path; + config.data_path = FLAGS_data_path; + config.tokenizer_path = FLAGS_tokenizer_path; + config.pos_embed_path = FLAGS_pos_embed_path; + config.max_image_bytes = static_cast(FLAGS_max_image_bytes); + config.max_sessions = FLAGS_max_sessions; + config.eos_id = FLAGS_eos_id; + config.artifact_mode = parse_artifact_mode(FLAGS_artifact_mode); + config.dflash_block_length = FLAGS_dflash_block_length; + config.dflash_n_draft = FLAGS_dflash_n_draft; + config.dflash_draft_argmax = FLAGS_dflash_draft_argmax; + config.enable_cuda_graph = FLAGS_cuda_graph; + + auto engine_result = llm::MuseGlimmerEngine::create(config); + if (engine_result.error() != Error::Ok) { + ET_LOG(Error, "muse_glimmer_worker: failed to create engine"); + return 1; + } + return run_muse_glimmer_worker_loop(*engine_result.get()); +} diff --git a/examples/models/muse-glimmer/runtime/runners/solo.cpp b/examples/models/muse-glimmer/runtime/runners/solo.cpp new file mode 100644 index 00000000000..becce4da33f --- /dev/null +++ b/examples/models/muse-glimmer/runtime/runners/solo.cpp @@ -0,0 +1,2059 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +// Muse Glimmer runner for the ExecuTorch CUDA and MLX backends. +// Text and vision generation use MuseGlimmerEngine. Vision inputs are +// host-preprocessed and spliced into the prompt at <|patch|> positions. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +extern "C" void et_pal_emit_log_message( + ET_UNUSED et_timestamp_t timestamp, + et_pal_log_level_t level, + const char* filename, + ET_UNUSED const char* function, + size_t line, + const char* message, + ET_UNUSED size_t length) { + if (level == 'D' || level == 'I') { + return; + } + fprintf(stderr, "%c [%s:%zu] %s\n", (char)level, filename, line, message); +} + +#ifdef EXECUTORCH_BUILD_CUDA +#include +#endif + +// The vision runtime translation unit owns the stb implementations; this file +// uses declarations for its direct vision path. +#include + +#include + +#ifdef EXECUTORCH_BUILD_MLX +// MLX build: option keys for MLXBackend::init (clear_cache_interval). +#include +#endif + +DEFINE_string(model_path, "", "Model .pte file path."); +DEFINE_string(data_path, "", "Data file (.ptd), if the export produced one."); +DEFINE_string( + tokenizer_path, + "", + "Hugging Face tokenizer.json path. Must encode the Harmony control " + "tokens; a raw BPE vocabulary will not."); +DEFINE_string(prompt, "The meaning of life is", "Prompt text."); +DEFINE_string( + prompt_file, + "", + "Path to file containing prompt text (overrides --prompt)."); +DEFINE_string( + prompt_tokens_file, + "", + "int64 LE pre-tokenized prompt IDs; bypasses encode in the timed path."); +DEFINE_bool( + tokens_have_bos, + false, + "If true the file already includes BOS; else BOS is prepended."); +DEFINE_double(temperature, 0.8, "Sampling temperature (0 = near-greedy)."); +DEFINE_double( + top_p, + 1.0, + "Top-p (nucleus) host sampling for MLX/CPU. 1.0 = disabled. Not supported " + "on CUDA, which samples on-device."); +DEFINE_int32( + top_k, + 0, + "Top-k host sampling for MLX/CPU. 0 = disabled. Not supported on CUDA, " + "which samples on-device."); +DEFINE_int64( + seed, + 0, + "RNG seed for host sampling (MLX/CPU) and the engine path. <=0 = " + "nondeterministic. Applies to both the direct-Module and engine generation " + "paths so a given seed reproduces the same sequence."); +DEFINE_int32(max_new_tokens, 128, "Maximum tokens to generate."); +DEFINE_bool( + ignore_eos, + false, + "Ignore EOS and emit exactly max_new_tokens tokens for benchmarking."); +DEFINE_string( + generated_tokens_file, + "", + "Optional path to write logical continuation token IDs as native int64 " + "values."); +DEFINE_int32(bos_id, 200000, "BOS token id."); +DEFINE_int32(eos_id, 200001, "EOS token id."); +DEFINE_bool( + cuda_graph, + true, + "Enable CUDA graph capture for the decode method. CUDA only; default on."); +DEFINE_string( + nll_tokens_file, + "", + "Path to binary file of int64 token IDs for NLL validation. " + "Runs chunked prefill, dumps logits to --nll_output_file, then exits."); +DEFINE_string( + nll_output_file, + "", + "Path to write binary logits (float32, [T, V]) for NLL validation."); +DEFINE_bool( + nll_use_prefill, + false, + "Use prefill method (multi-token) instead of decode (single-token) for NLL."); +DEFINE_string( + nll_image_manifest, + "", + "Path to a newline-delimited, ordered list of image paths for multimodal " + "NLL. When set together with --nll_tokens_file (CUDA vision --logits .pte), " + "the runner encodes each image with vision_encoder, splices the resulting " + "soft-token features into the <|patch|> runs of the token sequence in " + "order, prefills on embeddings, and writes (T-1) float32 per-position " + "next-token log-probs to --nll_output_file (position i scores tokens[i+1])."); +DEFINE_int32( + max_prefill_chunk, + 0, + "Override the prefill chunk size. Must be <= the model's exported " + "get_max_prefill_chunk (the baked dynamic seq_len bound); values above it " + "are ignored. 0 = use the model's value. Smaller chunks trade prefill " + "throughput for lower peak memory."); +DEFINE_string( + method, + "forward", + "Forward method to invoke, for whichever path runs. Text single-method " + "(token input): default 'forward'; use 'target_forward' to run a " + "DFlash-exported target autoregressively (non-draft). MLX vision (embeds " + "input, after splicing image soft-tokens): the default 'forward' maps to " + "'forward_from_embeddings' (solo vision export); use " + "'target_forward_from_embeddings' for a DFlash-vision .pte. Only " + "output[0] logits are used; any extra hidden output is ignored."); +DEFINE_int32( + vision_max_prefill_chunk, + 3072, + "Maximum prefill chunk for vision prompts. 0 disables this " + "vision-specific cap."); +DEFINE_string( + image_path, + "", + "Optional path to an image (JPEG/PNG). When set (CUDA or MLX build with a " + "vision-enabled .pte), the runner runs the vision_encoder, splices the " + "image soft-tokens at the prompt's single marker, and prefills on " + "embeds."); +DEFINE_string( + pos_embed_path, + "", + "Path to pos_embed.bin (vision positional-embedding table) written next to " + "model.pte by export.py. Defaults to /pos_embed.bin."); + +namespace llm = ::executorch::extension::llm; +using ::executorch::extension::from_blob; +using ::executorch::extension::Module; +using ::executorch::runtime::Error; +using ::executorch::runtime::EValue; + +using SizesType = executorch::aten::SizesType; + +// Whether the runner invokes a single exported method (--method) instead of the +// standard prefill/decode pair. Derived from the loaded .pte's exported methods +// (see main), not the build backend: a model exporting both `prefill` and +// `decode` uses the two-method path; a single-`forward` export or a DFlash +// target-only method selected via --method uses single-method execution. +// NOLINTNEXTLINE(facebook-avoid-non-const-global-variables) +static bool kSingleMethod = false; + +// Method to invoke for a chunk of `chunk_len` tokens. +static const char* method_for(int64_t chunk_len) { + if (kSingleMethod) { + return FLAGS_method.c_str(); + } + return (chunk_len == 1) ? "decode" : "prefill"; +} + +// Read a sampled token ID from a scalar float output (on-device sampling). +// Used by the CUDA sampling export (sample=True), whose methods return one +// Gumbel-max token id as a float scalar instead of full logits. +[[maybe_unused]] static uint64_t read_token( + const executorch::aten::Tensor& output) { + const void* ptr = output.const_data_ptr(); + float val = 0.0f; +#ifdef EXECUTORCH_BUILD_CUDA + cudaPointerAttributes attrs{}; + bool on_device = cudaPointerGetAttributes(&attrs, ptr) == cudaSuccess && + attrs.type == cudaMemoryTypeDevice; + if (on_device) { + cudaMemcpy(&val, ptr, sizeof(float), cudaMemcpyDeviceToHost); + } else { + memcpy(&val, ptr, sizeof(float)); + } +#else + memcpy(&val, ptr, sizeof(float)); +#endif + return static_cast(llrintf(val)); +} + +// Copy CUDA or MLX tensor storage to the host for embedding splices. +static Error +copy_to_host(const executorch::aten::Tensor& src, void* dst, size_t num_bytes) { + if (num_bytes > src.nbytes()) { + ET_LOG( + Error, + "copy_to_host requested %zu bytes from a %zu-byte tensor", + num_bytes, + src.nbytes()); + return Error::InvalidArgument; + } + const void* src_ptr = src.const_data_ptr(); +#ifdef EXECUTORCH_BUILD_CUDA + cudaPointerAttributes attrs{}; + bool on_device = cudaPointerGetAttributes(&attrs, src_ptr) == cudaSuccess && + attrs.type == cudaMemoryTypeDevice; + if (on_device) { + auto err = cudaMemcpy(dst, src_ptr, num_bytes, cudaMemcpyDeviceToHost); + if (err != cudaSuccess) { + ET_LOG(Error, "copy_to_host D2H failed: %s", cudaGetErrorString(err)); + return Error::Internal; + } + } else +#endif + { + memcpy(dst, src_ptr, num_bytes); + } + return Error::Ok; +} + +// Muse Glimmer image special-token ids (from the tokenizer / OnyxConfig). + +// Preprocess one image file, run the exported vision_encoder, and copy the +// resulting soft-token embeddings ([num_soft_tokens, hidden] bf16) to host. +// Used by the multimodal NLL path to score the image/perception reference. +static Error encode_image_nll( + Module& module, + const std::string& image_path, + const std::vector& pos_table, + std::vector& out_embeds, + int64_t& out_num_soft_tokens, + int64_t& out_hidden) { + namespace gv = ::executorch::examples::muse_glimmer_vision; + int img_w = 0, img_h = 0, img_c = 0; + unsigned char* img_data = + stbi_load(image_path.c_str(), &img_w, &img_h, &img_c, 3); + if (img_data == nullptr) { + ET_LOG(Error, "Failed to load image: %s", image_path.c_str()); + return Error::Internal; + } + gv::VisionInputs vis; + try { + vis = gv::preprocess_image(img_data, img_w, img_h, pos_table); + } catch (const std::exception& e) { + ET_LOG( + Error, + "preprocess_image failed for %s: %s", + image_path.c_str(), + e.what()); + stbi_image_free(img_data); + return Error::Internal; + } + stbi_image_free(img_data); + + std::vector ve_inputs; + ve_inputs.push_back(EValue(vis.patches)); + ve_inputs.push_back(EValue(vis.pos_emb)); + ve_inputs.push_back(EValue(vis.cos_2d)); + ve_inputs.push_back(EValue(vis.sin_2d)); + ve_inputs.push_back(EValue(vis.sparse_perm)); + ve_inputs.push_back(EValue(vis.inv_perm)); + ve_inputs.push_back(EValue(vis.global_mask)); + ve_inputs.push_back(EValue(vis.sparse_mask)); + ve_inputs.push_back(EValue(vis.pixel_perm)); + + auto ve_result = module.execute("vision_encoder", ve_inputs); + if (ve_result.error() != Error::Ok) { + ET_LOG(Error, "vision_encoder failed for %s", image_path.c_str()); + return Error::Internal; + } + const auto& image_embeds = ve_result.get()[0].toTensor(); + if (image_embeds.dim() != 3 || image_embeds.size(0) != 1) { + ET_LOG(Error, "vision_encoder output must be [1, N, hidden]"); + return Error::Internal; + } + out_num_soft_tokens = image_embeds.size(1); + out_hidden = image_embeds.size(2); + out_embeds.assign(static_cast(out_num_soft_tokens * out_hidden), 0); + return copy_to_host( + image_embeds, + out_embeds.data(), + static_cast(out_num_soft_tokens * out_hidden) * sizeof(uint16_t)); +} + +// Apply the optional --max_prefill_chunk override to the model's exported chunk +// size. The override may only lower the chunk, never exceed the exported bound +// (which is baked into the .pte as the dynamic seq_len limit). +static int64_t apply_prefill_chunk_override( + int64_t model_chunk, + bool is_vision = false) { + if (is_vision && FLAGS_vision_max_prefill_chunk > 0) { + model_chunk = + std::min(model_chunk, FLAGS_vision_max_prefill_chunk); + } + if (FLAGS_max_prefill_chunk > 0 && FLAGS_max_prefill_chunk < model_chunk) { + return FLAGS_max_prefill_chunk; + } + return model_chunk; +} + +#ifdef EXECUTORCH_BUILD_MLX +static Error read_activation_dtype( + Module& module, + executorch::aten::ScalarType& dtype) { + auto result = module.get("get_activation_dtype"); + if (!result.ok() || !result->isString()) { + ET_LOG(Error, "Model .pte is missing get_activation_dtype metadata"); + return Error::InvalidProgram; + } + const auto tag = result->toString(); + if (tag == "bfloat16") { + dtype = executorch::aten::ScalarType::BFloat16; + } else if (tag == "float16") { + dtype = executorch::aten::ScalarType::Half; + } else { + ET_LOG( + Error, + "Unsupported activation dtype '%.*s' in .pte metadata", + static_cast(tag.size()), + tag.data()); + return Error::InvalidProgram; + } + return Error::Ok; +} +#endif + +// Host-side sampling over full logits. Used by the --logits (NLL) export mode +// and the MLX `forward` export, which return full logits instead of a token. +[[maybe_unused]] static uint64_t sample_from_logits( + const executorch::aten::Tensor& logits, + int64_t seq_pos, + double temperature) { + // logits: (B, T, V) or (B, 1, V) float32. Sampling math is shared with the + // DFlash/engine path via sampling.h (muse_glimmer::). --top_p/--top_k are + // honored here (MLX/CPU); main() rejects them on CUDA, which samples + // on-device. + const int64_t vocab_size = logits.size(logits.dim() - 1); + const int64_t offset = seq_pos * vocab_size; + + // Copy logits for the target position to host (source may be device on CUDA). + std::vector host_logits(vocab_size); + const void* src = static_cast(logits.const_data_ptr()) + + offset * sizeof(float); + +#ifdef EXECUTORCH_BUILD_CUDA + cudaPointerAttributes attrs{}; + bool on_device = cudaPointerGetAttributes(&attrs, src) == cudaSuccess && + attrs.type == cudaMemoryTypeDevice; + if (on_device) { + cudaMemcpy( + host_logits.data(), + src, + vocab_size * sizeof(float), + cudaMemcpyDeviceToHost); + } else { + memcpy(host_logits.data(), src, vocab_size * sizeof(float)); + } +#else + memcpy(host_logits.data(), src, vocab_size * sizeof(float)); +#endif + + if (temperature <= 0.0) { + return muse_glimmer::argmax_index(host_logits.data(), vocab_size); + } + + static std::mt19937 rng( + FLAGS_seed > 0 ? static_cast(FLAGS_seed) + : std::random_device{}()); + static muse_glimmer::SamplingWorkspace workspace; + muse_glimmer::fill_sampling_probabilities( + host_logits.data(), + vocab_size, + temperature, + FLAGS_top_k, + FLAGS_top_p, + workspace); + return muse_glimmer::categorical_sample( + rng, workspace.probabilities.data(), vocab_size); +} + +// Unified autoregressive generation through the shared +// MuseGlimmerEngine/LLMSession stack used by muse_glimmer_worker and +// dflash_runner. +static int run_engine_generation(llm::Stats& stats) { + llm::MuseGlimmerConfig config; + config.model_path = FLAGS_model_path; + config.data_path = FLAGS_data_path; + config.tokenizer_path = FLAGS_tokenizer_path; + config.pos_embed_path = FLAGS_pos_embed_path; + config.max_sessions = 1; + config.eos_id = FLAGS_eos_id; + config.enable_cuda_graph = FLAGS_cuda_graph; + config.artifact_mode = llm::MuseGlimmerArtifactMode::Auto; + + auto engine_result = llm::MuseGlimmerEngine::create(config); + if (engine_result.error() != Error::Ok) { + ET_LOG(Error, "Failed to create MuseGlimmerEngine"); + return 1; + } + auto engine = std::move(engine_result.get()); + stats.model_load_end_ms = llm::time_in_ms(); + +#ifdef EXECUTORCH_BUILD_CUDA + { + size_t gpu_free_bytes = 0, gpu_total_bytes = 0; + cudaMemGetInfo(&gpu_free_bytes, &gpu_total_bytes); + stats.gpu_free_after_load_bytes = gpu_free_bytes; + } +#endif + + auto session_result = engine->create_session(); + if (session_result.error() != Error::Ok) { + ET_LOG(Error, "Failed to create LLMSession"); + return 1; + } + auto session = std::move(session_result.get()); + + const bool has_image = !FLAGS_image_path.empty(); + int64_t num_soft_tokens = 0; + if (has_image) { + if (!FLAGS_prompt_tokens_file.empty()) { + ET_LOG(Error, "--image_path is not supported with --prompt_tokens_file"); + return 1; + } + if (!engine->has_vision()) { + ET_LOG(Error, "--image_path requires an artifact with vision_encoder"); + return 1; + } + auto prepared = engine->prepare_image_from_file(FLAGS_image_path); + if (prepared.error() != Error::Ok) { + ET_LOG(Error, "Failed to prepare image"); + return 1; + } + num_soft_tokens = prepared->num_soft_tokens; + auto* multimodal = llm::as_muse_glimmer_multimodal_session(session.get()); + if (multimodal == nullptr) { + ET_LOG(Error, "Muse Glimmer session does not support image input"); + return 1; + } + multimodal->stage_image_for_next_prefill(std::move(prepared.get())); + } + + // Build prompt tokens, preserving the runner's input options (mirrors the + // non-image prompt handling in main()). + std::vector prompt_tokens; + if (!FLAGS_prompt_tokens_file.empty()) { + std::ifstream tf(FLAGS_prompt_tokens_file, std::ios::binary); + if (!tf.is_open()) { + ET_LOG( + Error, + "Cannot open --prompt_tokens_file: %s", + FLAGS_prompt_tokens_file.c_str()); + return 1; + } + tf.seekg(0, std::ios::end); + const std::streamoff nbytes = tf.tellg(); + tf.seekg(0, std::ios::beg); + if (nbytes < 0 || + nbytes % static_cast(sizeof(int64_t)) != 0) { + ET_LOG( + Error, + "--prompt_tokens_file size (%lld bytes) is not a positive multiple " + "of %zu", + static_cast(nbytes), + sizeof(int64_t)); + return 1; + } + const int64_t num_file_tokens = + static_cast(nbytes) / static_cast(sizeof(int64_t)); + std::vector file_tokens(num_file_tokens); + tf.read(reinterpret_cast(file_tokens.data()), nbytes); + if (tf.gcount() != nbytes) { + ET_LOG(Error, "Failed to read all of --prompt_tokens_file"); + return 1; + } + tf.close(); + if (!FLAGS_tokens_have_bos) { + prompt_tokens.push_back(static_cast(FLAGS_bos_id)); + } + prompt_tokens.insert( + prompt_tokens.end(), file_tokens.begin(), file_tokens.end()); + } else { + std::string prompt_text = FLAGS_prompt; + if (!FLAGS_prompt_file.empty()) { + std::ifstream f(FLAGS_prompt_file); + if (!f.is_open()) { + ET_LOG( + Error, "Failed to open prompt file: %s", FLAGS_prompt_file.c_str()); + return 1; + } + prompt_text = std::string( + (std::istreambuf_iterator(f)), + std::istreambuf_iterator()); + } + auto tokenized = llm::tokenize_muse_glimmer_prompt( + *engine->tokenizer(), + prompt_text, + static_cast(FLAGS_bos_id), + has_image ? std::optional(num_soft_tokens) : std::nullopt); + if (!tokenized.ok()) { + ET_LOG( + Error, + "Failed to tokenize prompt; --image_path requires exactly one " + " marker"); + return 1; + } + prompt_tokens = std::move(*tokenized); + } + + const int64_t num_prompt_tokens = static_cast(prompt_tokens.size()); + printf("Prompt tokens: %" PRId64 "\n", num_prompt_tokens); + stats.num_prompt_tokens = num_prompt_tokens; + + llm::SamplingConfig sampling; + sampling.temperature = static_cast(FLAGS_temperature); + sampling.top_p = static_cast(FLAGS_top_p); + sampling.top_k = FLAGS_top_k; + sampling.seed = FLAGS_seed > 0 ? static_cast(FLAGS_seed) : 0; + + // Tokenization is excluded from the prefill timer to match main()'s timing. + stats.inference_start_ms = llm::time_in_ms(); + if (session->prefill_tokens(prompt_tokens, &sampling) != Error::Ok) { + ET_LOG(Error, "prefill failed"); + return 1; + } + stats.prompt_eval_end_ms = llm::time_in_ms(); + const double prefill_ms = + static_cast(stats.prompt_eval_end_ms - stats.inference_start_ms); + printf( + "Prefill: %" PRId64 " tokens in %.1f ms (%.1f tok/s)\n", + num_prompt_tokens, + prefill_ms, + prefill_ms > 0.0 ? num_prompt_tokens * 1000.0 / prefill_ms : 0.0); + + int64_t num_generated = 0; + for (int32_t step = 0; step < FLAGS_max_new_tokens; ++step) { + auto decode_result = session->decode_one(sampling); + if (decode_result.error() != Error::Ok) { + ET_LOG(Error, "Decode step %d failed", step); + return 1; + } + const auto& decoded = decode_result.get(); + if (decoded.is_terminal) { + break; + } + if (num_generated == 0) { + stats.first_token_ms = llm::time_in_ms(); + } + if (!decoded.text_piece.empty()) { + fwrite(decoded.text_piece.data(), 1, decoded.text_piece.size(), stdout); + fflush(stdout); + } + ++num_generated; + } + + stats.inference_end_ms = llm::time_in_ms(); + stats.num_generated_tokens = num_generated; + printf("\n"); + const double decode_ms = + static_cast(stats.inference_end_ms - stats.prompt_eval_end_ms); + printf( + "Decode: %" PRId64 " tokens in %.1f ms (%.1f tok/s)\n", + num_generated, + decode_ms, + decode_ms > 0.0 ? num_generated * 1000.0 / decode_ms : 0.0); + +#ifdef EXECUTORCH_BUILD_CUDA + { + size_t gpu_free_bytes = 0, gpu_total_bytes = 0; + cudaMemGetInfo(&gpu_free_bytes, &gpu_total_bytes); + stats.gpu_free_after_generate_bytes = gpu_free_bytes; + stats.gpu_peak_usage_mb = + (stats.gpu_total_bytes - gpu_free_bytes) / 1024.0 / 1024.0; + } +#endif + + llm::print_report(stats); + return 0; +} + +int main(int argc, char** argv) { + gflags::ParseCommandLineFlags(&argc, &argv, true); + + if (FLAGS_model_path.empty()) { + ET_LOG(Error, "Must specify --model_path"); + return 1; + } + if (FLAGS_tokenizer_path.empty()) { + ET_LOG(Error, "Must specify --tokenizer_path"); + return 1; + } + +#ifdef EXECUTORCH_BUILD_CUDA + if (FLAGS_top_p != 1.0 || FLAGS_top_k != 0) { + ET_LOG( + Error, + "--top_p/--top_k are not supported on CUDA (sampling runs on-device); " + "omit them to use the on-device sampler."); + return 1; + } +#endif + + llm::Stats stats; + +#ifdef EXECUTORCH_BUILD_CUDA + size_t gpu_free_bytes = 0, gpu_total_bytes = 0; + cudaMemGetInfo(&gpu_free_bytes, &gpu_total_bytes); + stats.gpu_total_bytes = gpu_total_bytes; + stats.gpu_free_before_load_bytes = gpu_free_bytes; +#endif + + stats.model_load_start_ms = llm::time_in_ms(); + + // CUDA uses backend cross-method weight sharing and file loading; its tensors + // cannot use core shared memory arenas. MLX shares arenas for KV state and + // mmaps model weights. + std::vector data_files; + if (!FLAGS_data_path.empty()) { + data_files.push_back(FLAGS_data_path); + } +#ifdef EXECUTORCH_BUILD_CUDA + constexpr auto kLoadMode = Module::LoadMode::File; + constexpr bool kShareMemoryArenas = false; +#else + constexpr auto kLoadMode = Module::LoadMode::MmapUseMlockIgnoreErrors; + constexpr bool kShareMemoryArenas = true; +#endif + auto module = std::make_unique( + FLAGS_model_path, + data_files, + kLoadMode, + /*event_tracer=*/nullptr, + /*memory_allocator=*/nullptr, + /*temp_allocator=*/nullptr, + /*share_memory_arenas=*/kShareMemoryArenas); + + // Derive single-method mode from the artifact's unified Solo contract. + { + const auto method_names = module->method_names(); + bool has_solo_contract = method_names.ok() && + method_names->count("embed_text") != 0 && + method_names->count("forward_from_embeddings") != 0; +#ifndef EXECUTORCH_BUILD_MLX + has_solo_contract = + has_solo_contract && method_names->count("decode_from_embedding") != 0; +#endif + kSingleMethod = !has_solo_contract; + } + + // Generation uses the same engine/session path for CUDA, MLX, text, and + // vision. NLL and explicit single-method benches use the direct path below. + { + const auto engine_methods = module->method_names(); + bool has_solo_contract = engine_methods.ok() && + engine_methods->count("embed_text") != 0 && + engine_methods->count("forward_from_embeddings") != 0; +#ifndef EXECUTORCH_BUILD_MLX + has_solo_contract = has_solo_contract && + engine_methods->count("decode_from_embedding") != 0; +#endif + const bool is_dflash = + engine_methods.ok() && engine_methods->count("draft_forward") != 0; + const bool generation = + FLAGS_nll_tokens_file.empty() && FLAGS_method == "forward"; + if (generation && has_solo_contract && !is_dflash) { + // Release the probe module before MuseGlimmerEngine reloads the .pte, + // which builds its own tokenizer. The direct path below loads its own. + module.reset(); + return run_engine_generation(stats); + } + } + + // Same tokenizer the engine path builds. This used to be a Tiktoken whose + // only real special tokens were <|begin_of_text|> and <|end_of_text|>, so + // <|start|>, <|message|> and <|eot|> byte-pair encoded into ordinary text and + // every prompt measured here was longer than the one generation runs. + auto tokenizer = std::make_unique<::tokenizers::HFTokenizer>(); + if (tokenizer->load(FLAGS_tokenizer_path) != tokenizers::Error::Ok) { + ET_LOG( + Error, + "Failed to load tokenizer from %s", + FLAGS_tokenizer_path.c_str()); + return 1; + } + + // Get metadata + auto metadata_result = llm::get_llm_metadata(tokenizer.get(), module.get()); + if (metadata_result.error() != Error::Ok) { + ET_LOG(Error, "Failed to read model metadata"); + return 1; + } + +#ifdef EXECUTORCH_BUILD_CUDA + if (FLAGS_cuda_graph) { + executorch::runtime::BackendOptions<2> cuda_opts; + cuda_opts.set_option( + "enable_cuda_graph_for_method", "decode_from_embedding"); + executorch::runtime::set_option("CudaBackend", cuda_opts.view()); + printf("CUDA graph enabled for decode_from_embedding method\n"); + } + + // Cross-method per-FQN weight sharing keeps both decoder methods on one set + // of weights and KV-cache buffers. + { + executorch::runtime::BackendOptions<1> backend_options; + auto set_err = + backend_options.set_option("weight_sharing_across_methods", true); + if (set_err != Error::Ok) { + ET_LOG( + Error, + "Failed to construct weight_sharing_across_methods option: %d", + static_cast(set_err)); + return 1; + } + auto opt_err = + executorch::runtime::set_option("CudaBackend", backend_options.view()); + if (opt_err != Error::Ok) { + ET_LOG( + Error, + "Failed to enable weight_sharing_across_methods: %d", + static_cast(opt_err)); + return 1; + } + } +#else + if (FLAGS_cuda_graph) { + ET_LOG(Info, "--cuda_graph ignored on non-CUDA build"); + } +#endif + + printf("Loading methods...\n"); + const bool has_image = !FLAGS_image_path.empty(); +#ifdef EXECUTORCH_BUILD_CUDA + // On CUDA, kSingleMethod means a token single-method (--method) bench, which + // cannot splice an image. On MLX the vision path is selected by the + // artifact's vision_encoder (mlx_multimodal), and has_image is validated in + // that loader below, so this guard is CUDA-only. + if (has_image && kSingleMethod) { + ET_LOG(Error, "--image_path is not supported with --method"); + return 1; + } +#endif +#ifdef EXECUTORCH_BUILD_CUDA + // Two CUDA export flavors: + // * --logits (NLL) .pte: token-input `prefill`/`decode` returning logits. + // * sampling .pte (default): `embed_text` + embeds-input `prefill` + + // token-input `decode` (+ optional `vision_encoder`), returning a sampled + // token id. Multimodal NLL reuses its embeds-input short forward because + // that method returns logits for every position. + const bool nll_mode = !FLAGS_nll_tokens_file.empty(); + const bool nll_vision = nll_mode && !FLAGS_nll_image_manifest.empty(); + std::string nll_vision_forward_method = "prefill"; + bool nll_vision_uses_short_forward = false; + if (nll_vision) { + const auto method_names = module->method_names(); + if (method_names.ok() && + method_names->count("target_forward_from_embeddings") != 0) { + // DFlash long prefill intentionally computes lm_head for only the last + // position. NLL needs one logits row per input position, which the short + // verifier method already returns. + nll_vision_forward_method = "target_forward_from_embeddings"; + nll_vision_uses_short_forward = true; + } + } + // embed_text is needed for generation (splice image/text embeds) and for the + // multimodal NLL path; the text-only NLL path uses token-input + // prefill/decode. + if ((!nll_mode && !kSingleMethod) || nll_vision) { + if (module->load_method("embed_text") != Error::Ok) { + ET_LOG(Error, "Failed to load embed_text method"); + return 1; + } + } + if (nll_vision) { + if (module->load_method(nll_vision_forward_method.c_str()) != Error::Ok) { + ET_LOG( + Error, + "Failed to load multimodal NLL forward method %s", + nll_vision_forward_method.c_str()); + return 1; + } + } else if (kSingleMethod) { + if (module->load_method(FLAGS_method.c_str()) != Error::Ok) { + ET_LOG(Error, "Failed to load %s method", FLAGS_method.c_str()); + return 1; + } + } else { + if (module->load_method("prefill") != Error::Ok) { + ET_LOG(Error, "Failed to load prefill method"); + return 1; + } + // The multimodal NLL path scores whole docs via embeds-input `prefill` + // only; it never samples, so skip loading `decode` (saves its planned + // memory, which matters for large vision models near single-GPU capacity). + if (!nll_vision) { + if (module->load_method("decode") != Error::Ok) { + ET_LOG(Error, "Failed to load decode method"); + return 1; + } + } + } + if (nll_mode && has_image && !nll_vision) { + ET_LOG( + Error, + "--image_path is not supported in NLL mode; pass an ordered image " + "list via --nll_image_manifest for multimodal NLL."); + return 1; + } + if (has_image && !FLAGS_prompt_tokens_file.empty()) { + ET_LOG(Error, "--image_path is not supported with --prompt_tokens_file"); + return 1; + } + if (has_image || nll_vision) { + if (module->load_method("vision_encoder") != Error::Ok) { + ET_LOG( + Error, + "Failed to load vision_encoder — was the model exported with " + "--mmproj?"); + return 1; + } + } +#elif defined(EXECUTORCH_BUILD_MLX) + // MLX supports both a text-only `forward` .pte and a + // vision .pte (embed_text + embeds-input `forward_from_embeddings` + + // `vision_encoder`), detected by the method set. That embeds-forward is the + // only KV-writing method; decode reuses it. Host-side sampling. + bool mlx_multimodal = false; + { + auto result = module->get("has_vision_encoder"); + if (result.ok()) { + mlx_multimodal = result->toScalar().to(); + } + } + // One --method flag selects the forward for whichever path runs. The + // embeds-input vision path maps the default "forward" to + // "forward_from_embeddings" (its natural name) and otherwise uses the + // override (e.g. target_forward_from_embeddings for a DFlash-vision .pte). + const std::string vision_method = FLAGS_method == "forward" + ? std::string("forward_from_embeddings") + : FLAGS_method; + executorch::aten::ScalarType activation_dtype = + executorch::aten::ScalarType::BFloat16; + // MLX: release MLX's cached buffer pool every N calls to bound memory growth + // during long sessions (mirrors the gemma4 runner). + constexpr int kMLXClearCacheInterval = 1; + executorch::runtime::BackendOptions<1> mlx_opts; + executorch::runtime::LoadBackendOptionsMap mlx_options_map; + if (mlx_opts.set_option( + executorch::backends::mlx::kClearCacheIntervalKey, + kMLXClearCacheInterval) != Error::Ok || + mlx_options_map.set_options( + executorch::backends::mlx::kMLXBackendId, mlx_opts.view()) != + Error::Ok) { + ET_LOG(Error, "Failed to set MLX clear_cache_interval option"); + return 1; + } + ET_LOG(Info, "MLX clear_cache_interval=%d", kMLXClearCacheInterval); + executorch::runtime::LoadBackendOptionsMap* mlx_opts_ptr = &mlx_options_map; + if (mlx_multimodal) { + if (read_activation_dtype(*module, activation_dtype) != Error::Ok) { + return 1; + } + if (module->load_method("embed_text", nullptr, nullptr, mlx_opts_ptr) != + Error::Ok) { + ET_LOG(Error, "Failed to load embed_text method"); + return 1; + } + if (module->load_method( + vision_method.c_str(), nullptr, nullptr, mlx_opts_ptr) != + Error::Ok) { + ET_LOG(Error, "Failed to load %s method", vision_method.c_str()); + return 1; + } + if (has_image && + module->load_method("vision_encoder", nullptr, nullptr, mlx_opts_ptr) != + Error::Ok) { + ET_LOG( + Error, + "Failed to load vision_encoder — was the model exported with " + "--mmproj?"); + return 1; + } + } else { + if (has_image) { + ET_LOG( + Error, + "--image_path requires a vision-enabled .pte (export with --mmproj)"); + return 1; + } + if (module->load_method( + FLAGS_method.c_str(), nullptr, nullptr, mlx_opts_ptr) != + Error::Ok) { + ET_LOG(Error, "Failed to load %s method", FLAGS_method.c_str()); + return 1; + } + } +#endif + stats.model_load_end_ms = llm::time_in_ms(); + +#ifdef EXECUTORCH_BUILD_CUDA + cudaMemGetInfo(&gpu_free_bytes, &gpu_total_bytes); + stats.gpu_free_after_load_bytes = gpu_free_bytes; +#endif + + // --------------------------------------------------------------- + // NLL validation mode: read tokens, dump logits, exit + // --------------------------------------------------------------- + if (!FLAGS_nll_tokens_file.empty()) { + // Read token IDs from binary file (int64_t[]) + std::ifstream tf(FLAGS_nll_tokens_file, std::ios::binary); + if (!tf.is_open()) { + ET_LOG( + Error, + "Cannot open --nll_tokens_file: %s", + FLAGS_nll_tokens_file.c_str()); + return 1; + } + tf.seekg(0, std::ios::end); + int64_t nbytes = tf.tellg(); + tf.seekg(0, std::ios::beg); + int64_t num_tokens = nbytes / sizeof(int64_t); + std::vector tokens(num_tokens); + tf.read(reinterpret_cast(tokens.data()), nbytes); + tf.close(); + + printf("NLL mode: %lld tokens\n", (long long)num_tokens); + +#ifdef EXECUTORCH_BUILD_CUDA + if (nll_vision) { + // ------------------------------------------------------------- + // Multimodal NLL: encode ordered images, splice their soft-token + // features into the <|patch|> runs of the exact reference tokens, + // prefill on embeddings, and write (T-1) per-position next-token + // log-probs. The Python driver applies the patch/terminal mask and + // compares to the perception reference. + // ------------------------------------------------------------- + namespace gv = ::executorch::examples::muse_glimmer_vision; + // Positional-embedding table (written next to model.pte by export.py). + std::string pe_path = FLAGS_pos_embed_path; + if (pe_path.empty()) { + auto slash = FLAGS_model_path.find_last_of('/'); + std::string dir = (slash == std::string::npos) + ? "." + : FLAGS_model_path.substr(0, slash); + pe_path = dir + "/pos_embed.bin"; + } + std::vector pos_table; + try { + pos_table = gv::load_pos_embed_table(pe_path); + } catch (const std::exception& e) { + ET_LOG(Error, "Failed to load pos_embed.bin: %s", e.what()); + return 1; + } + + // Read the ordered image manifest (one path per line). + std::vector image_paths; + { + std::ifstream mf(FLAGS_nll_image_manifest); + if (!mf.is_open()) { + ET_LOG( + Error, + "Cannot open --nll_image_manifest: %s", + FLAGS_nll_image_manifest.c_str()); + return 1; + } + std::string line; + while (std::getline(mf, line)) { + while (!line.empty() && + (line.back() == '\n' || line.back() == '\r' || + line.back() == ' ' || line.back() == '\t')) { + line.pop_back(); + } + if (!line.empty()) { + image_paths.push_back(line); + } + } + } + if (image_paths.empty()) { + ET_LOG(Error, "--nll_image_manifest is empty"); + return 1; + } + + // Encode each image (in order) to host soft-token embeddings. + std::vector> img_embeds(image_paths.size()); + std::vector img_counts(image_paths.size(), 0); + int64_t vision_hidden = 0; + int64_t total_soft_tokens = 0; + for (size_t k = 0; k < image_paths.size(); ++k) { + int64_t n = 0, h = 0; + if (encode_image_nll( + *module, image_paths[k], pos_table, img_embeds[k], n, h) != + Error::Ok) { + return 1; + } + if (vision_hidden == 0) { + vision_hidden = h; + } else if (h != vision_hidden) { + ET_LOG(Error, "inconsistent vision hidden dim across images"); + return 1; + } + img_counts[k] = n; + total_soft_tokens += n; + printf( + " image %zu: %s -> %lld soft tokens\n", + k, + image_paths[k].c_str(), + (long long)n); + } + + // Fail if total <|patch|> tokens != total vision features. + int64_t patch_in_tokens = 0; + for (int64_t t : tokens) { + if (t == llm::kMuseGlimmerImagePatchTokenId) { + ++patch_in_tokens; + } + } + if (patch_in_tokens != total_soft_tokens) { + ET_LOG( + Error, + "patch-token count %lld != total vision features %lld", + (long long)patch_in_tokens, + (long long)total_soft_tokens); + return 1; + } + + // Embed using the large prefill bound. The logits-producing forward has + // its own bound below; long prefill cannot be used because it returns + // only its final logits row. + int64_t model_chunk = (*metadata_result)[llm::kMaxSeqLen] - 1; + { + auto gr = module->get("get_max_prefill_chunk"); + if (gr.ok()) { + model_chunk = gr->toScalar().to(); + } + } + const int64_t embed_chunk_sz = + apply_prefill_chunk_override(model_chunk, /*is_vision=*/true); + int64_t forward_chunk_sz = embed_chunk_sz; + if (nll_vision_uses_short_forward) { + int64_t short_forward_bound = 4; + auto gr = module->get("get_block_size"); + if (gr.ok()) { + short_forward_bound = gr->toScalar().to(); + } + forward_chunk_sz = + std::min(forward_chunk_sz, short_forward_bound); + } else if (forward_chunk_sz < 5) { + forward_chunk_sz = 5; + } + + // 1) embed_text over the whole doc (chunked) -> host embeds [T, hidden]. + int64_t hidden = 0; + std::vector embeds_host; + for (int64_t ep = 0; ep < num_tokens; ep += embed_chunk_sz) { + const int64_t elen = std::min(num_tokens - ep, embed_chunk_sz); + std::vector tok_chunk( + tokens.begin() + ep, tokens.begin() + ep + elen); + auto tok_t = from_blob( + tok_chunk.data(), + {1, static_cast(elen)}, + executorch::aten::ScalarType::Long); + auto et_res = module->execute("embed_text", {EValue(tok_t)}); + if (et_res.error() != Error::Ok) { + ET_LOG(Error, "embed_text failed at %lld", (long long)ep); + return 1; + } + const auto& te = et_res.get()[0].toTensor(); + if (te.dim() != 3 || te.size(1) != elen) { + ET_LOG(Error, "embed_text returned unexpected shape"); + return 1; + } + if (hidden == 0) { + hidden = te.size(2); + if (hidden != vision_hidden) { + ET_LOG( + Error, + "text hidden %lld != vision hidden %lld", + (long long)hidden, + (long long)vision_hidden); + return 1; + } + embeds_host.resize(static_cast(num_tokens * hidden)); + } + if (copy_to_host( + te, + embeds_host.data() + ep * hidden, + static_cast(elen * hidden) * sizeof(uint16_t)) != + Error::Ok) { + return 1; + } + } + + // 2) Splice vision features into the <|patch|> runs, in image order. + { + size_t cur_img = 0; + int64_t within = 0; // soft-token offset inside the current image + for (int64_t i = 0; i < num_tokens; ++i) { + if (tokens[i] != llm::kMuseGlimmerImagePatchTokenId) { + if (within != 0) { + if (within != img_counts[cur_img]) { + ET_LOG( + Error, + "patch run for image %zu has %lld tokens, expected %lld", + cur_img, + (long long)within, + (long long)img_counts[cur_img]); + return 1; + } + ++cur_img; + within = 0; + } + continue; + } + if (cur_img >= image_paths.size()) { + ET_LOG(Error, "more <|patch|> runs than images"); + return 1; + } + if (within >= img_counts[cur_img]) { + ET_LOG(Error, "patch run longer than image %zu features", cur_img); + return 1; + } + std::memcpy( + embeds_host.data() + i * hidden, + img_embeds[cur_img].data() + within * hidden, + static_cast(hidden) * sizeof(uint16_t)); + ++within; + } + if (within != 0) { // trailing run at end of sequence + if (within != img_counts[cur_img]) { + ET_LOG(Error, "final patch run mismatch for image %zu", cur_img); + return 1; + } + ++cur_img; + } + if (cur_img != image_paths.size()) { + ET_LOG( + Error, "spliced %zu of %zu images", cur_img, image_paths.size()); + return 1; + } + } + + // 3) Chunked forward on embeds; write per-position next-token log-prob. + std::ofstream out(FLAGS_nll_output_file, std::ios::binary); + if (!out.is_open()) { + ET_LOG( + Error, + "Cannot open --nll_output_file: %s", + FLAGS_nll_output_file.c_str()); + return 1; + } + int64_t pos = 0; + while (pos < num_tokens) { + int64_t clen = std::min(num_tokens - pos, forward_chunk_sz); + const int64_t tail = num_tokens - pos - clen; + if (!nll_vision_uses_short_forward && tail > 0 && tail < 5) { + clen -= (5 - tail); + } + std::vector pos_data(clen); + for (int64_t i = 0; i < clen; ++i) { + pos_data[i] = pos + i; + } + uint16_t* chunk_ptr = embeds_host.data() + pos * hidden; + auto chunk_embeds = from_blob( + chunk_ptr, + {1, static_cast(clen), static_cast(hidden)}, + executorch::aten::ScalarType::BFloat16); + auto pos_t = from_blob( + pos_data.data(), + {static_cast(clen)}, + executorch::aten::ScalarType::Long); + auto res = module->execute( + nll_vision_forward_method, {EValue(chunk_embeds), EValue(pos_t)}); + if (res.error() != Error::Ok) { + ET_LOG(Error, "NLL forward(embeds) failed at %lld", (long long)pos); + return 1; + } + const auto& logits = res.get()[0].toTensor(); + const int64_t vocab_size = logits.size(logits.dim() - 1); + const int64_t logits_rows = logits.size(logits.dim() - 2); + // CUDA outputs use their bounded capacity (four rows) even when the + // logical tail chunk has fewer rows. The valid logits are the leading + // `clen` rows, matching DFlashSession::process_target_outputs(). + if (logits_rows < clen) { + ET_LOG( + Error, + "%s returned only %lld logits rows for a %lld-token NLL chunk", + nll_vision_forward_method.c_str(), + (long long)logits_rows, + (long long)clen); + return 1; + } + std::vector host_logits(static_cast(clen) * vocab_size); + if (copy_to_host( + logits, + host_logits.data(), + static_cast(clen) * vocab_size * sizeof(float)) != + Error::Ok) { + return 1; + } + std::vector lps; + lps.reserve(clen); + for (int64_t r = 0; r < clen; ++r) { + const int64_t g = pos + r; + if (g >= num_tokens - 1) { + break; // last position has no next-token target + } + const float* row = + host_logits.data() + static_cast(r) * vocab_size; + float m = row[0]; + for (int64_t v = 1; v < vocab_size; ++v) { + if (row[v] > m) { + m = row[v]; + } + } + double sum_exp = 0.0; + for (int64_t v = 0; v < vocab_size; ++v) { + sum_exp += std::exp(static_cast(row[v]) - m); + } + const int64_t target = tokens[g + 1]; + const double lp = + static_cast(row[target]) - m - std::log(sum_exp); + lps.push_back(static_cast(lp)); + } + out.write( + reinterpret_cast(lps.data()), + lps.size() * sizeof(float)); + printf( + " nll chunk %lld-%lld done\n", + (long long)pos, + (long long)(pos + clen - 1)); + pos += clen; + } + out.close(); + printf( + "Wrote %lld logprobs to %s\n", + (long long)(num_tokens - 1), + FLAGS_nll_output_file.c_str()); + return 0; + } +#endif // EXECUTORCH_BUILD_CUDA + + if (FLAGS_nll_use_prefill && kSingleMethod) { + ET_LOG( + Error, + "MLX forward returns only last-token logits; " + "--nll_use_prefill requires the CUDA build."); + return 1; + } + + auto S = [](int64_t v) -> SizesType { return static_cast(v); }; + + int64_t max_prefill_chunk = (*metadata_result)[llm::kMaxSeqLen] - 1; + { + auto get_result = module->get("get_max_prefill_chunk"); + if (get_result.ok()) { + max_prefill_chunk = get_result->toScalar().to(); + } + } + max_prefill_chunk = apply_prefill_chunk_override(max_prefill_chunk); + + // Open output file + std::ofstream out(FLAGS_nll_output_file, std::ios::binary); + if (!out.is_open()) { + ET_LOG( + Error, + "Cannot open --nll_output_file: %s", + FLAGS_nll_output_file.c_str()); + return 1; + } + + if (FLAGS_nll_use_prefill) { + // Multi-token prefill: chunked, dump all logits (T, V) per chunk + int64_t pos = 0; + while (pos < num_tokens) { + int64_t chunk_len = std::min(num_tokens - pos, max_prefill_chunk); + const int64_t tail_len = num_tokens - pos - chunk_len; + constexpr int64_t kMinPrefillBucket = 5; + if (tail_len > 0 && tail_len < kMinPrefillBucket) { + chunk_len = + std::max(1, chunk_len - (kMinPrefillBucket - tail_len)); + } + std::string method = method_for(chunk_len); + + std::vector chunk_tokens( + tokens.begin() + pos, tokens.begin() + pos + chunk_len); + std::vector pos_data(chunk_len); + for (int64_t i = 0; i < chunk_len; i++) + pos_data[i] = pos + i; + + auto tok_t = from_blob( + chunk_tokens.data(), + {1, S(chunk_len)}, + executorch::aten::ScalarType::Long); + auto pos_t = from_blob( + pos_data.data(), + {S(chunk_len)}, + executorch::aten::ScalarType::Long); + + std::vector inputs; + inputs.push_back(EValue(tok_t)); + inputs.push_back(EValue(pos_t)); + + auto result = module->execute(method, inputs); + if (result.error() != Error::Ok) { + ET_LOG( + Error, "%s failed at pos %lld", method.c_str(), (long long)pos); + return 1; + } + + const auto& logits = result.get()[0].toTensor(); + int64_t vocab_size = logits.size(logits.dim() - 1); + int64_t total_floats = chunk_len * vocab_size; + std::vector host_logits(total_floats); + const void* src = logits.const_data_ptr(); + +#ifdef EXECUTORCH_BUILD_CUDA + cudaPointerAttributes attrs{}; + bool on_device = cudaPointerGetAttributes(&attrs, src) == cudaSuccess && + attrs.type == cudaMemoryTypeDevice; + if (on_device) { + cudaMemcpy( + host_logits.data(), + src, + total_floats * sizeof(float), + cudaMemcpyDeviceToHost); + } else { + memcpy(host_logits.data(), src, total_floats * sizeof(float)); + } +#else + memcpy(host_logits.data(), src, total_floats * sizeof(float)); +#endif + + out.write( + reinterpret_cast(host_logits.data()), + total_floats * sizeof(float)); + printf( + " prefill chunk %lld-%lld done\n", + (long long)pos, + (long long)(pos + chunk_len - 1)); + pos += chunk_len; + } + } else { + // Single-token loop via decode method + for (int64_t pos = 0; pos < num_tokens; pos++) { + std::vector tok_data = {tokens[pos]}; + std::vector pos_data = {pos}; + + auto tok_t = from_blob( + tok_data.data(), {1, 1}, executorch::aten::ScalarType::Long); + auto pos_t = + from_blob(pos_data.data(), {1}, executorch::aten::ScalarType::Long); + + std::vector inputs; + inputs.push_back(EValue(tok_t)); + inputs.push_back(EValue(pos_t)); + + auto result = module->execute(method_for(1), inputs); + if (result.error() != Error::Ok) { + ET_LOG(Error, "decode failed at pos %lld", (long long)pos); + return 1; + } + + const auto& logits = result.get()[0].toTensor(); + int64_t vocab_size = logits.size(logits.dim() - 1); + std::vector host_logits(vocab_size); + const void* src = logits.const_data_ptr(); + +#ifdef EXECUTORCH_BUILD_CUDA + cudaPointerAttributes attrs{}; + bool on_device = cudaPointerGetAttributes(&attrs, src) == cudaSuccess && + attrs.type == cudaMemoryTypeDevice; + if (on_device) { + cudaMemcpy( + host_logits.data(), + src, + vocab_size * sizeof(float), + cudaMemcpyDeviceToHost); + } else { + memcpy(host_logits.data(), src, vocab_size * sizeof(float)); + } +#else + memcpy(host_logits.data(), src, vocab_size * sizeof(float)); +#endif + + out.write( + reinterpret_cast(host_logits.data()), + vocab_size * sizeof(float)); + + if ((pos + 1) % 100 == 0) { + printf( + " %lld / %lld tokens\n", + (long long)(pos + 1), + (long long)num_tokens); + } + } + } + + out.close(); + printf("Wrote logits to %s\n", FLAGS_nll_output_file.c_str()); + return 0; + } + + // EOS token ids + auto eos_ids = llm::get_eos_ids(tokenizer.get(), module.get()); + eos_ids.insert(static_cast(FLAGS_eos_id)); + + auto S = [](int64_t v) -> SizesType { return static_cast(v); }; + + // Vision: preprocess image on host, run vision_encoder, pull soft-token + // embeddings back to host for splicing. Only when --image_path is set. + int64_t num_soft_tokens = 0; + int64_t vision_hidden = 0; + std::vector image_host; // [N, hidden] bf16 + namespace gv = ::executorch::examples::muse_glimmer_vision; + if (has_image) { + // Positional-embedding table (written next to model.pte by export.py). + std::string pe_path = FLAGS_pos_embed_path; + if (pe_path.empty()) { + auto slash = FLAGS_model_path.find_last_of('/'); + std::string dir = (slash == std::string::npos) + ? "." + : FLAGS_model_path.substr(0, slash); + pe_path = dir + "/pos_embed.bin"; + } + std::vector pos_table; + try { + pos_table = gv::load_pos_embed_table(pe_path); + } catch (const std::exception& e) { + ET_LOG(Error, "Failed to load pos_embed.bin: %s", e.what()); + return 1; + } + + int img_w = 0, img_h = 0, img_c = 0; + unsigned char* img_data = + stbi_load(FLAGS_image_path.c_str(), &img_w, &img_h, &img_c, 3); + if (img_data == nullptr) { + ET_LOG(Error, "Failed to load image: %s", FLAGS_image_path.c_str()); + return 1; + } + gv::VisionInputs vis; + try { + vis = gv::preprocess_image(img_data, img_w, img_h, pos_table); + } catch (const std::exception& e) { + ET_LOG(Error, "preprocess_image failed: %s", e.what()); + stbi_image_free(img_data); + return 1; + } + stbi_image_free(img_data); + + printf( + "Image: %dx%d -> %" PRId64 " patches -> %" PRId64 " soft tokens\n", + img_w, + img_h, + vis.num_patches, + vis.num_soft_tokens); + + std::vector ve_inputs; + ve_inputs.push_back(EValue(vis.patches)); + ve_inputs.push_back(EValue(vis.pos_emb)); + ve_inputs.push_back(EValue(vis.cos_2d)); + ve_inputs.push_back(EValue(vis.sin_2d)); + ve_inputs.push_back(EValue(vis.sparse_perm)); + ve_inputs.push_back(EValue(vis.inv_perm)); + ve_inputs.push_back(EValue(vis.global_mask)); + ve_inputs.push_back(EValue(vis.sparse_mask)); + ve_inputs.push_back(EValue(vis.pixel_perm)); + + auto ve_result = module->execute("vision_encoder", ve_inputs); + if (ve_result.error() != Error::Ok) { + ET_LOG(Error, "vision_encoder failed"); + return 1; + } + const auto& image_embeds = ve_result.get()[0].toTensor(); + if (image_embeds.dim() != 3 || image_embeds.size(0) != 1) { + ET_LOG(Error, "vision_encoder output must be [1, N, hidden]"); + return 1; + } + num_soft_tokens = image_embeds.size(1); + vision_hidden = image_embeds.size(2); + image_host.assign(static_cast(num_soft_tokens * vision_hidden), 0); + if (copy_to_host( + image_embeds, + image_host.data(), + static_cast(num_soft_tokens * vision_hidden) * + sizeof(uint16_t)) != Error::Ok) { + return 1; + } + } + + std::vector prompt_tokens; + if (!FLAGS_prompt_tokens_file.empty()) { + // Pre-tokenized path: read int64 LE token IDs (same format as the nll + // path) and bypass encoding, which is slow for big prompts. + std::ifstream tf(FLAGS_prompt_tokens_file, std::ios::binary); + if (!tf.is_open()) { + ET_LOG( + Error, + "Cannot open --prompt_tokens_file: %s", + FLAGS_prompt_tokens_file.c_str()); + return 1; + } + tf.seekg(0, std::ios::end); + int64_t nbytes = tf.tellg(); + tf.seekg(0, std::ios::beg); + int64_t num_tokens = nbytes / sizeof(int64_t); + std::vector file_tokens(num_tokens); + tf.read(reinterpret_cast(file_tokens.data()), nbytes); + tf.close(); + + prompt_tokens.assign(file_tokens.begin(), file_tokens.end()); + if (!FLAGS_tokens_have_bos) { + prompt_tokens.insert( + prompt_tokens.begin(), static_cast(FLAGS_bos_id)); + } + } else { + // Read prompt from file or flag + std::string prompt_text = FLAGS_prompt; + if (!FLAGS_prompt_file.empty()) { + std::ifstream f(FLAGS_prompt_file); + if (!f.is_open()) { + ET_LOG( + Error, "Failed to open prompt file: %s", FLAGS_prompt_file.c_str()); + return 1; + } + prompt_text = std::string( + (std::istreambuf_iterator(f)), + std::istreambuf_iterator()); + } + + auto tokenized = llm::tokenize_muse_glimmer_prompt( + *tokenizer, + prompt_text, + static_cast(FLAGS_bos_id), + has_image ? std::optional(num_soft_tokens) : std::nullopt); + if (!tokenized.ok()) { + ET_LOG( + Error, + "Failed to tokenize prompt; --image_path requires exactly one " + " marker"); + return 1; + } + prompt_tokens = std::move(*tokenized); + } + + int64_t num_prompt_tokens = static_cast(prompt_tokens.size()); + printf("Prompt tokens: %" PRId64 "\n", num_prompt_tokens); + stats.num_prompt_tokens = num_prompt_tokens; + + stats.inference_start_ms = llm::time_in_ms(); + + // On-device Gumbel sampling: temperature input (0 -> ~greedy via clamp). + // Methods return one sampled token; read_token() copies the 4-byte scalar. + // Unused on the MLX build (kSingleMethod), which samples on the host. + [[maybe_unused]] float temp_val = + FLAGS_temperature <= 0.0 ? 1e-6f : static_cast(FLAGS_temperature); + [[maybe_unused]] auto temp_tensor = + from_blob(&temp_val, {1}, executorch::aten::ScalarType::Float); + + // Prefill (chunked to respect ring-buffer KV cache limit) + int64_t max_prefill_chunk = (*metadata_result)[llm::kMaxSeqLen] - 1; + { + auto get_result = module->get("get_max_prefill_chunk"); + if (get_result.ok()) { + max_prefill_chunk = get_result->toScalar().to(); + } + } + max_prefill_chunk = + apply_prefill_chunk_override(max_prefill_chunk, has_image); + + uint64_t cur_token = 0; + +#ifdef EXECUTORCH_BUILD_CUDA + if (kSingleMethod) { + int64_t prefill_pos = 0; + while (prefill_pos < num_prompt_tokens) { + int64_t chunk_len = + std::min(num_prompt_tokens - prefill_pos, max_prefill_chunk); + if (FLAGS_method == "target_forward") { + chunk_len = std::min(chunk_len, 4); + } + std::vector token_data( + prompt_tokens.begin() + prefill_pos, + prompt_tokens.begin() + prefill_pos + chunk_len); + std::vector pos_data(chunk_len); + for (int64_t i = 0; i < chunk_len; i++) { + pos_data[i] = prefill_pos + i; + } + auto tokens_tensor = from_blob( + token_data.data(), + {1, S(chunk_len)}, + executorch::aten::ScalarType::Long); + auto pos_tensor = from_blob( + pos_data.data(), {S(chunk_len)}, executorch::aten::ScalarType::Long); + + auto result = module->execute( + FLAGS_method, {EValue(tokens_tensor), EValue(pos_tensor)}); + if (result.error() != Error::Ok) { + ET_LOG( + Error, + "%s failed at pos %" PRId64, + FLAGS_method.c_str(), + prefill_pos); + return 1; + } + const auto& logits = result.get()[0].toTensor(); + const int64_t last_pos = + (logits.dim() >= 3) ? logits.size(logits.dim() - 2) - 1 : 0; + cur_token = sample_from_logits(logits, last_pos, FLAGS_temperature); + prefill_pos += chunk_len; + } + } else { + // CUDA path: embed_text -> (splice image rows) -> chunked prefill on + // embeds. Build the full [T, hidden] bf16 embedding on host, splice, then + // chunk. + int64_t hidden_size = 0; + std::vector embeds_host; + for (int64_t ep = 0; ep < num_prompt_tokens; ep += max_prefill_chunk) { + const int64_t elen = std::min(num_prompt_tokens - ep, max_prefill_chunk); + std::vector token_chunk( + prompt_tokens.begin() + ep, prompt_tokens.begin() + ep + elen); + auto tokens_tensor = from_blob( + token_chunk.data(), {1, S(elen)}, executorch::aten::ScalarType::Long); + auto et_result = module->execute("embed_text", {EValue(tokens_tensor)}); + if (et_result.error() != Error::Ok) { + ET_LOG(Error, "embed_text failed at position %" PRId64, ep); + return 1; + } + const auto& text_embeds = et_result.get()[0].toTensor(); + if (text_embeds.dim() != 3 || text_embeds.size(1) != elen) { + ET_LOG(Error, "embed_text returned unexpected shape"); + return 1; + } + if (hidden_size == 0) { + hidden_size = text_embeds.size(2); + embeds_host.resize( + static_cast(num_prompt_tokens * hidden_size)); + } + if (text_embeds.size(2) != hidden_size || + copy_to_host( + text_embeds, + embeds_host.data() + ep * hidden_size, + static_cast(elen * hidden_size) * sizeof(uint16_t)) != + Error::Ok) { + return 1; + } + } + + if (has_image) { + if (vision_hidden != hidden_size) { + ET_LOG( + Error, + "vision hidden %" PRId64 " != text hidden %" PRId64, + vision_hidden, + hidden_size); + return 1; + } + int64_t img_idx = 0; + for (int64_t i = 0; i < num_prompt_tokens; ++i) { + if (prompt_tokens[i] != + static_cast(llm::kMuseGlimmerImagePatchTokenId)) { + continue; + } + if (img_idx >= num_soft_tokens) { + ET_LOG(Error, "more <|patch|> tokens than vision soft tokens"); + return 1; + } + std::memcpy( + embeds_host.data() + i * hidden_size, + image_host.data() + img_idx * hidden_size, + hidden_size * sizeof(uint16_t)); + ++img_idx; + } + if (img_idx != num_soft_tokens) { + ET_LOG( + Error, + "spliced %" PRId64 " of %" PRId64 " vision soft tokens", + img_idx, + num_soft_tokens); + return 1; + } + } + + int64_t prefill_pos = 0; + while (prefill_pos < num_prompt_tokens) { + int64_t chunk_len = + std::min(num_prompt_tokens - prefill_pos, max_prefill_chunk); + std::vector pos_data(chunk_len); + for (int64_t i = 0; i < chunk_len; i++) { + pos_data[i] = prefill_pos + i; + } + auto pos_tensor = from_blob( + pos_data.data(), {S(chunk_len)}, executorch::aten::ScalarType::Long); + // Single-token text chunks can use the faster token `decode` graph; image + // patch rows and multi-token chunks go through `prefill` on the embeds. + const bool is_patch = has_image && + prompt_tokens[prefill_pos] == + static_cast(llm::kMuseGlimmerImagePatchTokenId); + if (chunk_len == 1 && !is_patch) { + int64_t tok_val = static_cast(prompt_tokens[prefill_pos]); + auto tok_t = + from_blob(&tok_val, {1, 1}, executorch::aten::ScalarType::Long); + auto result = module->execute( + "decode", {EValue(tok_t), EValue(pos_tensor), EValue(temp_tensor)}); + if (result.error() != Error::Ok) { + ET_LOG( + Error, + "decode (prefill chunk=1) failed at %" PRId64, + prefill_pos); + return 1; + } + cur_token = read_token(result.get()[0].toTensor()); + } else { + uint16_t* chunk_ptr = embeds_host.data() + prefill_pos * hidden_size; + auto chunk_embeds = from_blob( + chunk_ptr, + {1, S(chunk_len), S(hidden_size)}, + executorch::aten::ScalarType::BFloat16); + auto result = module->execute( + "prefill", + {EValue(chunk_embeds), EValue(pos_tensor), EValue(temp_tensor)}); + if (result.error() != Error::Ok) { + ET_LOG(Error, "prefill failed at %" PRId64, prefill_pos); + return 1; + } + cur_token = read_token(result.get()[0].toTensor()); + } + prefill_pos += chunk_len; + } + } +#elif defined(EXECUTORCH_BUILD_MLX) + // MLX path. Vision-capable .pte: embed_text -> (splice image rows) -> + // chunked prefill on embeds. Text-only .pte: single token-input `forward`. + // Host sampling in both cases. + int64_t prefill_pos = 0; + if (mlx_multimodal) { + int64_t hidden_size = 0; + std::vector embeds_host; + for (int64_t ep = 0; ep < num_prompt_tokens; ep += max_prefill_chunk) { + const int64_t embed_len = + std::min(num_prompt_tokens - ep, max_prefill_chunk); + std::vector embed_tokens( + prompt_tokens.begin() + ep, prompt_tokens.begin() + ep + embed_len); + auto tokens_tensor = from_blob( + embed_tokens.data(), + {1, S(embed_len)}, + executorch::aten::ScalarType::Long); + auto embed_result = + module->execute("embed_text", {EValue(tokens_tensor)}); + if (embed_result.error() != Error::Ok) { + ET_LOG(Error, "embed_text failed at position %" PRId64, ep); + return 1; + } + const auto& text_embeds = embed_result.get()[0].toTensor(); + if (text_embeds.dim() != 3 || text_embeds.size(1) != embed_len) { + ET_LOG(Error, "embed_text returned unexpected shape"); + return 1; + } + if (hidden_size == 0) { + hidden_size = text_embeds.size(2); + embeds_host.resize( + static_cast(num_prompt_tokens * hidden_size)); + } + if (text_embeds.size(2) != hidden_size || + copy_to_host( + text_embeds, + embeds_host.data() + ep * hidden_size, + static_cast(embed_len * hidden_size) * + sizeof(uint16_t)) != Error::Ok) { + return 1; + } + } + + if (has_image) { + if (vision_hidden != hidden_size) { + ET_LOG( + Error, + "vision hidden %" PRId64 " != text hidden %" PRId64, + vision_hidden, + hidden_size); + return 1; + } + int64_t img_idx = 0; + for (int64_t i = 0; i < num_prompt_tokens; ++i) { + if (prompt_tokens[i] != + static_cast(llm::kMuseGlimmerImagePatchTokenId)) { + continue; + } + if (img_idx >= num_soft_tokens) { + ET_LOG(Error, "more <|patch|> tokens than vision soft tokens"); + return 1; + } + std::memcpy( + embeds_host.data() + i * hidden_size, + image_host.data() + img_idx * hidden_size, + hidden_size * sizeof(uint16_t)); + ++img_idx; + } + if (img_idx != num_soft_tokens) { + ET_LOG( + Error, + "spliced %" PRId64 " of %" PRId64 " vision soft tokens", + img_idx, + num_soft_tokens); + return 1; + } + } + + while (prefill_pos < num_prompt_tokens) { + int64_t chunk_len = + std::min(num_prompt_tokens - prefill_pos, max_prefill_chunk); + std::vector pos_data(chunk_len); + for (int64_t i = 0; i < chunk_len; i++) { + pos_data[i] = prefill_pos + i; + } + auto pos_tensor = from_blob( + pos_data.data(), {S(chunk_len)}, executorch::aten::ScalarType::Long); + uint16_t* chunk_ptr = embeds_host.data() + prefill_pos * hidden_size; + auto chunk_embeds = from_blob( + chunk_ptr, {1, S(chunk_len), S(hidden_size)}, activation_dtype); + auto result = module->execute( + vision_method, {EValue(chunk_embeds), EValue(pos_tensor)}); + if (result.error() != Error::Ok) { + ET_LOG( + Error, "%s failed at %" PRId64, vision_method.c_str(), prefill_pos); + return 1; + } + // `prefill` returns last-token logits [1,1,V]; a DFlash + // `target_forward_from_embeddings` returns full [1,T,V] (with hidden at + // output[1], ignored). Sampling the last row is correct for both. + const auto& vlogits = result.get()[0].toTensor(); + const int64_t vlast = + vlogits.dim() >= 2 ? vlogits.size(vlogits.dim() - 2) - 1 : 0; + cur_token = sample_from_logits(vlogits, vlast, FLAGS_temperature); + prefill_pos += chunk_len; + } + } else { + while (prefill_pos < num_prompt_tokens) { + int64_t chunk_len = + std::min(num_prompt_tokens - prefill_pos, max_prefill_chunk); + std::vector token_data( + prompt_tokens.begin() + prefill_pos, + prompt_tokens.begin() + prefill_pos + chunk_len); + std::vector pos_data(chunk_len); + for (int64_t i = 0; i < chunk_len; i++) { + pos_data[i] = prefill_pos + i; + } + auto tokens_tensor = from_blob( + token_data.data(), + {1, S(chunk_len)}, + executorch::aten::ScalarType::Long); + auto pos_tensor = from_blob( + pos_data.data(), {S(chunk_len)}, executorch::aten::ScalarType::Long); + + auto result = module->execute( + FLAGS_method, {EValue(tokens_tensor), EValue(pos_tensor)}); + if (result.error() != Error::Ok) { + ET_LOG( + Error, + "%s failed at pos %" PRId64, + FLAGS_method.c_str(), + prefill_pos); + return 1; + } + const auto& logits = result.get()[0].toTensor(); + const int64_t last_pos = + logits.dim() >= 3 ? logits.size(logits.dim() - 2) - 1 : 0; + cur_token = sample_from_logits(logits, last_pos, FLAGS_temperature); + prefill_pos += chunk_len; + } + } +#endif // EXECUTORCH_BUILD_CUDA + + stats.prompt_eval_end_ms = llm::time_in_ms(); + double prefill_ms = + static_cast(stats.prompt_eval_end_ms - stats.inference_start_ms); + printf( + "Prefill: %" PRId64 " tokens in %.1f ms (%.1f tok/s)\n", + num_prompt_tokens, + prefill_ms, + num_prompt_tokens * 1000.0 / prefill_ms); + +#ifdef EXECUTORCH_BUILD_CUDA + cudaDeviceSynchronize(); +#endif + + // Decode loop + int64_t pos = num_prompt_tokens; + std::vector decode_token_data = {static_cast(cur_token)}; + std::vector decode_pos_data = {pos}; + auto decode_tokens = from_blob( + decode_token_data.data(), {1, 1}, executorch::aten::ScalarType::Long); + auto decode_pos = from_blob( + decode_pos_data.data(), {1}, executorch::aten::ScalarType::Long); + + uint64_t prev_token = cur_token; + std::vector generated_tokens; + if (!FLAGS_generated_tokens_file.empty() && FLAGS_max_new_tokens > 0) { + generated_tokens.reserve(FLAGS_max_new_tokens); + generated_tokens.push_back(static_cast(cur_token)); + } + for (int32_t step = 0; step < FLAGS_max_new_tokens; step++) { + decode_token_data[0] = static_cast(cur_token); + decode_pos_data[0] = pos; + +#ifdef EXECUTORCH_BUILD_CUDA + // CUDA: token-input `decode`, on-device sampling. + std::vector decode_inputs; + decode_inputs.push_back(EValue(decode_tokens)); + decode_inputs.push_back(EValue(decode_pos)); + decode_inputs.push_back(EValue(temp_tensor)); + auto decode_result = module->execute("decode", decode_inputs); + if (decode_result.error() != Error::Ok) { + ET_LOG(Error, "Decode step %d failed", step); + return 1; + } + prev_token = cur_token; + cur_token = read_token(decode_result.get()[0].toTensor()); +#elif defined(EXECUTORCH_BUILD_MLX) + prev_token = cur_token; + if (mlx_multimodal) { + // MLX vision contract: decode = embed_text(token) -> prefill(embeds), + // host sampling (prefill is the single KV-writing method). + auto embed_result = + module->execute("embed_text", {EValue(decode_tokens)}); + if (embed_result.error() != Error::Ok) { + ET_LOG(Error, "embed_text failed at decode step %d", step); + return 1; + } + auto decode_embed = embed_result.get()[0].toTensor(); + if (decode_embed.dim() != 3 || decode_embed.size(0) != 1 || + decode_embed.size(1) != 1) { + ET_LOG(Error, "embed_text returned unexpected decode shape"); + return 1; + } + auto decode_result = module->execute( + vision_method, {EValue(decode_embed), EValue(decode_pos)}); + if (decode_result.error() != Error::Ok) { + ET_LOG(Error, "Decode step %d failed", step); + return 1; + } + const auto& vlogits = decode_result.get()[0].toTensor(); + const int64_t vlast = + vlogits.dim() >= 2 ? vlogits.size(vlogits.dim() - 2) - 1 : 0; + cur_token = sample_from_logits(vlogits, vlast, FLAGS_temperature); + } else { + // MLX text contract: token-input `forward` (or `--method`), host + // sampling. + auto decode_result = module->execute( + FLAGS_method, {EValue(decode_tokens), EValue(decode_pos)}); + if (decode_result.error() != Error::Ok) { + ET_LOG(Error, "Decode step %d failed", step); + return 1; + } + cur_token = sample_from_logits( + decode_result.get()[0].toTensor(), 0, FLAGS_temperature); + } +#endif + + if (step == 0) { + stats.first_token_ms = llm::time_in_ms(); + } + pos++; + if (!FLAGS_generated_tokens_file.empty() && + generated_tokens.size() < static_cast(FLAGS_max_new_tokens)) { + generated_tokens.push_back(static_cast(cur_token)); + } + + auto decode_str = tokenizer->decode(prev_token, cur_token); + if (decode_str.ok()) { + printf("%s", decode_str->c_str()); + fflush(stdout); + } + + if (!FLAGS_ignore_eos && eos_ids.find(cur_token) != eos_ids.end()) { + printf("\n"); + break; + } + } + + stats.inference_end_ms = llm::time_in_ms(); + printf("\n"); + + const int64_t num_generated = pos - num_prompt_tokens; + stats.num_generated_tokens = num_generated; + if (FLAGS_ignore_eos && num_generated != FLAGS_max_new_tokens) { + ET_LOG( + Error, + "Exact-output mode emitted %" PRId64 " tokens, expected %d", + num_generated, + FLAGS_max_new_tokens); + return 1; + } + if (!FLAGS_generated_tokens_file.empty()) { + if (generated_tokens.size() != static_cast(FLAGS_max_new_tokens)) { + ET_LOG(Error, "Failed to capture the requested logical continuation"); + return 1; + } + std::ofstream out(FLAGS_generated_tokens_file, std::ios::binary); + out.write( + reinterpret_cast(generated_tokens.data()), + generated_tokens.size() * sizeof(int64_t)); + if (!out) { + ET_LOG(Error, "Failed to write --generated_tokens_file"); + return 1; + } + } + double decode_ms = + static_cast(stats.inference_end_ms - stats.prompt_eval_end_ms); + printf( + "Decode: %" PRId64 " tokens in %.1f ms (%.1f tok/s)\n", + num_generated, + decode_ms, + num_generated * 1000.0 / decode_ms); + printf("Prompt tokens: %" PRId64 "\n", num_prompt_tokens); + +#ifdef EXECUTORCH_BUILD_CUDA + cudaMemGetInfo(&gpu_free_bytes, &gpu_total_bytes); + stats.gpu_free_after_generate_bytes = gpu_free_bytes; + stats.gpu_peak_usage_mb = + (stats.gpu_total_bytes - gpu_free_bytes) / 1024.0 / 1024.0; +#endif + + llm::print_report(stats); + return 0; +} diff --git a/examples/models/muse-glimmer/serving/__init__.py b/examples/models/muse-glimmer/serving/__init__.py new file mode 100644 index 00000000000..2e41cd717f6 --- /dev/null +++ b/examples/models/muse-glimmer/serving/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. diff --git a/examples/models/muse-glimmer/serving/serve.py b/examples/models/muse-glimmer/serving/serve.py new file mode 100644 index 00000000000..c944e280ee5 --- /dev/null +++ b/examples/models/muse-glimmer/serving/serve.py @@ -0,0 +1,507 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""OpenAI-compatible HTTP server for Muse Glimmer. + +The Python control plane drives ``muse_glimmer_worker`` over JSONL. +""" + +import argparse +import base64 +import logging +import os +import re +from pathlib import Path + +from executorch.examples.llm_server.python.chat_template import ChatTemplate +from executorch.examples.llm_server.python.errors import ( + APIError, + ContextLengthExceeded, + ModelNotFound, +) +from executorch.examples.llm_server.python.protocol import ChatCompletionRequest +from executorch.examples.llm_server.python.server import build_app +from executorch.examples.llm_server.python.serving_chat import ServingChat +from executorch.examples.llm_server.python.session_runtime import ( + PromptInput, + SessionRuntime, +) +from executorch.examples.llm_server.python.worker_client import spawn_worker +from executorch.examples.models.muse_glimmer.serving.tool_parsers import ( + AtemToolCallDetector, +) + +logger = logging.getLogger(__name__) + +# The template ends at this prefix; the model emits the recipient and message +# delimiter. +_ASSISTANT_HEADER = "<|start|>assistant" +_DEFAULT_MAX_IMAGE_BYTES = 20 * 1024 * 1024 +_IMAGE_ERROR_CODE = "invalid_image" +_IMAGE_PLACEHOLDER = "\x00muse_glimmer_image_placeholder\x00" +_IMAGE_DATA_URL_RE = re.compile( + r"\Adata:(image/(?:jpeg|png));base64,([A-Za-z0-9+/]*={0,2})\Z" +) + +# Harmony recipient headers may recur within one assistant turn. Treat their +# delimiters as content, then strip every header before returning visible text. +# The optional leading space handles text already trimmed by the tool parser; +# the lookbehind avoids matching prose such as "goto=". +_MUSE_GLIMMER_HEADER_SPECIALS = {"<|start|>", "<|message|>", "<|eom|>"} +_MUSE_GLIMMER_IDENT = r"[a-zA-Z_][a-zA-Z0-9_-]*" +_MUSE_GLIMMER_RECIPIENT = rf"{_MUSE_GLIMMER_IDENT}(?:\.{_MUSE_GLIMMER_IDENT})*" +_MUSE_GLIMMER_HEADER_RE = re.compile( + rf"(?assistant)?" + rf"\s?to={_MUSE_GLIMMER_RECIPIENT}" + rf"(?: constrain={_MUSE_GLIMMER_IDENT})?" + rf"<\|message\|>" +) +_MUSE_GLIMMER_ADDRESSED_HEADER_RE = re.compile( + rf"(?assistant)?" + rf"\s?to=({_MUSE_GLIMMER_RECIPIENT})" + rf"(?: constrain={_MUSE_GLIMMER_IDENT})?" + rf"<\|message\|>" +) +# Remove control tokens left without a complete recipient header. +_MUSE_GLIMMER_STRAY_SPECIAL_RE = re.compile( + r"<\|(?:start|message|channel|constrain|end|eom|eot)\|>" +) + + +def _strip_muse_glimmer_header(text: str) -> str: + text = _MUSE_GLIMMER_HEADER_RE.sub("", text) + text = _MUSE_GLIMMER_STRAY_SPECIAL_RE.sub("", text) + return text.strip() + + +def _extract_muse_glimmer_reasoning(text: str) -> tuple[str | None, str]: + """Split a Harmony turn into private `to=self` and remaining messages.""" + matches = list(_MUSE_GLIMMER_ADDRESSED_HEADER_RE.finditer(text)) + if not matches: + return None, text + + reasoning: list[str] = [] + visible: list[str] = [] + prefix = text[: matches[0].start()].strip() + if prefix: + visible.append(prefix) + + for index, match in enumerate(matches): + end = matches[index + 1].start() if index + 1 < len(matches) else len(text) + body = text[match.end() : end] + body = re.sub(r"(?:<\|eom\|>|<\|eot\|>)\s*$", "", body).strip() + if not body: + continue + if match.group(1) == "self": + reasoning.append(body) + else: + visible.append(body) + + return "\n\n".join(reasoning) or None, "\n\n".join(visible) + + +def _repo_root() -> Path: + starts = [Path(__file__).resolve(), Path(__file__).absolute(), Path.cwd().resolve()] + seen: set[Path] = set() + for start in starts: + cur = start if start.is_dir() else start.parent + for path in (cur, *cur.parents): + if path in seen: + continue + seen.add(path) + if (path / "CMakeLists.txt").exists() and ( + path / "examples" / "models" / "fb" / "muse_glimmer" + ).is_dir(): + return path + raise RuntimeError( + "Could not locate the ExecuTorch source checkout; pass --worker-bin " + "explicitly." + ) + + +def _default_worker_bin() -> str: + return str( + _repo_root() + / "cmake-out" + / "examples" + / "models" + / "fb" + / "muse_glimmer" + / "muse_glimmer_worker" + ) + + +def _invalid_image(message: str) -> APIError: + return APIError(400, message, "invalid_request_error", _IMAGE_ERROR_CODE) + + +def _normalize_image_request( # noqa: C901 + req: ChatCompletionRequest, max_image_bytes: int +) -> tuple[ChatCompletionRequest, dict | None]: + """Clone the request, replace its image with a marker, and return its payload.""" + normalized = req.model_copy(deep=True) + image_segment = None + + for message in normalized.messages: + if not isinstance(message.content, list): + continue + text_parts = [] + for part in message.content: + if part.get("type") != "image_url" and "image_url" not in part: + if part.get("type") == "text": + text_parts.append(str(part.get("text", ""))) + continue + if image_segment is not None: + raise _invalid_image( + "Only one image_url part is supported per request." + ) + if set(part) != {"type", "image_url"} or part.get("type") != "image_url": + raise _invalid_image( + "image_url parts must contain only type and image_url." + ) + image_url = part.get("image_url") + if not isinstance(image_url, dict) or set(image_url) != {"url"}: + raise _invalid_image("image_url must be an object containing only url.") + url = image_url.get("url") + if not isinstance(url, str): + raise _invalid_image("image_url.url must be a data URL string.") + match = _IMAGE_DATA_URL_RE.fullmatch(url) + if match is None: + raise _invalid_image( + "image_url.url must be a base64 JPEG or PNG data URL." + ) + mime_type, data = match.groups() + if not data: + raise _invalid_image("Image data must not be empty.") + try: + decoded = base64.b64decode(data, validate=True) + except ValueError as error: + raise _invalid_image("Image data is not valid base64.") from error + if not decoded: + raise _invalid_image("Image data must not be empty.") + if len(decoded) > max_image_bytes: + raise _invalid_image( + f"Decoded image exceeds the {max_image_bytes}-byte limit." + ) + image_segment = { + "image": { + "encoding": "base64", + "mime_type": mime_type, + "data": data, + } + } + text_parts.append(_IMAGE_PLACEHOLDER) + # Muse Glimmer's HF template expects string content rather than OpenAI's + # structured content-part list. The marker preserves the image's position + # until the rendered Harmony prompt is split into worker segments. + message.content = "".join(text_parts) + + return normalized, image_segment + + +class MuseGlimmerServingChat(ServingChat): + def __init__( + self, *args, max_image_bytes: int = _DEFAULT_MAX_IMAGE_BYTES, **kwargs + ): + super().__init__(*args, **kwargs) + self._max_image_bytes = max_image_bytes + + @staticmethod + def _with_image(prompt: PromptInput, image_segment: dict | None) -> PromptInput: + if image_segment is None: + return prompt + segments = ( + [{"text": prompt.text}] + if prompt.text is not None + else list(prompt.segments or []) + ) + output = [] + found = False + for segment in segments: + text = segment.get("text") + if not isinstance(text, str) or _IMAGE_PLACEHOLDER not in text: + output.append(segment) + continue + if found or text.count(_IMAGE_PLACEHOLDER) != 1: + raise RuntimeError( + "rendered prompt must contain exactly one image marker" + ) + before, after = text.split(_IMAGE_PLACEHOLDER) + if before: + output.append({"text": before}) + output.append(image_segment) + if after: + output.append({"text": after}) + found = True + if not found: + raise RuntimeError("rendered prompt is missing its image marker") + return PromptInput(segments=output) + + def _count_prompt_tokens(self, prompt: PromptInput) -> int | None: + if prompt.text is not None: + return super()._count_prompt_tokens(prompt) + text_segments = [ + segment for segment in prompt.segments or [] if "image" not in segment + ] + if not text_segments: + return self._prompt_token_offset + return super()._count_prompt_tokens(PromptInput(segments=text_segments)) + + async def create(self, req: ChatCompletionRequest): + # This intentionally tracks ServingChat.create closely. The generic class + # has no prompt-segment hook, while all response work remains inherited. + if req.model is not None and req.model != self._model_id: + raise ModelNotFound(req.model, self._model_id) + self._reject_invalid_values(req) + self._reject_unsupported_params(req) + if req.session_id is not None: + self._validate_session_id(req.session_id) + + req, image_segment = _normalize_image_request(req, self._max_image_bytes) + template_tools = None if req.tool_choice == "none" else req.tools + template_kwargs = dict(req.chat_template_kwargs or {}) + template_kwargs.pop("return_reasoning", None) + prompt = self._template.render( + req.messages, tools=template_tools, template_kwargs=template_kwargs + ) + prompt_input = self._transcript.build_prompt_input( + session_id=req.session_id, + messages=req.messages, + rendered_prompt=prompt, + tools=template_tools, + template_kwargs=template_kwargs, + ) + prompt_input = self._with_image(prompt_input, image_segment) + if self._max_context: + count = self._count_prompt_tokens(prompt_input) + if count is not None: + if count >= self._max_context: + raise ContextLengthExceeded(count, self._max_context) + requested = req.resolved_max_tokens() + if requested > 0 and count + requested > self._max_context: + raise ContextLengthExceeded(count, self._max_context, requested) + + if self._tools_active(req): + gen_stops = self._stops + self._request_stops(req) + else: + gen_stops = self._stops + self._content_specials + self._request_stops(req) + options = self._options(req, gen_stops) + preamble = self._template.generation_preamble( + template_kwargs, tools=template_tools + ) + if req.session_id is not None: + await self._preflight_session(req.session_id) + if req.stream: + return self._stream(req, prompt_input, options, preamble, gen_stops) + return await self._complete(req, prompt_input, options, preamble, gen_stops) + + +def _spawn(args): + env = dict(os.environ) + conda = os.environ.get("CONDA_PREFIX") + if conda: + existing = env.get("LD_LIBRARY_PATH", "") + env["LD_LIBRARY_PATH"] = ( + f"{conda}/lib:{existing}" if existing else f"{conda}/lib" + ) + worker_bin = args.worker_bin or _default_worker_bin() + cmd = [ + worker_bin, + "--model_path", + args.model_path, + "--tokenizer_path", + args.tokenizer_path, + "--max_sessions", + str(args.max_sessions), + f"--warm_resume={'true' if args.warm_resume else 'false'}", + "--bos_id", + str(args.bos_id), + "--eos_id", + str(args.eos_id), + "--artifact_mode", + args.artifact_mode, + "--dflash_block_length", + str(args.dflash_block_length), + "--dflash_n_draft", + str(args.dflash_n_draft), + f"--dflash_draft_argmax={'true' if args.dflash_draft_argmax else 'false'}", + f"--cuda_graph={'true' if args.cuda_graph else 'false'}", + ] + if args.data_path: + cmd += ["--data_path", args.data_path] + cmd += ["--max_image_bytes", str(args.max_image_bytes)] + if args.pos_embed_path: + cmd += ["--pos_embed_path", args.pos_embed_path] + logger.info("Starting Muse Glimmer worker subprocess (loads the model once).") + return spawn_worker(cmd, env=env) + + +def _tool_detector(name: str): + if name == "none": + return None + if name == "atem": + # The Hugging Face chat template supplies the ATEM tool definitions. + return AtemToolCallDetector + raise ValueError(f"unknown tool parser: {name}") + + +def build_app_from_args(args): + template = ChatTemplate( + args.hf_tokenizer, + assistant_header=_ASSISTANT_HEADER, + strip_rendered_bos=True, + append_generation_prompt_after_tool_response=True, + ) + worker = _spawn(args) + runtime = SessionRuntime(worker) + serving = MuseGlimmerServingChat( + runtime, + template, + args.model_id, + max_context=args.max_context, + max_image_bytes=args.max_image_bytes, + tool_detector_cls=_tool_detector(args.tool_parser), + # The worker prepends the numeric BOS the HF template renders as text and + # serve.py strips (strip_rendered_bos), so token counts include it. + prompt_token_offset=1, + content_filter=_strip_muse_glimmer_header, + content_filter_specials=_MUSE_GLIMMER_HEADER_SPECIALS, + reasoning_extractor=_extract_muse_glimmer_reasoning, + ) + app = build_app(serving, args.model_id) + + @app.on_event("shutdown") + def _stop_worker(): + runtime.close_worker() + + return app, args.model_id + + +def main() -> None: + p = argparse.ArgumentParser( + description="OpenAI-compatible LLM server for Muse Glimmer" + ) + p.add_argument("--model-path", required=True, help="Path to the .pte model") + p.add_argument("--data-path", default=None, help="Path to the delegate blob (.ptd)") + p.add_argument( + "--pos-embed-path", + default=None, + help="Optional path to precomputed image position embeddings.", + ) + p.add_argument( + "--max-image-bytes", + type=int, + default=_DEFAULT_MAX_IMAGE_BYTES, + help="Maximum decoded inline image size forwarded to the worker.", + ) + p.add_argument( + "--tokenizer-path", + required=True, + help="Path to the Hugging Face tokenizer.json", + ) + p.add_argument( + "--hf-tokenizer", + required=True, + help="HF tokenizer id/dir for the model's chat template", + ) + p.add_argument("--model-id", default="muse_glimmer") + p.add_argument("--host", default="127.0.0.1") + p.add_argument("--port", type=int, default=8000) + p.add_argument( + "--max-context", + type=int, + default=None, + help="Context window; prompts exceeding it are rejected with 400.", + ) + p.add_argument( + "--num-runners", + type=int, + default=1, + help="Worker processes. 1 only; more would duplicate the weights.", + ) + p.add_argument( + "--max-sessions", + type=int, + default=1, + help="Physical sessions the worker can host on one weight load. One slot " + "is reserved for anonymous requests, so addressable named sessions are " + "max-sessions - 1.", + ) + p.add_argument( + "--warm-resume", + action=argparse.BooleanOptionalAction, + default=True, + help="Warm append-only resume for named sessions when available.", + ) + p.add_argument( + "--tool-parser", + choices=("atem", "none"), + default="none", + help="Tool-call format parser to apply to model output. 'atem' parses the " + "Muse Glimmer `to=NAME<|message|>...` format " + "into OpenAI tool_calls.", + ) + p.add_argument( + "--bos-id", + type=int, + default=200000, + help="BOS token id to prepend in the worker. The launcher strips the HF " + "template's literal BOS before C++ tokenization.", + ) + p.add_argument("--eos-id", type=int, default=200001) + p.add_argument( + "--artifact-mode", + choices=("auto", "autoregressive", "dflash"), + default="auto", + help="Worker artifact mode. Auto detects the exported method contract.", + ) + p.add_argument( + "--dflash-block-length", + type=int, + default=4, + help="DFlash block length; zero uses the artifact's exported maximum.", + ) + p.add_argument( + "--dflash-n-draft", + type=int, + default=3, + help="DFlash candidates per iteration; zero uses block_length - 1.", + ) + p.add_argument( + "--dflash-draft-argmax", + action=argparse.BooleanOptionalAction, + default=True, + help="Use exact deterministic argmax proposals for stochastic DFlash drafting.", + ) + p.add_argument( + "--cuda-graph", + action=argparse.BooleanOptionalAction, + default=False, + help="Capture CUDA graphs for supported methods. This disables CUDA " + "multi-session state rebinding (default: off).", + ) + p.add_argument( + "--worker-bin", + default=None, + help="Path to muse_glimmer_worker. Defaults to the CMake output path.", + ) + args = p.parse_args() + logging.basicConfig(level=logging.INFO) + + if args.num_runners != 1: + p.error("Only 1 worker process is supported; more would duplicate weights.") + + app, _ = build_app_from_args(args) + + import uvicorn + + uvicorn.run(app, host=args.host, port=args.port) + + +if __name__ == "__main__": + main() diff --git a/examples/models/muse-glimmer/serving/tool_parsers/__init__.py b/examples/models/muse-glimmer/serving/tool_parsers/__init__.py new file mode 100644 index 00000000000..bfb875a282c --- /dev/null +++ b/examples/models/muse-glimmer/serving/tool_parsers/__init__.py @@ -0,0 +1,11 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +from .atem import AtemToolCallDetector + +__all__ = [ + "AtemToolCallDetector", +] diff --git a/examples/models/muse-glimmer/serving/tool_parsers/atem.py b/examples/models/muse-glimmer/serving/tool_parsers/atem.py new file mode 100644 index 00000000000..76daa0fef8f --- /dev/null +++ b/examples/models/muse-glimmer/serving/tool_parsers/atem.py @@ -0,0 +1,185 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""Parse Muse Glimmer ATEM text into OpenAI-compatible tool calls. + +Blocks may contain multiple invocations. Parameters are coerced using the +declared tool schema. Malformed blocks are hidden, while calls to undefined +tools remain visible text. +""" + +import json +import logging +import math +import re +from typing import Any, Optional + +from executorch.examples.llm_server.python.tool_parsers.types import ( + ParseResult, + ToolCallItem, +) + +logger = logging.getLogger(__name__) + +_START = "<|start|>" +_MESSAGE = "<|message|>" +_FUNCTION_CALLS_OPEN = "" +_INVOKE_OPEN = "(.*?)\s*' + r"(?=||\Z)", + re.DOTALL, +) +_PARAMETER_RE = re.compile( + r'(.*?)\s*' + r"(?=|\Z)", + re.DOTALL, +) + +# Match the optional assistant prefix and recipient header before an ATEM block. +_IDENT = r"[a-zA-Z_][a-zA-Z0-9_-]*" +_RECIPIENT = rf"{_IDENT}(?:\.{_IDENT})*" +_HEADER_RE = re.compile( + rf"(?:{re.escape(_START)}assistant)?" + rf" to={_RECIPIENT}" + rf"(?: constrain={_IDENT})?" + rf"{re.escape(_MESSAGE)}" +) + +_INT_RE = re.compile(r"[+-]?[0-9]+$") +_NUM_RE = re.compile(r"[+-]?(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][+-]?[0-9]+)?$") + + +class _UndefinedToolCall(Exception): + """Raised when a call names a tool absent from the request.""" + + +def _coerce(value: str, declared_type: Optional[str]) -> Any: + """Coerce a raw parameter using its declared JSON-schema type. + + Failed declared conversions remain strings. Untyped values use JSON parsing, + and non-finite numbers remain strings so serialized arguments stay valid. + """ + v = value.strip() + if declared_type == "string": + return value + if declared_type == "boolean": + low = v.lower() + if low == "true": + return True + if low == "false": + return False + return value # not a valid bool literal -> keep raw, don't mistype + if declared_type == "integer": + # strict: digits only (no float, no underscores) + return int(v) if _INT_RE.match(v) else value + if declared_type == "number": + if _NUM_RE.match(v): + f = float(v) + if math.isfinite(f): + return f + return value # non-numeric / non-finite -> keep raw, never emit NaN/Inf + # Unknown/absent declared type (also array/object): a JSON guess, but reject + # non-finite (json.loads parses NaN/Infinity by default, which json.dumps + # would then re-emit). + try: + guess = json.loads(v) + except (ValueError, TypeError): + return value + if isinstance(guess, float) and not math.isfinite(guess): + return value + return guess + + +class AtemToolCallDetector: + """Parse one request's Muse Glimmer ATEM tool calls.""" + + # The block open is the unambiguous trigger. serving_chat only reads + # ``bot_token`` for presence checks / leading-text cut points, so the ATEM + # block opener is the right marker here. + bot_token = _FUNCTION_CALLS_OPEN + + def __init__(self): + self._next_index = 0 + + def detect_and_parse(self, text: str, tools: dict[str, dict]) -> ParseResult: + """Return leading text + any complete tool calls. + + Missing markers preserve the text. Truncated or malformed blocks are + removed from the first marker; undefined tools preserve the full text. + ``tools`` maps tool names to their parameter schemas. + """ + first = _INVOKE_RE.search(text) + if first is None: + # No complete call. If a tool marker is present the call was + # truncated/partial -> strip it; otherwise there is no tool intent. + markers = [ + i + for i in (text.find(self.bot_token), text.find(_INVOKE_OPEN)) + if i != -1 + ] + if markers: + return ParseResult(normal_text=text[: min(markers)].strip()) + return ParseResult(normal_text=text) + # Leading text ends at the block open if present, else at the first + # ; a harmony "to=NAME<|message|>" header that immediately + # precedes it is excluded so the header does not leak into content. + block = text.find(self.bot_token) + cut = block if (block != -1 and block <= first.start()) else first.start() + header = self._preceding_header(text, cut) + if header is not None: + cut = header + normal = text[:cut].strip() + try: + calls = self._parse_calls(text, tools) + except _UndefinedToolCall as e: + logger.debug("undefined tool %s; returning raw text (no partial calls)", e) + return ParseResult(normal_text=text) + except Exception as e: # noqa: BLE001 - never crash + logger.debug("malformed ATEM tool call (%s); degrading to leading text", e) + return ParseResult(normal_text=normal) + if not calls: + return ParseResult(normal_text=text) + return ParseResult(normal_text=normal, calls=calls) + + @staticmethod + def _preceding_header(text: str, cut: int) -> Optional[int]: + """Return the start of a recipient header adjacent to ``cut``.""" + last: Optional[int] = None + for m in _HEADER_RE.finditer(text): + if m.end() <= cut and text[m.end() : cut].strip() == "": + last = m.start() + return last + + def _parse_calls(self, text: str, tools: dict[str, dict]) -> list[ToolCallItem]: + """Parse every invocation and coerce its parameters.""" + calls = [] + for im in _INVOKE_RE.finditer(text): + name, body = im.group(1), im.group(2) + props = (tools.get(name) or {}).get("properties", {}) + args = {} + for pm in _PARAMETER_RE.finditer(body): + key = pm.group(1) + args[key] = _coerce(pm.group(2), props.get(key, {}).get("type")) + calls.append(self._make_item(name, args, tools)) + return calls + + def _make_item( + self, name: Optional[str], arguments: dict, tools: dict[str, dict] + ) -> ToolCallItem: + if not name or name not in tools: + raise _UndefinedToolCall(repr(name)) + item = ToolCallItem( + tool_index=self._next_index, + name=name, + # Reject non-finite values that escaped coercion. + arguments=json.dumps(arguments, ensure_ascii=False, allow_nan=False), + ) + self._next_index += 1 + return item diff --git a/examples/models/muse-glimmer/source_transformations/__init__.py b/examples/models/muse-glimmer/source_transformations/__init__.py new file mode 100644 index 00000000000..2e41cd717f6 --- /dev/null +++ b/examples/models/muse-glimmer/source_transformations/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. diff --git a/examples/models/muse-glimmer/source_transformations/cuda.py b/examples/models/muse-glimmer/source_transformations/cuda.py new file mode 100644 index 00000000000..68045c654a4 --- /dev/null +++ b/examples/models/muse-glimmer/source_transformations/cuda.py @@ -0,0 +1,930 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""CUDA source transformations for Muse Glimmer. + +Global NoPE layers use length-bounded Triton attention, optionally with a +TurboQuant KV cache. Sliding-window RoPE layers retain their ring buffers. +""" + +from __future__ import annotations + +import types + +# Register the length-aware global-attention operator. +import executorch.backends.cuda.triton.kernels.sdpa # noqa: F401 + +# Register the TurboQuant attention operator. +import executorch.backends.cuda.triton.kernels.tq4_sdpa # noqa: F401 + +import torch +import torch.nn as nn +import torch.nn.functional as F +import triton +import triton.language as tl + +from executorch.examples.models.muse_glimmer.model.dflash_model import ( + build_dflash_swa_mask, + rotate_half, +) +from executorch.examples.models.muse_glimmer.model.model import FlatKVCache, RingKVCache +from executorch.examples.models.muse_glimmer.source_transformations.sampler import ( + sample, +) +from executorch.extension.llm.modules.turboquant import TurboQuantKVCache +from torch.library import triton_op, wrap_triton + + +def add_dflash_hidden_tapping(model: nn.Module, target_layer_ids: list[int]) -> None: + """Make a CUDA Muse Glimmer target return logits and DFlash tapped hidden states.""" + target_set = set(target_layer_ids) + model._dflash_target_layer_ids = target_layer_ids + + def _run_embeddings_with_hidden( + self, x: torch.Tensor, input_pos: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor]: + sliding_mask, global_mask = self._build_masks(input_pos) + tapped = [] + for i, layer in enumerate(self.layers): + if i in target_set: + tapped.append(x) + x = layer(x, input_pos, sliding_mask, global_mask) + + return self.output_norm(x), torch.cat(tapped, dim=-1) + + def _run_with_hidden( + self, tokens: torch.Tensor, input_pos: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor]: + return _run_embeddings_with_hidden(self, self.embed_text(tokens), input_pos) + + def _forward_with_hidden( + self, tokens: torch.Tensor, input_pos: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor]: + x, tapped = _run_with_hidden(self, tokens, input_pos) + return self._soft_cap(self.lm_head(x)), tapped + + def _prefill_with_hidden( + self, tokens: torch.Tensor, input_pos: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor]: + x, tapped = _run_with_hidden(self, tokens, input_pos) + return self._soft_cap(self.lm_head(x[:, -1:, :])), tapped + + def _forward_embeddings_with_hidden( + self, inputs_embeds: torch.Tensor, input_pos: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor]: + x, tapped = _run_embeddings_with_hidden(self, inputs_embeds, input_pos) + return self._soft_cap(self.lm_head(x)), tapped + + def _prefill_embeddings_with_hidden( + self, inputs_embeds: torch.Tensor, input_pos: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor]: + x, tapped = _run_embeddings_with_hidden(self, inputs_embeds, input_pos) + return self._soft_cap(self.lm_head(x[:, -1:, :])), tapped + + model.forward = types.MethodType(_forward_with_hidden, model) + model.dflash_prefill_forward = types.MethodType(_prefill_with_hidden, model) + model.target_forward_from_embeddings = types.MethodType( + _forward_embeddings_with_hidden, model + ) + model.target_prefill_from_embeddings = types.MethodType( + _prefill_embeddings_with_hidden, model + ) + + +class CUDADFlashAttention(nn.Module): + """CUDA-optimized DFlash cross-attention (flat KV cache + length-aware sdpa). + + Full-module replacement for ``DFlashAttention`` on the CUDA export path, + mirroring how ``MLXDFlashAttention`` replaces it for MLX. ``dflash_model.py`` + stays backend-agnostic; all CUDA specifics live here: + + - Global (non-sliding) layers write the transient draft block into a flat KV + cache with block-sized scratch, then bound attention to the valid context + via a runtime ``kv_len`` GPU scalar routed through + ``torch.ops.triton.sdpa`` (fixed shapes -> CUDA-graph capturable). + - Sliding-window layers keep the concat + boolean-mask + ``F.scaled_dot_product_attention`` path over a ring buffer. + """ + + @classmethod + def from_attention(cls, attn: nn.Module, block_size: int) -> "CUDADFlashAttention": + m = cls.__new__(cls) + nn.Module.__init__(m) + + m.n_heads = attn.n_heads + m.n_kv_heads = attn.n_kv_heads + m.head_dim = attn.head_dim + m.attn_scale = attn.attn_scale + m.rope_theta = attn.rope_theta + m.is_sliding = attn.is_sliding + m.window_size = attn.window_size + + m.q_proj = attn.q_proj + m.k_proj = attn.k_proj + m.v_proj = attn.v_proj + m.o_proj = attn.o_proj + m.q_norm = attn.q_norm + m.k_norm = attn.k_norm + + # Own KV cache. Buffers are created on meta and materialized to the + # activation dtype later by materialize_dflash_runtime_buffers. Global + # layers get block_size scratch positions so the transient draft block + # can be written just past the valid context. + with torch.device("meta"): + if attn.is_sliding: + m.kv_cache = RingKVCache( + max_batch_size=1, + window_size=attn.window_size, + num_kv_heads=attn.n_kv_heads, + head_dim=attn.head_dim, + ) + else: + ctx_len = attn.kv_cache.k_cache.shape[2] + m.kv_cache = FlatKVCache( + max_batch_size=1, + max_seq_len=ctx_len + block_size, + num_kv_heads=attn.n_kv_heads, + head_dim=attn.head_dim, + ) + return m + + def forward( + self, + x: torch.Tensor, + target_hidden: torch.Tensor, + ctx_cos: torch.Tensor, + ctx_sin: torch.Tensor, + block_cos: torch.Tensor, + block_sin: torch.Tensor, + input_pos: torch.Tensor, + valid_ctx_len: torch.Tensor | None = None, + ) -> torch.Tensor: + B, T, _ = x.shape + n_new = target_hidden.shape[1] + + # Project new context K/V, apply k_norm, RoPE, then cache. + k_new = self.k_proj(target_hidden).view( + B, n_new, self.n_kv_heads, self.head_dim + ) + v_new = self.v_proj(target_hidden).view( + B, n_new, self.n_kv_heads, self.head_dim + ) + k_new = self.k_norm(k_new) + k_new = k_new.transpose(1, 2) + v_new = v_new.transpose(1, 2) + k_new = rotate_half(k_new, ctx_cos, ctx_sin) + positions = torch.arange(n_new, device=k_new.device) + input_pos[0] + k_cached, v_cached = self.kv_cache.update(positions, k_new, v_new) + + total_ctx = input_pos[0] + ( + n_new if valid_ctx_len is None else valid_ctx_len[0] + ) + + if self.is_sliding: + attn_mask = build_dflash_swa_mask( + total_ctx, + T, + self.kv_cache.buf_size, + self.window_size, + ) + k_ctx = k_cached + v_ctx = v_cached + else: + attn_mask = None + + # Block K/V — computed fresh each call. + k_blk = self.k_proj(x).view(B, T, self.n_kv_heads, self.head_dim) + v_blk = self.v_proj(x).view(B, T, self.n_kv_heads, self.head_dim) + k_blk = self.k_norm(k_blk) + k_blk = k_blk.transpose(1, 2) + v_blk = v_blk.transpose(1, 2) + k_blk = rotate_half(k_blk, block_cos, block_sin) + + # Q from block tokens. + xq = self.q_proj(x).view(B, T, self.n_heads, self.head_dim) + xq = self.q_norm(xq) + xq = xq.transpose(1, 2) + xq = rotate_half(xq, block_cos, block_sin) + + if self.is_sliding: + k = torch.cat([k_ctx, k_blk], dim=2) + v = torch.cat([v_ctx, v_blk], dim=2) + # PyTorch SDPA broadcasts the singleton query dimension, while the + # CUDA Triton lowering requires the explicit [B, 1, T, K] shape. + attn_mask = attn_mask.expand(B, 1, T, -1) + y = F.scaled_dot_product_attention( + xq, + k, + v, + attn_mask=attn_mask, + is_causal=False, + enable_gqa=True, + scale=self.attn_scale, + ) + else: + # Store the transient block immediately after valid context; the next + # call overwrites it with accepted context/block data. kv_len + # (total_ctx + T) is a runtime GPU scalar, so the KV loop stays + # O(context) and shapes remain CUDA-graph capturable. + block_positions = torch.arange(T, device=k_blk.device) + total_ctx + k, v = self.kv_cache.update(block_positions, k_blk, v_blk) + y = torch.ops.triton.sdpa( + xq, + k, + v, + None, + 0.0, + False, + self.attn_scale, + True, + total_ctx + T, + ) + y = y.transpose(1, 2).contiguous().reshape(B, T, -1) + return self.o_proj(y) + + +def _replace_dflash_cuda_layer_forward(layer: nn.Module) -> None: + """Replace DFlashDecoderLayer.forward to pass precomputed ctx/block RoPE.""" + + def _cuda_dflash_layer_forward( + self, + x: torch.Tensor, + target_hidden: torch.Tensor, + ctx_cos: torch.Tensor, + ctx_sin: torch.Tensor, + block_cos: torch.Tensor, + block_sin: torch.Tensor, + input_pos: torch.Tensor, + valid_ctx_len: torch.Tensor | None = None, + ) -> torch.Tensor: + x = x + self.self_attn( + self.input_layernorm(x), + target_hidden, + ctx_cos, + ctx_sin, + block_cos, + block_sin, + input_pos, + valid_ctx_len, + ) + x = x + self.mlp(self.post_attention_layernorm(x)) + return x + + layer.forward = types.MethodType(_cuda_dflash_layer_forward, layer) + + +def _replace_dflash_cuda_model_forward(model: nn.Module) -> None: + """Replace DFlashDraftModel.forward to precompute ctx/block RoPE (no .item()).""" + + def _cuda_dflash_forward( + self, + noise_embedding: torch.Tensor, + target_hidden: torch.Tensor, + input_pos: torch.Tensor, + valid_ctx_len: torch.Tensor | None = None, + ) -> torch.Tensor: + ctx = self.hidden_norm(self.fc(target_hidden)) + n_new = ctx.shape[1] + valid_new = n_new if valid_ctx_len is None else valid_ctx_len[0] + T = noise_embedding.shape[1] + inv_freq = 1.0 / ( + self.rope_theta + ** ( + torch.arange( + 0, + self.head_dim, + 2, + device=input_pos.device, + dtype=torch.float32, + ) + / self.head_dim + ) + ) + ctx_positions = ( + torch.arange(n_new, device=input_pos.device, dtype=torch.float32) + + input_pos[0] + ) + block_positions = ( + torch.arange(T, device=input_pos.device, dtype=torch.float32) + + input_pos[0] + + valid_new + ) + ctx_freqs = torch.outer(ctx_positions, inv_freq) + block_freqs = torch.outer(block_positions, inv_freq) + ctx_cos = torch.cos(ctx_freqs).unsqueeze(0).unsqueeze(0) + ctx_sin = torch.sin(ctx_freqs).unsqueeze(0).unsqueeze(0) + block_cos = torch.cos(block_freqs).unsqueeze(0).unsqueeze(0) + block_sin = torch.sin(block_freqs).unsqueeze(0).unsqueeze(0) + + x = noise_embedding + for layer in self.layers: + x = layer( + x, + ctx, + ctx_cos, + ctx_sin, + block_cos, + block_sin, + input_pos, + valid_ctx_len, + ) + + return self.norm(x) + + model.forward = types.MethodType(_cuda_dflash_forward, model) + + +def dflash_cuda_source_transformations(model: nn.Module) -> None: + """Apply CUDA source transformations to a DFlashDraftModel in place. + + Mirrors ``dflash_mlx_source_transformations``: swaps each layer's + ``DFlashAttention`` for ``CUDADFlashAttention`` (flat KV cache with block + scratch + length-aware ``torch.ops.triton.sdpa``) and replaces the layer and + model forwards to precompute RoPE and thread ``input_pos`` through. Keeps + ``dflash_model.py`` fully backend-agnostic. + + Args: + model: ``DFlashDraftModel`` instance to transform in place. + """ + block_size = model.config.block_size + n_swapped = 0 + for layer in model.layers: + layer.self_attn = CUDADFlashAttention.from_attention( + layer.self_attn, block_size + ) + _replace_dflash_cuda_layer_forward(layer) + n_swapped += 1 + _replace_dflash_cuda_model_forward(model) + print( + f"[muse_glimmer cuda] DFlash: swapped {n_swapped} attention layers with " + f"CUDADFlashAttention (flat KV cache + length-aware triton.sdpa)" + ) + + +def materialize_dflash_runtime_buffers( + model: nn.Module, dtype: torch.dtype, device: str = "cpu" +) -> None: + """Materialize meta-device DFlash KV caches after checkpoint loading. + + ``CUDADFlashAttention`` creates its KV caches on the meta device; this fills + them with real zero buffers of the activation dtype, after the attention swap + and quantized-tensor conversion. + """ + for fqn, buf in list(model.named_buffers()): + if buf.device.type != "meta": + continue + parts = fqn.rsplit(".", 1) + parent = model.get_submodule(parts[0]) if len(parts) > 1 else model + parent.register_buffer( + parts[-1], + torch.zeros(buf.shape, dtype=dtype, device=device), + persistent=False, + ) + + +def _project_qkvo(self, h: torch.Tensor): + if self.fuse_qko: + qko = self.qko_proj(h) + q_end = self.q_dim + k_end = q_end + self.kv_dim + xq = qko[..., :q_end] + xk = qko[..., q_end:k_end] + og = qko[..., k_end:] if self.use_o_gate else None + xv = self.v_proj(h) + elif self.fuse_qkv: + qkv = self.qkv_proj(h) + q_end = self.q_dim + k_end = q_end + self.kv_dim + v_end = k_end + self.kv_dim + xq = qkv[..., :q_end] + xk = qkv[..., q_end:k_end] + xv = qkv[..., k_end:v_end] + og = qkv[..., v_end:] if self.use_o_gate else None + else: + xq = self.q_proj(h) + xk = self.k_proj(h) + xv = self.v_proj(h) + og = self.og_proj(h) if self.use_o_gate else None + return xq, xk, xv, og + + +def _turboquant_attention_forward( + self, + x: torch.Tensor, + input_pos: torch.Tensor, + attn_mask: torch.Tensor, +) -> torch.Tensor: + """Drop-in replacement for ``MuseGlimmerAttention.forward`` on global/NoPE layers. + + Mirrors the default forward but (1) applies NO RoPE (these are global NoPE + layers) and (2) routes attention through ``torch.ops.triton.tq4_sdpa`` over + a ``TurboQuantKVCache``. + + NOTE: ``attn_mask`` is unused — the global mask is standard causal, so it is + reconstructed in the kernel (``mask_is_causal=True``) to save data transfer. + """ + B, T, _ = x.shape + + h = self.qkv_proj_norm(x) + xq, xk, xv, og = _project_qkvo(self, h) + + xq = xq.view(B, T, self.n_heads, self.head_dim) + xk = xk.view(B, T, self.n_kv_heads, self.head_dim) + xv = xv.view(B, T, self.n_kv_heads, self.head_dim) + + # Scaleless QK-norm (query scaling absorbed into attn_scale below). + if self.q_norm is not None: + xq = self.q_norm(xq) + xk = self.k_norm(xk) + + # (B, H, T, D) for the KV cache / SDPA. + xq = xq.transpose(1, 2) + xk = xk.transpose(1, 2) + xv = xv.transpose(1, 2) + + # NoPE: global layers apply no positional encoding (no RoPE here). + + # Compress + write. tq4_sdpa decompresses per tile, so the full + # uncompressed K/V is never materialized. + k_packed, k_norms, v_packed, v_norms = self.kv_cache.update(input_pos, xk, xv) + + # Number of valid (filled) KV positions = input_pos[0] + T. Bounds the + # tq4_sdpa KV loop to the actual context instead of the full pre-allocated + # buffer (max_seq_len), making attention O(context) instead of + # O(max_seq_len). Kept as a GPU scalar (no ``.item()``) so the bound is + # captured by the decode CUDA graph. Decode: T=1 -> input_pos+1; prefill + # chunk: T -> chunk_end. + kv_len = input_pos[0] + input_pos.shape[0] + + # scale=self.attn_scale absorbs the muP query scaling and 1/sqrt(D), + # overriding tq4_sdpa's default 1/sqrt(D). + y = torch.ops.triton.tq4_sdpa( + xq, + k_packed, + k_norms, + v_packed, + v_norms, + self.kv_cache.centroids, + self.kv_cache.rotation, + None, # reconstruct the causal mask in the kernel to save data transfer + False, # is_causal: needs L_q==L_kv; causal comes from mask_is_causal + self.attn_scale, + kv_len, + True, # mask_is_causal: muse_glimmer global-attention mask is standard causal + ) + + y = y.transpose(1, 2).contiguous() + + # Output gate: sigmoid(OG) * attn_output. + if self.use_o_gate and og is not None: + og = og.view(B, T, self.n_heads, self.head_dim) + y = torch.sigmoid(og) * y + + y = y.reshape(B, T, -1) + return self.o_proj(y) + + +def _lenaware_attention_forward( + self, + x: torch.Tensor, + input_pos: torch.Tensor, + attn_mask: torch.Tensor, +) -> torch.Tensor: + """Drop-in ``MuseGlimmerAttention.forward`` for global/NoPE layers on the + non-TurboQuant CUDA path that bounds SDPA to the valid context length. + + Identical to the default forward (plain bf16 ``FlatKVCache``, NO RoPE, + output gate) except the final ``F.scaled_dot_product_attention`` is replaced + with ``torch.ops.triton.sdpa(..., kv_len=...)``. Passing ``kv_len`` bounds + the KV loop to the filled context instead of the full pre-allocated buffer + (``max_seq_len``), making decode O(context) instead of O(max_seq_len) — and + routes L_q==1 decode through the length-aware split-K flash-decoding kernel. + Sliding-window layers are not patched (they already use a bounded ring + buffer). + """ + B, T, _ = x.shape + + h = self.qkv_proj_norm(x) + xq, xk, xv, og = _project_qkvo(self, h) + + xq = xq.view(B, T, self.n_heads, self.head_dim) + xk = xk.view(B, T, self.n_kv_heads, self.head_dim) + xv = xv.view(B, T, self.n_kv_heads, self.head_dim) + + # Scaleless QK-norm (query scaling absorbed into attn_scale below). + if self.q_norm is not None: + xq = self.q_norm(xq) + xk = self.k_norm(xk) + + # (B, H, T, D) for the KV cache / SDPA. + xq = xq.transpose(1, 2) + xk = xk.transpose(1, 2) + xv = xv.transpose(1, 2) + + # NoPE: global layers apply no positional encoding (no RoPE here). + + # Update cache and read back the full (pre-allocated) bf16 K/V buffers. + k, v = self.kv_cache.update(input_pos, xk, xv) + + # Number of valid (filled) KV positions = input_pos[0] + T. Bounds the sdpa + # KV loop to the actual context (O(context) instead of O(max_seq_len)). Kept + # as a GPU scalar so the bound is captured by the decode CUDA graph. + kv_len = input_pos[0] + input_pos.shape[0] + + # scale=self.attn_scale absorbs the muP query scaling and 1/sqrt(D). + # enable_gqa=True lets the kernel handle the 16:1 head ratio without + # materializing expanded K/V. + y = torch.ops.triton.sdpa( + xq, + k, + v, + attn_mask, + 0.0, # dropout_p + False, # is_causal: attn_mask already encodes causal masking + self.attn_scale, + True, # enable_gqa + kv_len, + ) + + y = y.transpose(1, 2).contiguous() + + # Output gate: sigmoid(OG) * attn_output. + if self.use_o_gate and og is not None: + og = og.view(B, T, self.n_heads, self.head_dim) + y = torch.sigmoid(og) * y + + y = y.reshape(B, T, -1) + return self.o_proj(y) + + +def cuda_source_transformations( + model: nn.Module, + *, + use_turboquant: bool = False, +) -> None: + """Apply CUDA source transformations to a Muse Glimmer model in place. + + Always bounds global-attention SDPA to the valid context via a runtime + ``kv_len`` (O(context) decode). Optionally also swaps the global KV caches + for TurboQuant TQ4. Sliding-window layers are untouched in both cases (they + already use a bounded ring buffer). + + Args: + model: ``MuseGlimmerModel`` instance to transform. + use_turboquant: When True, swap the global (NoPE) layers' KV caches for + ``TurboQuantKVCache`` (TQ4, ~3.8x cache memory savings) and route + their attention through ``torch.ops.triton.tq4_sdpa``. When False, + keep the bf16 ``FlatKVCache`` but route global attention through the + length-aware ``torch.ops.triton.sdpa``. + """ + if not use_turboquant: + # Non-TurboQuant path: keep the bf16 FlatKVCache but bound global + # attention to the valid context via a runtime kv_len scalar (routes + # through torch.ops.triton.sdpa, which dispatches L_q==1 decode to the + # length-aware split-K flash-decoding kernel). Sliding-window layers + # already use a bounded ring buffer, so they are left untouched. + n_bounded = 0 + for layer in model.layers: + attn = layer.self_attn + if attn.is_sliding: + continue + attn.forward = types.MethodType(_lenaware_attention_forward, attn) + n_bounded += 1 + print( + f"[muse_glimmer cuda] length-aware SDPA: bounded {n_bounded} global-attention " + f"layers to runtime kv_len (O(context) attention)" + ) + return + + config = model.config + n_swapped = 0 + for layer in model.layers: + attn = layer.self_attn + if attn.is_sliding: + continue + attn.kv_cache = TurboQuantKVCache( + n_heads=attn.n_kv_heads, + head_dim=attn.head_dim, + max_seq_len=config.max_seq_len, + ) + attn.forward = types.MethodType(_turboquant_attention_forward, attn) + n_swapped += 1 + + print( + f"[muse_glimmer cuda] TurboQuant: swapped {n_swapped} global-attention " + f"KV caches with TurboQuantKVCache (TQ4)" + ) + + +def _embed_text_forward( + self, + tokens: torch.Tensor, +) -> torch.Tensor: + """Exported ``embed_text`` entry: token embedding lookup, no sampling. + + Returns bf16 ``(B, T, dim)`` embeddings for the runner to (optionally) splice + vision features into before calling the embeddings-input forward entry. + """ + return self.embed_text(tokens) + + +def _forward_from_embeddings_sampling( + self, + inputs_embeds: torch.Tensor, + input_pos: torch.Tensor, + temperature: torch.Tensor, +) -> torch.Tensor: + """Embeddings-input prefill entry that samples one token on-device. + + Runs the decoder stack over pre-computed ``inputs_embeds`` (built by the + runner from ``embed_text`` plus any image splice) and returns a single + Gumbel-max token id ``(B, 1)`` from the last position. Only the last + position's logits are computed, so ``lm_head`` runs on ``(B, 1, H)``. + """ + x = self._run_blocks(inputs_embeds, input_pos) + x = self.output_norm(x) + last = self._soft_cap(self.lm_head(x[:, -1, :])) + return sample(last, temperature) + + +def _decode_from_embedding_sampling( + self, + input_embedding: torch.Tensor, + input_pos: torch.Tensor, + temperature: torch.Tensor, +) -> torch.Tensor: + """Single-embedding decode entry that samples one token on-device.""" + x = self._run_blocks(input_embedding, input_pos) + x = self.output_norm(x) + last = self._soft_cap(self.lm_head(x[:, -1, :])) + return sample(last, temperature) + + +def add_on_device_sampler(model: nn.Module) -> None: + """Bind the three on-device-sampling entry points to a Muse Glimmer model in place. + + Exposes bound methods used by ``export.py`` via a per-method + ``forward``-swap: + + * ``embed_text_forward(tokens) -> (B, T, dim)`` bf16 embeddings (no sampling) + * ``forward_from_embeddings(inputs_embeds, input_pos, temperature)`` + * ``decode_from_embedding(input_embedding, input_pos, temperature)`` + + Splitting ``embed_text`` from both decoder entry points gives CUDA and MLX + the same method contract and lets the runner splice vision features before + prefill. The NLL-validation path exports the sampler-free model methods. + + Args: + model: ``MuseGlimmerModel`` instance to transform. + """ + model.embed_text_forward = types.MethodType(_embed_text_forward, model) + model.forward_from_embeddings = types.MethodType( + _forward_from_embeddings_sampling, model + ) + model.decode_from_embedding = types.MethodType( + _decode_from_embedding_sampling, model + ) + + +# Vision encoder: optional FP32 GEMM (CUDA only) +# The shared vision model remains backend-neutral; CUDA rewrites are applied +# only during export. + + +@triton.jit +def _bf16_fp32_matmul_kernel( + x, + weight, + output, + M, + N: tl.constexpr, + K: tl.constexpr, + stride_xm, + stride_xk, + stride_wn, + stride_wk, + stride_om, + stride_on, + BLOCK_M: tl.constexpr, + BLOCK_N: tl.constexpr, + BLOCK_K: tl.constexpr, +): + pid_m = tl.program_id(0) + pid_n = tl.program_id(1) + offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + offs_k = tl.arange(0, BLOCK_K) + + x_ptrs = x + offs_m[:, None] * stride_xm + offs_k[None, :] * stride_xk + w_ptrs = weight + offs_n[None, :] * stride_wn + offs_k[:, None] * stride_wk + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) + + for k_start in range(0, K, BLOCK_K): + k_mask = k_start + offs_k < K + x_tile = tl.load( + x_ptrs, + mask=(offs_m[:, None] < M) & k_mask[None, :], + other=0.0, + ) + w_tile = tl.load( + w_ptrs, + mask=k_mask[:, None] & (offs_n[None, :] < N), + other=0.0, + ) + acc += tl.dot(x_tile, w_tile) + x_ptrs += BLOCK_K * stride_xk + w_ptrs += BLOCK_K * stride_wk + + out_ptrs = output + offs_m[:, None] * stride_om + offs_n[None, :] * stride_on + tl.store( + out_ptrs, + acc, + mask=(offs_m[:, None] < M) & (offs_n[None, :] < N), + ) + + +@triton_op("triton::bf16_fp32_matmul", mutates_args={}) +def bf16_fp32_matmul(x: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: + """Compute ``x @ weight.T`` with bf16 operands and F32 output storage.""" + if x.dtype != torch.bfloat16 or weight.dtype != torch.bfloat16: + raise TypeError("bf16_fp32_matmul requires bf16 inputs") + if x.ndim != 2 or weight.ndim != 2 or x.shape[1] != weight.shape[1]: + raise ValueError("expected x[M,K] and weight[N,K]") + + m, _ = x.shape + n = weight.shape[0] + if not x.is_cuda: + return torch.mm(x.float(), weight.float().t()) + + output = torch.empty((m, n), dtype=torch.float32, device=x.device) + grid = lambda meta: ( # noqa: E731 + triton.cdiv(m, meta["BLOCK_M"]), + triton.cdiv(n, meta["BLOCK_N"]), + ) + wrap_triton(_bf16_fp32_matmul_kernel)[grid]( + x, + weight, + output, + m, + n, + x.shape[1], + x.stride(0), + x.stride(1), + weight.stride(0), + weight.stride(1), + output.stride(0), + output.stride(1), + BLOCK_M=64, + BLOCK_N=128, + BLOCK_K=32, + num_warps=8, + num_stages=3, + ) + return output + + +@bf16_fp32_matmul.register_fake +def _bf16_fp32_matmul_fake(x: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: + return torch.empty( + (x.shape[0], weight.shape[0]), dtype=torch.float32, device=x.device + ) + + +def _f32_linear_forward(self, x: torch.Tensor) -> torch.Tensor: + """``nn.Linear.forward`` with bf16 operands and an F32-accumulated output.""" + shape = x.shape[:-1] + y = bf16_fp32_matmul( + x.reshape(-1, self.in_features).to(torch.bfloat16), + self.weight.to(torch.bfloat16), + ) + if self.bias is not None: + y = y + self.bias.to(torch.float32) + return y.view(*shape, self.out_features) + + +def _make_fp32_encoder_forward(start: int, end: int, out_dtype: torch.dtype): + """Encoder ``forward`` that runs blocks [start, end] in F32. + + Mirrors the stock ``MuseGlimmerVisionEncoder.forward`` but adds the dtype + transitions around the F32 block range. Kept as a closure so ``start`` / + ``end`` / ``out_dtype`` are trace-time constants and none of this state has + to exist on the shared module. + """ + + def _forward( + self, + patches: torch.Tensor, + pos_emb: torch.Tensor, + cos_2d: torch.Tensor, + sin_2d: torch.Tensor, + sparse_perm: torch.Tensor, + inv_perm: torch.Tensor, + global_mask: torch.Tensor, + sparse_mask: torch.Tensor, + pixel_perm: torch.Tensor, + ) -> torch.Tensor: + w_dtype = self.conv1_linear.weight.dtype + x = self.conv1_linear(patches.to(w_dtype)) + x = x + pos_emb.to(w_dtype) + x = self.ln_pre(x) + + x = x.index_select(1, sparse_perm) + cos_p = cos_2d.index_select(0, sparse_perm) + sin_p = sin_2d.index_select(0, sparse_perm) + cos_b = cos_p.unsqueeze(0).unsqueeze(2) + sin_b = sin_p.unsqueeze(0).unsqueeze(2) + + for i, block in enumerate(self.blocks): + if i == start: + x = x.to(torch.float32) + cos_b = cos_b.to(torch.float32) + sin_b = sin_b.to(torch.float32) + elif i == end + 1: + x = x.to(out_dtype) + cos_b = cos_b.to(out_dtype) + sin_b = sin_b.to(out_dtype) + mask = global_mask if self._is_global[i] else sparse_mask + x = block(x, cos_b, sin_b, mask) + if end == len(self.blocks) - 1: + x = x.to(out_dtype) + + x = x.index_select(1, inv_perm) + x = self.ln_post(x) + + x = x.index_select(1, pixel_perm) + b, p, d = x.shape + f = self.downsample_factor + x_ds = x.view(b, p // (f * f), (f * f) * d) + + x_ds = self.adapter_fc(x_ds) + x_ds = F.gelu(self.adapter_proj(x_ds)) + x_ds = self.vision_proj(x_ds) + x_ds = self.perception_emb_norm(x_ds) + return x_ds.to(w_dtype) + + return _forward + + +def vision_cuda_source_transformations( + vision_model: nn.Module, + *, + start: int = 0, + end: int = 34, + use_triton_mm: bool = True, +) -> None: + """Run vision blocks [start, end] in F32 on the CUDA export path. + + Two sub-modes, matching ``--vision-fp32-mm``: + + - ``use_triton_mm=True`` ("triton"): keep bf16 weights and swap each + ``nn.Linear.forward`` in range for an F32-output Triton GEMM. + - ``use_triton_mm=False`` ("native"): cast the modules themselves to F32. + + Must run AFTER the checkpoint is loaded (weights are assigned by FQN, and + CUDA has already run ``convert_quantized_tensors_for_cuda``) and BEFORE + ``torch.export``. Wraps ``forward`` rather than swapping module classes so + module identity and ``state_dict`` keys stay stable. + """ + n_blocks = len(vision_model.blocks) + if not (0 <= start <= end < n_blocks): + raise ValueError(f"invalid F32 block range [{start}, {end}]") + + out_dtype = vision_model.conv1_linear.weight.dtype + vision_model.forward = types.MethodType( + _make_fp32_encoder_forward(start, end, out_dtype), vision_model + ) + + if not use_triton_mm: + if start == 0: + vision_model.conv1_linear.to(torch.float32) + vision_model.ln_pre.to(torch.float32) + for block in vision_model.blocks[start : end + 1]: + block.to(torch.float32) + print( + f"[muse_glimmer cuda] vision: native F32 blocks [{start}, {end}] " + f"of {n_blocks}" + ) + return + + n_swapped = 0 + if start == 0: + vision_model.conv1_linear.forward = types.MethodType( + _f32_linear_forward, vision_model.conv1_linear + ) + n_swapped += 1 + vision_model.ln_pre.to(torch.float32) + for i in range(start, end + 1): + block = vision_model.blocks[i] + block.ln_1.to(torch.float32) + block.ln_2.to(torch.float32) + for module in block.modules(): + if isinstance(module, nn.Linear): + module.forward = types.MethodType(_f32_linear_forward, module) + n_swapped += 1 + print( + f"[muse_glimmer cuda] vision: F32-output Triton GEMM on {n_swapped} linears " + f"in blocks [{start}, {end}] of {n_blocks}" + ) diff --git a/examples/models/muse-glimmer/source_transformations/mlx.py b/examples/models/muse-glimmer/source_transformations/mlx.py new file mode 100644 index 00000000000..6702e79cc07 --- /dev/null +++ b/examples/models/muse-glimmer/source_transformations/mlx.py @@ -0,0 +1,563 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""MLX source transformations for Muse Glimmer. + +The transformations replace attention, RoPE, and KV-cache operations with MLX +operators while preserving sliding-window and global-attention behavior. +""" + +import inspect +import types + +import executorch.backends.mlx.custom_ops # noqa: F401 — registers mlx:: ops +import torch +import torch.nn as nn +import torch.nn.functional as F +from executorch.backends.mlx.llm.cache import ( + KVCache as MLXKVCache, + RingBufferKVCache as MLXRingKVCache, +) +from executorch.examples.models.muse_glimmer.model.dflash_model import ( + build_dflash_swa_mask, +) +from executorch.examples.models.muse_glimmer.model.model import MuseGlimmerAttention + + +class MLXMuseGlimmerAttention(nn.Module): + """Muse Glimmer attention backed by MLX operators and KV caches.""" + + @classmethod + def from_attention( + cls, + attn: "MuseGlimmerAttention", + max_seq_len: int, + dtype: torch.dtype = torch.bfloat16, + max_write_len: int | None = None, + ) -> "MLXMuseGlimmerAttention": + m = cls.__new__(cls) + nn.Module.__init__(m) + + m.n_heads = attn.n_heads + m.n_kv_heads = attn.n_kv_heads + m.head_dim = attn.head_dim + m.q_dim = attn.q_dim + m.kv_dim = attn.kv_dim + m.fuse_qkv = attn.fuse_qkv + m.use_rope = attn.use_rope + m.is_sliding = attn.is_sliding + m.window_size = attn.window_size + m.use_o_gate = attn.use_o_gate + m.attn_scale = attn.attn_scale + m.rope_theta = attn.rope_theta + + m.qkv_proj_norm = attn.qkv_proj_norm + if attn.fuse_qkv: + m.qkv_proj = attn.qkv_proj + else: + m.q_proj = attn.q_proj + m.k_proj = attn.k_proj + m.v_proj = attn.v_proj + if attn.use_o_gate: + m.og_proj = attn.og_proj + m.o_proj = attn.o_proj + m.q_norm = attn.q_norm + m.k_norm = attn.k_norm + + if attn.is_sliding: + ring_kwargs = { + "max_batch_size": 1, + "max_context_length": attn.window_size, + "n_heads": attn.n_kv_heads, + "head_dim": attn.head_dim, + "dtype": dtype, + } + if max_write_len is not None and _ring_supports_mwl(): + ring_kwargs["max_write_len"] = max_write_len + m.kv_cache = MLXRingKVCache(**ring_kwargs) + else: + m.kv_cache = MLXKVCache( + max_batch_size=1, + max_context_length=max_seq_len, + n_heads=attn.n_kv_heads, + head_dim=attn.head_dim, + enable_dynamic_shape=True, + dtype=dtype, + ) + + return m + + def forward(self, x: torch.Tensor, input_pos: torch.Tensor) -> torch.Tensor: + B, T, _ = x.shape + start_pos = input_pos[0].item() + + h = self.qkv_proj_norm(x) + if self.fuse_qkv: + qkv = self.qkv_proj(h) + q_end = self.q_dim + k_end = q_end + self.kv_dim + v_end = k_end + self.kv_dim + xq = qkv[..., :q_end].view(B, T, self.n_heads, self.head_dim) + xk = qkv[..., q_end:k_end].view(B, T, self.n_kv_heads, self.head_dim) + xv = qkv[..., k_end:v_end].view(B, T, self.n_kv_heads, self.head_dim) + og = qkv[..., v_end:] if self.use_o_gate else None + else: + xq = self.q_proj(h).view(B, T, self.n_heads, self.head_dim) + xk = self.k_proj(h).view(B, T, self.n_kv_heads, self.head_dim) + xv = self.v_proj(h).view(B, T, self.n_kv_heads, self.head_dim) + og = self.og_proj(h) if self.use_o_gate else None + + if self.q_norm is not None: + xq = self.q_norm(xq) + xk = self.k_norm(xk) + + q = xq.transpose(1, 2) + k = xk.transpose(1, 2) + v = xv.transpose(1, 2) + + if self.use_rope: + q = torch.ops.mlx.rope( + q, self.head_dim, start_pos, True, self.rope_theta, 1.0, None + ) + k = torch.ops.mlx.rope( + k, self.head_dim, start_pos, True, self.rope_theta, 1.0, None + ) + + k_cache, v_cache = self.kv_cache.update(start_pos, k, v) + + if self.is_sliding: + sdpa_mask = self.kv_cache.create_sliding_window_mask(start_pos, T) + y = torch.ops.mlx.custom_sdpa( + q, + k_cache, + v_cache, + start_pos=self.kv_cache.buffer_size - T, + attn_mask=sdpa_mask, + dropout_p=0.0, + is_causal=False, + scale=self.attn_scale, + ) + else: + y = torch.ops.mlx.custom_sdpa( + q, + k_cache, + v_cache, + start_pos=start_pos, + dropout_p=0.0, + is_causal=True, + scale=self.attn_scale, + ) + + y = y.transpose(1, 2).contiguous() + + if self.use_o_gate and og is not None: + og = og.view(B, T, self.n_heads, self.head_dim) + y = torch.sigmoid(og) * y + + y = y.reshape(B, T, -1) + return self.o_proj(y) + + +def _ring_supports_mwl() -> bool: + return "max_write_len" in inspect.signature(MLXRingKVCache.__init__).parameters + + +def _replace_layer_forward(layer: nn.Module) -> None: + """Replace MuseGlimmerDecoderLayer's forward to drop the mask parameters.""" + + def _mlx_layer_forward( + self, x: torch.Tensor, input_pos: torch.Tensor + ) -> torch.Tensor: + attn_out = self.self_attn(x, input_pos) + x = x + self.post_attn_norm(attn_out) + + ffn_out = self.mlp(x) + x = x + self.post_ffn_norm(ffn_out) + return x + + layer.forward = types.MethodType(_mlx_layer_forward, layer) + + +def _replace_model_forward(model: nn.Module) -> None: + """Install sampler-free MLX entry points. + + MLX samples on the host, so prefill returns softcapped last-token logits + ``(B, V)``. Splitting embedding (``mlx_embed_text``) from the decoder stack + (``mlx_prefill_forward``, embeddings-input) is what lets the C++ runner + splice image soft-tokens into the prompt embeddings before prefill (the MLX + vision path). The token-input ``forward`` is kept as a text-only convenience + and stays equivalent to ``mlx_embed_text`` followed by + ``mlx_prefill_forward``. + + Each MLX attention builds its own mask via ``custom_sdpa``, so there is no + ``_build_masks`` call and no per-layer mask arguments. + """ + + def _mlx_embed_text(self, tokens: torch.Tensor) -> torch.Tensor: + x = self.embed_tokens(tokens) + if self.normalize_tok_embeddings: + x = self.tok_norm(x) + return x.to(self.activation_dtype) + + def _mlx_logits_from_embeds( + self, inputs_embeds: torch.Tensor, input_pos: torch.Tensor + ) -> torch.Tensor: + x = inputs_embeds + for layer in self.layers: + x = layer(x, input_pos) + + x = self.output_norm(x) + last = self.lm_head(x[:, -1, :]).float() + mult = self.output_multiplier.float() + cap = self.logit_softcap.float() + return torch.tanh(last * mult / cap) * cap + + def _mlx_prefill_forward( + self, inputs_embeds: torch.Tensor, input_pos: torch.Tensor + ) -> torch.Tensor: + return self.mlx_logits_from_embeds(inputs_embeds, input_pos) + + def _mlx_model_forward( + self, tokens: torch.Tensor, input_pos: torch.Tensor + ) -> torch.Tensor: + return self.mlx_prefill_forward(self.mlx_embed_text(tokens), input_pos) + + model.mlx_embed_text = types.MethodType(_mlx_embed_text, model) + model.mlx_logits_from_embeds = types.MethodType(_mlx_logits_from_embeds, model) + model.mlx_prefill_forward = types.MethodType(_mlx_prefill_forward, model) + model.forward = types.MethodType(_mlx_model_forward, model) + + +def _apply_mlx_transforms( + model: nn.Module, + dtype: torch.dtype = torch.bfloat16, + max_write_len: int | None = None, +) -> None: + """Shared MLX transforms: swap attention modules, patch layer forwards, fuse norms.""" + config = model.config + + # Record the activation compute dtype so the patched forwards cast to it. + model.activation_dtype = dtype + + for layer in model.layers: + layer.self_attn = MLXMuseGlimmerAttention.from_attention( + layer.self_attn, + max_seq_len=config.max_seq_len, + dtype=dtype, + max_write_len=max_write_len, + ) + _replace_layer_forward(layer) + + +def mlx_source_transformations( + model: nn.Module, + dtype: torch.dtype = torch.bfloat16, + max_write_len: int | None = None, +) -> None: + """Apply MLX source transformations to a Muse Glimmer model in-place. + + Self-contained MLX adaptation. After calling this, the model exposes + sampler-free, mask-free entry points that return ``(B, V)`` last-token + logits (host-side sampling): + + * ``forward(tokens, input_pos)`` — text-only convenience. + * ``mlx_embed_text(tokens)`` — token embedding lookup (+ tok_norm), cast to + the activation dtype. + * ``mlx_prefill_forward(inputs_embeds, input_pos)`` — embeddings-input + prefill (lets the runner splice image soft-tokens before the decoder + stack; used by the MLX vision path). + + Args: + model: MuseGlimmerModel to transform in place. + dtype: dtype for KV cache buffers (bf16 by default). + max_write_len: largest single write to the sliding-window ring buffer + (i.e. the max prefill chunk). When set, the ring buffer is sized to + ``window + max_write_len - 1`` instead of ``2 * window``, saving + memory for chunked prefill. Ignored if the installed + ``RingBufferKVCache`` predates the ``max_write_len`` parameter. + """ + _apply_mlx_transforms(model, dtype, max_write_len) + _replace_model_forward(model) + + +# DFlash: target model with hidden state tapping + + +def _replace_model_forward_with_hidden_tapping( + model: nn.Module, target_layer_ids: list[int] +) -> None: + """Install MLX DFlash token- and embeddings-input target entry points. + + ``target_forward_from_embeddings`` owns the target traversal and returns + full-sequence ``(logits, hidden)`` tensors. The token-input ``forward`` + remains backward compatible and delegates after embedding the tokens. + """ + target_set = set(target_layer_ids) + model._dflash_target_layer_ids = target_layer_ids + + def _mlx_embed_text(self, tokens: torch.Tensor) -> torch.Tensor: + x = self.embed_tokens(tokens) + if self.normalize_tok_embeddings: + x = self.tok_norm(x) + return x.to(self.activation_dtype) + + def _mlx_target_forward_from_embeddings( + self, inputs_embeds: torch.Tensor, input_pos: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor]: + x = inputs_embeds.to(self.activation_dtype) + tapped = [] + for i, layer in enumerate(self.layers): + if i in target_set: + tapped.append(x) + x = layer(x, input_pos) + + x = self.output_norm(x) + all_logits = self.lm_head(x).float() + mult = self.output_multiplier.float() + cap = self.logit_softcap.float() + logits = torch.tanh(all_logits * mult / cap) * cap + return logits, torch.cat(tapped, dim=-1) + + def _mlx_model_forward_with_hidden( + self, tokens: torch.Tensor, input_pos: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor]: + return self.target_forward_from_embeddings(self.embed_text(tokens), input_pos) + + model.embed_text = types.MethodType(_mlx_embed_text, model) + model.target_forward_from_embeddings = types.MethodType( + _mlx_target_forward_from_embeddings, model + ) + model.forward = types.MethodType(_mlx_model_forward_with_hidden, model) + + +def mlx_source_transformations_dflash_target( + model: nn.Module, + target_layer_ids: list[int], + dtype: torch.dtype = torch.bfloat16, + max_write_len: int | None = None, +) -> None: + """Apply MLX source transformations for the DFlash target model. + + Same as ``mlx_source_transformations`` but installs a shared embeddings-input + target traversal that also returns concatenated hidden states from + ``target_layer_ids``. + + After calling this, the model exposes: + ``forward(tokens, input_pos) -> (logits [B, T, V], hidden [B, T, N*D])`` + ``embed_text(tokens) -> inputs_embeds [B, T, D]`` + ``target_forward_from_embeddings(inputs_embeds, input_pos)`` with the + same full-sequence logits and hidden outputs as ``forward``. + """ + _apply_mlx_transforms(model, dtype, max_write_len) + _replace_model_forward_with_hidden_tapping(model, target_layer_ids) + + +# DFlash: draft model MLX source transformations + + +class MLXDFlashAttention(nn.Module): + """MLX-optimized DFlash cross-attention with KV cache for context. + + Context K/V (from projected target hidden states) are cached across calls. + Only new target hidden states are projected each call. Block token K/V are + computed fresh every call. + """ + + @classmethod + def from_attention( + cls, + attn, + max_context_length: int, + dtype: torch.dtype = torch.bfloat16, + is_sliding: bool = False, + window_size: int | None = None, + max_write_len: int | None = None, + ) -> "MLXDFlashAttention": + m = cls.__new__(cls) + nn.Module.__init__(m) + + m.n_heads = attn.n_heads + m.n_kv_heads = attn.n_kv_heads + m.head_dim = attn.head_dim + m.attn_scale = attn.attn_scale + m.rope_theta = attn.rope_theta + m.is_sliding = is_sliding + + m.q_proj = attn.q_proj + m.k_proj = attn.k_proj + m.v_proj = attn.v_proj + m.o_proj = attn.o_proj + m.q_norm = attn.q_norm + m.k_norm = attn.k_norm + + if is_sliding: + ring_kwargs = { + "max_batch_size": 1, + "max_context_length": window_size, + "n_heads": attn.n_kv_heads, + "head_dim": attn.head_dim, + "dtype": dtype, + } + if max_write_len is not None and _ring_supports_mwl(): + ring_kwargs["max_write_len"] = max_write_len + m.kv_cache = MLXRingKVCache(**ring_kwargs) + else: + m.kv_cache = MLXKVCache( + max_batch_size=1, + max_context_length=max_context_length, + n_heads=attn.n_kv_heads, + head_dim=attn.head_dim, + enable_dynamic_shape=True, + dtype=dtype, + ) + + return m + + def forward( + self, + x: torch.Tensor, + target_hidden: torch.Tensor, + input_pos: torch.Tensor, + ) -> torch.Tensor: + B, T, _ = x.shape + n_new = target_hidden.shape[1] + ctx_start = input_pos[0].item() + total_ctx = ctx_start + n_new + + # Project new context K/V, apply k_norm + RoPE, write to cache + k_new = self.k_proj(target_hidden).view( + B, n_new, self.n_kv_heads, self.head_dim + ) + v_new = self.v_proj(target_hidden).view( + B, n_new, self.n_kv_heads, self.head_dim + ) + k_new = self.k_norm(k_new) + k_new = k_new.transpose(1, 2) + v_new = v_new.transpose(1, 2) + k_new = torch.ops.mlx.rope( + k_new, self.head_dim, ctx_start, False, self.rope_theta, 1.0, None + ) + k_ctx, v_ctx = self.kv_cache.update(ctx_start, k_new, v_new) + + if self.is_sliding: + attn_mask = build_dflash_swa_mask( + total_ctx, + T, + self.kv_cache.buffer_size, + self.kv_cache.window_size, + ) + else: + torch._check(ctx_start >= 0) + torch._check(total_ctx <= self.kv_cache.max_context_length) + k_ctx = k_ctx[:, :, :total_ctx, :] + v_ctx = v_ctx[:, :, :total_ctx, :] + attn_mask = None + + # Block K/V — computed fresh each call + k_blk = self.k_proj(x).view(B, T, self.n_kv_heads, self.head_dim) + v_blk = self.v_proj(x).view(B, T, self.n_kv_heads, self.head_dim) + k_blk = self.k_norm(k_blk) + k_blk = k_blk.transpose(1, 2) + v_blk = v_blk.transpose(1, 2) + k_blk = torch.ops.mlx.rope( + k_blk, self.head_dim, total_ctx, False, self.rope_theta, 1.0, None + ) + + # Q from block tokens + xq = self.q_proj(x).view(B, T, self.n_heads, self.head_dim) + xq = self.q_norm(xq) + q = xq.transpose(1, 2) + q = torch.ops.mlx.rope( + q, self.head_dim, total_ctx, False, self.rope_theta, 1.0, None + ) + + # SDPA over cached context + block + k = torch.cat([k_ctx, k_blk], dim=2) + v = torch.cat([v_ctx, v_blk], dim=2) + + n_rep = self.n_heads // self.n_kv_heads + if n_rep > 1: + k = k.repeat_interleave(n_rep, dim=1) + v = v.repeat_interleave(n_rep, dim=1) + + y = F.scaled_dot_product_attention( + q, k, v, attn_mask=attn_mask, scale=self.attn_scale, is_causal=False + ) + + y = y.transpose(1, 2).contiguous().reshape(B, T, -1) + return self.o_proj(y) + + +def _replace_dflash_layer_forward(layer: nn.Module) -> None: + """Replace DFlashDecoderLayer forward to take input_pos instead of cos/sin.""" + + def _mlx_dflash_layer_forward( + self, + x: torch.Tensor, + target_hidden: torch.Tensor, + input_pos: torch.Tensor, + ) -> torch.Tensor: + x = x + self.self_attn(self.input_layernorm(x), target_hidden, input_pos) + x = x + self.mlp(self.post_attention_layernorm(x)) + return x + + layer.forward = types.MethodType(_mlx_dflash_layer_forward, layer) + + +def _replace_dflash_model_forward(model: nn.Module) -> None: + """Replace DFlashDraftModel forward to pass input_pos to layers instead of cos/sin. + + After this, the model accepts only new target hidden states per call. + Context K/V caching is handled by the per-layer MLXDFlashAttention modules. + """ + + def _mlx_dflash_forward( + self, + noise_embedding: torch.Tensor, + target_hidden: torch.Tensor, + input_pos: torch.Tensor, + ) -> torch.Tensor: + ctx = self.hidden_norm(self.fc(target_hidden)) + + x = noise_embedding + for layer in self.layers: + x = layer(x, ctx, input_pos) + + return self.norm(x) + + model.forward = types.MethodType(_mlx_dflash_forward, model) + + +def dflash_mlx_source_transformations( + model: nn.Module, + max_context_length: int = 4096, + dtype: torch.dtype = torch.bfloat16, + sliding_window: int | None = None, + sliding_window_pattern: list[bool] | None = None, + max_write_len: int | None = None, +) -> nn.Module: + """Apply MLX source transformations to a DFlashDraftModel in-place. + + Swaps each layer's DFlashAttention with MLXDFlashAttention (which has a + per-layer KV cache for context K/V) and replaces layer and model forwards + to pass input_pos instead of cos/sin. + """ + for i, layer in enumerate(model.layers): + is_sliding = ( + sliding_window_pattern[i] if sliding_window_pattern is not None else False + ) + layer.self_attn = MLXDFlashAttention.from_attention( + layer.self_attn, + max_context_length, + dtype, + is_sliding=is_sliding, + window_size=sliding_window if is_sliding else None, + max_write_len=max_write_len if is_sliding else None, + ) + _replace_dflash_layer_forward(layer) + + _replace_dflash_model_forward(model) + return model diff --git a/examples/models/muse-glimmer/source_transformations/sampler.py b/examples/models/muse-glimmer/source_transformations/sampler.py new file mode 100644 index 00000000000..bcd73404d83 --- /dev/null +++ b/examples/models/muse-glimmer/source_transformations/sampler.py @@ -0,0 +1,39 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""GPU-side Gumbel-max sampler. + +A single-output sampler that lets one exported program be re-driven with +different temperatures without re-export. +""" + +from typing import Optional + +import torch + + +def sample( + logits: torch.Tensor, + temperature: Optional[torch.Tensor] = None, +) -> torch.Tensor: + """Draw a single token per batch row using the Gumbel-max trick. + + Args: + logits: ``[B, V]`` float32 logits (already soft-capped). + temperature: 0-D or 1-D float tensor; clamped to >= 1e-6. + When ``None``, returns ``logits`` unchanged. + + Returns: + ``[B, 1]`` float32 token IDs, or unmodified logits when + ``temperature`` is ``None``. + """ + if temperature is None: + return logits + + logits = logits / temperature.clamp(min=1e-6) + noise = torch.rand_like(logits) + gumbel = -torch.log(-torch.log(noise + 1e-20) + 1e-20) + return (logits + gumbel).argmax(dim=-1, keepdim=True).float() diff --git a/examples/models/muse-glimmer/tests/__init__.py b/examples/models/muse-glimmer/tests/__init__.py new file mode 100644 index 00000000000..2e41cd717f6 --- /dev/null +++ b/examples/models/muse-glimmer/tests/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. diff --git a/examples/models/muse-glimmer/tests/data/prompt_golden.json b/examples/models/muse-glimmer/tests/data/prompt_golden.json new file mode 100644 index 00000000000..cc9bf16410a --- /dev/null +++ b/examples/models/muse-glimmer/tests/data/prompt_golden.json @@ -0,0 +1,378 @@ +{ + "cases": { + "harmony_multi_turn": { + "ids_sha256": "2f61b1b3483b9324e99fb2a51317960c1972eaa8d2bac7ad1d5fcf1782c6c304", + "num_soft_tokens": 0, + "num_tokens": 33, + "prompt": "<|start|>system<|message|>You are a helpful AI assistant.<|eot|><|start|>user<|message|>Hi.<|eot|><|start|>assistant<|message|>Hello.<|eot|><|start|>user<|message|>And again?<|eot|><|start|>assistant", + "special_runs": [ + [ + 0, + 200000, + 1 + ], + [ + 1, + 200022, + 1 + ], + [ + 3, + 200023, + 1 + ], + [ + 11, + 200008, + 1 + ], + [ + 12, + 200022, + 1 + ], + [ + 14, + 200023, + 1 + ], + [ + 17, + 200008, + 1 + ], + [ + 18, + 200022, + 1 + ], + [ + 20, + 200023, + 1 + ], + [ + 23, + 200008, + 1 + ], + [ + 24, + 200022, + 1 + ], + [ + 26, + 200023, + 1 + ], + [ + 30, + 200008, + 1 + ], + [ + 31, + 200022, + 1 + ] + ] + }, + "harmony_reasoning_then_answer": { + "ids_sha256": "b0b15fbc6ff88f37de110f5ea626bcbbd6372bd987abf2f54c9abc56cf6a02e9", + "num_soft_tokens": 0, + "num_tokens": 16, + "prompt": "<|start|>assistant to=self<|message|>Thinking.<|eom|><|start|>assistant<|message|>Answer.<|eot|>", + "special_runs": [ + [ + 0, + 200000, + 1 + ], + [ + 1, + 200022, + 1 + ], + [ + 5, + 200023, + 1 + ], + [ + 9, + 200007, + 1 + ], + [ + 10, + 200022, + 1 + ], + [ + 12, + 200023, + 1 + ], + [ + 15, + 200008, + 1 + ] + ] + }, + "harmony_single_turn": { + "ids_sha256": "9c48a3a06773b9db3748feddcf6d9f2940fa51ec25cf149ad48d2bcf861836af", + "num_soft_tokens": 0, + "num_tokens": 15, + "prompt": "<|start|>user<|message|>What is 17 * 23?<|eot|><|start|>assistant", + "special_runs": [ + [ + 0, + 200000, + 1 + ], + [ + 1, + 200022, + 1 + ], + [ + 3, + 200023, + 1 + ], + [ + 12, + 200008, + 1 + ], + [ + 13, + 200022, + 1 + ] + ] + }, + "harmony_with_system": { + "ids_sha256": "8153652af10601ff43368325ab9cc02977991559579a57e1e82ed3191e9222b3", + "num_soft_tokens": 0, + "num_tokens": 22, + "prompt": "<|start|>system<|message|>You are a helpful AI assistant.<|eot|><|start|>user<|message|>Name three primes.<|eot|><|start|>assistant", + "special_runs": [ + [ + 0, + 200000, + 1 + ], + [ + 1, + 200022, + 1 + ], + [ + 3, + 200023, + 1 + ], + [ + 11, + 200008, + 1 + ], + [ + 12, + 200022, + 1 + ], + [ + 14, + 200023, + 1 + ], + [ + 19, + 200008, + 1 + ], + [ + 20, + 200022, + 1 + ] + ] + }, + "image_large": { + "ids_sha256": "506abf60a1505f948ee5842b6f0c7ef88e3ae200e888804419a6a5e2d31647d4", + "num_soft_tokens": 256, + "num_tokens": 268, + "prompt": "<|start|>user<|message|>Describe this image: <|eot|><|start|>assistant", + "special_runs": [ + [ + 0, + 200000, + 1 + ], + [ + 1, + 200022, + 1 + ], + [ + 3, + 200023, + 1 + ], + [ + 9, + 200092, + 256 + ], + [ + 265, + 200008, + 1 + ], + [ + 266, + 200022, + 1 + ] + ] + }, + "image_small": { + "ids_sha256": "0335689d8708398a95c51637c63c75411308d7619b028945074927210aca8830", + "num_soft_tokens": 4, + "num_tokens": 16, + "prompt": "<|start|>user<|message|>Describe this image: <|eot|><|start|>assistant", + "special_runs": [ + [ + 0, + 200000, + 1 + ], + [ + 1, + 200022, + 1 + ], + [ + 3, + 200023, + 1 + ], + [ + 9, + 200092, + 4 + ], + [ + 13, + 200008, + 1 + ], + [ + 14, + 200022, + 1 + ] + ] + }, + "readme_minimal_user": { + "ids_sha256": "f155e8ffe8ef139f05ddfb2906424f988d52d6707035a70e674ede1ddc4b65eb", + "num_soft_tokens": 0, + "num_tokens": 14, + "prompt": "<|start|>user<|message|>What is the meaning of life?<|eot|><|start|>assistant", + "special_runs": [ + [ + 0, + 200000, + 1 + ], + [ + 1, + 200022, + 1 + ], + [ + 3, + 200023, + 1 + ], + [ + 11, + 200008, + 1 + ], + [ + 12, + 200022, + 1 + ] + ] + }, + "readme_target_only": { + "ids_sha256": "ffb960a85bd36683430209f378193c1425820187e4833fbec3b0b03fce3dfdbd", + "num_soft_tokens": 0, + "num_tokens": 24, + "prompt": "<|start|>system<|message|>You are a helpful assistant.<|eot|><|start|>user<|message|>What is the meaning of life?<|eot|><|start|>assistant", + "special_runs": [ + [ + 0, + 200000, + 1 + ], + [ + 1, + 200022, + 1 + ], + [ + 3, + 200023, + 1 + ], + [ + 10, + 200008, + 1 + ], + [ + 11, + 200022, + 1 + ], + [ + 13, + 200023, + 1 + ], + [ + 21, + 200008, + 1 + ], + [ + 22, + 200022, + 1 + ] + ] + }, + "text_plain": { + "ids_sha256": "7494d47019eb24fc44194578794b9abf3ebb36652d45e142bfec377b47d20d4c", + "num_soft_tokens": 0, + "num_tokens": 6, + "prompt": "The meaning of life is", + "special_runs": [ + [ + 0, + 200000, + 1 + ] + ] + } + }, + "comment": "Regenerate with tests/gen_prompt_golden.py. Commits that change these numbers must say why.", + "tokenizer_sha256": "c9dbee66967b58f31a7c27f723c3760da3526ccd0427578e8905b0abb0031c4d" +} diff --git a/examples/models/muse-glimmer/tests/dflash_timing_test.cpp b/examples/models/muse-glimmer/tests/dflash_timing_test.cpp new file mode 100644 index 00000000000..eac0505b00e --- /dev/null +++ b/examples/models/muse-glimmer/tests/dflash_timing_test.cpp @@ -0,0 +1,96 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include +#include + +namespace { + +using executorch::extension::llm::DFlashCycleTiming; +using executorch::extension::llm::DFlashDecodeTiming; + +bool test_accumulates_speculative_and_target_only_cycles() { + DFlashDecodeTiming timing; + DFlashCycleTiming speculative; + speculative.draft_execute_ms = 1.0; + speculative.draft_logits_copy_ms = 2.0; + speculative.draft_sampling_ms = 3.0; + speculative.target_execute_ms = 4.0; + speculative.target_logits_copy_ms = 5.0; + speculative.target_hidden_copy_ms = 6.0; + speculative.accept_correction_ms = 7.0; + speculative.state_commit_ms = 8.0; + speculative.total_cycle_ms = 40.0; + speculative.draft_attempts_by_row = {1, 1, 1}; + speculative.draft_accepts_by_row = {1, 1, 0}; + timing.record(speculative); + + DFlashCycleTiming early_rejection; + early_rejection.draft_attempts_by_row = {1}; + early_rejection.draft_accepts_by_row = {0}; + timing.record(early_rejection); + + DFlashCycleTiming target_only; + target_only.target_execute_ms = 10.0; + target_only.target_logits_copy_ms = 11.0; + target_only.target_hidden_copy_ms = 12.0; + target_only.accept_correction_ms = 13.0; + target_only.state_commit_ms = 14.0; + target_only.total_cycle_ms = 65.0; + target_only.target_only = true; + timing.record(target_only); + + return timing.cycles == 3 && timing.speculative_cycles == 2 && + timing.target_only_cycles == 1 && timing.draft_execute_ms == 1.0 && + timing.draft_logits_copy_ms == 2.0 && timing.draft_sampling_ms == 3.0 && + timing.target_execute_ms == 14.0 && + timing.target_logits_copy_ms == 16.0 && + timing.target_hidden_copy_ms == 18.0 && + timing.accept_correction_ms == 20.0 && timing.state_commit_ms == 22.0 && + timing.total_cycle_ms == 105.0 && + timing.draft_attempts_by_row == std::vector({2, 1, 1}) && + timing.draft_accepts_by_row == std::vector({1, 1, 0}); +} + +bool test_reset_clears_all_metrics() { + DFlashDecodeTiming timing; + DFlashCycleTiming cycle; + cycle.draft_execute_ms = 1.0; + cycle.total_cycle_ms = 2.0; + cycle.draft_attempts_by_row = {1}; + cycle.draft_accepts_by_row = {1}; + timing.record(cycle); + timing.reset(); + + return timing.cycles == 0 && timing.speculative_cycles == 0 && + timing.target_only_cycles == 0 && timing.draft_execute_ms == 0.0 && + timing.draft_logits_copy_ms == 0.0 && timing.draft_sampling_ms == 0.0 && + timing.target_execute_ms == 0.0 && timing.target_logits_copy_ms == 0.0 && + timing.target_hidden_copy_ms == 0.0 && + timing.accept_correction_ms == 0.0 && timing.state_commit_ms == 0.0 && + timing.total_cycle_ms == 0.0 && timing.draft_attempts_by_row.empty() && + timing.draft_accepts_by_row.empty(); +} + +} // namespace + +int main() { + if (!test_accumulates_speculative_and_target_only_cycles()) { + std::fprintf( + stderr, "FAILED: accumulates speculative and target-only cycles\n"); + return 1; + } + if (!test_reset_clears_all_metrics()) { + std::fprintf(stderr, "FAILED: reset clears all metrics\n"); + return 1; + } + std::printf("All DFlash timing tests passed.\n"); + return 0; +} diff --git a/examples/models/muse-glimmer/tests/gen_prompt_golden.py b/examples/models/muse-glimmer/tests/gen_prompt_golden.py new file mode 100644 index 00000000000..872524b97f6 --- /dev/null +++ b/examples/models/muse-glimmer/tests/gen_prompt_golden.py @@ -0,0 +1,82 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""Regenerate tests/data/prompt_golden.json from the real tokenizer. + + MUSE_GLIMMER_HF_DIR=assets/hf \ + python dev/run.py executorch.examples.models.muse_glimmer.tests.gen_prompt_golden + +Only lengths, the special-token skeleton, and a digest of the full id sequence +are written. The text ids themselves stay out of the repo. + +Re-validating after a regeneration +---------------------------------- +``tokenizer.json`` and the golden are pinned to each other by sha256, so drift is +caught automatically and the checks below are not worth running on a schedule. +Run them once whenever you bump the pinned revision, to confirm the new +tokenizer still agrees with the independent sources. + +1. tiktoken over ``l4_200k_base`` from the quantized repo. A different BPE + implementation reading a different vocab file. Build the Encoding as + ``meta_reference_implementation/standalone_inference.py`` does, registering + ``tokenizer_config.json``'s ``extra_special_tokens`` at ``200000 + index``, + then compare ``encode(prompt, allowed_special="all")`` against this + tokenizer for every case prompt. Last run: identical ids, all 7 cases. + +2. The vocab embedded in ``onyx-rl_v2-q4km-gs128.gguf``. Compare all 202048 + id-to-string pairs against ``tokenizer.json``. Last run: zero mismatches. + +3. ``transformers`` with the Onyx wheel from the transformers_onyx repo, to + check assembly rather than the BPE. Pass ``current_date`` explicitly: the + template calls ``strftime_now``, so a rendering left to default is not + reproducible tomorrow. Last run: ``apply_chat_template`` output matched a + raw encode of the same text, 64 ids. +""" + +import json +import os +import sys + +from executorch.examples.models.muse_glimmer.tests import prompt_cases as pc + +GOLDEN_PATH = os.path.join( + os.path.dirname(os.path.abspath(__file__)), "data", "prompt_golden.json" +) + + +def build(): + directory = pc.hf_dir() + if directory is None: + sys.exit(f"Set {pc.HF_DIR_ENV} to a directory containing tokenizer.json") + encode = pc.real_encoder(directory) + + entries = {} + for case in pc.CASES: + ids = pc.build_prompt_ids(encode, case) + entries[case.name] = { + "prompt": case.prompt, + "num_soft_tokens": case.num_soft_tokens, + "num_tokens": len(ids), + "special_runs": pc.special_runs(ids), + "ids_sha256": pc.ids_sha256(ids), + } + return { + "comment": "Regenerate with tests/gen_prompt_golden.py. " + "Commits that change these numbers must say why.", + "tokenizer_sha256": pc.file_sha256(os.path.join(directory, "tokenizer.json")), + "cases": entries, + } + + +if __name__ == "__main__": + golden = build() + os.makedirs(os.path.dirname(GOLDEN_PATH), exist_ok=True) + with open(GOLDEN_PATH, "w") as fh: + json.dump(golden, fh, indent=2, sort_keys=True) + fh.write("\n") + print(f"wrote {GOLDEN_PATH}") + for name, e in sorted(golden["cases"].items()): + print(f" {name:<32} {e['num_tokens']:>5} tokens {e['ids_sha256'][:16]}") diff --git a/examples/models/muse-glimmer/tests/gen_resize_golden.py b/examples/models/muse-glimmer/tests/gen_resize_golden.py new file mode 100644 index 00000000000..3861e55d903 --- /dev/null +++ b/examples/models/muse-glimmer/tests/gen_resize_golden.py @@ -0,0 +1,46 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""Emit the PIL LANCZOS goldens embedded in the resize parity tests. + +Run: + python gen_resize_golden.py +""" + +from PIL import Image + + +def make_image(w: int, h: int) -> Image.Image: + """Deterministic RGB content with edges and a gradient (no RNG).""" + px = bytearray() + for y in range(h): + for x in range(w): + px.append((x * 37 + y * 11) % 256) # R: diagonal ramp + px.append(255 if (x < w // 3 and y < h // 2) else 16) # G: hard edge + px.append((x * x + y * y * 3) % 256) # B: curved gradient + return Image.frombytes("RGB", (w, h), bytes(px)) + + +def emit(src_w: int, src_h: int, dst_w: int, dst_h: int) -> None: + src = make_image(src_w, src_h) + dst = src.resize((dst_w, dst_h), Image.LANCZOS) + print(f" // {src_w}x{src_h} -> {dst_w}x{dst_h}") + print(f" {{{src_w}, {src_h}, {dst_w}, {dst_h},") + vals = list(dst.tobytes()) + for i in range(0, len(vals), 12): + chunk = ", ".join(str(v) for v in vals[i : i + 12]) + print(f" {chunk},") + print(" },") + + +def main() -> None: + print("// Generated by gen_resize_golden.py -- PIL LANCZOS reference output.") + emit(9, 7, 5, 4) # downscale, support stretched on both axes + emit(4, 3, 7, 6) # upscale + emit(16, 16, 8, 8) # exact 2x downscale + + +main() diff --git a/examples/models/muse-glimmer/tests/prompt_cases.py b/examples/models/muse-glimmer/tests/prompt_cases.py new file mode 100644 index 00000000000..e17c2cbd930 --- /dev/null +++ b/examples/models/muse-glimmer/tests/prompt_cases.py @@ -0,0 +1,193 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""Prompt matrix and the reference token builder behind the golden tests. + +The builder states the runner's prompt contract rather than mirroring its +implementation, so a refactor that preserves the contract leaves the golden +untouched and a refactor that does not shows up as a golden diff. +""" + +import hashlib +import os +from dataclasses import dataclass + +BOS_ID = 200000 +IMAGE_START_ID = 200080 +IMAGE_END_ID = 200081 +PATCH_ID = 200092 +IMAGE_MARKER = "" + +# Tokens the image span costs beyond the patches themselves. Zero: the canonical +# format is a bare <|patch|> run, which is what OnyxProcessor.replace_image_token +# emits and what meta_reference_implementation splices on. +IMAGE_WRAPPER_TOKENS = 0 + +HF_DIR_ENV = "MUSE_GLIMMER_HF_DIR" + +_SYSTEM = "<|start|>system<|message|>You are a helpful AI assistant.<|eot|>" +_ASSISTANT_HEADER = "<|start|>assistant" + + +@dataclass(frozen=True) +class Case: + name: str + prompt: str + num_soft_tokens: int = 0 + + +CASES = [ + Case("text_plain", "The meaning of life is"), + Case( + "harmony_single_turn", + f"<|start|>user<|message|>What is 17 * 23?<|eot|>{_ASSISTANT_HEADER}", + ), + Case( + "harmony_with_system", + f"{_SYSTEM}<|start|>user<|message|>Name three primes.<|eot|>{_ASSISTANT_HEADER}", + ), + Case( + "harmony_multi_turn", + f"{_SYSTEM}<|start|>user<|message|>Hi.<|eot|>" + "<|start|>assistant<|message|>Hello.<|eot|>" + f"<|start|>user<|message|>And again?<|eot|>{_ASSISTANT_HEADER}", + ), + Case( + "harmony_reasoning_then_answer", + "<|start|>assistant to=self<|message|>Thinking.<|eom|>" + "<|start|>assistant<|message|>Answer.<|eot|>", + ), + # The two prompts the README quotes, so the counts it cites stay honest. + Case( + "readme_minimal_user", + "<|start|>user<|message|>What is the meaning of life?<|eot|>" + f"{_ASSISTANT_HEADER}", + ), + Case( + "readme_target_only", + "<|start|>system<|message|>You are a helpful assistant.<|eot|>" + "<|start|>user<|message|>What is the meaning of life?<|eot|>" + f"{_ASSISTANT_HEADER}", + ), + Case( + "image_small", + f"<|start|>user<|message|>Describe this image: {IMAGE_MARKER}<|eot|>" + f"{_ASSISTANT_HEADER}", + num_soft_tokens=4, + ), + Case( + "image_large", + f"<|start|>user<|message|>Describe this image: {IMAGE_MARKER}<|eot|>" + f"{_ASSISTANT_HEADER}", + num_soft_tokens=256, + ), +] + + +def text_only_len(golden_case, case): + """Golden length with the image span removed, so a real image can be sized in.""" + if not case.num_soft_tokens: + return golden_case["num_tokens"] + return golden_case["num_tokens"] - case.num_soft_tokens - IMAGE_WRAPPER_TOKENS + + +def build_prompt_ids(encode, case): + """Prompt contract: BOS, with the image patch run replacing ````. + + ``encode`` takes text and returns ids without special-token insertion. + """ + ids = [BOS_ID] + if not case.num_soft_tokens: + if IMAGE_MARKER in case.prompt: + raise ValueError("text-only prompt cannot contain ") + ids.extend(encode(case.prompt)) + return ids + + if case.prompt.count(IMAGE_MARKER) != 1: + raise ValueError("image prompt must contain exactly one ") + before, after = case.prompt.split(IMAGE_MARKER) + ids.extend(encode(before)) + ids.extend([PATCH_ID] * case.num_soft_tokens) + ids.extend(encode(after)) + return ids + + +def stub_encode(text): + """Deterministic stand-in for the BPE, so shape can be tested without assets. + + Special-token substrings resolve to their real ids; everything else becomes + one id per character in a range that cannot collide with them. + """ + specials = { + "<|begin_of_text|>": BOS_ID, + "<|end_of_text|>": 200001, + "<|eom|>": 200007, + "<|eot|>": 200008, + "<|start|>": 200022, + "<|message|>": 200023, + "<|image_start|>": IMAGE_START_ID, + "<|image_end|>": IMAGE_END_ID, + "<|patch|>": PATCH_ID, + } + ids = [] + i = 0 + while i < len(text): + for piece, pid in specials.items(): + if text.startswith(piece, i): + ids.append(pid) + i += len(piece) + break + else: + ids.append(ord(text[i]) % 1000) + i += 1 + return ids + + +def hf_dir(): + """Directory holding the real tokenizer.json, or None when unset.""" + path = os.environ.get(HF_DIR_ENV) + if path and os.path.isfile( + os.path.join(os.path.expanduser(path), "tokenizer.json") + ): + return os.path.expanduser(path) + return None + + +def real_encoder(directory): + from tokenizers import Tokenizer + + tok = Tokenizer.from_file(os.path.join(directory, "tokenizer.json")) + return lambda text: tok.encode(text, add_special_tokens=False).ids + + +def ids_sha256(ids): + """Stable digest of an id sequence. Committed instead of the ids themselves.""" + return hashlib.sha256(",".join(str(i) for i in ids).encode()).hexdigest() + + +def file_sha256(path): + h = hashlib.sha256() + with open(path, "rb") as fh: + for chunk in iter(lambda: fh.read(1 << 20), b""): + h.update(chunk) + return h.hexdigest() + + +def special_runs(ids): + """Run-length view of the special-token skeleton: [[index, id, count], ...]. + + Run-length keeps a 256-patch image case readable, and makes a golden diff say + what actually moved instead of renumbering every following position. + """ + runs = [] + for i, tok in enumerate(ids): + if tok < 200000: + continue + if runs and runs[-1][1] == tok and i == runs[-1][0] + runs[-1][2]: + runs[-1][2] += 1 + else: + runs.append([i, tok, 1]) + return runs diff --git a/examples/models/muse-glimmer/tests/sampling_test.cpp b/examples/models/muse-glimmer/tests/sampling_test.cpp new file mode 100644 index 00000000000..ff0b7c1739e --- /dev/null +++ b/examples/models/muse-glimmer/tests/sampling_test.cpp @@ -0,0 +1,379 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr float kTolerance = 1e-6f; + +bool near(float actual, float expected) { + return std::abs(actual - expected) <= kTolerance; +} + +bool check_normalized(const std::vector& probs) { + double sum = 0.0; + for (const float probability : probs) { + if (probability < 0.0f) { + return false; + } + sum += probability; + } + return std::abs(sum - 1.0) <= kTolerance; +} + +std::vector reference_probabilities( + const std::vector& logits, + double temperature, + int32_t top_k, + double top_p) { + std::vector indices(logits.size()); + std::iota(indices.begin(), indices.end(), 0); + std::sort(indices.begin(), indices.end(), [&](int64_t lhs, int64_t rhs) { + if (logits[lhs] != logits[rhs]) { + return logits[lhs] > logits[rhs]; + } + return lhs < rhs; + }); + + int64_t retained = logits.size(); + if (top_k > 0 && top_k < retained) { + retained = top_k; + } + std::vector probs(logits.size(), 0.0f); + const float max_val = logits[indices.front()]; + double sum = 0.0; + for (int64_t i = 0; i < retained; ++i) { + probs[indices[i]] = std::exp( + (logits[indices[i]] - max_val) / static_cast(temperature)); + sum += probs[indices[i]]; + } + if (top_p > 0.0 && top_p < 1.0) { + double nucleus_sum = 0.0; + int64_t cutoff = 0; + while (cutoff < retained && nucleus_sum < top_p * sum) { + nucleus_sum += probs[indices[cutoff++]]; + } + for (int64_t i = cutoff; i < retained; ++i) { + probs[indices[i]] = 0.0f; + } + retained = cutoff; + sum = nucleus_sum; + } + for (int64_t i = 0; i < retained; ++i) { + probs[indices[i]] /= static_cast(sum); + } + return probs; +} + +bool test_argmax_index_tie_and_tail() { + const std::vector values = {-4.0f, 3.0f, 1.0f, 3.0f, 2.0f, 3.0f, 0.0f}; + return muse_glimmer::argmax_index(values.data(), values.size()) == 1; +} + +bool test_max_value_all_negative_with_tail() { + const std::vector values = {-9.0f, -4.0f, -7.0f, -8.0f, -5.0f}; + return muse_glimmer::max_value(values.data(), values.size()) == -4.0f; +} + +bool test_normalize_probabilities_with_tail() { + std::vector probabilities = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f}; + muse_glimmer::normalize_probabilities( + probabilities.data(), probabilities.size(), 15.0f); + const std::vector expected = { + 1.0f / 15.0f, 2.0f / 15.0f, 3.0f / 15.0f, 4.0f / 15.0f, 5.0f / 15.0f}; + for (size_t i = 0; i < probabilities.size(); ++i) { + if (!near(probabilities[i], expected[i])) { + return false; + } + } + return check_normalized(probabilities); +} + +bool test_unfiltered_softmax() { + const std::vector logits = {0.0f, 1.0f, 2.0f}; + const auto probs = muse_glimmer::sampling_probabilities( + logits.data(), logits.size(), 1.0, 0, 1.0); + const double sum = 1.0 + std::exp(1.0) + std::exp(2.0); + return check_normalized(probs) && near(probs[0], 1.0 / sum) && + near(probs[1], std::exp(1.0) / sum) && + near(probs[2], std::exp(2.0) / sum); +} + +bool test_top_k() { + const std::vector logits = {0.0f, 3.0f, 1.0f, 2.0f}; + const auto probs = muse_glimmer::sampling_probabilities( + logits.data(), logits.size(), 1.0, 2, 1.0); + const double sum = std::exp(3.0) + std::exp(2.0); + return check_normalized(probs) && probs[0] == 0.0f && + near(probs[1], std::exp(3.0) / sum) && probs[2] == 0.0f && + near(probs[3], std::exp(2.0) / sum); +} + +bool test_top_p_includes_crossing_token() { + const std::vector logits = { + std::log(0.5f), std::log(0.3f), std::log(0.15f), std::log(0.05f)}; + const auto probs = muse_glimmer::sampling_probabilities( + logits.data(), logits.size(), 1.0, 0, 0.75); + return check_normalized(probs) && near(probs[0], 0.625f) && + near(probs[1], 0.375f) && probs[2] == 0.0f && probs[3] == 0.0f; +} + +bool test_top_p_tie_breaks_by_token_id() { + const std::vector logits = {-0.0f, 0.0f, 0.0f}; + const auto probs = muse_glimmer::sampling_probabilities( + logits.data(), logits.size(), 1.0, 0, 0.5); + return check_normalized(probs) && near(probs[0], 0.5f) && + near(probs[1], 0.5f) && probs[2] == 0.0f; +} + +bool test_top_k_then_top_p() { + const std::vector logits = { + std::log(0.4f), std::log(0.3f), std::log(0.2f), std::log(0.1f)}; + const auto probs = muse_glimmer::sampling_probabilities( + logits.data(), logits.size(), 1.0, 3, 0.6); + return check_normalized(probs) && near(probs[0], 4.0f / 7.0f) && + near(probs[1], 3.0f / 7.0f) && probs[2] == 0.0f && probs[3] == 0.0f; +} + +bool test_top_k_tie_breaks_by_token_id() { + const std::vector logits = {1.0f, 1.0f, 1.0f, 0.0f}; + const auto probs = muse_glimmer::sampling_probabilities( + logits.data(), logits.size(), 1.0, 2, 1.0); + return check_normalized(probs) && near(probs[0], 0.5f) && + near(probs[1], 0.5f) && probs[2] == 0.0f && probs[3] == 0.0f; +} + +bool test_full_vocab_overwrites_reused_probability_buffer() { + const std::vector logits = { + std::log(0.5f), std::log(0.3f), std::log(0.15f), std::log(0.05f)}; + muse_glimmer::SamplingWorkspace workspace; + workspace.probabilities.assign(logits.size(), 123.0f); + const float* probabilities_data = workspace.probabilities.data(); + muse_glimmer::fill_sampling_probabilities( + logits.data(), + logits.size(), + 1.0, + 0, + 0.75, + workspace.probabilities, + workspace.candidates); + return workspace.probabilities.data() == probabilities_data && + check_normalized(workspace.probabilities) && + near(workspace.probabilities[0], 0.625f) && + near(workspace.probabilities[1], 0.375f) && + workspace.probabilities[2] == 0.0f && workspace.probabilities[3] == 0.0f; +} + +bool test_reuses_workspace_buffers() { + const std::vector logits = {0.0f, 3.0f, 1.0f, 2.0f}; + muse_glimmer::SamplingWorkspace workspace; + muse_glimmer::fill_sampling_probabilities( + logits.data(), + logits.size(), + 1.0, + 0, + 0.95, + workspace.probabilities, + workspace); + const float* probabilities_data = workspace.probabilities.data(); + const int32_t* candidates_data = workspace.candidates.data(); + const uint32_t* radix_keys_data = workspace.radix_keys.data(); + const int32_t* radix_scratch_data = workspace.radix_scratch.data(); + muse_glimmer::fill_sampling_probabilities( + logits.data(), + logits.size(), + 0.7, + 0, + 0.8, + workspace.probabilities, + workspace); + return workspace.probabilities.data() == probabilities_data && + workspace.candidates.data() == candidates_data && + workspace.radix_keys.data() == radix_keys_data && + workspace.radix_scratch.data() == radix_scratch_data && + check_normalized(workspace.probabilities); +} + +bool test_accept_with_probability() { + std::mt19937 rejected_rng(42); + const auto rejected_rng_before = rejected_rng; + if (muse_glimmer::accept_with_probability(rejected_rng, 0.0f) || + rejected_rng == rejected_rng_before) { + return false; + } + + std::mt19937 accepted_rng(42); + const std::vector probabilities = {0.2f, 0.5f, 0.3f}; + const auto probabilities_before = probabilities; + return muse_glimmer::accept_with_probability(accepted_rng, 1.0f) && + probabilities == probabilities_before; +} + +bool test_excluded_token_correction() { + std::mt19937 rng(42); + std::vector probabilities = {0.2f, 0.5f, 0.3f}; + const float* probabilities_data = probabilities.data(); + const uint64_t sampled = + muse_glimmer::sample_excluding_token_in_place(rng, probabilities, 1); + return probabilities.data() == probabilities_data && sampled != 1 && + check_normalized(probabilities) && near(probabilities[0], 0.4f) && + probabilities[1] == 0.0f && near(probabilities[2], 0.6f); +} + +bool test_argmax_rejection_rng_draws() { + std::mt19937 actual(42); + std::mt19937 expected(42); + std::vector probabilities = {0.4f, 0.0f, 0.6f}; + if (muse_glimmer::accept_with_probability(actual, 0.0f)) { + return false; + } + muse_glimmer::sample_excluding_token_in_place(actual, probabilities, 1); + + std::uniform_real_distribution uniform(0.0f, 1.0f); + uniform(expected); + uniform(expected); + return actual == expected; +} + +bool test_residual_in_place() { + std::mt19937 rng(42); + std::vector target = {0.1f, 0.6f, 0.3f}; + const std::vector draft = {0.2f, 0.2f, 0.6f}; + const float* target_data = target.data(); + const uint64_t sampled = + muse_glimmer::sample_from_residual_in_place(rng, target, draft); + return target.data() == target_data && target[0] == 0.0f && + near(target[1], 1.0f) && target[2] == 0.0f && sampled == 1; +} + +bool probabilities_match( + const std::vector& actual, + const std::vector& expected) { + if (!check_normalized(actual) || actual.size() != expected.size()) { + return false; + } + for (size_t i = 0; i < actual.size(); ++i) { + if ((actual[i] == 0.0f) != (expected[i] == 0.0f) || + !near(actual[i], expected[i])) { + return false; + } + } + return true; +} + +bool test_matches_full_sort_reference() { + const std::vector logits = { + -2.0f, 1.2f, 0.3f, 4.0f, -0.7f, 2.1f, 1.2f, 0.0f}; + const struct { + double temperature; + int32_t top_k; + double top_p; + } configs[] = { + {0.7, 0, 1.0}, + {1.0, 0, 0.95}, + {1.3, 5, 1.0}, + {0.9, 5, 0.8}, + {2.0, 1, 0.1}, + }; + + for (const auto& config : configs) { + const auto actual = muse_glimmer::sampling_probabilities( + logits.data(), + logits.size(), + config.temperature, + config.top_k, + config.top_p); + const auto expected = reference_probabilities( + logits, config.temperature, config.top_k, config.top_p); + if (!probabilities_match(actual, expected)) { + return false; + } + } + return true; +} + +bool test_partition_top_p_matches_full_sort_reference() { + std::mt19937 rng(12345); + std::uniform_real_distribution logit_distribution(-8.0f, 8.0f); + const double temperatures[] = {0.5, 1.0, 1.7}; + const double top_ps[] = {0.1, 0.5, 0.8, 0.95, 0.999}; + const int32_t top_ks[] = {0, 1, 7, 31, 127}; + + for (int iteration = 0; iteration < 20; ++iteration) { + std::vector logits(257); + for (float& logit : logits) { + logit = logit_distribution(rng); + } + for (size_t i = 0; i < logits.size(); i += 17) { + logits[i] = 2.0f; + } + + for (const double temperature : temperatures) { + for (const double top_p : top_ps) { + for (const int32_t top_k : top_ks) { + const auto actual = muse_glimmer::sampling_probabilities( + logits.data(), logits.size(), temperature, top_k, top_p); + const auto expected = + reference_probabilities(logits, temperature, top_k, top_p); + if (!probabilities_match(actual, expected)) { + return false; + } + } + } + } + } + return true; +} + +} // namespace + +int main() { + const struct { + const char* name; + bool (*run)(); + } tests[] = { + {"argmax_index_tie_and_tail", test_argmax_index_tie_and_tail}, + {"max_value_all_negative_with_tail", + test_max_value_all_negative_with_tail}, + {"normalize_probabilities_with_tail", + test_normalize_probabilities_with_tail}, + {"unfiltered_softmax", test_unfiltered_softmax}, + {"top_k", test_top_k}, + {"top_p_includes_crossing_token", test_top_p_includes_crossing_token}, + {"top_p_tie_breaks_by_token_id", test_top_p_tie_breaks_by_token_id}, + {"top_k_then_top_p", test_top_k_then_top_p}, + {"top_k_tie_breaks_by_token_id", test_top_k_tie_breaks_by_token_id}, + {"full_vocab_overwrites_reused_probability_buffer", + test_full_vocab_overwrites_reused_probability_buffer}, + {"reuses_workspace_buffers", test_reuses_workspace_buffers}, + {"accept_with_probability", test_accept_with_probability}, + {"excluded_token_correction", test_excluded_token_correction}, + {"argmax_rejection_rng_draws", test_argmax_rejection_rng_draws}, + {"residual_in_place", test_residual_in_place}, + {"matches_full_sort_reference", test_matches_full_sort_reference}, + {"partition_top_p_matches_full_sort_reference", + test_partition_top_p_matches_full_sort_reference}, + }; + + for (const auto& test : tests) { + if (!test.run()) { + std::fprintf(stderr, "FAILED: %s\n", test.name); + return 1; + } + } + std::printf("All sampling tests passed.\n"); + return 0; +} diff --git a/examples/models/muse-glimmer/tests/scripts/test_multisession.sh b/examples/models/muse-glimmer/tests/scripts/test_multisession.sh new file mode 100755 index 00000000000..f2ade7a16c5 --- /dev/null +++ b/examples/models/muse-glimmer/tests/scripts/test_multisession.sh @@ -0,0 +1,246 @@ +#!/usr/bin/env bash +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +# ============================================================================= +# test_multisession.sh +# +# Black-box smoke test for the muse_glimmer OpenAI-compatible server's multi-session +# support. It exercises three independent properties over plain HTTP (no code +# imports, no access to the server process) so it can run against any live +# server instance: +# +# TEST 1 Same-session multi-turn context coherence +# Two turns on the SAME session_id. The client sends the full +# conversation history on turn 2 and the model must recall a secret +# code introduced on turn 1. This proves the server correctly threads +# the client-supplied history through a multi-turn exchange. +# +# IMPORTANT: this does NOT prove KV warm-resume was engaged. The +# warm-resume optimization is output-transparent by design -- with or +# without it, and regardless of session_id, the reply is identical +# because correctness comes from the history in the REQUEST, not from +# server-side memory. The only signal that KV was actually reused is +# the server-side log line +# llm_turn_stats ... reused_prompt_tokens= +# which is NOT exposed in the HTTP response, so it cannot be asserted +# from this black-box script. To confirm reuse, watch the server +# stdout for reused_prompt_tokens > 0 on the second turn. +# +# TEST 2 Concurrent session isolation +# N distinct session_ids fired in parallel, each asked to echo its own +# unique token. Every response must contain ONLY its own token -> +# proves concurrent sessions do not cross-contaminate. +# +# TEST 3 Cross-session isolation +# A fresh session asks for another session's secret. It must NOT know +# it -> proves per-session state is isolated. +# +# The server caps live sessions at --max-sessions (default 16). This script +# tracks every session_id it opens and closes them all on exit (DELETE +# /v1/sessions/{id}), so it is self-cleaning and safe to re-run back-to-back +# without exhausting the session pool. +# +# The server must be started separately (this script does NOT launch it). Start +# it, for example, with: +# +# PYTHONPATH=/path/to/executorch:/path/to/parent \ +# LD_LIBRARY_PATH=/lib:/lib64 \ +# CUDA_VISIBLE_DEVICES=0 NO_PROXY=127.0.0.1,localhost no_proxy=127.0.0.1,localhost \ +# conda run -n --no-capture-output python -m \ +# executorch.examples.models.muse_glimmer.serving.serve \ +# --model-path --data-path \ +# --tokenizer-path --hf-tokenizer \ +# --worker-bin /examples/models/muse-glimmer/muse_glimmer_worker \ +# --tool-parser atem --model-id muse_glimmer --max-context 131072 \ +# --max-sessions 16 --host 127.0.0.1 --port 8000 +# +# ----------------------------------------------------------------------------- +# USAGE +# bash test_multisession.sh [HOST_PORT] [MODEL_ID] [NUM_CONCURRENT] +# +# HOST_PORT host:port of the running server (default: 127.0.0.1:8000) +# MODEL_ID model id served by the server (default: muse_glimmer) +# NUM_CONCURRENT concurrent sessions for TEST 2 (default: 8) +# +# EXAMPLES +# bash test_multisession.sh +# bash test_multisession.sh 127.0.0.1:8001 +# bash test_multisession.sh 127.0.0.1:8000 muse_glimmer 16 +# +# REQUIREMENTS +# curl, python3 (stdlib only). No extra packages. +# +# EXIT CODE +# 0 if all three tests pass, non-zero otherwise. +# ============================================================================= + +set -u + +HOST_PORT="${1:-127.0.0.1:8000}" +MODEL_ID="${2:-muse_glimmer}" +NUM_CONCURRENT="${3:-8}" +BASE="http://${HOST_PORT}/v1/chat/completions" +HEALTH="http://${HOST_PORT}/health" + +# Never route localhost through a proxy. +export NO_PROXY=127.0.0.1,localhost +export no_proxy=127.0.0.1,localhost + +CURL=(curl -s --noproxy '*' -m 120 -H "Content-Type: application/json") +SESS_BASE="http://${HOST_PORT}/v1/sessions" + +# Track every session_id we create so we can free them on exit. The server +# caps live sessions at --max-sessions; leaking them would exhaust the pool and +# make later runs fail with "capacity_exhausted". +OPENED_SESSIONS=() +track_session() { OPENED_SESSIONS+=("$1"); } +cleanup_sessions() { + for sid in "${OPENED_SESSIONS[@]:-}"; do + [ -n "$sid" ] || continue + curl -s --noproxy '*' -m 15 -X DELETE "${SESS_BASE}/${sid}" -o /dev/null 2>/dev/null || true + done +} +trap cleanup_sessions EXIT + +pass=0 +fail=0 +ok() { echo " [PASS] $1"; pass=$((pass + 1)); } +bad() { echo " [FAIL] $1"; fail=$((fail + 1)); } + +# Extract the assistant message content from a chat-completion response. +content_of() { + python3 -c "import sys,json; d=json.load(sys.stdin); print(d['choices'][0]['message'].get('content') or '')" +} + +# ----------------------------------------------------------------------------- +echo "=== muse_glimmer multi-session smoke test ===" +echo "server : ${BASE}" +echo "model : ${MODEL_ID}" +echo + +# Health check first so failures are obvious. +if ! "${CURL[@]}" -o /dev/null -w '%{http_code}' "${HEALTH}" 2>/dev/null | grep -q '200'; then + echo "ERROR: server health check failed at ${HEALTH}" + echo " Start the server first (see header of this script), then retry." + exit 2 +fi +echo "health : ok" +echo + +# ----------------------------------------------------------------------------- +# TEST 1: same-session multi-turn context (recall a secret code). +# ----------------------------------------------------------------------------- +echo "TEST 1: same-session multi-turn context coherence" +# NOTE: This checks that the model consumes the client-supplied history, not +# that KV warm-resume fired (warm-resume is output-transparent; its only signal +# is the server-side reused_prompt_tokens log, not visible over HTTP). +SESS_TRIP="sessTrip_$" +track_session "$SESS_TRIP" +SECRET="FALCON-77" +LONG="You are helping me plan a trip. I have 7 days and a budget of 3000 dollars, \ +I love hiking and museums, and I want you to remember this secret trip code: ${SECRET}. \ +Please acknowledge with OK and the code." + +REQ1=$(python3 -c ' +import json,sys +long=sys.argv[1]; sid=sys.argv[2]; model=sys.argv[3] +print(json.dumps({"model":model,"session_id":sid,"temperature":0,"max_tokens":40, + "messages":[{"role":"user","content":long}]})) +' "$LONG" "$SESS_TRIP" "$MODEL_ID") +A1=$(printf '%s' "$REQ1" | "${CURL[@]}" -d @- "$BASE" | content_of) +echo " turn1 assistant: $(printf '%s' "$A1" | tr '\n' ' ' | cut -c1-80)" + +REQ2=$(python3 -c ' +import json,sys +long=sys.argv[1]; a1=sys.argv[2]; sid=sys.argv[3]; model=sys.argv[4] +msgs=[{"role":"user","content":long}, + {"role":"assistant","content":a1}, + {"role":"user","content":"What was the secret trip code I gave you? Answer with just the code."}] +print(json.dumps({"model":model,"session_id":sid,"temperature":0,"max_tokens":40,"messages":msgs})) +' "$LONG" "$A1" "$SESS_TRIP" "$MODEL_ID") +A2=$(printf '%s' "$REQ2" | "${CURL[@]}" -d @- "$BASE" | content_of) +echo " turn2 assistant: $(printf '%s' "$A2" | tr '\n' ' ' | cut -c1-80)" + +if printf '%s' "$A2" | grep -q "$SECRET"; then + ok "turn2 recalled the secret code (${SECRET}) from the supplied history" +else + bad "turn2 did NOT recall the secret code (${SECRET})" +fi +echo + +# ----------------------------------------------------------------------------- +# TEST 2: concurrent session isolation. +# ----------------------------------------------------------------------------- +echo "TEST 2: ${NUM_CONCURRENT} concurrent distinct sessions must not cross" +TMPDIR_T2=$(mktemp -d) +CONCUR_PREFIX="concur_$" +for i in $(seq 1 "$NUM_CONCURRENT"); do + track_session "${CONCUR_PREFIX}_${i}" +done +for i in $(seq 1 "$NUM_CONCURRENT"); do + ( + REQ=$(python3 -c ' +import json,sys +i=sys.argv[1]; model=sys.argv[2]; sid=sys.argv[3] +print(json.dumps({"model":model,"session_id":sid, + "temperature":0,"max_tokens":16, + "messages":[{"role":"user","content":f"Reply with exactly this word and nothing else: TOKEN{i}"}]})) +' "$i" "$MODEL_ID" "${CONCUR_PREFIX}_${i}") + printf '%s' "$REQ" | "${CURL[@]}" -d @- "$BASE" | content_of > "${TMPDIR_T2}/${i}.out" + ) & +done +wait + +cross=0 +for i in $(seq 1 "$NUM_CONCURRENT"); do + out=$(cat "${TMPDIR_T2}/${i}.out" 2>/dev/null) + if ! printf '%s' "$out" | grep -q "TOKEN${i}\b"; then + echo " session ${i}: expected TOKEN${i}, got: $(printf '%s' "$out" | tr '\n' ' ' | cut -c1-40)" + cross=$((cross + 1)) + fi + # Also verify no OTHER session's token leaked in. + for j in $(seq 1 "$NUM_CONCURRENT"); do + if [ "$j" -ne "$i" ] && printf '%s' "$out" | grep -q "TOKEN${j}\b"; then + echo " session ${i}: LEAKED TOKEN${j}" + cross=$((cross + 1)) + fi + done +done +rm -rf "$TMPDIR_T2" + +if [ "$cross" -eq 0 ]; then + ok "all ${NUM_CONCURRENT} concurrent sessions returned only their own token" +else + bad "${cross} concurrent-session mismatch/leak(s) detected" +fi +echo + +# ----------------------------------------------------------------------------- +# TEST 3: cross-session isolation (a fresh session must not know the secret). +# ----------------------------------------------------------------------------- +echo "TEST 3: fresh session must NOT know another session's secret" +SESS_OTHER="sessOther_$" +track_session "$SESS_OTHER" +REQ3=$(python3 -c ' +import json,sys +sid=sys.argv[1]; model=sys.argv[2] +print(json.dumps({"model":model,"session_id":sid,"temperature":0,"max_tokens":40, + "messages":[{"role":"user","content":"What was the secret trip code I gave you earlier? If you were not given one, say NONE."}]})) +' "$SESS_OTHER" "$MODEL_ID") +A3=$(printf '%s' "$REQ3" | "${CURL[@]}" -d @- "$BASE" | content_of) +echo " assistant: $(printf '%s' "$A3" | tr '\n' ' ' | cut -c1-80)" + +if printf '%s' "$A3" | grep -q "$SECRET"; then + bad "fresh session leaked the other session's secret (${SECRET})" +else + ok "fresh session did not know the other session's secret" +fi +echo + +# ----------------------------------------------------------------------------- +echo "=== summary: ${pass} passed, ${fail} failed ===" +[ "$fail" -eq 0 ] diff --git a/examples/models/muse-glimmer/tests/scripts/test_multisession_buck.sh b/examples/models/muse-glimmer/tests/scripts/test_multisession_buck.sh new file mode 100755 index 00000000000..528297f47e8 --- /dev/null +++ b/examples/models/muse-glimmer/tests/scripts/test_multisession_buck.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +set -euo pipefail + +if [[ -z "${MUSE_GLIMMER_SERVER_URL:-}" ]]; then + echo "SKIP: set MUSE_GLIMMER_SERVER_URL=host:port to run the multi-session smoke test" + exit 0 +fi + +exec "$(dirname "$0")/test_multisession.sh" "$MUSE_GLIMMER_SERVER_URL" "${MUSE_GLIMMER_MODEL_ID:-muse_glimmer}" "${MUSE_GLIMMER_NUM_CONCURRENT:-8}" diff --git a/examples/models/muse-glimmer/tests/test_atem_tool_parser.py b/examples/models/muse-glimmer/tests/test_atem_tool_parser.py new file mode 100644 index 00000000000..0673128edcc --- /dev/null +++ b/examples/models/muse-glimmer/tests/test_atem_tool_parser.py @@ -0,0 +1,404 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""Tests for AtemToolCallDetector (Muse Glimmer ATEM XML tool format). + +The Muse Glimmer tool-call surface the model emits is a harmony assistant message +whose body is an ATEM XML block, byte-for-byte: + + [<|start|>assistant] to=NAME<|message|> + + VALUE + + [<|eom|>|<|eot|>] + +Test inputs are hand-built from that spec (the fragment constants / _atem builder +below), NOT copied from parser output, so the assertions independently pin the +format, including the exact newline placement used by the reference renderer. +""" + +import json + +from executorch.examples.models.muse_glimmer.serving.tool_parsers import ( + AtemToolCallDetector, +) + +# Harmony framing fragments, assembled by hand into model-output strings. +_START = "<|start|>" +_MESSAGE = "<|message|>" +_EOM = "<|eom|>" +_EOT = "<|eot|>" + + +def _atem(name, params): + """Byte-exact ATEM block for one , mirroring the golden renderer: + newline after , after , and after EVERY + ; newline after ; NO trailing newline after + .""" + s = '\n\n' + for k, v in params: + s += '' + v + "\n" + s += "\n" + return s + + +_TOOLS = { + "get_weather": { + "type": "object", + "properties": { + "city": {"type": "string"}, + "units": {"type": "string"}, + }, + }, + "add": { + "type": "object", + "properties": {"a": {"type": "integer"}, "b": {"type": "integer"}}, + }, +} + + +def _parse(text, tools=_TOOLS): + return AtemToolCallDetector().detect_and_parse(text, tools) + + +def test_basic_call_terminated(): + # A tool call as the worker would surface it with the terminator intact. + text = ( + f" to=get_weather{_MESSAGE}" + _atem("get_weather", [("city", "Paris")]) + _EOM + ) + r = _parse(text) + assert len(r.calls) == 1 + assert r.calls[0].name == "get_weather" + assert json.loads(r.calls[0].arguments) == {"city": "Paris"} + assert r.normal_text == "" + + +def test_basic_call_without_terminator(): + # The worker registers <|eom|>/<|eot|> as EOS and stops WITHOUT emitting them, + # so a complete call commonly arrives with no trailing terminator. + text = f" to=get_weather{_MESSAGE}" + _atem("get_weather", [("city", "Paris")]) + r = _parse(text) + assert len(r.calls) == 1 + assert r.calls[0].name == "get_weather" + assert json.loads(r.calls[0].arguments) == {"city": "Paris"} + + +def test_call_with_start_prefix(): + # A non-first message in a turn carries its own <|start|>assistant prefix. + text = ( + f"{_START}assistant to=add{_MESSAGE}" + + _atem("add", [("a", "1"), ("b", "2")]) + + _EOT + ) + r = _parse(text) + assert len(r.calls) == 1 + assert r.calls[0].name == "add" + assert json.loads(r.calls[0].arguments) == {"a": 1, "b": 2} + + +def test_call_with_constrain_field(): + # constrain=json is an optional header field after to=; it must not break + # detection or leak into the surfaced content. + text = ( + f" to=get_weather constrain=json{_MESSAGE}" + + _atem("get_weather", [("city", "SF")]) + + _EOM + ) + r = _parse(text) + assert len(r.calls) == 1 + assert r.calls[0].name == "get_weather" + assert json.loads(r.calls[0].arguments) == {"city": "SF"} + assert r.normal_text == "" + + +def test_call_without_harmony_header(): + # The block alone (no to= header) still parses -- the ATEM block is the + # trigger, not the harmony header. + text = _atem("get_weather", [("city", "Paris")]) + r = _parse(text) + assert len(r.calls) == 1 + assert r.calls[0].name == "get_weather" + assert json.loads(r.calls[0].arguments) == {"city": "Paris"} + + +def test_multiple_invokes_in_one_block(): + # Parallel calls as multiple inside a single block (the ts_xml + # canonical shape). + block = ( + '\n\n' + '1\n' + '2\n' + "\n" + '\n' + '3\n' + '4\n' + "\n" + ) + text = f" to=add{_MESSAGE}" + block + _EOT + r = _parse(text) + assert [c.tool_index for c in r.calls] == [0, 1] + assert [json.loads(c.arguments) for c in r.calls] == [ + {"a": 1, "b": 2}, + {"a": 3, "b": 4}, + ] + + +def test_multiple_parallel_calls_across_messages(): + # Parallel calls as one invoke per block across separate assistant messages + # joined by <|eom|> (the muse_glimmer HF chat-template shape). + text = ( + f" to=add{_MESSAGE}" + + _atem("add", [("a", "1"), ("b", "2")]) + + _EOM + + f"{_START}assistant to=add{_MESSAGE}" + + _atem("add", [("a", "3"), ("b", "4")]) + + _EOT + ) + r = _parse(text) + assert [c.tool_index for c in r.calls] == [0, 1] + assert [json.loads(c.arguments) for c in r.calls] == [ + {"a": 1, "b": 2}, + {"a": 3, "b": 4}, + ] + + +def test_multi_param_call(): + text = f" to=get_weather{_MESSAGE}" + _atem( + "get_weather", [("city", "Paris"), ("units", "celsius")] + ) + r = _parse(text) + assert len(r.calls) == 1 + assert json.loads(r.calls[0].arguments) == {"city": "Paris", "units": "celsius"} + + +def test_leading_prose_before_call_is_preserved(): + text = ( + f"Checking now. to=add{_MESSAGE}" + + _atem("add", [("a", "5"), ("b", "6")]) + + _EOM + ) + r = _parse(text) + assert len(r.calls) == 1 + assert r.calls[0].name == "add" + assert r.normal_text == "Checking now." + + +def test_cot_then_tool_call_leading_text_preserved(): + # A private-CoT message (to=self) precedes the tool call; the CoT body is + # returned as leading text and only the ATEM block is a call. + text = ( + f" to=self{_MESSAGE}Let me check the weather.{_EOM}" + + f"{_START}assistant to=get_weather{_MESSAGE}" + + _atem("get_weather", [("city", "Paris")]) + + _EOM + ) + r = _parse(text) + assert len(r.calls) == 1 + assert r.calls[0].name == "get_weather" + assert "Let me check the weather." in r.normal_text + + +def test_plain_text_passes_through(): + text = "The weather is nice today." + r = _parse(text) + assert r.calls == [] + assert r.normal_text == text + + +def test_undefined_tool_degrades_to_full_text(): + # A well-formed call to a tool not in the request degrades the WHOLE response + # to the raw text (surface intent, never a partial set). + text = ( + f" to=delete_everything{_MESSAGE}" + + _atem("delete_everything", [("target", "all")]) + + _EOM + ) + r = _parse(text) + assert r.calls == [] + assert r.normal_text == text + + +def test_truncated_call_degrades_without_leaking_markup(): + # A call cut off by max_tokens (no ) must NOT leak the partial + # markup -- only the leading text survives. + text = ( + 'Sure! \n\n' + 'Paris' + ) + r = _parse(text) + assert not r.calls + assert " best-effort JSON guess (so loosely-typed tools work). + tools = {"f": {"properties": {}}} + text = _atem("f", [("n", "42"), ("items", "[1, 2]")]) + args = json.loads(_parse(text, tools).calls[0].arguments) + assert args == {"n": 42, "items": [1, 2]} + + +def test_array_and_object_values_json_decoded(): + # List/object params are rendered as compact JSON; coercion JSON-decodes them. + tools = { + "f": { + "properties": { + "lst": {"type": "array"}, + "d": {"type": "object"}, + } + } + } + text = _atem("f", [("lst", "[1, 2]"), ("d", '{"k": "v"}')]) + args = json.loads(_parse(text, tools).calls[0].arguments) + assert args == {"lst": [1, 2], "d": {"k": "v"}} + + +_TYPED = { + "code_tool": {"type": "object", "properties": {"code": {"type": "string"}}}, + "calc": { + "type": "object", + "properties": { + "n": {"type": "integer"}, + "x": {"type": "number"}, + "flag": {"type": "boolean"}, + }, + }, +} + + +def test_declared_integer_with_float_string_kept_raw(): + text = _atem("calc", [("n", "10.0")]) + val = json.loads(_parse(text, _TYPED).calls[0].arguments)["n"] + assert val == "10.0" and isinstance(val, str) # not float 10.0 + + +def test_declared_boolean_with_one_kept_raw(): + text = _atem("calc", [("flag", "1")]) + val = json.loads(_parse(text, _TYPED).calls[0].arguments)["flag"] + assert val == "1" and isinstance(val, str) # not int 1 + + +def test_declared_integer_with_underscores_kept_raw(): + text = _atem("calc", [("n", "1_000")]) + val = json.loads(_parse(text, _TYPED).calls[0].arguments)["n"] + assert val == "1_000" and isinstance(val, str) # not int 1000 + + +def _reject_bare_constant(c): + # json.loads parse_constant hook: fires only for bare NaN/Infinity/-Infinity. + raise AssertionError(f"emitted bare non-finite constant: {c}") + + +def test_declared_number_non_finite_never_emitted(): + for bad in ("NaN", "Infinity", "-Infinity", "1e999"): + text = _atem("calc", [("x", bad)]) + args = _parse(text, _TYPED).calls[0].arguments + # Strict-client safe: no bare NaN/Infinity constant in the emitted JSON. + json.loads(args, parse_constant=_reject_bare_constant) + assert json.loads(args)["x"] == bad # kept as the raw string + + +def test_param_value_with_literal_parameter_close_preserved(): + # A value containing literal must be preserved, not + # truncated at the first delimiter. + body = ( + '\n\n' + 'a b\n' + "\n" + ) + r = _parse(body, _TYPED) + assert json.loads(r.calls[0].arguments) == {"code": "a b"} + + +def test_param_value_with_xmlish_markup_not_truncated(): + # A value containing -like markup must stay in the value, not split + # the call or truncate at the first tag. + body = ( + '\n\n' + 'x = \n' + "\n" + ) + r = _parse(body, _TYPED) + assert len(r.calls) == 1 + assert json.loads(r.calls[0].arguments) == {"code": 'x = '} + + +def test_value_with_angle_brackets_kept_as_string(): + # A string value containing < and > must survive intact (no truncation). + tools = {"f": {"properties": {"expr": {"type": "string"}}}} + body = ( + '\n\n' + 'a < b && c > d\n' + "\n" + ) + r = _parse(body, tools) + assert json.loads(r.calls[0].arguments) == {"expr": "a < b && c > d"} + + +def test_per_request_index_is_isolated(): + # A fresh detector per request restarts tool_index at 0. + text = f" to=add{_MESSAGE}" + _atem("add", [("a", "1"), ("b", "2")]) + first = AtemToolCallDetector().detect_and_parse(text, _TOOLS) + second = AtemToolCallDetector().detect_and_parse(text, _TOOLS) + assert first.calls[0].tool_index == 0 + assert second.calls[0].tool_index == 0 diff --git a/examples/models/muse-glimmer/tests/test_benchmark_dflash_long_context.py b/examples/models/muse-glimmer/tests/test_benchmark_dflash_long_context.py new file mode 100644 index 00000000000..e7bedeed98d --- /dev/null +++ b/examples/models/muse-glimmer/tests/test_benchmark_dflash_long_context.py @@ -0,0 +1,174 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +from __future__ import annotations + +import os +import stat +import tempfile +import unittest +from pathlib import Path + +from executorch.examples.models.muse_glimmer.dev.benchmark_dflash_long_context import ( + BOS_TOKEN_ID, + build_runner_command, + DEFAULT_OUTPUT_TOKENS, + generate_prompt_files, + make_prompt_tokens, + MAX_SEQ_LEN, + parse_runner_metrics, + PROMPT_LENGTHS, + RANDOM_VOCAB_LIMIT, + run_case, + token_file_length, + validate_context_boundary, + validate_generated_tokens_match, +) + + +class BenchmarkDFlashLongContextTest(unittest.TestCase): + def test_prompts_have_exact_lengths_and_common_prefixes(self) -> None: + with tempfile.TemporaryDirectory() as temp_dir: + files = generate_prompt_files( + Path(temp_dir), PROMPT_LENGTHS, seed=17, output_tokens=512 + ) + + contents = {length: path.read_bytes() for length, path in files.items()} + for length, path in files.items(): + self.assertEqual(token_file_length(path), length) + self.assertEqual( + contents[length][:8], BOS_TOKEN_ID.to_bytes(8, "little") + ) + self.assertEqual( + contents[length], contents[PROMPT_LENGTHS[-1]][: length * 8] + ) + + def test_random_payload_excludes_reserved_tokens(self) -> None: + tokens = make_prompt_tokens(4096, seed=9) + self.assertEqual(tokens[0], BOS_TOKEN_ID) + self.assertTrue(all(0 <= token < RANDOM_VOCAB_LIMIT for token in tokens[1:])) + + def test_longest_case_fits_with_transient_verifier(self) -> None: + validate_context_boundary(PROMPT_LENGTHS[-1], DEFAULT_OUTPUT_TOKENS) + with self.assertRaisesRegex(ValueError, "exceeds max sequence length"): + validate_context_boundary(MAX_SEQ_LEN - 1, DEFAULT_OUTPUT_TOKENS) + + def test_runner_commands_share_exact_input_contract(self) -> None: + common = { + "model": Path("/tmp/model.pte"), + "data": Path("/tmp/model.ptd"), + "tokenizer": Path("/tmp/tokenizer"), + "prompt": Path("/tmp/prompt.i64"), + "generated": Path("/tmp/generated.i64"), + "output_tokens": 512, + } + solo = build_runner_command( + implementation="solo", runner=Path("/tmp/solo"), **common + ) + dflash = build_runner_command( + implementation="dflash", runner=Path("/tmp/dflash"), **common + ) + + for command in (solo, dflash): + self.assertIn("--cuda_graph", command) + self.assertNotIn("--cuda_graph_target", command) + self.assertNotIn("--cuda_graph_draft", command) + self.assertIn("--tokens_have_bos", command) + self.assertIn("--temperature=0", command) + self.assertIn("--max_new_tokens=512", command) + self.assertIn("--ignore_eos", command) + self.assertIn("--prompt_tokens_file=/tmp/prompt.i64", command) + + def test_run_case_creates_generated_directory_and_overwrites_old_file( + self, + ) -> None: + with tempfile.TemporaryDirectory() as temp_dir: + root = Path(temp_dir) + runner = root / "fake_runner.py" + runner.write_text( + "#!/usr/bin/env python3\n" + "from pathlib import Path\n" + "import sys\n" + "output = next(a.split('=', 1)[1] for a in sys.argv " + "if a.startswith('--generated_tokens_file='))\n" + "Path(output).write_bytes((7).to_bytes(8, 'little', signed=True))\n" + "print('Prefill: 1 tokens in 1.0 ms (1000.0 tok/s)')\n" + "print('Decode: 1 tokens in 1.0 ms (1000.0 tok/s)')\n", + encoding="utf-8", + ) + runner.chmod(runner.stat().st_mode | stat.S_IXUSR) + generated = root / "nested" / "generated.i64" + metrics = run_case( + [str(runner), f"--generated_tokens_file={generated}"], + root / "logs" / "runner.log", + generated, + expected_output_tokens=1, + environment=os.environ.copy(), + ) + self.assertEqual(generated.stat().st_size, 8) + self.assertEqual(metrics["actual_generated_tokens"], 1) + + def test_run_case_rejects_missing_metrics(self) -> None: + with tempfile.TemporaryDirectory() as temp_dir: + root = Path(temp_dir) + runner = root / "fake_runner.py" + runner.write_text( + "#!/usr/bin/env python3\n" + "from pathlib import Path\n" + "import sys\n" + "output = next(a.split('=', 1)[1] for a in sys.argv " + "if a.startswith('--generated_tokens_file='))\n" + "Path(output).write_bytes((7).to_bytes(8, 'little', signed=True))\n", + encoding="utf-8", + ) + runner.chmod(runner.stat().st_mode | stat.S_IXUSR) + generated = root / "generated.i64" + with self.assertRaisesRegex(RuntimeError, "missing required metrics"): + run_case( + [str(runner), f"--generated_tokens_file={generated}"], + root / "runner.log", + generated, + expected_output_tokens=1, + environment=os.environ.copy(), + ) + + def test_generated_tokens_must_match(self) -> None: + with tempfile.TemporaryDirectory() as temp_dir: + root = Path(temp_dir) + solo = root / "solo.i64" + dflash = root / "dflash.i64" + solo.write_bytes(b"same") + dflash.write_bytes(b"same") + validate_generated_tokens_match(solo, dflash) + + dflash.write_bytes(b"different") + with self.assertRaisesRegex(RuntimeError, "different token sequences"): + validate_generated_tokens_match(solo, dflash) + + def test_parse_runner_metrics(self) -> None: + metrics = parse_runner_metrics( + """ +Prefill: 8192 tokens in 100.0 ms (81920.0 tok/s) +Decode: 512 tokens in 2000.0 ms (256.0 tok/s) +DFlashDecodeTiming {"cycles":128,"speculative_cycles":100,"target_only_cycles":28,"draft_execute_ms":312.0,"target_execute_ms":800.0,"draft_attempts_by_row":[128,128,128],"draft_accepts_by_row":[120,100,80]} +PyTorchObserver {"decode_token_per_sec": 256.0, "inference_start_ms": 1000, "first_token_ms": 1100, "inference_end_ms": 3000} +""" + ) + self.assertEqual(metrics["prompt_tokens"], 8192) + self.assertEqual(metrics["generated_tokens"], 512) + self.assertAlmostEqual(metrics["acceptance_percent"], 78.125) + self.assertEqual(metrics["cycles"], 128) + self.assertEqual(metrics["draft_tokens"], 384) + self.assertEqual(metrics["accepted_draft_tokens"], 300) + self.assertEqual(metrics["draft_execute_ms"], 312.0) + self.assertEqual(metrics["target_execute_ms"], 800.0) + self.assertEqual(metrics["ttft_ms"], 100) + self.assertEqual(metrics["inference_end_to_end_ms"], 2000) + self.assertEqual(metrics["observer"]["decode_token_per_sec"], 256.0) + + +if __name__ == "__main__": + unittest.main() diff --git a/examples/models/muse-glimmer/tests/test_cuda_pipeline.py b/examples/models/muse-glimmer/tests/test_cuda_pipeline.py new file mode 100644 index 00000000000..993a6fc51fe --- /dev/null +++ b/examples/models/muse-glimmer/tests/test_cuda_pipeline.py @@ -0,0 +1,354 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""CUDA-specific integration tests for the Muse Glimmer pipeline. + +Tests pack -> inference -> export on a tiny model using the CUDA backend. +Backend-agnostic tests (quantize, save, load) live in ``test_pipeline.py``. + +Requires CUDA. + +Usage: + python -m pytest examples/models/muse-glimmer/tests/test_cuda_pipeline.py -v +""" + +import json +import os +import tempfile +import unittest +from dataclasses import replace + +import executorch.backends.cuda.quantize_op_dispatch as _quantize_op_dispatch # noqa: F401 +import torch +from executorch.backends.cuda.coalesced_int4_tensor import CudaCoalescedInt4Tensor +from executorch.examples.models.muse_glimmer.export.common import ( + mutable_buffer_metadata, +) +from executorch.examples.models.muse_glimmer.export.export_solo import ( + export_and_lower, + load_prequantized_model, +) +from executorch.examples.models.muse_glimmer.inference import ( + _move_to_cuda, + BOS_TOKEN_ID, + generate, +) +from executorch.examples.models.muse_glimmer.loaders.checkpoint_loader import _finalize +from executorch.examples.models.muse_glimmer.model.model import FlatKVCache +from executorch.examples.models.muse_glimmer.source_transformations.cuda import ( + add_dflash_hidden_tapping, + add_on_device_sampler, + cuda_source_transformations, +) +from executorch.examples.models.muse_glimmer.tests.test_pipeline import ( + build_random_tiny_model, + DEFAULT_RECIPE, + MockTokenizer, + save_checkpoint, + TINY_CONFIG, +) +from executorch.extension.llm.export.quant import quantize_model + + +def _require_cuda(testcase: unittest.TestCase) -> None: + if not torch.cuda.is_available(): + testcase.skipTest("CUDA required") + + +class TestMutableBufferMetadataTest(unittest.TestCase): + def test_combined_model_contains_target_and_draft_kv_caches(self): + combined = torch.nn.Module() + combined.target = torch.nn.Module() + combined.target.kv_cache = FlatKVCache(1, 4, 2, 8) + combined.draft = torch.nn.Module() + combined.draft.kv_cache = FlatKVCache(1, 4, 2, 8) + + metadata = json.loads(mutable_buffer_metadata(combined)) + + self.assertEqual(1, metadata["version"]) + self.assertCountEqual( + [ + "target.kv_cache.k_cache", + "target.kv_cache.v_cache", + "draft.kv_cache.k_cache", + "draft.kv_cache.v_cache", + ], + metadata["mutable_buffers"], + ) + + +class TestCudaInferenceTest(unittest.TestCase): + def setUp(self): + _require_cuda(self) + + def test_generate(self): + """save -> load -> pack -> generate produces valid tokens.""" + with tempfile.TemporaryDirectory() as tmpdir: + save_checkpoint(tmpdir) + model, config = load_prequantized_model( + tmpdir, max_seq_len=TINY_CONFIG.max_seq_len + ) + _move_to_cuda(model) + model.eval() + tokenizer = MockTokenizer(TINY_CONFIG.vocab_size) + + bos = min(BOS_TOKEN_ID, TINY_CONFIG.vocab_size - 1) + torch.manual_seed(0) + out = generate( + model, + tokenizer, + prompt="hi", + max_new_tokens=5, + temperature=1.0, + bos_token_id=bos, + eos_token_id=TINY_CONFIG.vocab_size - 1, + ) + self.assertIsInstance(out, str) + self.assertGreater(len(out), 0) + + def test_generate_greedy(self): + """Near-greedy generation (temperature=0) produces valid output.""" + with tempfile.TemporaryDirectory() as tmpdir: + save_checkpoint(tmpdir) + model, config = load_prequantized_model( + tmpdir, max_seq_len=TINY_CONFIG.max_seq_len + ) + _move_to_cuda(model) + model.eval() + tokenizer = MockTokenizer(TINY_CONFIG.vocab_size) + + bos = min(BOS_TOKEN_ID, TINY_CONFIG.vocab_size - 1) + out = generate( + model, + tokenizer, + prompt="hi", + max_new_tokens=3, + temperature=0.0, + bos_token_id=bos, + eos_token_id=TINY_CONFIG.vocab_size - 1, + ) + self.assertIsInstance(out, str) + self.assertGreater(len(out), 0) + + +class TestChunkedPrefillTest(unittest.TestCase): + """Verify that chunked prefill matches one-token-at-a-time prefill.""" + + def setUp(self): + _require_cuda(self) + + def test_chunked_prefill_matches_sequential(self): + """Long prompt chunked across ring buffer gives same logits as sequential.""" + with tempfile.TemporaryDirectory() as tmpdir: + save_checkpoint(tmpdir) + model_seq, config = load_prequantized_model( + tmpdir, max_seq_len=TINY_CONFIG.max_seq_len + ) + model_chunk, _ = load_prequantized_model( + tmpdir, max_seq_len=TINY_CONFIG.max_seq_len + ) + + _move_to_cuda(model_seq) + _move_to_cuda(model_chunk) + model_seq.eval() + model_chunk.eval() + + # Sliding window from tiny config + window = 0 + for layer in model_seq.layers: + if layer.is_sliding: + window = layer.self_attn.window_size + break + buf_size = window * 2 + prompt_len = buf_size + 4 + torch.manual_seed(0) + prompt = torch.randint(0, config.vocab_size, (1, prompt_len), device="cuda") + + # Sequential: one token at a time + with torch.no_grad(): + for i in range(prompt_len): + tok = prompt[:, i : i + 1] + pos = torch.tensor([i], dtype=torch.long, device="cuda") + logits_seq = model_seq(tok, pos) + + # Chunked: two chunks + with torch.no_grad(): + chunk1 = prompt[:, :buf_size] + pos1 = torch.arange(buf_size, dtype=torch.long, device="cuda") + model_chunk(chunk1, pos1) + + chunk2 = prompt[:, buf_size:] + pos2 = torch.arange(buf_size, prompt_len, dtype=torch.long, device="cuda") + logits_chunk = model_chunk(chunk2, pos2) + + max_diff = (logits_seq[0, -1].float() - logits_chunk[0, -1].float()).abs().max() + self.assertTrue( + torch.allclose( + logits_seq[0, -1].float(), + logits_chunk[0, -1].float(), + atol=1e-2, + rtol=1e-3, + ), + f"Chunked prefill diverged: max_diff={max_diff:.4g}", + ) + + +class TestDFlashTargetPrefillTest(unittest.TestCase): + def setUp(self): + _require_cuda(self) + + def test_target_prefill_matches_target_and_continues_shared_cache(self): + with tempfile.TemporaryDirectory() as tmpdir: + save_checkpoint(tmpdir) + target_ref, config = load_prequantized_model( + tmpdir, max_seq_len=TINY_CONFIG.max_seq_len + ) + target_prefill, _ = load_prequantized_model( + tmpdir, max_seq_len=TINY_CONFIG.max_seq_len + ) + + for model in (target_ref, target_prefill): + _move_to_cuda(model) + model.eval() + cuda_source_transformations(model) + add_dflash_hidden_tapping(model, [0]) + + torch.manual_seed(7) + prompt = torch.randint(0, config.vocab_size, (1, 7), device="cuda") + prefill_tokens = prompt[:, :5] + prefill_pos = torch.arange(5, dtype=torch.long, device="cuda") + verify_tokens = prompt[:, 5:] + verify_pos = torch.arange(5, 7, dtype=torch.long, device="cuda") + + with torch.no_grad(): + ref_logits, ref_hidden = target_ref(prefill_tokens, prefill_pos) + prefill_logits, prefill_hidden = target_prefill.dflash_prefill_forward( + prefill_tokens, prefill_pos + ) + + ref_verify_logits, ref_verify_hidden = target_ref(verify_tokens, verify_pos) + shared_verify_logits, shared_verify_hidden = target_prefill( + verify_tokens, verify_pos + ) + + self.assertEqual(prefill_logits.shape, torch.Size([1, 1, config.vocab_size])) + torch.testing.assert_close( + prefill_logits, ref_logits[:, -1:, :], rtol=1e-3, atol=1e-2 + ) + torch.testing.assert_close(prefill_hidden, ref_hidden, rtol=1e-3, atol=1e-2) + torch.testing.assert_close( + shared_verify_logits, ref_verify_logits, rtol=1e-3, atol=1e-2 + ) + torch.testing.assert_close( + shared_verify_hidden, ref_verify_hidden, rtol=1e-3, atol=1e-2 + ) + + +class TestCudaExportTest(unittest.TestCase): + def setUp(self): + _require_cuda(self) + + def test_export_from_quantized_checkpoint(self): + """--prequantized path: load -> pack -> export.""" + from executorch.runtime import Runtime, Verification + + with ( + tempfile.TemporaryDirectory() as ckpt_dir, + tempfile.TemporaryDirectory() as out_dir, + ): + save_checkpoint(ckpt_dir) + model, config = load_prequantized_model( + ckpt_dir, max_seq_len=TINY_CONFIG.max_seq_len + ) + export_and_lower(model, config, out_dir) + pte = os.path.join(out_dir, "model.pte") + self.assertTrue(os.path.exists(pte)) + ptd_files = [f for f in os.listdir(out_dir) if f.endswith(".ptd")] + self.assertGreater(len(ptd_files), 0) + program = Runtime.get().load_program(pte, verification=Verification.Minimal) + self.assertTrue( + { + "embed_text", + "forward_from_embeddings", + "decode_from_embedding", + }.issubset(program.method_names) + ) + + def test_export_from_bf16_quantize_inline(self): + """Build bf16 model -> quantize -> pack -> export.""" + model = build_random_tiny_model() + atomic_sd = quantize_model(model, DEFAULT_RECIPE) + + # _finalize sets config.fuse_* in place, so pass a copy of the shared + # fixture rather than TINY_CONFIG itself. + config = replace(TINY_CONFIG) + model = _finalize(atomic_sd, "cuda", config, torch.bfloat16) + + with tempfile.TemporaryDirectory() as out_dir: + export_and_lower(model, config, out_dir) + self.assertTrue(os.path.exists(os.path.join(out_dir, "model.pte"))) + + +class TestInt4InferenceTest(unittest.TestCase): + """Test Int4Tensor passthrough with dispatch override.""" + + def setUp(self): + _require_cuda(self) + with tempfile.TemporaryDirectory() as tmpdir: + save_checkpoint(tmpdir) + self.model, self.config = load_prequantized_model( + tmpdir, max_seq_len=TINY_CONFIG.max_seq_len + ) + _move_to_cuda(self.model) + self.model.eval() + # The model returns logits; enable on-device sampling for these int4 + # inference tests via the CUDA source transform. + add_on_device_sampler(self.model) + + def _forward(self): + with torch.no_grad(): + tok = torch.tensor([[1]], dtype=torch.long, device="cuda") + pos = torch.tensor([0], dtype=torch.long, device="cuda") + return self.model(tok, pos) + + def test_int4_weights_preserved(self): + """Packing converts Int4Tensor to CudaCoalescedInt4Tensor.""" + w = self.model.layers[0].mlp.gate_up_proj.weight.data + self.assertIsInstance(w, CudaCoalescedInt4Tensor) + + def test_inference_produces_valid_output(self): + out = self._forward() + self.assertEqual(out.shape, torch.Size([1, 1, self.config.vocab_size])) + self.assertFalse(out.isnan().any()) + + def test_deterministic(self): + """Same seed produces same output.""" + torch.manual_seed(99) + out1 = self._forward() + # Reset KV cache by reloading + with tempfile.TemporaryDirectory() as tmpdir: + save_checkpoint(tmpdir) + model2, _ = load_prequantized_model( + tmpdir, max_seq_len=TINY_CONFIG.max_seq_len + ) + _move_to_cuda(model2) + model2.eval() + add_on_device_sampler(model2) + with torch.no_grad(): + tok = torch.tensor([[1]], dtype=torch.long, device="cuda") + pos = torch.tensor([0], dtype=torch.long, device="cuda") + torch.manual_seed(99) + out2 = model2(tok, pos) + torch.testing.assert_close(out1, out2, rtol=0, atol=0) + + def test_embedding_works(self): + tok = torch.tensor([[1]], dtype=torch.long, device="cuda") + emb = self.model.embed_tokens(tok) + self.assertFalse(emb.isnan().any()) + + +if __name__ == "__main__": + unittest.main() diff --git a/examples/models/muse-glimmer/tests/test_export_dflash.py b/examples/models/muse-glimmer/tests/test_export_dflash.py new file mode 100644 index 00000000000..d544b542c7e --- /dev/null +++ b/examples/models/muse-glimmer/tests/test_export_dflash.py @@ -0,0 +1,51 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +from __future__ import annotations + +from unittest import TestCase + +from executorch.examples.models.muse_glimmer.export import export_dflash + + +class DFlashExportOptionsTest(TestCase): + def test_cuda_uses_delegate_mutable_buffer_sharing(self) -> None: + self.assertFalse(export_dflash._share_graph_mutable_buffers("cuda")) + + def test_mlx_uses_graph_mutable_buffer_sharing(self) -> None: + self.assertTrue(export_dflash._share_graph_mutable_buffers("mlx")) + + def test_cuda_embed_text_covers_target_prefill(self) -> None: + self.assertEqual(export_dflash._embed_text_max_len("cuda", 4, 4096), 4096) + + def test_mlx_embed_text_uses_target_bound(self) -> None: + self.assertEqual(export_dflash._embed_text_max_len("mlx", 2048, 0), 2048) + + def test_draft_prefill_uses_sliding_window_bound(self) -> None: + config = type( + "Config", + (), + {"sliding_window": 2048, "sliding_window_pattern": [True] * 3}, + )() + self.assertEqual(export_dflash._max_draft_prefill_len(config, 4096), 2048) + + def test_global_draft_prefill_uses_target_bound(self) -> None: + config = type( + "Config", + (), + {"sliding_window": 2048, "sliding_window_pattern": [True, False]}, + )() + self.assertEqual(export_dflash._max_draft_prefill_len(config, 4096), 4096) + + def test_cuda_vision_options_are_valid(self) -> None: + self.assertIsNone(export_dflash.validate_dflash_export_options("cuda")) + + def test_mlx_vision_options_are_valid(self) -> None: + self.assertIsNone(export_dflash.validate_dflash_export_options("mlx")) + + def test_callable_rejects_unknown_backend(self) -> None: + with self.assertRaisesRegex(ValueError, "Unsupported DFlash backend: cpu"): + export_dflash.validate_dflash_export_options("cpu") diff --git a/examples/models/muse-glimmer/tests/test_mlx_pipeline.py b/examples/models/muse-glimmer/tests/test_mlx_pipeline.py new file mode 100644 index 00000000000..8641312618f --- /dev/null +++ b/examples/models/muse-glimmer/tests/test_mlx_pipeline.py @@ -0,0 +1,216 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""MLX integration tests for the Muse Glimmer pipeline. + +Run from an OSS ExecuTorch checkout with the MLX backend installed, via +``run.py``: + + python dev/run.py executorch.examples.models.muse_glimmer.tests.test_mlx_pipeline + +Backend-agnostic tests live in ``test_pipeline.py``; CUDA tests in +``test_cuda_pipeline.py``. +""" + +import os +import tempfile +import unittest +from dataclasses import replace + +import torch +from executorch.examples.models.muse_glimmer.model.model import MuseGlimmerModel +from executorch.examples.models.muse_glimmer.tests.test_pipeline import ( + build_random_tiny_model, + HAS_QUANT_DEPS, + TINY_CONFIG, +) + +# MLX export fixes the prefill chunk at 512, which sets two minimums: the KV +# cache length, and the sliding-window size (the ring buffer requires +# max_write_len <= window). The shared tiny fixture uses a 64-token cache and a +# window of 16, so widen both here. +MLX_CONFIG = replace(TINY_CONFIG, max_seq_len=1024, global_attn_cfg="[512,512,512,0]") + + +def _require_mlx(testcase: unittest.TestCase) -> None: + try: + import executorch.backends.mlx.custom_ops # noqa: F401 + except Exception as e: # noqa: BLE001 — any import failure means MLX is absent + testcase.skipTest(f"MLX backend required (OSS-only): {e}") + + +class MLXSourceTransformTest(unittest.TestCase): + def setUp(self) -> None: + _require_mlx(self) + + def test_swaps_attention_modules(self) -> None: + """Each layer's attention is replaced with the MLX attention module.""" + from executorch.examples.models.muse_glimmer.source_transformations.mlx import ( + mlx_source_transformations, + MLXMuseGlimmerAttention, + ) + + model = build_random_tiny_model() + mlx_source_transformations(model, dtype=torch.bfloat16) + + for layer in model.layers: + self.assertIsInstance(layer.self_attn, MLXMuseGlimmerAttention) + + def test_installs_prefill_entry_points(self) -> None: + """The MLX transforms install the embed_text / prefill entry points used + by the vision path (embeds-input prefill + host sampling).""" + from executorch.examples.models.muse_glimmer.source_transformations.mlx import ( + mlx_source_transformations, + ) + + model = build_random_tiny_model() + mlx_source_transformations(model, dtype=torch.bfloat16) + + for name in ( + "mlx_embed_text", + "mlx_prefill_forward", + "mlx_logits_from_embeds", + ): + self.assertTrue(callable(getattr(model, name, None)), name) + + +@unittest.skipUnless(HAS_QUANT_DEPS, "torchao quantization dependencies not available") +class MLXExportTest(unittest.TestCase): + def setUp(self) -> None: + _require_mlx(self) + + def test_export_produces_pte(self) -> None: + """quantize -> pack (MLX) -> export lowers to a .pte via the MLX backend.""" + from executorch.examples.models.muse_glimmer.export.export_solo import ( + export_and_lower, + ) + from executorch.examples.models.muse_glimmer.tests.test_pipeline import ( + DEFAULT_RECIPE, + ) + from executorch.extension.llm.export.load import assign_state_dict + from executorch.extension.llm.export.quant import quantize_model, to_default + from executorch.runtime import Runtime, Verification + + model = build_random_tiny_model() + state_dict = quantize_model(model, DEFAULT_RECIPE) + + with torch.device("meta"): + model = MuseGlimmerModel(MLX_CONFIG) + assign_state_dict(model, state_dict, convert=to_default) + model.eval() + + with tempfile.TemporaryDirectory() as out_dir: + export_and_lower(model, MLX_CONFIG, out_dir, backend="mlx") + pte = os.path.join(out_dir, "model.pte") + self.assertTrue(os.path.exists(pte)) + program = Runtime.get().load_program(pte, verification=Verification.Minimal) + self.assertTrue( + { + "embed_text", + "forward_from_embeddings", + }.issubset(program.method_names) + ) + self.assertNotIn("decode_from_embedding", program.method_names) + + def test_vision_export_produces_pte(self) -> None: + """Vision is additive to the shared embeddings-input contract.""" + try: + import gguf # noqa: F401 + except (ImportError, ModuleNotFoundError): # noqa: B014 + self.skipTest("gguf package required") + + from executorch.examples.models.muse_glimmer.export.export_solo import ( + export_and_lower, + ) + from executorch.examples.models.muse_glimmer.loaders.checkpoint_loader import ( + load_mmproj_vision_model, + ) + from executorch.examples.models.muse_glimmer.tests.test_pipeline import ( + _mmproj_vision_config, + build_mmproj_gguf, + DEFAULT_RECIPE, + ) + from executorch.extension.llm.export.load import assign_state_dict + from executorch.extension.llm.export.quant import quantize_model, to_default + + model = build_random_tiny_model() + state_dict = quantize_model(model, DEFAULT_RECIPE) + with torch.device("meta"): + model = MuseGlimmerModel(MLX_CONFIG) + assign_state_dict(model, state_dict, convert=to_default) + model.eval() + + with tempfile.TemporaryDirectory() as tmp: + gguf_path = os.path.join(tmp, "mmproj.gguf") + build_mmproj_gguf(gguf_path) + vision_model, pos_table, _ = load_mmproj_vision_model( + gguf_path, config=_mmproj_vision_config(), backend="mlx" + ) + out_dir = os.path.join(tmp, "out") + export_and_lower( + model, + MLX_CONFIG, + out_dir, + backend="mlx", + vision_model=vision_model, + pos_embed_table=pos_table, + max_vision_patches=1024, + ) + self.assertTrue(os.path.exists(os.path.join(out_dir, "model.pte"))) + self.assertTrue(os.path.exists(os.path.join(out_dir, "pos_embed.bin"))) + + +class MLXVisionLoaderTest(unittest.TestCase): + """MLX packing keeps quantized vision weights as raw GGUF tensors (for the + MLX quantized/gguf custom kernels) rather than the CUDA packed classes.""" + + def setUp(self) -> None: + try: + import gguf # noqa: F401 + except (ImportError, ModuleNotFoundError): # noqa: B014 + self.skipTest("gguf package required") + + def test_mlx_backend_keeps_raw_gguf(self) -> None: + from executorch.examples.models.muse_glimmer.loaders.checkpoint_loader import ( + load_mmproj_vision_model, + ) + from executorch.examples.models.muse_glimmer.tests.test_pipeline import ( + _mmproj_vision_config, + build_mmproj_gguf, + ) + from executorch.extension.llm.export.gguf import ExportableGGUFTensor + + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "mmproj.gguf") + build_mmproj_gguf(path) + model, pos_table, _ = load_mmproj_vision_model( + path, config=_mmproj_vision_config(), backend="mlx" + ) + + blk0 = model.blocks[0] + # Q4_K and Q6_K weights alike stay raw ExportableGGUFTensor for MLX. + self.assertIsInstance(blk0.attn.q_proj.weight.data, ExportableGGUFTensor) + self.assertIsInstance(blk0.attn.v_proj.weight.data, ExportableGGUFTensor) + self.assertIsInstance(model.vision_proj.weight.data, ExportableGGUFTensor) + # Biases / norms / patch embed stay plain bf16 (both backends). + self.assertEqual(blk0.attn.q_proj.bias.dtype, torch.bfloat16) + self.assertEqual(model.conv1_linear.weight.dtype, torch.bfloat16) + self.assertEqual(pos_table.dtype, torch.bfloat16) + + +if __name__ == "__main__": + # run.py executes this module via runpy without installing it as + # sys.modules["__main__"], so unittest.main()'s default __main__ discovery + # finds no tests. Collect this module's TestCases explicitly instead. + import sys + + loader = unittest.TestLoader() + suite = unittest.TestSuite() + for _obj in list(globals().values()): + if isinstance(_obj, type) and issubclass(_obj, unittest.TestCase): + suite.addTests(loader.loadTestsFromTestCase(_obj)) + _result = unittest.TextTestRunner(verbosity=2).run(suite) + sys.exit(0 if _result.wasSuccessful() else 1) diff --git a/examples/models/muse-glimmer/tests/test_ondevice_serving.py b/examples/models/muse-glimmer/tests/test_ondevice_serving.py new file mode 100644 index 00000000000..9e27eed6444 --- /dev/null +++ b/examples/models/muse-glimmer/tests/test_ondevice_serving.py @@ -0,0 +1,62 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import json +import os +import urllib.request + +import pytest + +from executorch.examples.llm_server.python.chat_template import ChatTemplate +from executorch.examples.llm_server.python.protocol import ChatMessage + +_SERVER = os.environ.get("MUSE_GLIMMER_SERVER_URL") +_HF_DIR = os.environ.get("MUSE_GLIMMER_HF_DIR") + +pytestmark = pytest.mark.skipif( + not _SERVER or not _HF_DIR or not os.path.isdir(_HF_DIR), + reason="set MUSE_GLIMMER_SERVER_URL and MUSE_GLIMMER_HF_DIR to run Muse Glimmer on-device tests", +) + + +def _post(path: str, payload: dict) -> dict: + data = json.dumps(payload).encode("utf-8") + req = urllib.request.Request( + _SERVER.rstrip("/") + path, + data=data, + headers={"Content-Type": "application/json"}, + method="POST", + ) + with urllib.request.urlopen(req, timeout=120) as resp: + return json.loads(resp.read().decode("utf-8")) + + +def test_prompt_tokens_match_real_template_with_numeric_bos_prefix(): + pytest.importorskip("transformers") + from transformers import AutoTokenizer + + template = ChatTemplate( + _HF_DIR, + assistant_header="<|start|>assistant", + strip_rendered_bos=True, + append_generation_prompt_after_tool_response=True, + ) + tok = AutoTokenizer.from_pretrained(_HF_DIR) + messages = [ChatMessage(role="user", content="Say ok.")] + rendered = template.render(messages) + expected_ids = [tok.bos_token_id] + tok.encode(rendered, add_special_tokens=False) + + body = _post( + "/v1/chat/completions", + { + "model": "muse_glimmer", + "messages": [{"role": "user", "content": "Say ok."}], + "max_tokens": 1, + "temperature": 0, + "session_id": "muse_glimmer-bos-regression", + }, + ) + assert body["usage"]["prompt_tokens"] == len(expected_ids) diff --git a/examples/models/muse-glimmer/tests/test_pipeline.py b/examples/models/muse-glimmer/tests/test_pipeline.py new file mode 100644 index 00000000000..150d223fdcd --- /dev/null +++ b/examples/models/muse-glimmer/tests/test_pipeline.py @@ -0,0 +1,1235 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""Backend-agnostic integration tests for the Muse Glimmer pipeline. + +Tests the quantize -> save -> load roundtrip on a tiny model, KV cache +correctness, and checkpoint key mapping. No CUDA required. Backend-specific +tests (pack, inference, export) live in ``test_cuda_pipeline.py``. + +Usage: + python -m pytest examples/models/muse-glimmer/tests/test_pipeline.py -v +""" + +import json +import os +import tempfile +import unittest +from dataclasses import dataclass, replace + +import torch +from executorch.examples.models.muse_glimmer.model.model import ( + _ckpt_to_model_key, + _fix_raw_key, + _split_fused_qkv, + _split_fused_qkv_to_qko, + FlatKVCache, + MuseGlimmerConfig, + MuseGlimmerModel, + RingKVCache, +) + +try: + from executorch.backends.cuda.coalesced_int4_tensor import CudaCoalescedInt4Tensor + from executorch.backends.cuda.dp4a_planar_int6_tensor import ( + CudaDp4aPlanarInt6Tensor, + ) + from executorch.examples.models.muse_glimmer.loaders.quantize_and_save import ( + build_recipes, + ) + from executorch.extension.llm.export.quant import ( + identity, + QuantConfig, + quantize_model, + QuantRecipe, + QuantRule, + ) + from safetensors import safe_open + from safetensors.torch import save_file + from torchao.prototype.safetensors.safetensors_support import ( + flatten_tensor_state_dict, + unflatten_tensor_state_dict, + ) + from torchao.quantization import IntxUnpackedToInt8Tensor + from torchao.quantization.quantize_.workflows.int4.int4_tensor import Int4Tensor + + HAS_QUANT_DEPS = True +except Exception: + # Any import-time failure (missing package, or a broken torchao/triton/torch + # version skew that raises AttributeError) means the quant deps are unusable. + HAS_QUANT_DEPS = False + + +# --------------------------------------------------------------------------- +# Shared fixtures — imported by test_cuda_pipeline.py. + +TINY_CONFIG = MuseGlimmerConfig( + dim=256, + n_layers=8, + n_heads=4, + n_kv_heads=2, + head_dim=64, + ffn_dim_multiplier=2.0, + vocab_size=256, + norm_eps=1e-5, + rope_theta=500_000.0, + use_qk_norm=True, + use_attn_o_gate=True, + output_soft_cap_temp=20.0, + global_attn_cfg="[16,16,16,0]", + every_n_layers_nope=4, + normalize_tok_embeddings=True, + output_multiplier=0.19611613513, + post_norm_eps=1e-8, + max_seq_len=64, +) + +# GGUF fixtures need K (= dim) a multiple of the k-quant super-block QK_K=256. +# head_dim*n_kv_heads and the fused dims stay small; only ``dim`` must be 256. +GGUF_CONFIG = MuseGlimmerConfig( + dim=256, + n_layers=8, + n_heads=4, + n_kv_heads=2, + head_dim=64, + ffn_dim_multiplier=1.0, + vocab_size=256, + norm_eps=1e-5, + rope_theta=500_000.0, + use_qk_norm=True, + use_attn_o_gate=True, + output_soft_cap_temp=20.0, + global_attn_cfg="[16,16,16,0]", + every_n_layers_nope=4, + normalize_tok_embeddings=True, + output_multiplier=0.19611613513, + post_norm_eps=1e-8, + max_seq_len=64, +) + +if HAS_QUANT_DEPS: + QUANT_4W = QuantConfig(bits=4, group_size=32, symmetric=False, method="min_max") + QUANT_8W_PER_AXIS = QuantConfig( + bits=8, + group_size=TINY_CONFIG.dim, + symmetric=True, + method="min_max", + ) + + DEFAULT_RECIPE = QuantRecipe( + rules=[ + QuantRule(r"embed_tokens\.weight", QUANT_8W_PER_AXIS), + QuantRule(r".*norm\.weight", None), + QuantRule(r".*\.weight", QUANT_4W), + ] + ) + + +@dataclass(frozen=True) +class MockEncoding: + """The `.ids` carrier that tokenizers.Tokenizer.encode returns.""" + + ids: list[int] + + +class MockTokenizer: + """Mirrors the tokenizers.Tokenizer surface inference.py calls.""" + + def __init__(self, vocab_size: int): + self.vocab_size = vocab_size + + def encode(self, text: str, add_special_tokens: bool = True) -> MockEncoding: + return MockEncoding([1, 2, 3, 4]) + + def decode(self, ids: list[int], skip_special_tokens: bool = True) -> str: + return "" + + def token_to_id(self, token: str) -> int | None: + return {"<|patch|>": 200092}.get(token) + + +def build_random_tiny_model() -> MuseGlimmerModel: + torch.manual_seed(42) + model = MuseGlimmerModel(TINY_CONFIG) + model.to(dtype=torch.bfloat16) + for p in model.parameters(): + if p.device.type != "meta": + p.data.normal_(0, 0.02) + model.eval() + return model + + +def save_checkpoint(output_dir: str) -> None: + """Build tiny model, quantize, and save as prequantized checkpoint.""" + model = build_random_tiny_model() + state_dict = quantize_model(model, DEFAULT_RECIPE, convert=identity) + os.makedirs(output_dir, exist_ok=True) + td, md = flatten_tensor_state_dict(state_dict) + save_file(td, os.path.join(output_dir, "model.safetensors"), metadata=md) + + config_dict = { + "dim": TINY_CONFIG.dim, + "n_layers": TINY_CONFIG.n_layers, + "n_heads": TINY_CONFIG.n_heads, + "n_kv_heads": TINY_CONFIG.n_kv_heads, + "head_dim": TINY_CONFIG.head_dim, + "ffn_dim_multiplier": TINY_CONFIG.ffn_dim_multiplier, + "vocab_size": TINY_CONFIG.vocab_size, + "norm_eps": TINY_CONFIG.norm_eps, + "rope_theta": TINY_CONFIG.rope_theta, + "use_qk_norm": TINY_CONFIG.use_qk_norm, + "use_attn_o_gate": TINY_CONFIG.use_attn_o_gate, + "output_soft_cap_temp": TINY_CONFIG.output_soft_cap_temp, + "global_attn_cfg": TINY_CONFIG.global_attn_cfg, + "every_n_layers_nope": TINY_CONFIG.every_n_layers_nope, + "normalize_tok_embeddings": TINY_CONFIG.normalize_tok_embeddings, + "output_multiplier": TINY_CONFIG.output_multiplier, + "post_norm_eps": TINY_CONFIG.post_norm_eps, + } + with open(os.path.join(output_dir, "params.json"), "w") as f: + json.dump(config_dict, f) + + +# --------------------------------------------------------------------------- +# Tests (CPU only, no backend dependency) + + +@unittest.skipUnless(HAS_QUANT_DEPS, "torchao quantization dependencies not available") +class TestQuantizeSaveLoadRoundtripTest(unittest.TestCase): + def test_roundtrip_preserves_weights(self): + """quantize -> save -> load recovers all weights.""" + model = build_random_tiny_model() + state_dict = quantize_model(model, DEFAULT_RECIPE, convert=identity) + + with tempfile.TemporaryDirectory() as tmpdir: + path = os.path.join(tmpdir, "model.safetensors") + td, md = flatten_tensor_state_dict(state_dict) + save_file(td, path, metadata=md) + + with safe_open(path, framework="pt", device="cpu") as f: + loaded_meta = f.metadata() + loaded_tensors = {k: f.get_tensor(k) for k in f.keys()} + loaded, _ = unflatten_tensor_state_dict(loaded_tensors, loaded_meta) + + self.assertEqual(set(state_dict.keys()), set(loaded.keys())) + for fqn in state_dict: + orig = state_dict[fqn] + got = loaded[fqn] + self.assertEqual(type(orig).__name__, type(got).__name__) + if isinstance(orig, Int4Tensor): + self.assertTrue(torch.equal(orig.qdata, got.qdata)) + self.assertTrue(torch.equal(orig.scale, got.scale)) + elif isinstance(orig, IntxUnpackedToInt8Tensor): + self.assertTrue(torch.equal(orig.qdata, got.qdata)) + self.assertTrue(torch.equal(orig.scale, got.scale)) + elif isinstance(orig, torch.Tensor): + self.assertTrue(torch.equal(orig, got)) + + def test_embedding_quantized_as_int8(self): + """embed_tokens is quantized to INT8 (IntxUnpackedToInt8Tensor).""" + model = build_random_tiny_model() + state_dict = quantize_model(model, DEFAULT_RECIPE, convert=identity) + + self.assertIn("embed_tokens.weight", state_dict) + self.assertIsInstance( + state_dict["embed_tokens.weight"], IntxUnpackedToInt8Tensor + ) + + def test_norms_not_quantized(self): + """Norm weights stay as plain tensors (not quantized).""" + model = build_random_tiny_model() + state_dict = quantize_model(model, DEFAULT_RECIPE, convert=identity) + + norm_keys = [k for k in state_dict if "norm" in k] + self.assertGreater(len(norm_keys), 0) + for k in norm_keys: + self.assertIsInstance(state_dict[k], torch.Tensor) + self.assertNotIn("Int4", type(state_dict[k]).__name__) + + +class TestRingKVCacheTest(unittest.TestCase): + def _make_cache(self, window=4, heads=2, head_dim=8): + return RingKVCache( + max_batch_size=1, + window_size=window, + num_kv_heads=heads, + head_dim=head_dim, + ) + + def test_sequential_write_read(self): + """Writing positions 0..buf_size-1 fills every slot exactly once.""" + cache = self._make_cache(window=4) + buf_size = cache.buf_size + for i in range(buf_size): + pos = torch.tensor([i], dtype=torch.long) + k = torch.full((1, 2, 1, 8), float(i)) + v = torch.full((1, 2, 1, 8), float(i + 100)) + k_out, v_out = cache.update(pos, k, v) + for i in range(buf_size): + slot = i % buf_size + self.assertEqual(k_out[0, 0, slot, 0].item(), float(i)) + self.assertEqual(v_out[0, 0, slot, 0].item(), float(i + 100)) + + def test_wraparound_overwrites_oldest(self): + """Position buf_size overwrites slot 0 (the oldest entry).""" + cache = self._make_cache(window=4) + buf_size = cache.buf_size + for i in range(buf_size + 1): + pos = torch.tensor([i], dtype=torch.long) + k = torch.full((1, 2, 1, 8), float(i)) + v = torch.full((1, 2, 1, 8), float(i)) + k_out, _ = cache.update(pos, k, v) + self.assertEqual(k_out[0, 0, 0, 0].item(), float(buf_size)) + self.assertEqual(k_out[0, 0, 1, 0].item(), 1.0) + + def test_multi_token_prefill(self): + """Writing multiple positions in one call places them correctly.""" + cache = self._make_cache(window=4) + pos = torch.arange(4, dtype=torch.long) + k = torch.arange(4).float().view(1, 1, 4, 1).expand(1, 2, 4, 8) + v = torch.zeros(1, 2, 4, 8) + k_out, _ = cache.update(pos, k, v) + for i in range(4): + self.assertEqual(k_out[0, 0, i, 0].item(), float(i)) + + +class TestFlatKVCacheTest(unittest.TestCase): + def _make_cache(self, max_seq=16, heads=2, head_dim=8): + return FlatKVCache( + max_batch_size=1, + max_seq_len=max_seq, + num_kv_heads=heads, + head_dim=head_dim, + ) + + def test_sequential_write_read(self): + cache = self._make_cache() + for i in range(8): + pos = torch.tensor([i], dtype=torch.long) + k = torch.full((1, 2, 1, 8), float(i)) + v = torch.full((1, 2, 1, 8), float(i + 100)) + k_out, v_out = cache.update(pos, k, v) + for i in range(8): + self.assertEqual(k_out[0, 0, i, 0].item(), float(i)) + self.assertEqual(v_out[0, 0, i, 0].item(), float(i + 100)) + + def test_multi_token_prefill(self): + cache = self._make_cache() + pos = torch.arange(6, dtype=torch.long) + k = torch.arange(6).float().view(1, 1, 6, 1).expand(1, 2, 6, 8) + v = torch.zeros(1, 2, 6, 8) + k_out, _ = cache.update(pos, k, v) + for i in range(6): + self.assertEqual(k_out[0, 0, i, 0].item(), float(i)) + + +class TestCheckpointKeyMappingTest(unittest.TestCase): + def test_raw_key_fixes(self): + self.assertEqual( + _fix_raw_key("layers.0.attention.qkv_proj.norm_weight"), + "layers.0.attention.qkv_proj_norm.weight", + ) + self.assertEqual( + _fix_raw_key("layers.5.feed_forward.norm_weight"), + "layers.5.feed_forward.norm.weight", + ) + self.assertEqual( + _fix_raw_key("output.norm_weight"), + "output_norm.weight", + ) + self.assertEqual( + _fix_raw_key("output.norm.weight"), + "output_norm.weight", + ) + + def test_attention_keys(self): + # qkv_proj_norm and o_proj map directly. + self.assertEqual( + _ckpt_to_model_key("layers.0.attention.qkv_proj_norm.weight"), + "layers.0.self_attn.qkv_proj_norm.weight", + ) + self.assertEqual( + _ckpt_to_model_key("layers.51.attention.o_proj.weight"), + "layers.51.self_attn.o_proj.weight", + ) + # The fused qkv_proj weight maps directly to the model's fused qkv_proj; + # the split/qko layouts are produced by a post-load split in + # from_checkpoint (_split_fused_qkv / _split_fused_qkv_to_qko). + self.assertEqual( + _ckpt_to_model_key("layers.3.attention.qkv_proj.weight"), + "layers.3.self_attn.qkv_proj.weight", + ) + + def test_fused_qkv_split_to_qko(self): + """The consolidated [Q|K|V|OG] weight splits into qko_proj + v_proj.""" + cfg = TINY_CONFIG + q_dim = cfg.n_heads * cfg.head_dim + kv_dim = cfg.n_kv_heads * cfg.head_dim + og_dim = q_dim if cfg.use_attn_o_gate else 0 + fused = torch.randn(q_dim + 2 * kv_dim + og_dim, cfg.dim) + prefix = "layers.7.self_attn." + sd = {f"{prefix}qkv_proj.weight": fused} + + out = _split_fused_qkv_to_qko(sd, cfg) + qko = out[f"{prefix}qko_proj.weight"] + v = out[f"{prefix}v_proj.weight"] + + # Shapes: qko = [Q|K|OG], v = [V]. + self.assertEqual(qko.shape, (q_dim + kv_dim + og_dim, cfg.dim)) + self.assertEqual(v.shape, (kv_dim, cfg.dim)) + self.assertNotIn(f"{prefix}qkv_proj.weight", out) + + # Row-for-row content: qko is Q, K, then OG; v is the middle V slice. + self.assertTrue(torch.equal(qko[:q_dim], fused[:q_dim])) + self.assertTrue( + torch.equal(qko[q_dim : q_dim + kv_dim], fused[q_dim : q_dim + kv_dim]) + ) + self.assertTrue(torch.equal(qko[q_dim + kv_dim :], fused[q_dim + 2 * kv_dim :])) + self.assertTrue(torch.equal(v, fused[q_dim + kv_dim : q_dim + 2 * kv_dim])) + + def test_mlp_keys(self): + self.assertEqual( + _ckpt_to_model_key("layers.0.feed_forward.norm.weight"), + "layers.0.mlp.norm.weight", + ) + self.assertEqual( + _ckpt_to_model_key("layers.5.feed_forward.fc1_weight"), + "layers.5.mlp.gate_up_proj.weight", + ) + self.assertEqual( + _ckpt_to_model_key("layers.5.feed_forward.fc2_weight"), + "layers.5.mlp.down_proj.weight", + ) + + def test_global_keys(self): + self.assertEqual( + _ckpt_to_model_key("tok_embeddings.weight"), + "embed_tokens.weight", + ) + self.assertEqual( + _ckpt_to_model_key("output_norm.weight"), + "output_norm.weight", + ) + self.assertEqual( + _ckpt_to_model_key("output.weight"), + "lm_head.weight", + ) + + def test_post_norm_keys_pass_through(self): + self.assertEqual( + _ckpt_to_model_key("layers.0.post_attn_norm.weight"), + "layers.0.post_attn_norm.weight", + ) + self.assertEqual( + _ckpt_to_model_key("layers.0.post_ffn_norm.weight"), + "layers.0.post_ffn_norm.weight", + ) + + def test_vision_keys_ignored(self): + self.assertIsNone(_ckpt_to_model_key("vision_projection.weight")) + self.assertIsNone(_ckpt_to_model_key("perception_emb_norm.weight")) + + def test_unknown_key_returns_none(self): + self.assertIsNone(_ckpt_to_model_key("some.unknown.key")) + + +class TestLayerClassificationTest(unittest.TestCase): + def test_tiny_config_layer_types(self): + """Verify iRoPE and SWA layer classification on tiny config.""" + cfg = TINY_CONFIG + rope_layers = [i for i in range(cfg.n_layers) if cfg.layer_use_rope(i)] + nope_layers = [i for i in range(cfg.n_layers) if not cfg.layer_use_rope(i)] + swa_layers = [i for i in range(cfg.n_layers) if cfg.layer_window_size(i) > 0] + global_layers = [ + i for i in range(cfg.n_layers) if cfg.layer_window_size(i) == 0 + ] + + self.assertEqual(nope_layers, global_layers) + self.assertEqual(rope_layers, swa_layers) + self.assertEqual(len(rope_layers) + len(nope_layers), cfg.n_layers) + + def test_full_config_layer_types(self): + """Verify 39 RoPE+SWA and 13 NoPE+Global on the real 52-layer config.""" + cfg = MuseGlimmerConfig() + rope_count = sum(1 for i in range(cfg.n_layers) if cfg.layer_use_rope(i)) + global_count = sum( + 1 for i in range(cfg.n_layers) if cfg.layer_window_size(i) == 0 + ) + self.assertEqual(rope_count, 39) + self.assertEqual(global_count, 13) + + +class TestTinyModelForwardTest(unittest.TestCase): + def test_forward_produces_logits(self): + """Tiny model forward pass produces valid logits on CPU.""" + model = build_random_tiny_model() + tokens = torch.tensor([[1, 2, 3]], dtype=torch.long) + input_pos = torch.arange(3, dtype=torch.long) + with torch.no_grad(): + logits = model(tokens, input_pos) + self.assertEqual(logits.shape, (1, 3, TINY_CONFIG.vocab_size)) + self.assertFalse(logits.isnan().any()) + self.assertFalse(logits.isinf().any()) + + def test_decode_step_produces_logits(self): + """Single-token decode step produces valid logits.""" + model = build_random_tiny_model() + tokens = torch.tensor([[5]], dtype=torch.long) + input_pos = torch.tensor([0], dtype=torch.long) + with torch.no_grad(): + logits = model(tokens, input_pos) + self.assertEqual(logits.shape, (1, 1, TINY_CONFIG.vocab_size)) + self.assertFalse(logits.isnan().any()) + + def test_soft_capping_bounds_logits(self): + """Output soft-capping keeps logits within [-cap, cap].""" + model = build_random_tiny_model() + tokens = torch.tensor([[1, 2, 3, 4, 5]], dtype=torch.long) + input_pos = torch.arange(5, dtype=torch.long) + with torch.no_grad(): + logits = model(tokens, input_pos) + cap = TINY_CONFIG.output_soft_cap_temp + self.assertTrue((logits.abs() <= cap + 1e-5).all()) + + +class TestUnfuseQkvTest(unittest.TestCase): + def test_split_fused_qkv_shapes_and_values(self): + """_split_fused_qkv splits the fused rows into q/k/v/og by size.""" + cfg = replace(TINY_CONFIG, fuse_qkv=False) + q_dim = cfg.n_heads * cfg.head_dim + kv_dim = cfg.n_kv_heads * cfg.head_dim + og_dim = q_dim + fused_w = torch.randn(q_dim + 2 * kv_dim + og_dim, cfg.dim) + prefix = "layers.0.self_attn." + sd = { + f"{prefix}qkv_proj.weight": fused_w, + "embed_tokens.weight": torch.randn(4, cfg.dim), + } + + out = _split_fused_qkv(sd, cfg) + + self.assertNotIn(f"{prefix}qkv_proj.weight", out) + self.assertIn("embed_tokens.weight", out) + self.assertEqual(out[f"{prefix}q_proj.weight"].shape, (q_dim, cfg.dim)) + self.assertEqual(out[f"{prefix}k_proj.weight"].shape, (kv_dim, cfg.dim)) + self.assertEqual(out[f"{prefix}v_proj.weight"].shape, (kv_dim, cfg.dim)) + self.assertEqual(out[f"{prefix}og_proj.weight"].shape, (og_dim, cfg.dim)) + self.assertTrue( + torch.equal( + out[f"{prefix}v_proj.weight"], + fused_w[q_dim + kv_dim : q_dim + 2 * kv_dim], + ) + ) + + def test_fused_and_unfused_forward_match(self): + """Unfused q/k/v/og projections reproduce the fused forward output.""" + torch.manual_seed(0) + fused = MuseGlimmerModel(replace(TINY_CONFIG, fuse_qkv=True)).to(torch.bfloat16) + for p in fused.parameters(): + p.data.normal_(0, 0.02) + fused.eval() + + unfused_cfg = replace(TINY_CONFIG, fuse_qkv=False) + unfused = MuseGlimmerModel(unfused_cfg).to(torch.bfloat16) + unfused.load_state_dict( + _split_fused_qkv(fused.state_dict(), unfused_cfg), strict=False + ) + unfused.eval() + + tokens = torch.tensor([[1, 2, 3, 4]], dtype=torch.long) + input_pos = torch.arange(4, dtype=torch.long) + with torch.no_grad(): + out_fused = fused(tokens, input_pos) + out_unfused = unfused(tokens, input_pos) + + torch.testing.assert_close(out_fused, out_unfused, atol=1e-1, rtol=1e-1) + + +@unittest.skipUnless(HAS_QUANT_DEPS, "torchao quantization dependencies not available") +class TestGgufRecipeTest(unittest.TestCase): + def test_gguf_bit_assignment(self): + """gguf recipe: int6 on v_proj/down_proj/lm_head, int4 elsewhere.""" + recipe = build_recipes()["gguf"] + for fqn in ( + "layers.0.self_attn.v_proj.weight", + "layers.7.mlp.down_proj.weight", + "lm_head.weight", + ): + cfg = recipe.get_config(fqn) + self.assertIsNotNone(cfg, fqn) + self.assertEqual(cfg.bits, 6, fqn) + self.assertEqual(cfg.group_size, 32, fqn) + for fqn in ( + "layers.0.self_attn.q_proj.weight", + "layers.0.self_attn.k_proj.weight", + "layers.0.self_attn.og_proj.weight", + "layers.0.self_attn.o_proj.weight", + "layers.0.mlp.gate_up_proj.weight", + "embed_tokens.weight", + ): + cfg = recipe.get_config(fqn) + self.assertIsNotNone(cfg, fqn) + self.assertEqual(cfg.bits, 4, fqn) + self.assertIsNone(recipe.get_config("layers.0.post_attn_norm.weight")) + + def test_gguf_int8_bit_assignment(self): + """gguf_int8 recipe: int8 gs128 on v_proj/down_proj/lm_head, int4 else.""" + recipe = build_recipes()["gguf_int8"] + for fqn in ( + "layers.0.self_attn.v_proj.weight", + "layers.7.mlp.down_proj.weight", + "lm_head.weight", + ): + cfg = recipe.get_config(fqn) + self.assertIsNotNone(cfg, fqn) + self.assertEqual(cfg.bits, 8, fqn) + self.assertEqual(cfg.group_size, 128, fqn) + for fqn in ( + "layers.0.self_attn.q_proj.weight", + "layers.0.self_attn.k_proj.weight", + "layers.0.self_attn.og_proj.weight", + "layers.0.self_attn.o_proj.weight", + "layers.0.mlp.gate_up_proj.weight", + "embed_tokens.weight", + ): + cfg = recipe.get_config(fqn) + self.assertIsNotNone(cfg, fqn) + self.assertEqual(cfg.bits, 4, fqn) + self.assertIsNone(recipe.get_config("layers.0.post_attn_norm.weight")) + + def test_int4_recipe_all_int4(self): + """int4 recipe: int4 everywhere incl. embedding; norms unquantized.""" + recipe = build_recipes()["int4"] + for fqn in ( + "embed_tokens.weight", + "layers.0.self_attn.qkv_proj.weight", + "layers.0.self_attn.o_proj.weight", + "layers.0.mlp.gate_up_proj.weight", + "layers.7.mlp.down_proj.weight", + "lm_head.weight", + ): + cfg = recipe.get_config(fqn) + self.assertIsNotNone(cfg, fqn) + self.assertEqual(cfg.bits, 4, fqn) + self.assertIsNone(recipe.get_config("layers.0.post_attn_norm.weight")) + + +# --------------------------------------------------------------------------- +# GGUF native-bit-width loading (CPU: packing needs no CUDA) + + +# Q6_K shards per GGUF leaf: which layers store this leaf at Q6_K (else Q4_K). +# Exercises mixed per-layer bit-width for the standalone v_proj and ffn_down. +_GGUF_Q6_LAYERS = { + "attn_v": {0, 3, 5}, + "ffn_down": {1, 4}, +} +# Top-level output (lm_head) stored at Q6_K. +_GGUF_Q6_OUTPUT = True + + +def build_muse_glimmer_gguf(path: str, config: MuseGlimmerConfig = GGUF_CONFIG) -> None: + """Write a tiny Muse Glimmer GGUF with mixed Q4_K/Q6_K to exercise bit-width routing. + + Layout mirrors a real Muse Glimmer GGUF: separate ``attn_q/k/v/output_gate`` and + ``ffn_gate/up`` shards (fused only inside the model), plus ``ffn_down``, + ``attn_output``, norms, ``token_embd`` (Q4_K), and ``output`` (Q6_K). + ``attn_v`` / ``ffn_down`` are Q6_K on the layers in ``_GGUF_Q6_LAYERS``. + Requires the ``gguf`` package. K (= dim) must be a multiple of QK_K. + """ + import gguf + from executorch.extension.llm.export.gguf import ( + _Q4_K_BLOCK_BYTES, + _Q6_K_BLOCK_BYTES, + QK_K, + ) + + def _fp16_bytes(x: float): + return torch.tensor([x], dtype=torch.float16).view(torch.uint8) + + def _make_q4k_raw(n: int, nb: int, seed: int): + g = torch.Generator().manual_seed(seed) + blk = torch.randint( + 0, 256, (n * nb, _Q4_K_BLOCK_BYTES), dtype=torch.uint8, generator=g + ) + blk[:, 0:2] = _fp16_bytes(0.01) # d + blk[:, 2:4] = _fp16_bytes(0.01) # dmin + blk[:, 4:16] = 0x21 # fixed mid-range 6-bit sub-scales/mins (non-zero) + return blk.reshape(n, nb * _Q4_K_BLOCK_BYTES) + + def _make_q6k_raw(n: int, nb: int, seed: int): + g = torch.Generator().manual_seed(seed) + blk = torch.randint( + 0, 256, (n * nb, _Q6_K_BLOCK_BYTES), dtype=torch.uint8, generator=g + ) + blk[:, 192:208] = 0x10 # fixed int8 sub-scales (non-zero) + blk[:, 208:210] = _fp16_bytes(0.01) # d + return blk.reshape(n, nb * _Q6_K_BLOCK_BYTES) + + dim = config.dim + q_dim = config.n_heads * config.head_dim + kv_dim = config.n_kv_heads * config.head_dim + ffn = config.ffn_dim + nb = dim // QK_K # blocks along K (all linears project from `dim`) + + def q4(n: int, seed: int): + return _make_q4k_raw(n, nb, seed).numpy(), gguf.GGMLQuantizationType.Q4_K + + def q6(n: int, seed: int): + return _make_q6k_raw(n, nb, seed).numpy(), gguf.GGMLQuantizationType.Q6_K + + def f32(*shape): + return torch.ones(shape, dtype=torch.float32).numpy() + + writer = gguf.GGUFWriter(path, "muse_glimmer") + seed = 0 + for i in range(config.n_layers): + # Fused-in-model shards (always Q4_K). + for leaf, n in ( + ("attn_q", q_dim), + ("attn_k", kv_dim), + ("attn_output_gate", q_dim), + ("ffn_gate", ffn), + ("ffn_up", ffn), + ): + blob, dt = q4(n, seed) + seed += 1 + writer.add_tensor(f"blk.{i}.{leaf}.weight", blob, raw_dtype=dt) + # Standalone shards with per-layer bit-width. + for leaf, n in (("attn_v", kv_dim), ("ffn_down", dim), ("attn_output", dim)): + use_q6 = i in _GGUF_Q6_LAYERS.get(leaf, set()) + blob, dt = q6(n, seed) if use_q6 else q4(n, seed) + seed += 1 + writer.add_tensor(f"blk.{i}.{leaf}.weight", blob, raw_dtype=dt) + # Norms (F32) + all-ones QK-norms (ignored by the loader). + writer.add_tensor(f"blk.{i}.attn_norm.weight", f32(dim)) + writer.add_tensor(f"blk.{i}.ffn_norm.weight", f32(dim)) + writer.add_tensor(f"blk.{i}.post_attention_norm.weight", f32(dim)) + writer.add_tensor(f"blk.{i}.post_ffw_norm.weight", f32(dim)) + writer.add_tensor(f"blk.{i}.attn_q_norm.weight", f32(config.head_dim)) + writer.add_tensor(f"blk.{i}.attn_k_norm.weight", f32(config.head_dim)) + + # Top-level: token_embd (Q4_K), output/lm_head (Q6_K), output_norm (F32). + emb, dt = q4(config.vocab_size, seed) + seed += 1 + writer.add_tensor("token_embd.weight", emb, raw_dtype=dt) + out, dt = ( + q6(config.vocab_size, seed) if _GGUF_Q6_OUTPUT else q4(config.vocab_size, seed) + ) + seed += 1 + writer.add_tensor("output.weight", out, raw_dtype=dt) + writer.add_tensor("output_norm.weight", f32(dim)) + + writer.write_header_to_file() + writer.write_kv_data_to_file() + writer.write_tensors_to_file() + writer.close() + + +@unittest.skipUnless(HAS_QUANT_DEPS, "torchao quantization dependencies not available") +class TestGgufBitWidthTest(unittest.TestCase): + """GGUF load preserves native per-tensor bit-width (Q4_K->INT4, Q6_K->INT6). + + Packing is CPU-safe (no CUDA required); only kernel execution needs CUDA. + """ + + def setUp(self): + try: + import gguf # noqa: F401 + except ImportError: + self.skipTest("gguf package required") + + def _load(self): + from executorch.examples.models.muse_glimmer.loaders.checkpoint_loader import ( + load_gguf_model, + ) + + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "tiny.gguf") + build_muse_glimmer_gguf(path) + return load_gguf_model(path, backend="cuda", config=GGUF_CONFIG) + + def test_bit_widths_match_source(self): + model, _ = self._load() + + # v_proj / ffn_down honor per-layer bit-width. + for i in range(GGUF_CONFIG.n_layers): + v = model.layers[i].self_attn.v_proj.weight.data + want_v6 = i in _GGUF_Q6_LAYERS["attn_v"] + self.assertIsInstance( + v, + CudaDp4aPlanarInt6Tensor if want_v6 else CudaCoalescedInt4Tensor, + f"layer {i} v_proj bit-width mismatch", + ) + d = model.layers[i].mlp.down_proj.weight.data + want_d6 = i in _GGUF_Q6_LAYERS["ffn_down"] + self.assertIsInstance( + d, + CudaDp4aPlanarInt6Tensor if want_d6 else CudaCoalescedInt4Tensor, + f"layer {i} down_proj bit-width mismatch", + ) + + # Fused qko_proj / gate_up_proj (all-Q4_K shards) -> INT4. + self.assertIsInstance( + model.layers[0].self_attn.qko_proj.weight.data, CudaCoalescedInt4Tensor + ) + self.assertIsInstance( + model.layers[0].mlp.gate_up_proj.weight.data, CudaCoalescedInt4Tensor + ) + # o_proj is Q4_K -> INT4. + self.assertIsInstance( + model.layers[0].self_attn.o_proj.weight.data, CudaCoalescedInt4Tensor + ) + # lm_head is Q6_K -> INT6; token embedding is gatherable int4-in-int8. + self.assertIsInstance(model.lm_head.weight.data, CudaDp4aPlanarInt6Tensor) + self.assertIsInstance(model.embed_tokens.weight.data, IntxUnpackedToInt8Tensor) + + def test_fused_qko_shape(self): + """qko_proj fuses [Q|K|OG]; v_proj is separate with [V] rows.""" + model, _ = self._load() + q_dim = GGUF_CONFIG.n_heads * GGUF_CONFIG.head_dim + kv_dim = GGUF_CONFIG.n_kv_heads * GGUF_CONFIG.head_dim + og_dim = q_dim # use_attn_o_gate + self.assertEqual( + model.layers[0].self_attn.qko_proj.weight.shape, + (q_dim + kv_dim + og_dim, GGUF_CONFIG.dim), + ) + self.assertEqual( + model.layers[0].self_attn.v_proj.weight.shape, + (kv_dim, GGUF_CONFIG.dim), + ) + + def test_mixed_quant_fusion_groups_remain_atomic(self): + """A mixed-precision group stays separate across the whole model.""" + from executorch.examples.models.muse_glimmer.loaders.checkpoint_loader import ( + _fuse_state_dict, + ) + from executorch.extension.llm.export.gguf import ( + _Q4_K_BLOCK_BYTES, + _Q6_K_BLOCK_BYTES, + ExportableGGUFTensor, + ) + + def weight(rows, ggml_type, row_bytes): + raw = torch.zeros((rows, row_bytes), dtype=torch.uint8) + return ExportableGGUFTensor(raw, ggml_type, torch.bfloat16) + + atomic = { + "layers.0.self_attn.q_proj.weight": weight(4, "q4_k", _Q4_K_BLOCK_BYTES), + "layers.0.self_attn.k_proj.weight": weight(2, "q6_k", _Q6_K_BLOCK_BYTES), + "layers.0.self_attn.og_proj.weight": weight(4, "q4_k", _Q4_K_BLOCK_BYTES), + "layers.0.mlp.gate_proj.weight": weight(8, "q4_k", _Q4_K_BLOCK_BYTES), + "layers.0.mlp.up_proj.weight": weight(8, "q6_k", _Q6_K_BLOCK_BYTES), + } + + state_dict, fused_groups = _fuse_state_dict(atomic, "cuda", n_layers=1) + + self.assertEqual(fused_groups, set()) + self.assertEqual(set(state_dict), set(atomic)) + for fqn, tensor in atomic.items(): + self.assertIs(state_dict[fqn], tensor) + + +# --------------------------------------------------------------------------- +# mmproj (vision encoder) native-bit-width loading (CPU: packing needs no CUDA) + + +# Vision config small enough for a fast test; K (= latent_dim / adapter dims) +# must be a multiple of QK_K=256 for the k-quant block layout. +_MMPROJ_LATENT = 256 +_MMPROJ_MLP = 512 +_MMPROJ_ADAPTER = 256 +_MMPROJ_HIDDEN = 256 +_MMPROJ_ENC_OUT = _MMPROJ_LATENT * 4 # latent * downsample^2 +_MMPROJ_LAYERS = 3 +_MMPROJ_POS_TOKENS = 1024 # 32*32 +_MMPROJ_PATCH_DIM = 2 * 3 * 14 * 14 # 1176 + + +def _mmproj_vision_config(): + from executorch.examples.models.muse_glimmer.vision.precompute import ( + MuseGlimmerVisionConfig, + ) + + return MuseGlimmerVisionConfig( + latent_dim=_MMPROJ_LATENT, + n_heads=4, + n_layers=_MMPROJ_LAYERS, + mlp_hidden=_MMPROJ_MLP, + adapter_dim=_MMPROJ_ADAPTER, + encoder_output_dim=_MMPROJ_ENC_OUT, + hidden_size=_MMPROJ_HIDDEN, + ) + + +def build_mmproj_gguf( + path: str, + *, + numeric_projector_names: bool = False, + folded_patch_embedding: bool = False, +) -> None: + """Write a tiny mmproj (clip/muse_glimmer) GGUF exercising the vision name map. + + Mirrors the real schema: ``v.blk.{i}.{attn_q/k/out,ffn_up}`` Q4_K, + ``attn_v``/``ffn_down`` Q6_K, all ``.bias``/norms F32, ``v.patch_embd`` and + ``v.position_embd`` BF16, and ``mm.adapter_fc/adapter_proj/vision_proj`` + Q4_K. K dims are multiples of QK_K. + """ + import gguf + from executorch.extension.llm.export.gguf import ( + _Q4_K_BLOCK_BYTES, + _Q6_K_BLOCK_BYTES, + QK_K, + ) + + def _fp16_bytes(x: float): + return torch.tensor([x], dtype=torch.float16).view(torch.uint8) + + def _q4k(n: int, k: int, seed: int): + nb = k // QK_K + g = torch.Generator().manual_seed(seed) + blk = torch.randint( + 0, 256, (n * nb, _Q4_K_BLOCK_BYTES), dtype=torch.uint8, generator=g + ) + blk[:, 0:2] = _fp16_bytes(0.01) + blk[:, 2:4] = _fp16_bytes(0.01) + blk[:, 4:16] = 0x21 + return blk.reshape(n, nb * _Q4_K_BLOCK_BYTES).numpy(), ( + gguf.GGMLQuantizationType.Q4_K + ) + + def _q6k(n: int, k: int, seed: int): + nb = k // QK_K + g = torch.Generator().manual_seed(seed) + blk = torch.randint( + 0, 256, (n * nb, _Q6_K_BLOCK_BYTES), dtype=torch.uint8, generator=g + ) + blk[:, 192:208] = 0x10 + blk[:, 208:210] = _fp16_bytes(0.01) + return blk.reshape(n, nb * _Q6_K_BLOCK_BYTES).numpy(), ( + gguf.GGMLQuantizationType.Q6_K + ) + + def _f32(*shape): + return torch.ones(shape, dtype=torch.float32).numpy() + + latent = _MMPROJ_LATENT + writer = gguf.GGUFWriter(path, "clip") + seed = 0 + for i in range(_MMPROJ_LAYERS): + # Q4_K weights: attn_q/k/out (K=latent), ffn_up (K=latent). + for leaf, n, k in ( + ("attn_q", latent, latent), + ("attn_k", latent, latent), + ("attn_out", latent, latent), + ("ffn_up", _MMPROJ_MLP, latent), + ): + blob, dt = _q4k(n, k, seed) + seed += 1 + writer.add_tensor(f"v.blk.{i}.{leaf}.weight", blob, raw_dtype=dt) + # attn_v (Q6_K, K=latent), ffn_down (Q6_K, K=mlp). + blob, dt = _q6k(latent, latent, seed) + seed += 1 + writer.add_tensor(f"v.blk.{i}.attn_v.weight", blob, raw_dtype=dt) + blob, dt = _q6k(latent, _MMPROJ_MLP, seed) + seed += 1 + writer.add_tensor(f"v.blk.{i}.ffn_down.weight", blob, raw_dtype=dt) + # Biases (F32) for each linear. + for leaf, n in ( + ("attn_q", latent), + ("attn_k", latent), + ("attn_v", latent), + ("attn_out", latent), + ("ffn_up", _MMPROJ_MLP), + ("ffn_down", latent), + ): + writer.add_tensor(f"v.blk.{i}.{leaf}.bias", _f32(n)) + # LayerNorms (weight + bias, F32). + for leaf in ("ln1", "ln2"): + writer.add_tensor(f"v.blk.{i}.{leaf}.weight", _f32(latent)) + writer.add_tensor(f"v.blk.{i}.{leaf}.bias", _f32(latent)) + + # Patch/pos embed (F32 here; real mmproj uses BF16 — the loader casts both + # float dtypes to bf16 identically). conv1_linear.weight is [latent, + # patch_dim] (out, in); the positional table is [pos_tokens, latent] (used + # by host grid_sample). The gguf writer + iter_gguf round-trip preserves the + # numpy shape, so pass the natural torch shapes directly. + if folded_patch_embedding: + writer.add_tensor("v.patch_embd.weight", _f32(latent, 3, 14, 14)) + else: + writer.add_tensor("v.patch_embd.weight", _f32(latent, _MMPROJ_PATCH_DIM)) + writer.add_tensor("v.position_embd.weight", _f32(_MMPROJ_POS_TOKENS, latent)) + writer.add_tensor("v.pre_ln.weight", _f32(latent)) + writer.add_tensor("v.pre_ln.bias", _f32(latent)) + writer.add_tensor("v.post_ln.weight", _f32(latent)) + writer.add_tensor("v.post_ln.bias", _f32(latent)) + + # Adapter + projection (Q4_K). _q4k writes (out, in); adapter_fc maps + # encoder_output_dim -> adapter_dim, so its weight is (adapter, enc_out). + blob, dt = _q4k(_MMPROJ_ADAPTER, _MMPROJ_ENC_OUT, seed) + seed += 1 + projector_names = ( + ("mm.0.weight", "mm.1.weight", "mm.2.weight") + if numeric_projector_names + else ( + "mm.adapter_fc.weight", + "mm.adapter_proj.weight", + "mm.vision_proj.weight", + ) + ) + writer.add_tensor(projector_names[0], blob, raw_dtype=dt) + blob, dt = _q4k(_MMPROJ_ADAPTER, _MMPROJ_ADAPTER, seed) + seed += 1 + writer.add_tensor(projector_names[1], blob, raw_dtype=dt) + blob, dt = _q4k(_MMPROJ_HIDDEN, _MMPROJ_ADAPTER, seed) + seed += 1 + writer.add_tensor(projector_names[2], blob, raw_dtype=dt) + + writer.write_header_to_file() + writer.write_kv_data_to_file() + writer.write_tensors_to_file() + writer.close() + + +@unittest.skipUnless(HAS_QUANT_DEPS, "torchao quantization dependencies not available") +class TestMmprojLoadingTest(unittest.TestCase): + """mmproj load packs vision weights at native bit-width; pos table returned.""" + + def setUp(self): + try: + import gguf # noqa: F401 + except ImportError: + self.skipTest("gguf package required") + + def _load(self): + from executorch.examples.models.muse_glimmer.loaders.checkpoint_loader import ( + load_mmproj_vision_model, + ) + + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "mmproj.gguf") + build_mmproj_gguf(path) + return load_mmproj_vision_model(path, config=_mmproj_vision_config()) + + def test_bit_widths_and_pos_table(self): + model, pos_table, cfg = self._load() + + # Q4_K attn/ffn_up/adapter -> INT4; Q6_K attn_v/ffn_down -> INT6. + blk0 = model.blocks[0] + self.assertIsInstance(blk0.attn.q_proj.weight.data, CudaCoalescedInt4Tensor) + self.assertIsInstance(blk0.attn.o_proj.weight.data, CudaCoalescedInt4Tensor) + self.assertIsInstance(blk0.attn.v_proj.weight.data, CudaDp4aPlanarInt6Tensor) + self.assertIsInstance(blk0.mlp.c_fc.weight.data, CudaCoalescedInt4Tensor) + self.assertIsInstance(blk0.mlp.c_proj.weight.data, CudaDp4aPlanarInt6Tensor) + self.assertIsInstance(model.vision_proj.weight.data, CudaCoalescedInt4Tensor) + + # Biases + norms are plain bf16 tensors. + self.assertEqual(blk0.attn.q_proj.bias.dtype, torch.bfloat16) + self.assertEqual(blk0.ln_1.weight.dtype, torch.bfloat16) + self.assertEqual(model.ln_pre.bias.dtype, torch.bfloat16) + + # conv1_linear (patch embed) is plain bf16. + self.assertEqual(model.conv1_linear.weight.dtype, torch.bfloat16) + + # Positional table returned separately at [pos_tokens, latent]. + self.assertEqual(tuple(pos_table.shape), (_MMPROJ_POS_TOKENS, _MMPROJ_LATENT)) + self.assertEqual(pos_table.dtype, torch.bfloat16) + + def test_no_meta_params_left(self): + model, _, _ = self._load() + for fqn, p in model.named_parameters(): + self.assertNotEqual(p.device.type, "meta", f"{fqn} left on meta device") + + def test_numeric_projector_names_load_on_cuda_and_mlx(self): + """The 30B numeric mmproj spelling is shared by both backends.""" + from executorch.examples.models.muse_glimmer.loaders.checkpoint_loader import ( + load_mmproj_vision_model, + ) + + for backend in ("cuda", "mlx"): + with self.subTest(backend=backend), tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "mmproj-numeric.gguf") + build_mmproj_gguf( + path, + numeric_projector_names=True, + folded_patch_embedding=True, + ) + model, pos_table, _ = load_mmproj_vision_model( + path, config=_mmproj_vision_config(), backend=backend + ) + self.assertEqual( + tuple(model.adapter_fc.weight.shape), + (_MMPROJ_ADAPTER, _MMPROJ_ENC_OUT), + ) + self.assertEqual( + tuple(model.adapter_proj.weight.shape), + (_MMPROJ_ADAPTER, _MMPROJ_ADAPTER), + ) + self.assertEqual( + tuple(model.vision_proj.weight.shape), + (_MMPROJ_HIDDEN, _MMPROJ_ADAPTER), + ) + self.assertEqual( + tuple(pos_table.shape), + (_MMPROJ_POS_TOKENS, _MMPROJ_LATENT), + ) + patch_weight = model.conv1_linear.weight.float() + folded_dim = 3 * 14 * 14 + self.assertTrue( + torch.equal( + patch_weight[:, :folded_dim], + torch.ones_like(patch_weight[:, :folded_dim]), + ) + ) + self.assertTrue( + torch.equal( + patch_weight[:, folded_dim:], + torch.zeros_like(patch_weight[:, folded_dim:]), + ) + ) + + +def build_muse_glimmer_gguf_bf16( + path: str, config: MuseGlimmerConfig = GGUF_CONFIG +) -> None: + """Write a tiny all-bf16 Muse Glimmer GGUF (``general.file_type`` MOSTLY_BF16). + + Every weight is BF16 and every norm F32, matching a non-quantized GGUF + (e.g. the muse_glimmer-provided reference). ``iter_gguf`` returns these as plain + tensors, so the loader must skip int4 packing — the fused ``qko_proj`` / + ``gate_up_proj`` groups are row-concatenated as bf16. Requires ``gguf``. + """ + import gguf + import numpy as np + + def bf16(n: int, seed: int): + g = torch.Generator().manual_seed(seed) + t = (torch.randn(n, config.dim, generator=g) * 0.02).to(torch.bfloat16) + # GGUFWriter expects the raw element buffer; view bf16 as uint16 so the + # 2-bytes-per-element layout is written verbatim (a float32 array would + # be misread as bf16 bytes). + return t.view(torch.int16).numpy().view(np.uint16), t + + def f32(*shape): + return torch.ones(shape, dtype=torch.float32).numpy() + + writer = gguf.GGUFWriter(path, "muse_glimmer") + writer.add_file_type(gguf.LlamaFileType.MOSTLY_BF16) + q_dim = config.n_heads * config.head_dim + kv_dim = config.n_kv_heads * config.head_dim + ffn = config.ffn_dim + seed = 0 + for i in range(config.n_layers): + for leaf, n in ( + ("attn_q", q_dim), + ("attn_k", kv_dim), + ("attn_output_gate", q_dim), + ("ffn_gate", ffn), + ("ffn_up", ffn), + ("attn_v", kv_dim), + ("ffn_down", config.dim), + ("attn_output", config.dim), + ): + blob, _ = bf16(n, seed) + seed += 1 + writer.add_tensor( + f"blk.{i}.{leaf}.weight", + blob, + raw_dtype=gguf.GGMLQuantizationType.BF16, + ) + writer.add_tensor(f"blk.{i}.attn_norm.weight", f32(config.dim)) + writer.add_tensor(f"blk.{i}.ffn_norm.weight", f32(config.dim)) + writer.add_tensor(f"blk.{i}.post_attention_norm.weight", f32(config.dim)) + writer.add_tensor(f"blk.{i}.post_ffw_norm.weight", f32(config.dim)) + writer.add_tensor(f"blk.{i}.attn_q_norm.weight", f32(config.head_dim)) + writer.add_tensor(f"blk.{i}.attn_k_norm.weight", f32(config.head_dim)) + + emb, _ = bf16(config.vocab_size, seed) + seed += 1 + writer.add_tensor( + "token_embd.weight", emb, raw_dtype=gguf.GGMLQuantizationType.BF16 + ) + out, _ = bf16(config.vocab_size, seed) + seed += 1 + writer.add_tensor("output.weight", out, raw_dtype=gguf.GGMLQuantizationType.BF16) + writer.add_tensor("output_norm.weight", f32(config.dim)) + + writer.write_header_to_file() + writer.write_kv_data_to_file() + writer.write_tensors_to_file() + writer.close() + + +@unittest.skipUnless(HAS_QUANT_DEPS, "torchao quantization dependencies not available") +class TestGgufBf16Test(unittest.TestCase): + """A MOSTLY_BF16 GGUF loads as plain bf16 (no int4 packing). + + The fused ``qko_proj`` / ``gate_up_proj`` groups arrive as plain bf16 + shards (``iter_gguf`` does not wrap bf16), so ``_flush_fused_group`` must + row-concatenate them as bf16 rather than raising or int4-packing. Packing + is CPU-safe; only kernel execution needs CUDA. + """ + + def setUp(self): + try: + import gguf # noqa: F401 + except ImportError: + self.skipTest("gguf package required") + + def _load(self): + from executorch.examples.models.muse_glimmer.loaders.checkpoint_loader import ( + load_gguf_model, + ) + + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "tiny_bf16.gguf") + build_muse_glimmer_gguf_bf16(path) + return load_gguf_model(path, backend="cuda", config=GGUF_CONFIG) + + def test_all_weights_plain_bf16(self): + """Every weight loads as a plain bf16 tensor (no torchao subclass).""" + model, _ = self._load() + q_dim = GGUF_CONFIG.n_heads * GGUF_CONFIG.head_dim + kv_dim = GGUF_CONFIG.n_kv_heads * GGUF_CONFIG.head_dim + og_dim = q_dim # use_attn_o_gate + + # Fused groups: plain bf16, concatenated to the model's [Q|K|OG] / + # [gate|up] row layout. + qko = model.layers[0].self_attn.qko_proj.weight.data + self.assertIs(type(qko), torch.Tensor) + self.assertEqual(qko.dtype, torch.bfloat16) + self.assertEqual(qko.shape, (q_dim + kv_dim + og_dim, GGUF_CONFIG.dim)) + + gate_up = model.layers[0].mlp.gate_up_proj.weight.data + self.assertIs(type(gate_up), torch.Tensor) + self.assertEqual(gate_up.dtype, torch.bfloat16) + self.assertEqual(gate_up.shape, (2 * GGUF_CONFIG.ffn_dim, GGUF_CONFIG.dim)) + + # Standalone + top-level weights: plain bf16, no subclass. + for w in ( + model.layers[0].self_attn.v_proj.weight.data, + model.layers[0].self_attn.o_proj.weight.data, + model.layers[0].mlp.down_proj.weight.data, + model.lm_head.weight.data, + model.embed_tokens.weight.data, + ): + self.assertIs(type(w), torch.Tensor) + self.assertEqual(w.dtype, torch.bfloat16) + + def test_forward_runs_on_cpu(self): + """A bf16-loaded model produces finite logits (plain nn.Linear path).""" + model, _ = self._load() + tokens = torch.tensor([[1, 2, 3, 4]], dtype=torch.long) + input_pos = torch.arange(4, dtype=torch.long) + with torch.no_grad(): + logits = model(tokens, input_pos) + self.assertEqual(logits.shape, (1, 4, GGUF_CONFIG.vocab_size)) + self.assertFalse(logits.isnan().any()) + self.assertFalse(logits.isinf().any()) + + +if __name__ == "__main__": + unittest.main() diff --git a/examples/models/muse-glimmer/tests/test_prompt_tokens.py b/examples/models/muse-glimmer/tests/test_prompt_tokens.py new file mode 100644 index 00000000000..c94c88a4735 --- /dev/null +++ b/examples/models/muse-glimmer/tests/test_prompt_tokens.py @@ -0,0 +1,365 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""Golden prompt-token tests, the invariance guard for the tokenizer refactor. + +Three tiers, each running only when its inputs are available: + +1. Structure. No assets. Asserts the prompt skeleton: BOS first, image span + shape, ordering. Always runs. +2. Real tokenizer. Needs ``MUSE_GLIMMER_HF_DIR`` pointing at a directory with + ``tokenizer.json``. Asserts token counts and a digest of the full id + sequence against tests/data/prompt_golden.json. +3. Runner. Runs a binary with ``--max_new_tokens 0`` and asserts the + ``Prompt tokens:`` line matches the golden count. Four combinations, each + gated on its own variables and skipped, never failed, when they are unset: + + solo text MUSE_GLIMMER_SOLO_RUNNER + MUSE_GLIMMER_SOLO_PTE + solo image ... + MUSE_GLIMMER_SOLO_VISION_PTE + dflash text MUSE_GLIMMER_DFLASH_RUNNER + MUSE_GLIMMER_DFLASH_PTE + dflash image ... + MUSE_GLIMMER_DFLASH_VISION_PTE + + All four also need ``MUSE_GLIMMER_HF_DIR``. The image combinations use + ``MUSE_GLIMMER_TEST_IMAGE`` when set and otherwise synthesize one, sizing the + expected patch count with ``vision.precompute.compute_grid_size``. A sibling + ``.ptd`` is passed as ``--data_path`` automatically, which CUDA exports need. + + Prompt assembly is duplicated per binary (solo.cpp:553, dflash.cpp:417) and + the image span has two independent validators (muse_glimmer_engine.cpp:716, + dflash_session.cpp:506), so one binary does not stand in for the other. + + Known gap: this tier compares counts, not ids. A same-length substitution, + say a wrong BOS id, passes here and is caught only by tier 2, which exercises + the Python tokenizer rather than the runner's. Closing it needs the runner to + be able to dump its prompt ids. Nothing here observes the EOS set either. + +Usage: + python dev/run.py unittest -v \ + executorch.examples.models.muse_glimmer.tests.test_prompt_tokens + + MUSE_GLIMMER_HF_DIR=assets/hf python dev/run.py unittest -v \ + executorch.examples.models.muse_glimmer.tests.test_prompt_tokens + +A skip still exits 0, so read the "Ran N tests" block, not the exit code. +""" + +import json +import os +import re +import subprocess +import tempfile +import unittest + +from executorch.examples.models.muse_glimmer.tests import prompt_cases as pc + +GOLDEN_PATH = os.path.join( + os.path.dirname(os.path.abspath(__file__)), "data", "prompt_golden.json" +) +PROMPT_TOKENS_RE = re.compile(r"^Prompt tokens:\s*(\d+)\s*$", re.MULTILINE) + + +def load_golden(): + with open(GOLDEN_PATH) as fh: + return json.load(fh) + + +class PromptStructure(unittest.TestCase): + """Tier 1: shape of the assembled prompt, no assets required.""" + + def ids(self, case): + return pc.build_prompt_ids(pc.stub_encode, case) + + def test_bos_is_first_and_appears_once(self): + for case in pc.CASES: + with self.subTest(case=case.name): + ids = self.ids(case) + self.assertEqual(ids[0], pc.BOS_ID) + self.assertEqual(ids.count(pc.BOS_ID), 1) + + def test_text_only_cases_have_no_image_tokens(self): + for case in (c for c in pc.CASES if not c.num_soft_tokens): + with self.subTest(case=case.name): + ids = self.ids(case) + for tok in (pc.IMAGE_START_ID, pc.IMAGE_END_ID, pc.PATCH_ID): + self.assertNotIn(tok, ids) + + def test_image_span_shape(self): + """Canonical contract: one bare patch run replacing ````.""" + for case in (c for c in pc.CASES if c.num_soft_tokens): + with self.subTest(case=case.name): + ids = self.ids(case) + n = case.num_soft_tokens + self.assertEqual(ids.count(pc.PATCH_ID), n) + for wrapper in (pc.IMAGE_START_ID, pc.IMAGE_END_ID): + self.assertNotIn(wrapper, ids) + + def test_image_span_replaces_marker_in_place(self): + case = next(c for c in pc.CASES if c.num_soft_tokens) + ids = self.ids(case) + before, after = case.prompt.split(pc.IMAGE_MARKER) + patch_start = 1 + len(pc.stub_encode(before)) + patch_end = patch_start + case.num_soft_tokens + self.assertEqual( + ids, + [pc.BOS_ID] + + pc.stub_encode(before) + + [pc.PATCH_ID] * case.num_soft_tokens + + pc.stub_encode(after), + ) + self.assertEqual( + ids[patch_start:patch_end], [pc.PATCH_ID] * case.num_soft_tokens + ) + + def test_image_costs_exactly_its_patches(self): + """No wrapper: an image costs its patch run and nothing else.""" + for with_image in (c for c in pc.CASES if c.num_soft_tokens): + with self.subTest(case=with_image.name): + text_only = pc.Case( + "bare", with_image.prompt.replace(pc.IMAGE_MARKER, "") + ) + self.assertEqual( + len(self.ids(with_image)) - len(self.ids(text_only)), + with_image.num_soft_tokens + pc.IMAGE_WRAPPER_TOKENS, + ) + + def test_case_names_are_unique(self): + names = [c.name for c in pc.CASES] + self.assertEqual(len(names), len(set(names))) + + +class RealTokenizerGolden(unittest.TestCase): + """Tier 2: exact ids against the committed golden.""" + + @classmethod + def setUpClass(cls): + cls.dir = pc.hf_dir() + if cls.dir is None: + raise unittest.SkipTest(f"{pc.HF_DIR_ENV} unset or has no tokenizer.json") + cls.encode = staticmethod(pc.real_encoder(cls.dir)) + cls.golden = load_golden() + + def test_tokenizer_matches_the_one_the_golden_was_built_from(self): + actual = pc.file_sha256(os.path.join(self.dir, "tokenizer.json")) + self.assertEqual( + actual, + self.golden["tokenizer_sha256"], + "tokenizer.json differs from the one used to generate the golden; " + "regenerate with tests/gen_prompt_golden.py and explain the diff", + ) + + def test_every_case_is_covered(self): + self.assertEqual(sorted(self.golden["cases"]), sorted(c.name for c in pc.CASES)) + + def test_token_counts_and_ids_match_golden(self): + for case in pc.CASES: + with self.subTest(case=case.name): + want = self.golden["cases"][case.name] + ids = pc.build_prompt_ids(self.encode, case) + self.assertEqual(len(ids), want["num_tokens"]) + self.assertEqual(pc.special_runs(ids), want["special_runs"]) + self.assertEqual(pc.ids_sha256(ids), want["ids_sha256"]) + + def test_harmony_pieces_resolve_to_the_documented_ids(self): + """Guards against a tokenizer that silently BPEs the control tokens.""" + expected = { + "<|begin_of_text|>": 200000, + "<|end_of_text|>": 200001, + "<|eom|>": 200007, + "<|eot|>": 200008, + "<|start|>": 200022, + "<|message|>": 200023, + "<|image_start|>": 200080, + "<|image_end|>": 200081, + "<|patch|>": 200092, + } + for piece, want in expected.items(): + with self.subTest(piece=piece): + self.assertEqual(self.encode(piece), [want]) + + def test_end_token_is_not_in_the_vocabulary(self): + """<|end|> looks plausible and is not real; it BPEs into ordinary text.""" + self.assertGreater(len(self.encode("<|end|>")), 1) + + def readme_text(self): + readme = os.path.join( + os.path.dirname(os.path.abspath(__file__)), "..", "README.md" + ) + with open(readme) as fh: + return fh.read() + + def test_every_control_token_in_the_readme_is_real(self): + """A doc example using a non-existent token is wrong but not rejected.""" + pieces = set(re.findall(r"<\|[a-z0-9_]+\|>", self.readme_text())) + pieces.discard("<|end|>") # covered by the test below, which is stricter + self.assertTrue(pieces, "no control tokens found; did the README move?") + for piece in sorted(pieces): + with self.subTest(piece=piece): + self.assertEqual( + len(self.encode(piece)), + 1, + f"{piece} is not a single token; it will encode as text", + ) + + def test_end_appears_only_in_the_sentence_denying_it_exists(self): + """Blanket-excluding <|end|> would let an example reintroduce it unseen. + + Pin the one legitimate mention instead, so a second occurrence anywhere, + prose or example, fails. + """ + text = self.readme_text() + occurrences = [m.start() for m in re.finditer(re.escape("<|end|>"), text)] + self.assertEqual( + len(occurrences), + 1, + f"<|end|> is not a real token; expected exactly one mention " + f"explaining that, found {len(occurrences)}", + ) + self.assertIn( + "There is no\n`<|end|>` token", + text, + "the single <|end|> is no longer the sentence denying it exists", + ) + + +class RunnerPromptCount(unittest.TestCase): + """Tier 3: the C++ path, checked through the printed prompt-token count.""" + + RUNNER_TIMEOUT_S = 900 + SYNTHETIC_IMAGE_SIZE = (224, 224) + + def target(self, runner_env, pte_env): + """Resolve one runner/model pair, or skip listing precisely what is absent.""" + reasons = [] + directory = pc.hf_dir() + if directory is None: + reasons.append(f"{pc.HF_DIR_ENV} unset or has no tokenizer.json") + resolved = {} + for env in (runner_env, pte_env): + value = os.environ.get(env) + if not value: + reasons.append(f"{env} unset") + elif not os.path.isfile(os.path.expanduser(value)): + reasons.append(f"{env}={value} not found") + else: + resolved[env] = os.path.expanduser(value) + if reasons: + self.skipTest("; ".join(reasons)) + return resolved[runner_env], resolved[pte_env], directory + + @staticmethod + def data_path_for(pte): + """CUDA exports put delegate weights in a sibling .ptd the runner needs.""" + directory = os.path.dirname(pte) or "." + ptds = sorted(f for f in os.listdir(directory) if f.endswith(".ptd")) + return os.path.join(directory, ptds[0]) if len(ptds) == 1 else None + + def prompt_tokens(self, runner, pte, directory, prompt, image=None): + cmd = [ + runner, + "--model_path", + pte, + "--tokenizer_path", + os.path.join(directory, "tokenizer.json"), + "--prompt", + prompt, + # Not 0: dflash_runner rejects a non-positive value in validate_flags + # and exits before tokenizing, and it prints the count only after the + # decode loop. One token also means prefill really runs, so the image + # span validators are exercised rather than skipped. + "--max_new_tokens", + "1", + ] + data_path = self.data_path_for(pte) + if data_path: + cmd += ["--data_path", data_path] + if image: + cmd += ["--image_path", image] + proc = subprocess.run( + cmd, capture_output=True, text=True, timeout=self.RUNNER_TIMEOUT_S + ) + context = ( + f"{os.path.basename(runner)} exit={proc.returncode}\n" + f"cmd: {' '.join(cmd)}\n" + f"stdout tail:\n{proc.stdout[-2000:]}\nstderr tail:\n{proc.stderr[-2000:]}" + ) + # solo_runner prints the count before prefill, so a later failure would + # otherwise be read as a pass. + self.assertEqual(proc.returncode, 0, f"runner failed.\n{context}") + match = PROMPT_TOKENS_RE.search(proc.stdout) + self.assertIsNotNone(match, f"no 'Prompt tokens:' line.\n{context}") + return int(match.group(1)) + + def image_and_patch_count(self): + """Path to an image plus the soft-token count the vision encoder will emit.""" + try: + from PIL import Image + except ImportError: + self.skipTest("Pillow not installed") + from executorch.examples.models.muse_glimmer.vision.precompute import ( + compute_grid_size, + ) + + supplied = os.environ.get("MUSE_GLIMMER_TEST_IMAGE") + if supplied: + path = os.path.expanduser(supplied) + if not os.path.isfile(path): + self.skipTest(f"MUSE_GLIMMER_TEST_IMAGE={supplied} not found") + with Image.open(path) as img: + width, height = img.size + else: + width, height = self.SYNTHETIC_IMAGE_SIZE + handle, path = tempfile.mkstemp(suffix=".png") + os.close(handle) + self.addCleanup(os.unlink, path) + Image.new("RGB", (width, height), (127, 127, 127)).save(path) + return path, compute_grid_size(width, height)[2] + + def check_text_cases(self, runner_env, pte_env): + runner, pte, directory = self.target(runner_env, pte_env) + golden = load_golden() + for case in (c for c in pc.CASES if not c.num_soft_tokens): + with self.subTest(case=case.name): + self.assertEqual( + self.prompt_tokens(runner, pte, directory, case.prompt), + golden["cases"][case.name]["num_tokens"], + ) + + def check_image_case(self, runner_env, pte_env): + runner, pte, directory = self.target(runner_env, pte_env) + golden = load_golden() + case = next(c for c in pc.CASES if c.num_soft_tokens) + image, num_soft_tokens = self.image_and_patch_count() + expected = ( + pc.text_only_len(golden["cases"][case.name], case) + + num_soft_tokens + + pc.IMAGE_WRAPPER_TOKENS + ) + self.assertEqual( + self.prompt_tokens(runner, pte, directory, case.prompt, image=image), + expected, + f"expected text({pc.text_only_len(golden['cases'][case.name], case)}) " + f"+ patches({num_soft_tokens}) + wrapper({pc.IMAGE_WRAPPER_TOKENS})", + ) + + def test_solo_text(self): + self.check_text_cases("MUSE_GLIMMER_SOLO_RUNNER", "MUSE_GLIMMER_SOLO_PTE") + + def test_solo_image(self): + self.check_image_case( + "MUSE_GLIMMER_SOLO_RUNNER", "MUSE_GLIMMER_SOLO_VISION_PTE" + ) + + def test_dflash_text(self): + self.check_text_cases("MUSE_GLIMMER_DFLASH_RUNNER", "MUSE_GLIMMER_DFLASH_PTE") + + def test_dflash_image(self): + self.check_image_case( + "MUSE_GLIMMER_DFLASH_RUNNER", "MUSE_GLIMMER_DFLASH_VISION_PTE" + ) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/examples/models/muse-glimmer/tests/test_serve.py b/examples/models/muse-glimmer/tests/test_serve.py new file mode 100644 index 00000000000..b7bb62913a1 --- /dev/null +++ b/examples/models/muse-glimmer/tests/test_serve.py @@ -0,0 +1,575 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""Hermetic tests for the Muse Glimmer OpenAI serving launcher.""" + +import asyncio +import base64 +import pathlib +from types import SimpleNamespace + +import pytest + +from executorch.examples.llm_server.python import chat_template +from executorch.examples.llm_server.python.errors import APIError +from executorch.examples.llm_server.python.protocol import ChatCompletionRequest +from executorch.examples.llm_server.python.session_runtime import PromptInput +from executorch.examples.models.muse_glimmer.serving import serve + +_HERE = pathlib.Path(serve.__file__).resolve().parent +_LLM_SERVER_PYTHON = pathlib.Path(chat_template.__file__).resolve().parent + + +def test_generic_server_does_not_reference_muse_glimmer(): + # The generic control plane must stay model-agnostic. Model-specific + # tool-call parsers legitimately live in the tool_parsers/ package + # (gemma.py, qwen.py, hermes.py, muse_glimmer.py) with matching tests/ -- the same + # established pattern as the other models -- so those are NOT part of the + # generic plumbing and are intentionally excluded here. This asserts the + # shared plumbing files themselves carry no muse_glimmer coupling. + plumbing = _LLM_SERVER_PYTHON + generic_files = [ + plumbing / "server.py", + plumbing / "serving_chat.py", + plumbing / "chat_template.py", + plumbing / "session_runtime.py", + plumbing / "worker_client.py", + plumbing / "protocol.py", + plumbing / "errors.py", + plumbing / "openai_transcript.py", + ] + offenders = [] + for p in generic_files: + text = p.read_text() + if "muse_glimmer" in text.lower() or "MuseGlimmerEngine" in text: + offenders.append(p) + assert ( + offenders == [] + ), f"generic server must not reference Muse Glimmer: {offenders}" + + +def test_control_plane_runs_no_model_code(): + serve_src = (_HERE / "serve.py").read_text() + assert "MuseGlimmerEngine" not in serve_src + worker_src = ( + _HERE.parent / "runtime" / "runners" / "muse_glimmer_worker.cpp" + ).read_text() + assert "MuseGlimmerEngine" in worker_src + + +def test_python_worker_and_pybind_are_absent(): + assert not (_HERE / "worker.py").exists() + assert not (_HERE / "muse_glimmer_pybindings.cpp").exists() + + +def test_spawn_builds_worker_command(monkeypatch): + captured = {} + + def fake_spawn(cmd, env=None): + captured["cmd"] = cmd + captured["env"] = env + return object() + + monkeypatch.setattr(serve, "spawn_worker", fake_spawn) + serve._spawn( + SimpleNamespace( + worker_bin="/bin/muse_glimmer_worker", + model_path="m.pte", + tokenizer_path="t.json", + data_path="d.ptd", + pos_embed_path=None, + max_image_bytes=1024, + max_sessions=4, + warm_resume=True, + bos_id=200000, + eos_id=200001, + artifact_mode="auto", + dflash_block_length=4, + dflash_n_draft=3, + dflash_draft_argmax=True, + cuda_graph=True, + ) + ) + assert captured["cmd"] == [ + "/bin/muse_glimmer_worker", + "--model_path", + "m.pte", + "--tokenizer_path", + "t.json", + "--max_sessions", + "4", + "--warm_resume=true", + "--bos_id", + "200000", + "--eos_id", + "200001", + "--artifact_mode", + "auto", + "--dflash_block_length", + "4", + "--dflash_n_draft", + "3", + "--dflash_draft_argmax=true", + "--cuda_graph=true", + "--data_path", + "d.ptd", + "--max_image_bytes", + "1024", + ] + + +def test_spawn_forwards_explicit_dflash_and_vision_options(monkeypatch): + captured = {} + monkeypatch.setattr( + serve, "spawn_worker", lambda cmd, env=None: captured.update(cmd=cmd) + ) + serve._spawn( + SimpleNamespace( + worker_bin="/bin/muse_glimmer_worker", + model_path="m.pte", + tokenizer_path="t.json", + data_path=None, + pos_embed_path="pos.bin", + max_image_bytes=2048, + max_sessions=1, + warm_resume=True, + bos_id=200000, + eos_id=200001, + artifact_mode="dflash", + dflash_block_length=4, + dflash_n_draft=3, + dflash_draft_argmax=False, + cuda_graph=False, + ) + ) + + assert captured["cmd"][-12:] == [ + "--artifact_mode", + "dflash", + "--dflash_block_length", + "4", + "--dflash_n_draft", + "3", + "--dflash_draft_argmax=false", + "--cuda_graph=false", + "--max_image_bytes", + "2048", + "--pos_embed_path", + "pos.bin", + ] + + +def test_spawn_defaults_worker_bin_and_omits_empty_data_path(monkeypatch): + captured = {} + monkeypatch.setattr( + serve, "spawn_worker", lambda cmd, env=None: captured.update(cmd=cmd) + ) + monkeypatch.setattr( + serve, "_default_worker_bin", lambda: "/bin/muse_glimmer_worker" + ) + serve._spawn( + SimpleNamespace( + worker_bin=None, + model_path="m.pte", + tokenizer_path="t.json", + data_path=None, + pos_embed_path=None, + max_image_bytes=serve._DEFAULT_MAX_IMAGE_BYTES, + max_sessions=1, + warm_resume=False, + bos_id=200000, + eos_id=200001, + artifact_mode="auto", + dflash_block_length=4, + dflash_n_draft=3, + dflash_draft_argmax=True, + cuda_graph=True, + ) + ) + cmd = captured["cmd"] + assert cmd[0].endswith("muse_glimmer_worker") + assert "--data_path" not in cmd + assert "--max_image_bytes" in cmd + assert "--warm_resume=false" in cmd + + +def test_build_app_uses_muse_glimmer_options(monkeypatch): + assert issubclass(serve.MuseGlimmerServingChat, serve.ServingChat) + captured = {} + + class _FakeTemplate: + def __init__(self, *args, **kwargs): + captured["template_kwargs"] = kwargs + + class _FakeRuntime: + def close_worker(self): + pass + + class _FakeApp: + def on_event(self, event): + captured["event"] = event + return lambda fn: fn + + monkeypatch.setattr(serve, "ChatTemplate", _FakeTemplate) + monkeypatch.setattr(serve, "_spawn", lambda args: object()) + monkeypatch.setattr(serve, "SessionRuntime", lambda worker: _FakeRuntime()) + + def fake_serving(*args, **kwargs): + captured["serving_kwargs"] = kwargs + return object() + + monkeypatch.setattr(serve, "MuseGlimmerServingChat", fake_serving) + monkeypatch.setattr(serve, "build_app", lambda serving, model_id: _FakeApp()) + serve.build_app_from_args( + SimpleNamespace( + hf_tokenizer="hf", + model_id="muse_glimmer", + max_context=10, + max_image_bytes=1234, + tool_parser="none", + ) + ) + + assert captured["template_kwargs"] == { + "assistant_header": "<|start|>assistant", + "strip_rendered_bos": True, + "append_generation_prompt_after_tool_response": True, + } + assert captured["serving_kwargs"]["tool_detector_cls"] is None + assert captured["serving_kwargs"]["max_image_bytes"] == 1234 + assert captured["serving_kwargs"]["prompt_token_offset"] == 1 + assert ( + captured["serving_kwargs"]["content_filter"] is serve._strip_muse_glimmer_header + ) + assert ( + captured["serving_kwargs"]["reasoning_extractor"] + is serve._extract_muse_glimmer_reasoning + ) + assert ( + captured["serving_kwargs"]["content_filter_specials"] + == serve._MUSE_GLIMMER_HEADER_SPECIALS + ) + assert captured["event"] == "shutdown" + + +def _image_request(url, *, parts=None): + content = parts or [ + {"type": "text", "text": "before"}, + {"type": "image_url", "image_url": {"url": url}}, + {"type": "text", "text": "after"}, + ] + return ChatCompletionRequest( + model="muse_glimmer", messages=[{"role": "user", "content": content}] + ) + + +@pytest.mark.parametrize( + "mime_type,payload", + [("image/jpeg", b"jpeg-bytes"), ("image/png", b"png-bytes")], +) +def test_normalize_image_request_preserves_text_and_original(mime_type, payload): + data = base64.b64encode(payload).decode("ascii") + request = _image_request(f"data:{mime_type};base64,{data}") + original = request.model_dump() + + normalized, image = serve._normalize_image_request(request, len(payload)) + + assert image == { + "image": {"encoding": "base64", "mime_type": mime_type, "data": data} + } + assert normalized.messages[0].content == (f"before{serve._IMAGE_PLACEHOLDER}after") + assert request.model_dump() == original + + +@pytest.mark.parametrize( + "url", + [ + "https://example.com/image.jpg", # @lint-ignore + "/tmp/image.jpg", + "data:image/gif;base64,Z2lm", + "data:image/jpg;base64,anBn", + "data:image/png;utf8,png", + "data:image/png;base64,", + "data:image/png;base64,***", + "data:image/png;base64,QQ=", + ], +) +def test_normalize_image_request_rejects_invalid_urls(url): + with pytest.raises(APIError) as error: + serve._normalize_image_request(_image_request(url), 1024) + + assert error.value.status == 400 + assert error.value.err_type == "invalid_request_error" + assert error.value.code == "invalid_image" + + +@pytest.mark.parametrize( + "part", + [ + {"type": "image_url"}, + {"type": "image_url", "image_url": "data:image/png;base64,eA=="}, + {"type": "image_url", "image_url": {}}, + { + "type": "image_url", + "image_url": {"url": "data:image/png;base64,eA==", "detail": "auto"}, + }, + {"type": "text", "image_url": {"url": "data:image/png;base64,eA=="}}, + ], +) +def test_normalize_image_request_rejects_bad_schema(part): + with pytest.raises(APIError) as error: + serve._normalize_image_request(_image_request("unused", parts=[part]), 1024) + + assert error.value.status == 400 + assert error.value.err_type == "invalid_request_error" + assert error.value.code == "invalid_image" + + +def test_normalize_image_request_rejects_oversize_image(): + data = base64.b64encode(b"too large").decode("ascii") + with pytest.raises(APIError) as error: + serve._normalize_image_request( + _image_request(f"data:image/jpeg;base64,{data}"), 3 + ) + + assert error.value.code == "invalid_image" + assert "3-byte limit" in error.value.message + + +def test_normalize_image_request_rejects_multiple_images(): + data = base64.b64encode(b"image").decode("ascii") + image = { + "type": "image_url", + "image_url": {"url": f"data:image/png;base64,{data}"}, + } + request = _image_request( + "unused", parts=[image, {"type": "text", "text": "middle"}, image] + ) + + with pytest.raises(APIError) as error: + serve._normalize_image_request(request, 1024) + + assert error.value.code == "invalid_image" + assert "Only one" in error.value.message + + +class _ImageTemplate: + def __init__(self): + self.rendered_messages = None + + def turn_stop_sequences(self): + return [] + + def special_tokens(self): + return [] + + def assistant_header(self): + return "<|start|>assistant" + + def render(self, messages, *, tools, template_kwargs): + self.rendered_messages = messages + if any(not isinstance(message.content, str) for message in messages): + raise TypeError("template requires string content") + return f"<|start|>user<|message|>{messages[0].content}<|eot|>" + + def generation_preamble(self, template_kwargs, *, tools): + return "" + + def count_tokens(self, text): + return len(text.split()) + + +class _ImageRuntime: + def __init__(self): + self.prompt = None + + async def generate_stream(self, session_id, prompt, options, stats): + self.prompt = prompt + stats.prompt_tokens = 2 + stats.completion_tokens = 1 + yield "answer" + + +def test_muse_glimmer_serving_injects_image_segment_into_runtime(): + template = _ImageTemplate() + runtime = _ImageRuntime() + serving = serve.MuseGlimmerServingChat( + runtime, template, "muse_glimmer", max_image_bytes=1024 + ) + data = base64.b64encode(b"png").decode("ascii") + request = _image_request(f"data:image/png;base64,{data}") + + response = asyncio.run(serving.create(request)) + + assert response.choices[0].message.content == "answer" + assert runtime.prompt == PromptInput( + segments=[ + {"text": "<|start|>user<|message|>before"}, + { + "image": { + "encoding": "base64", + "mime_type": "image/png", + "data": data, + } + }, + {"text": "after<|eot|>"}, + ] + ) + assert template.rendered_messages[0].content == ( + f"before{serve._IMAGE_PLACEHOLDER}after" + ) + assert len(request.messages[0].content) == 3 + + +def test_muse_glimmer_prompt_count_ignores_image_segment(): + serving = serve.MuseGlimmerServingChat(object(), _ImageTemplate(), "muse_glimmer") + prompt = PromptInput( + segments=[ + {"image": {"encoding": "base64", "mime_type": "image/png", "data": "eA=="}}, + {"text": "two tokens"}, + {"ids": [1, 2, 3]}, + ] + ) + + assert serving._count_prompt_tokens(prompt) == 5 + + +def test_strip_muse_glimmer_header_returns_visible_answer(): + # The model self-emits " to=user<|message|>ANSWER" ahead of the visible text + # because the generation prompt ends at "<|start|>assistant". + assert serve._strip_muse_glimmer_header(" to=user<|message|>Paris.") == "Paris." + + +def test_strip_muse_glimmer_header_strips_tool_recipient(): + text = ' to=functions.get_weather<|message|>{"city": "Paris"}' + assert serve._strip_muse_glimmer_header(text) == '{"city": "Paris"}' + + +def test_strip_muse_glimmer_header_passthrough_plain_text(): + assert ( + serve._strip_muse_glimmer_header("The capital of France is Paris.") + == "The capital of France is Paris." + ) + + +def test_strip_muse_glimmer_header_removes_message_terminators(): + assert serve._strip_muse_glimmer_header("Test complete.<|eom|>") == "Test complete." + assert serve._strip_muse_glimmer_header("Final answer.<|eot|>") == "Final answer." + + +def test_strip_muse_glimmer_header_strips_constrain_field(): + text = ' to=functions.get_weather constrain=json<|message|>{"city": "Paris"}' + assert serve._strip_muse_glimmer_header(text) == '{"city": "Paris"}' + + +def test_extract_muse_glimmer_reasoning_preserves_final_answer(): + text = ( + " to=self<|message|>We should calculate first.<|eom|>" + "<|start|>assistant to=user<|message|>The answer is 42.<|eot|>" + ) + reasoning, visible = serve._extract_muse_glimmer_reasoning(text) + assert reasoning == "We should calculate first." + assert visible == "The answer is 42." + + +def test_extract_muse_glimmer_reasoning_handles_multiple_private_messages(): + text = ( + "to=self<|message|>First step.<|eom|>" + "<|start|>assistant to=self<|message|>Second step.<|eom|>" + "<|start|>assistant to=user<|message|>Done.<|eot|>" + ) + reasoning, visible = serve._extract_muse_glimmer_reasoning(text) + assert reasoning == "First step.\n\nSecond step." + assert visible == "Done." + + +def test_extract_muse_glimmer_reasoning_plain_text_fallback(): + text = "The capital of France is Paris." + assert serve._extract_muse_glimmer_reasoning(text) == (None, text) + + +def test_self_reasoning_then_tool_call_content_clean_calls_unchanged(): + # End-to-end of the parser -> content_filter path: a to=self reasoning message + # precedes an ATEM tool call. The reasoning body is surfaced as content with NO + # leaked "to=self<|message|>" prefix, and the tool call is still extracted. + from executorch.examples.models.muse_glimmer.serving.tool_parsers import ( + AtemToolCallDetector, + ) + + block = ( + '\n\n' + 'Paris\n' + "\n" + ) + text = ( + " to=self<|message|>We should check the weather.<|eom|>" + "<|start|>assistant to=get_weather<|message|>" + block + "<|eom|>" + ) + tools = {"get_weather": {"properties": {"city": {"type": "string"}}}} + parsed = AtemToolCallDetector().detect_and_parse(text, tools) + # tool_calls extraction is unchanged: the get_weather call is still parsed. + assert [c.name for c in parsed.calls] == ["get_weather"] + reasoning, visible = serve._extract_muse_glimmer_reasoning(parsed.normal_text) + assert reasoning == "We should check the weather." + assert visible == "" + + +def test_extract_muse_glimmer_reasoning_preserves_visible_prefix(): + text = ( + "Visible prefix.\n" + "to=self<|message|>Private step.<|eom|>" + "<|start|>assistant to=user<|message|>Visible final.<|eot|>" + ) + reasoning, visible = serve._extract_muse_glimmer_reasoning(text) + assert reasoning == "Private step." + assert visible == "Visible prefix.\n\nVisible final." + + +def test_strip_muse_glimmer_header_preserves_prose_lookalikes(): + # Negative cases: real prose tokens that merely CONTAIN "to=" as a substring + # (goto=, auto=, photo=) must NOT be stripped -- only a genuine harmony header + # (start-of-string / whitespace / ">"-introduced "to=<|message|>"). + text = "Use goto=label; set auto=true; field photo=front." + assert serve._strip_muse_glimmer_header(text) == text + + +def test_tool_parser_atem_returns_detector(): + from executorch.examples.models.muse_glimmer.serving.tool_parsers import ( + AtemToolCallDetector, + ) + + assert serve._tool_detector("atem") is AtemToolCallDetector + + +def test_tool_parser_none_returns_none(): + assert serve._tool_detector("none") is None + + +def test_tool_parser_unknown_raises(): + with pytest.raises(ValueError): + serve._tool_detector("nonexistent") + + +def test_rejects_multiple_runners(monkeypatch): + import sys + + monkeypatch.setattr( + sys, + "argv", + [ + "serve.py", + "--model-path", + "m.pte", + "--tokenizer-path", + "t.json", + "--hf-tokenizer", + "hf", + "--num-runners", + "2", + ], + ) + with pytest.raises(SystemExit): + serve.main() diff --git a/examples/models/muse-glimmer/tests/test_vision_precompute.py b/examples/models/muse-glimmer/tests/test_vision_precompute.py new file mode 100644 index 00000000000..d4c171a7f38 --- /dev/null +++ b/examples/models/muse-glimmer/tests/test_vision_precompute.py @@ -0,0 +1,272 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""Unit tests for the Muse Glimmer vision host-precompute (vision_precompute.py). + +Verifies the host-side precomputed tensors (patchify, positional-embedding +interpolation, 2D-RoPE, sparse permutation, block-diagonal masks, pixel-shuffle +permutation) match the eager ``OnyxVisionEncoder`` math. Runs on CPU. +""" + +import unittest + +import torch +from executorch.examples.models.muse_glimmer.vision.precompute import ( + compute_grid_size, + interpolate_pos_emb, + make_2d_rope, + MuseGlimmerVisionConfig, + patchify_image, + pixel_shuffle_perm, + precompute_vision_inputs, + sparse_perm_and_slens, +) + + +def _small_config() -> MuseGlimmerVisionConfig: + # Real vision hyperparams; only the token count varies with image size. + return MuseGlimmerVisionConfig() + + +class PatchifyTest(unittest.TestCase): + def test_shapes_and_grid(self): + cfg = _small_config() + # 28-px cell (patch 14 * downsample 2); use a 4x4-cell image (112px). + h = w = cfg.patch_size * 4 # 56 -> grid 4x4 + image = torch.randn(3, h, w) + patches, grid_h, grid_w = patchify_image(image, cfg) + self.assertEqual((grid_h, grid_w), (4, 4)) + self.assertEqual(patches.shape, (1, 16, cfg.patch_dim)) + self.assertEqual(patches.dtype, torch.float32) + + def test_temporal_replication(self): + """The 2 temporal copies of an image are identical per patch.""" + cfg = _small_config() + image = torch.randn(3, cfg.patch_size, cfg.patch_size) # 1 patch + patches, _, _ = patchify_image(image, cfg) + row = patches[0, 0] # [patch_dim = pt*3*ps*ps] + half = row.numel() // cfg.patch_temporal + self.assertTrue(torch.equal(row[:half], row[half:])) + + +class PosEmbInterpTest(unittest.TestCase): + def test_identity_grid_matches_table(self): + """Interpolating to the native 32x32 grid ~ returns the table itself.""" + cfg = _small_config() + gh, gw = cfg.pos_emb_grid_h, cfg.pos_emb_grid_w + table = torch.randn(gh * gw, cfg.latent_dim, dtype=torch.bfloat16) + pos = interpolate_pos_emb(table, gh, gw, cfg) + self.assertEqual(pos.shape, (1, gh * gw, cfg.latent_dim)) + self.assertEqual(pos.dtype, torch.bfloat16) + + def test_downscaled_shape(self): + cfg = _small_config() + table = torch.randn( + cfg.pos_emb_grid_h * cfg.pos_emb_grid_w, + cfg.latent_dim, + dtype=torch.bfloat16, + ) + pos = interpolate_pos_emb(table, 8, 8, cfg) + self.assertEqual(pos.shape, (1, 64, cfg.latent_dim)) + + +class Rope2DTest(unittest.TestCase): + def test_shape_and_range(self): + cfg = _small_config() + cos, sin = make_2d_rope(6, 6, cfg) + self.assertEqual(cos.shape, (36, cfg.head_dim // 2)) + self.assertEqual(sin.shape, (36, cfg.head_dim // 2)) + self.assertTrue((cos.abs() <= 1.0 + 1e-6).all()) + self.assertTrue((sin.abs() <= 1.0 + 1e-6).all()) + + def test_matches_eager_complex_form(self): + """Real (cos,sin) reproduce the eager complex freqs_cis element-wise.""" + cfg = _small_config() + grid_h = grid_w = 5 + cos, sin = make_2d_rope(grid_h, grid_w, cfg) + + # Eager reference (OnyxVisionEncoder._make_2d_rope), inline. + head_dim = cfg.head_dim + half_dim = head_dim // 2 + quarter = half_dim // 2 + theta = cfg.rope_theta + inv_freq = 1.0 / ( + theta + ** (torch.arange(0, half_dim, 2, dtype=torch.float32)[:quarter] / half_dim) + ) + idx_h = torch.arange(1, grid_h + 1, dtype=torch.float32) + idx_w = torch.arange(1, grid_w + 1, dtype=torch.float32) + idx_ij_h = idx_h.unsqueeze(1).expand(-1, grid_w).reshape(-1) + idx_ij_w = idx_w.unsqueeze(0).expand(grid_h, -1).reshape(-1) + freq_h = torch.outer(idx_ij_h, inv_freq) + freq_w = torch.outer(idx_ij_w, inv_freq) + freq = torch.cat([freq_w, freq_h], dim=-1) + freqs_cis = torch.view_as_complex( + torch.stack([torch.cos(freq), torch.sin(freq)], dim=-1) + ) + torch.testing.assert_close(cos, freqs_cis.real, atol=1e-6, rtol=1e-6) + torch.testing.assert_close(sin, freqs_cis.imag, atol=1e-6, rtol=1e-6) + + +class SparsePermTest(unittest.TestCase): + def test_identity_when_grid_fits_one_tile(self): + """A grid <= 32x32 fits in one window: perm is identity, one group.""" + cfg = _small_config() + perm, slens = sparse_perm_and_slens(8, 8, cfg) + self.assertTrue(torch.equal(perm, torch.arange(64))) + self.assertEqual(slens, [64]) + + def test_multi_tile_partition(self): + """A 64x64 grid tiles into four 32x32 blocks of 1024 tokens each.""" + cfg = _small_config() + grid = 2 * cfg.pos_emb_grid_h # 64 + perm, slens = sparse_perm_and_slens(grid, grid, cfg) + self.assertEqual(slens, [1024, 1024, 1024, 1024]) + # A valid permutation of all tokens. + self.assertEqual(sorted(perm.tolist()), list(range(grid * grid))) + + def test_inv_perm_roundtrip(self): + cfg = _small_config() + perm, _ = sparse_perm_and_slens(40, 48, cfg) + n = perm.numel() + inv = torch.empty_like(perm) + inv[perm] = torch.arange(n, dtype=perm.dtype) + x = torch.randn(n, 3) + torch.testing.assert_close(x[perm][inv], x) + + +class PixelShufflePermTest(unittest.TestCase): + def test_matches_eager(self): + cfg = _small_config() + grid_h, grid_w, f = 6, 8, cfg.downsample_factor + perm = pixel_shuffle_perm(grid_h, grid_w, cfg) + ds = torch.arange(grid_h * grid_w).view(grid_h // f, f, grid_w // f, f) + ds = ds.permute(0, 2, 1, 3).reshape(-1) + self.assertTrue(torch.equal(perm, ds.to(torch.int64))) + + +class GridSizeTest(unittest.TestCase): + def test_divisible_by_cell(self): + cfg = _small_config() + cell = cfg.patch_size * cfg.downsample_factor + for w, h in [(640, 480), (100, 800), (1024, 1024)]: + th, tw, n = compute_grid_size(w, h, cfg) + self.assertEqual(th % cell, 0) + self.assertEqual(tw % cell, 0) + self.assertEqual(n, (th // cell) * (tw // cell)) + self.assertLessEqual(n, 4096) + + +# Grids this function is expected to produce, mirrored verbatim by +# tests/vision_grid_parity_test.cpp so the runner and the tokenizer agree. +# +# Many are exact cost ties that ``min`` breaks by CPython set-iteration order, +# which follows no rule: 1440x1440 resolves to the larger grid and 225x225 to +# the smaller one (both from P2447507824). That order is stable -- it ignores +# PYTHONHASHSEED and has not changed since CPython 3.8 -- but it is not a +# guarantee CPython makes. If a future runtime reorders it, THIS test is what +# fails, and the C++ table has to be regenerated to match. +_REFERENCE_GRIDS = [ + # (img_w, img_h, nph, npw) + (1440, 1440, 52, 52), + (225, 225, 8, 8), + (512, 512, 19, 19), + (1024, 1024, 37, 37), + (200, 203, 8, 8), + (24, 60, 3, 1), + (700, 700, 25, 25), + (336, 336, 12, 12), + (1000, 2500, 90, 36), + (6000, 6000, 64, 64), + (1, 1, 1, 1), + (27, 27, 1, 1), + (28, 28, 1, 1), + (1, 10000, 358, 1), +] + + +class GridReferenceParityTest(unittest.TestCase): + def test_grids_match_pinned_table(self): + cfg = _small_config() + cell = cfg.patch_size * cfg.downsample_factor + actual = [] + expected = [] + for w, h, nph, npw in _REFERENCE_GRIDS: + th, tw, _ = compute_grid_size(w, h, cfg) + actual.append((w, h, th // cell, tw // cell)) + expected.append((w, h, nph, npw)) + self.assertEqual(actual, expected) + + def test_ties_resolve_in_opposite_directions(self): + # The pair from P2447507824 that rules out any fixed tie-break: both + # are exact ties, resolved in opposite directions. + cfg = _small_config() + cell = cfg.patch_size * cfg.downsample_factor + th_ceil, _, _ = compute_grid_size(1440, 1440, cfg) + th_floor, _, _ = compute_grid_size(225, 225, cfg) + self.assertEqual((th_ceil // cell, th_floor // cell), (52, 8)) + + +class ResizeReferenceParityTest(unittest.TestCase): + """Pillow's LANCZOS output, pinned so a Pillow upgrade cannot drift silently. + + tests/vision_resize_parity_test.cpp asserts the C++ ``resize_rgb_lanczos`` + reproduces these same bytes. Regenerate both with + ``python gen_resize_golden.py``. + """ + + def test_matches_pinned_golden(self): + from executorch.examples.models.muse_glimmer.tests.gen_resize_golden import ( + make_image, + ) + from PIL import Image + + # Spot values sampled across each output; the C++ test pins every byte. + expectations = [ + (9, 7, 5, 4, [19, 255, 1], [68, 16, 153]), + (4, 3, 7, 6, [0, 255, 0], [137, 16, 22]), + (16, 16, 8, 8, [25, 250, 1], [184, 16, 99]), + ] + actual = [] + expected = [] + for sw, sh, dw, dh, head, tail in expectations: + out = list(make_image(sw, sh).resize((dw, dh), Image.LANCZOS).tobytes()) + self.assertEqual(len(out), dw * dh * 3) + actual.append((out[:3], out[-3:])) + expected.append((head, tail)) + self.assertEqual(actual, expected) + + +class PrecomputeBundleTest(unittest.TestCase): + def test_all_inputs_consistent(self): + cfg = _small_config() + # 8x8 grid image (fits one tile -> identity sparse perm). + px = 8 * cfg.patch_size + image = torch.randn(3, px, px) + table = torch.randn( + cfg.pos_emb_grid_h * cfg.pos_emb_grid_w, + cfg.latent_dim, + dtype=torch.bfloat16, + ) + out = precompute_vision_inputs(image, table, cfg) + p = 64 # 8*8 patches + self.assertEqual(out.patches.shape, (1, p, cfg.patch_dim)) + self.assertEqual(out.pos_emb.shape, (1, p, cfg.latent_dim)) + self.assertEqual(out.cos_2d.shape, (p, cfg.head_dim // 2)) + self.assertEqual(out.sin_2d.shape, (p, cfg.head_dim // 2)) + self.assertEqual(out.sparse_perm.shape, (p,)) + self.assertEqual(out.inv_perm.shape, (p,)) + self.assertEqual(out.global_mask.shape, (1, 1, p, p)) + self.assertEqual(out.sparse_mask.shape, (1, 1, p, p)) + self.assertEqual(out.pixel_perm.shape, (p,)) + # Single tile: global == sparse (all-True) and both are full attention. + self.assertTrue(out.global_mask.all()) + self.assertTrue(out.sparse_mask.all()) + self.assertEqual(len(out.as_args()), 9) + + +if __name__ == "__main__": + unittest.main() diff --git a/examples/models/muse-glimmer/tests/test_vision_tower.py b/examples/models/muse-glimmer/tests/test_vision_tower.py new file mode 100644 index 00000000000..b711a005427 --- /dev/null +++ b/examples/models/muse-glimmer/tests/test_vision_tower.py @@ -0,0 +1,235 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""Unit tests for the export-friendly Muse Glimmer vision encoder (vision_tower.py). + +Checks (CPU): + * ``MuseGlimmerVisionEncoder`` reproduces an inline eager reference (the onyx vision + math) to bf16 tolerance, given shared random weights. + * The forward runs on a single-tile image (identity sparse perm) and a + multi-tile image (non-trivial sparse perm), producing the right shapes. + * ``torch.export(strict=True)`` traces the encoder with a dynamic num_patches. +""" + +import unittest + +import torch +import torch.nn.functional as F +from executorch.examples.models.muse_glimmer.model.vision_tower import ( + MuseGlimmerVisionEncoder, +) + +from executorch.examples.models.muse_glimmer.vision.precompute import ( + MuseGlimmerVisionConfig, + precompute_vision_inputs, +) + + +def _tiny_config() -> MuseGlimmerVisionConfig: + """A small but structurally-faithful vision config (fast on CPU).""" + return MuseGlimmerVisionConfig( + patch_size=14, + patch_temporal=2, + downsample_factor=2, + sparse_attention_factor=4, + pos_emb_grid_h=8, + pos_emb_grid_w=8, + latent_dim=32, + n_heads=4, + n_layers=6, + rope_theta=10000.0, + mlp_hidden=64, + adapter_dim=48, + encoder_output_dim=32 * 4, # latent * downsample^2 + hidden_size=40, + rms_norm_eps=1e-5, + ) + + +def _init_random(model: torch.nn.Module, seed: int = 0) -> None: + torch.manual_seed(seed) + for p in model.parameters(): + if p.device.type != "meta": + p.data.normal_(0, 0.05) + for b in model.buffers(): + if b.device.type != "meta" and b.dtype.is_floating_point: + b.data.normal_(0, 0.05) + + +# --------------------------------------------------------------------------- +# Inline eager reference (mirrors OnyxVisionEncoder math on float32). + + +def _rotate_interleaved_complex(x, cos, sin): + """Adjacent-pair rotation via complex mul (eager onyx formulation).""" + freqs = torch.complex(cos, sin) # [P, d/2] + xc = torch.view_as_complex(x.float().reshape(*x.shape[:-1], -1, 2)) + out = torch.view_as_real(xc * freqs.unsqueeze(0).unsqueeze(2)).flatten(-2) + return out.to(x.dtype) + + +def _eager_reference( + model: MuseGlimmerVisionEncoder, inputs, cfg: MuseGlimmerVisionConfig +): + """Recompute the encoder output in float32 straight from the module weights. + + Uses the same submodule weights as ``model`` but a plain float32 path (no + quantization, complex RoPE) so it is an independent reference for parity. + """ + patches = inputs.patches.float() + pos_emb = inputs.pos_emb.float() + cos = inputs.cos_2d.float() + sin = inputs.sin_2d.float() + perm = inputs.sparse_perm + inv_perm = inputs.inv_perm + gmask = inputs.global_mask + smask = inputs.sparse_mask + pixel_perm = inputs.pixel_perm + + x = F.linear(patches, model.conv1_linear.weight.float()) + x = x + pos_emb + x = F.layer_norm( + x, (cfg.latent_dim,), model.ln_pre.weight.float(), model.ln_pre.bias.float() + ) + + x = x.index_select(1, perm) + cos_p = cos.index_select(0, perm) + sin_p = sin.index_select(0, perm) + + n_heads, head_dim = cfg.n_heads, cfg.head_dim + for i, blk in enumerate(model.blocks): + mask = gmask if model._is_global[i] else smask + h = F.layer_norm( + x, (cfg.latent_dim,), blk.ln_1.weight.float(), blk.ln_1.bias.float() + ) + B, P, _ = h.shape + q = F.linear(h, blk.attn.q_proj.weight.float(), blk.attn.q_proj.bias.float()) + k = F.linear(h, blk.attn.k_proj.weight.float(), blk.attn.k_proj.bias.float()) + v = F.linear(h, blk.attn.v_proj.weight.float(), blk.attn.v_proj.bias.float()) + q = q.view(B, P, n_heads, head_dim) + k = k.view(B, P, n_heads, head_dim) + v = v.view(B, P, n_heads, head_dim) + q = _rotate_interleaved_complex(q, cos_p, sin_p).transpose(1, 2) + k = _rotate_interleaved_complex(k, cos_p, sin_p).transpose(1, 2) + v = v.transpose(1, 2) + attn = F.scaled_dot_product_attention(q, k, v, attn_mask=mask) + attn = attn.transpose(1, 2).contiguous().view(B, P, n_heads * head_dim) + attn = F.linear( + attn, blk.attn.o_proj.weight.float(), blk.attn.o_proj.bias.float() + ) + x = x + attn + + h = F.layer_norm( + x, (cfg.latent_dim,), blk.ln_2.weight.float(), blk.ln_2.bias.float() + ) + h = F.linear(h, blk.mlp.c_fc.weight.float(), blk.mlp.c_fc.bias.float()) + h = F.gelu(h) + h = F.linear(h, blk.mlp.c_proj.weight.float(), blk.mlp.c_proj.bias.float()) + x = x + h + + x = x.index_select(1, inv_perm) + x = F.layer_norm( + x, (cfg.latent_dim,), model.ln_post.weight.float(), model.ln_post.bias.float() + ) + + f = cfg.downsample_factor + d = cfg.latent_dim + x_flat = x[0].index_select(0, pixel_perm) + x_ds = ( + x_flat.view(-1, f * f, d).permute(0, 2, 1).contiguous().view(1, -1, d * f * f) + ) + + x_ds = F.gelu(F.linear(x_ds, model.adapter_fc.weight.float())) + x_ds = F.gelu(F.linear(x_ds, model.adapter_proj.weight.float())) + x_ds = F.linear(x_ds, model.vision_proj.weight.float()) + x_ds = F.rms_norm(x_ds.float(), (cfg.hidden_size,), None, cfg.rms_norm_eps) + return x_ds + + +class VisionTowerParityTest(unittest.TestCase): + def _run(self, grid_side: int, dtype: torch.dtype = torch.float32): + cfg = _tiny_config() + model = MuseGlimmerVisionEncoder(cfg) + _init_random(model) + model.to(dtype) + model.eval() + + px = grid_side * cfg.patch_size + image = torch.randn(3, px, px) + table = torch.randn( + cfg.pos_emb_grid_h * cfg.pos_emb_grid_w, + cfg.latent_dim, + dtype=torch.bfloat16, + ) + inputs = precompute_vision_inputs(image, table, cfg) + with torch.no_grad(): + out = model(*inputs.as_args()) + ref = _eager_reference(model, inputs, cfg) + return out, ref, grid_side, cfg + + def test_single_tile_parity(self): + out, ref, grid_side, cfg = self._run(grid_side=6) # 6x6 <= 8x8 tile + n_out = (grid_side // cfg.downsample_factor) ** 2 + self.assertEqual(out.shape, (1, n_out, cfg.hidden_size)) + self.assertEqual(out.dtype, torch.float32) + torch.testing.assert_close(out.float(), ref.float(), atol=2e-2, rtol=2e-2) + + def test_multi_tile_parity(self): + # 16x16 grid > 8x8 tile -> 4 tiles -> non-trivial sparse permutation. + out, ref, grid_side, cfg = self._run(grid_side=16) + n_out = (grid_side // cfg.downsample_factor) ** 2 + self.assertEqual(out.shape, (1, n_out, cfg.hidden_size)) + torch.testing.assert_close(out.float(), ref.float(), atol=2e-2, rtol=2e-2) + + def test_output_dtype_follows_compute_dtype(self): + for dtype in (torch.float32, torch.bfloat16): + with self.subTest(dtype=dtype): + out, _, _, _ = self._run(grid_side=6, dtype=dtype) + self.assertEqual(out.dtype, dtype) + + +class VisionTowerExportTest(unittest.TestCase): + def test_strict_export_dynamic_patches(self): + from torch.export import Dim, export + + cfg = _tiny_config() + model = MuseGlimmerVisionEncoder(cfg) + _init_random(model) + model.eval() + + px = 8 * cfg.patch_size + image = torch.randn(3, px, px) + table = torch.randn( + cfg.pos_emb_grid_h * cfg.pos_emb_grid_w, + cfg.latent_dim, + dtype=torch.bfloat16, + ) + inputs = precompute_vision_inputs(image, table, cfg) + + ds2 = cfg.downsample_factor**2 + groups = Dim("vis_groups", min=1, max=64) + p = ds2 * groups + dyn = ( + {1: p}, + {1: p}, + {0: p}, + {0: p}, + {0: p}, + {0: p}, + {2: p, 3: p}, + {2: p, 3: p}, + {0: p}, + ) + with torch.no_grad(): + ep = export(model, inputs.as_args(), dynamic_shapes=dyn, strict=True) + self.assertIsNotNone(ep) + # Re-run the exported program on the same inputs. + out = ep.module()(*inputs.as_args()) + self.assertEqual(out.shape[-1], cfg.hidden_size) + + +if __name__ == "__main__": + unittest.main() diff --git a/examples/models/muse-glimmer/tests/vision_grid_parity_test.cpp b/examples/models/muse-glimmer/tests/vision_grid_parity_test.cpp new file mode 100644 index 00000000000..9507a97425f --- /dev/null +++ b/examples/models/muse-glimmer/tests/vision_grid_parity_test.cpp @@ -0,0 +1,117 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +// Pins the C++ patch-grid choice to the Python reference's, tie-break included. +// +// vision/preprocess.h::compute_grid_size must agree with +// vision_precompute.compute_grid_size for every image size, because the two +// disagreeing means the runner resizes to a different resolution and emits a +// different <|patch|> count than whatever tokenized the prompt. +// +// The Python side of the same table lives in +// tests/test_vision_precompute.py::GridReferenceParityTest. Keep them in sync: +// the C++ test catches C++ regressions, the Python one catches the reference +// moving out from under us (see the CPython note in vision/preprocess.h). + +#include + +#include + +#include +#include + +namespace { + +using ::executorch::examples::muse_glimmer_vision::compute_grid_size; +using ::executorch::examples::muse_glimmer_vision::kCell; +using ::executorch::examples::muse_glimmer_vision::kMaxImageTokens; + +struct GridCase { + int32_t img_w; + int32_t img_h; + int32_t nph; // grid rows the Python reference picks + int32_t npw; // grid cols the Python reference picks +}; + +// Grids produced by running the Python reference, NOT by running the code +// under test. Several are exact cost ties that the reference resolves via +// CPython set order, following no rule -- which is precisely why they are +// worth pinning. +constexpr GridCase kReferenceGrids[] = { + // Ties. 1440x1440 and 225x225 are the two cases named in P2447507824. + {1440, 1440, 52, 52}, // reference takes the LARGER grid + {225, 225, 8, 8}, // reference takes the SMALLER grid + {512, 512, 19, 19}, + {1024, 1024, 37, 37}, + {200, 203, 8, 8}, // ties despite not being square + {24, 60, 3, 1}, // ties on ratios straddling the aspect (2 and 3 vs 2.5) + // No tie: both sides are exact multiples of the 28px cell. + {700, 700, 25, 25}, + {336, 336, 12, 12}, + {1000, 2500, 90, 36}, + // Token cap: the ideal grid is rescaled to sqrt(4096) = 64 exactly. + {6000, 6000, 64, 64}, + // Smaller than one cell, so floor() is 0 and only survives because the + // >=1 filter runs after the candidate set is built, not before. + {1, 1, 1, 1}, + {27, 27, 1, 1}, + {28, 28, 1, 1}, + // Extreme aspect ratio. + {1, 10000, 358, 1}, +}; + +TEST(VisionGridParityTest, MatchesPythonReference) { + for (const GridCase& grid_case : kReferenceGrids) { + int32_t target_h = 0; + int32_t target_w = 0; + compute_grid_size(grid_case.img_w, grid_case.img_h, target_h, target_w); + + const std::pair expected{ + grid_case.nph * kCell, grid_case.npw * kCell}; + EXPECT_EQ(std::make_pair(target_h, target_w), expected) + << "image " << grid_case.img_w << "x" << grid_case.img_h; + } +} + +// The crux of P2447507824: these two are both exact ties and the reference +// resolves them in OPPOSITE directions, so no fixed "prefer larger" or +// "prefer smaller" rule can satisfy both. A regression to either rule breaks +// exactly one of these assertions. +TEST(VisionGridParityTest, TiesResolveInOppositeDirections) { + int32_t takes_ceil_h = 0; + int32_t takes_ceil_w = 0; + compute_grid_size(1440, 1440, takes_ceil_h, takes_ceil_w); + EXPECT_EQ(takes_ceil_h / kCell, 52) << "1440x1440 must take ceil, not 51"; + + int32_t takes_floor_h = 0; + int32_t takes_floor_w = 0; + compute_grid_size(225, 225, takes_floor_h, takes_floor_w); + EXPECT_EQ(takes_floor_h / kCell, 8) << "225x225 must take floor, not 9"; +} + +// Invariants solo.cpp relies on when it splices soft tokens into the prompt. +TEST(VisionGridParityTest, TargetsAreCellAlignedAndWithinCap) { + for (int32_t w = 1; w <= 600; w += 7) { + for (int32_t h = 1; h <= 600; h += 11) { + int32_t target_h = 0; + int32_t target_w = 0; + compute_grid_size(w, h, target_h, target_w); + + ASSERT_GT(target_h, 0) << w << "x" << h; + ASSERT_GT(target_w, 0) << w << "x" << h; + ASSERT_EQ(target_h % kCell, 0) << w << "x" << h; + ASSERT_EQ(target_w % kCell, 0) << w << "x" << h; + ASSERT_LE( + static_cast(target_h / kCell) * (target_w / kCell), + kMaxImageTokens) + << w << "x" << h; + } + } +} + +} // namespace diff --git a/examples/models/muse-glimmer/tests/vision_resize_parity_test.cpp b/examples/models/muse-glimmer/tests/vision_resize_parity_test.cpp new file mode 100644 index 00000000000..8fc0e161259 --- /dev/null +++ b/examples/models/muse-glimmer/tests/vision_resize_parity_test.cpp @@ -0,0 +1,116 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +// Pins the image path's resize to Pillow's LANCZOS. +// +// The reference preprocessing resizes with PIL LANCZOS on the sRGB bytes. The +// runner used to resize with stb Catmull-Rom in linear light instead, which +// differs on essentially every image. +// +// Goldens are Pillow's own output, emitted by tests/gen_resize_golden.py. The +// Python side of the same table lives in +// tests/test_vision_precompute.py::ResizeReferenceParityTest, so a Pillow +// upgrade that changes resampling fails there rather than silently drifting +// away from the C++. + +#include + +#include + +#include +#include + +namespace { + +using ::executorch::examples::muse_glimmer_vision::resize_rgb_lanczos; + +// Deterministic RGB content with a hard edge and two gradients. Must stay +// byte-identical to make_image() in tests/gen_resize_golden.py. +std::vector MakeImage(int32_t w, int32_t h) { + std::vector px; + px.reserve(static_cast(w) * h * 3); + for (int32_t y = 0; y < h; ++y) { + for (int32_t x = 0; x < w; ++x) { + px.push_back(static_cast((x * 37 + y * 11) % 256)); + px.push_back((x < w / 3 && y < h / 2) ? 255 : 16); + px.push_back(static_cast((x * x + y * y * 3) % 256)); + } + } + return px; +} + +struct ResizeCase { + int32_t src_w; + int32_t src_h; + int32_t dst_w; + int32_t dst_h; + std::vector expected; +}; + +// Generated by gen_resize_golden.py -- PIL LANCZOS reference output. +std::vector ReferenceResizes() { + return { + // Downscale: Pillow stretches the filter support on both axes. + {9, 7, 5, 4, {19, 255, 1, 83, 189, 6, 161, 0, 17, 182, 20, 35, + 26, 16, 59, 38, 190, 13, 102, 134, 18, 179, 4, 29, + 213, 19, 47, 46, 16, 71, 58, 0, 46, 120, 5, 51, + 208, 17, 62, 123, 16, 80, 54, 16, 104, 77, 20, 95, + 138, 19, 100, 231, 16, 111, 95, 16, 129, 68, 16, 153}}, + // Upscale. + {4, 3, 7, 6, {0, 255, 0, 8, 207, 0, 33, 33, 1, 55, 0, 2, + 76, 19, 4, 101, 19, 8, 113, 16, 9, 1, 211, 0, + 10, 154, 0, 35, 28, 1, 57, 3, 2, 78, 18, 4, + 103, 18, 8, 115, 16, 9, 4, 79, 1, 16, 60, 1, + 41, 20, 2, 63, 12, 3, 84, 17, 5, 109, 17, 9, + 121, 16, 10, 12, 0, 6, 24, 0, 6, 49, 14, 7, + 71, 18, 8, 92, 16, 10, 117, 16, 14, 129, 16, 15, + 17, 1, 11, 30, 6, 11, 55, 15, 12, 77, 17, 13, + 98, 16, 15, 123, 16, 19, 135, 16, 20, 20, 25, 13, + 32, 22, 13, 57, 17, 14, 79, 15, 15, 100, 16, 17, + 125, 16, 21, 137, 16, 22}}, + // Exact 2x downscale. + {16, + 16, + 8, + 8, + {25, 250, 1, 92, 255, 7, 194, 135, 21, 119, 0, 43, 43, 20, + 73, 145, 16, 111, 205, 16, 157, 48, 16, 211, 46, 249, 18, 115, + 254, 24, 211, 135, 38, 132, 0, 60, 63, 20, 90, 176, 16, 124, + 160, 16, 178, 48, 16, 233, 68, 254, 60, 143, 255, 66, 213, 137, + 76, 56, 0, 99, 97, 20, 134, 209, 16, 187, 127, 16, 223, 47, + 16, 91, 87, 237, 130, 176, 242, 137, 169, 129, 167, 50, 1, 186, + 130, 20, 193, 210, 16, 176, 96, 16, 82, 83, 16, 61, 108, 29, + 204, 205, 29, 200, 117, 22, 111, 55, 15, 117, 162, 16, 56, 201, + 16, 66, 48, 16, 119, 115, 16, 181, 138, 12, 92, 197, 12, 105, + 48, 14, 96, 90, 16, 119, 197, 16, 142, 136, 16, 173, 49, 16, + 167, 144, 16, 95, 162, 17, 195, 208, 17, 145, 57, 16, 101, 119, + 16, 143, 201, 16, 102, 82, 16, 94, 77, 16, 128, 165, 16, 138, + 199, 16, 135, 131, 16, 122, 50, 16, 114, 153, 16, 140, 201, 16, + 171, 40, 16, 113, 109, 16, 145, 184, 16, 99}}, + }; +} + +TEST(VisionResizeParityTest, MatchesPillowLanczos) { + for (const ResizeCase& resize_case : ReferenceResizes()) { + const std::vector src = + MakeImage(resize_case.src_w, resize_case.src_h); + + const std::vector actual = resize_rgb_lanczos( + src.data(), + resize_case.src_w, + resize_case.src_h, + resize_case.dst_w, + resize_case.dst_h); + + EXPECT_EQ(actual, resize_case.expected) + << resize_case.src_w << "x" << resize_case.src_h << " -> " + << resize_case.dst_w << "x" << resize_case.dst_h; + } +} + +} // namespace diff --git a/examples/models/muse-glimmer/vision/__init__.py b/examples/models/muse-glimmer/vision/__init__.py new file mode 100644 index 00000000000..2e41cd717f6 --- /dev/null +++ b/examples/models/muse-glimmer/vision/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. diff --git a/examples/models/muse-glimmer/vision/precompute.py b/examples/models/muse-glimmer/vision/precompute.py new file mode 100644 index 00000000000..1ab287ff023 --- /dev/null +++ b/examples/models/muse-glimmer/vision/precompute.py @@ -0,0 +1,297 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""Host-side preprocessing for the Muse Glimmer vision encoder. + +This module computes the data-dependent inputs to the exported graph and is +mirrored by ``vision/preprocess.h`` for the C++ runtime. +""" + +from __future__ import annotations + +import itertools +import math +from dataclasses import dataclass + +import torch +import torch.nn.functional as F + + +# Configuration from the model and mmproj metadata. + + +@dataclass +class MuseGlimmerVisionConfig: + patch_size: int = 14 + patch_temporal: int = 2 + downsample_factor: int = 2 + sparse_attention_factor: int = 4 + pos_emb_grid_h: int = 32 + pos_emb_grid_w: int = 32 + latent_dim: int = 1536 + n_heads: int = 16 + n_layers: int = 50 + rope_theta: float = 10000.0 + mlp_hidden: int = 8960 + adapter_dim: int = 4096 + encoder_output_dim: int = 6144 # latent_dim * downsample_factor**2 + hidden_size: int = 6656 # text hidden size (vision_projection output) + rms_norm_eps: float = 1e-5 + + @property + def head_dim(self) -> int: + return self.latent_dim // self.n_heads # 96 + + @property + def patch_dim(self) -> int: + return self.patch_temporal * 3 * self.patch_size**2 # 1176 + + def layer_is_global(self, layer_idx: int) -> bool: + sf = self.sparse_attention_factor + return (layer_idx == self.n_layers - 1) or ((layer_idx + 1) % sf == 0) + + +# Individual preprocessing steps. + + +def patchify_image( + image: torch.Tensor, # [3, H, W] normalized to [-1, 1], any float dtype + config: MuseGlimmerVisionConfig, +) -> tuple[torch.Tensor, int, int]: + """Unfold a normalized image into patch vectors (mirrors the c==3 path). + + Returns ``(patches [1, P, patch_dim] float32, grid_h, grid_w)`` where + ``patch_dim = patch_temporal * 3 * patch_size**2`` and the temporal axis is + a replicate of the single frame (image path). + """ + ps = config.patch_size + pt = config.patch_temporal + if image.ndim == 3: + image = image.unsqueeze(0) # [1, 3, H, W] + _, c, h, w = image.shape + if c != 3: + raise ValueError(f"patchify_image expects 3 channels, got {c}") + if h % ps != 0 or w % ps != 0: + raise ValueError(f"image {h}x{w} not divisible by patch_size {ps}") + grid_h, grid_w = h // ps, w // ps + n_tokens = grid_h * grid_w + + patches = image.unfold(2, ps, ps).unfold(3, ps, ps) + patches = patches.contiguous().view(1, c, grid_h, grid_w, ps, ps) + patches = patches.permute(0, 2, 3, 1, 4, 5).contiguous() # [1,gh,gw,c,ps,ps] + patches = patches.unsqueeze(3).expand(-1, -1, -1, pt, -1, -1, -1) + patches = patches.reshape(1, n_tokens, -1) # [1, n_tokens, pt*c*ps*ps] + return patches.to(torch.float32), grid_h, grid_w + + +def interpolate_pos_emb( + pos_embed_table: torch.Tensor, # [pos_grid_h*pos_grid_w, latent_dim] bf16 + grid_h: int, + grid_w: int, + config: MuseGlimmerVisionConfig, +) -> torch.Tensor: + """Interpolate the positional table to ``grid_h`` by ``grid_w``. + + Interpolation stays in the table's native dtype to preserve reference + numerics. Returns ``[1, grid_h*grid_w, latent_dim]``. + """ + gh, gw = config.pos_emb_grid_h, config.pos_emb_grid_w + latent = config.latent_dim + dtype = pos_embed_table.dtype + pos_emb = ( + pos_embed_table.view(gh, gw, latent).permute(2, 0, 1).unsqueeze(0) + ) # [1, latent, gh, gw] + inv_h = 1.0 / grid_h + inv_w = 1.0 / grid_w + ys = torch.linspace(-1 + inv_h, 1 - inv_h, grid_h, dtype=dtype) + xs = torch.linspace(-1 + inv_w, 1 - inv_w, grid_w, dtype=dtype) + pos_xy = torch.stack(torch.meshgrid(ys, xs, indexing="xy"), dim=-1).reshape(-1, 2)[ + None, None + ] + sampled = F.grid_sample(pos_emb, pos_xy, mode="bilinear", align_corners=False) + pos = sampled[0, :, 0, :].T # [n_tokens, latent] + return pos.unsqueeze(0).contiguous() # [1, n_tokens, latent] + + +def make_2d_rope( + grid_h: int, + grid_w: int, + config: MuseGlimmerVisionConfig, +) -> tuple[torch.Tensor, torch.Tensor]: + """Return real 2D RoPE cos/sin tensors for interleaved rotation. + + The result is numerically equivalent to the reference complex formulation. + """ + head_dim = config.head_dim + half_dim = head_dim // 2 # 48 + quarter = half_dim // 2 # 24 + theta = config.rope_theta + inv_freq = 1.0 / ( + theta + ** (torch.arange(0, half_dim, 2, dtype=torch.float32)[:quarter] / half_dim) + ) + idx_h = torch.arange(1, grid_h + 1, dtype=torch.float32) + idx_w = torch.arange(1, grid_w + 1, dtype=torch.float32) + idx_ij_h = idx_h.unsqueeze(1).expand(-1, grid_w).reshape(-1) + idx_ij_w = idx_w.unsqueeze(0).expand(grid_h, -1).reshape(-1) + freq_h = torch.outer(idx_ij_h, inv_freq) + freq_w = torch.outer(idx_ij_w, inv_freq) + freq = torch.cat([freq_w, freq_h], dim=-1) # [n_tokens, half_dim] + return torch.cos(freq), torch.sin(freq) + + +def sparse_perm_and_slens( + grid_h: int, + grid_w: int, + config: MuseGlimmerVisionConfig, +) -> tuple[torch.Tensor, list[int]]: + """Return the sparse-attention permutation and block lengths.""" + gh, gw = config.pos_emb_grid_h, config.pos_emb_grid_w + pad_h = math.ceil(grid_h / gh) * gh + pad_w = math.ceil(grid_w / gw) * gw + idx = torch.arange(grid_h * grid_w).view(grid_h, grid_w) + idx = F.pad(idx, (0, pad_w - grid_w, 0, pad_h - grid_h), value=-1).flatten() + idx = idx.view(pad_h // gh, gh, pad_w // gw, gw) + idx = idx.permute(0, 2, 1, 3).reshape(-1) + sp_perm = idx[idx != -1] + valid = (idx != -1).view(-1, gh * gw) + sp_slens = valid.sum(dim=1).tolist() + return sp_perm.to(torch.int64), sp_slens + + +def block_diag_mask(slens: list[int]) -> torch.Tensor: + """Bool block-diagonal mask ``[total, total]`` (True = attend within block).""" + total = sum(slens) + mask = torch.zeros(total, total, dtype=torch.bool) + offset = 0 + for s in slens: + mask[offset : offset + s, offset : offset + s] = True + offset += s + return mask + + +def pixel_shuffle_perm( + grid_h: int, + grid_w: int, + config: MuseGlimmerVisionConfig, +) -> torch.Tensor: + """Return the token permutation for pixel-shuffle downsampling.""" + f = config.downsample_factor + ds_perm = torch.arange(grid_h * grid_w) + ds_perm = ds_perm.view(grid_h // f, f, grid_w // f, f) + ds_perm = ds_perm.permute(0, 2, 1, 3).reshape(-1) + return ds_perm.to(torch.int64) + + +# Top-level bundle + + +@dataclass +class VisionEncoderInputs: + """The 9 tensor inputs to the exported ``vision_encoder`` graph.""" + + patches: torch.Tensor # [1, P, patch_dim] f32 + pos_emb: torch.Tensor # [1, P, latent] bf16 + cos_2d: torch.Tensor # [P, head_dim//2] f32 + sin_2d: torch.Tensor # [P, head_dim//2] f32 + sparse_perm: torch.Tensor # [P] i64 + inv_perm: torch.Tensor # [P] i64 + global_mask: torch.Tensor # [1, 1, P, P] bool + sparse_mask: torch.Tensor # [1, 1, P, P] bool + pixel_perm: torch.Tensor # [P] i64 + + def as_args(self) -> tuple[torch.Tensor, ...]: + return ( + self.patches, + self.pos_emb, + self.cos_2d, + self.sin_2d, + self.sparse_perm, + self.inv_perm, + self.global_mask, + self.sparse_mask, + self.pixel_perm, + ) + + +def precompute_vision_inputs( + image: torch.Tensor, # [3, H, W] normalized to [-1, 1] + pos_embed_table: torch.Tensor, # [pos_grid_h*pos_grid_w, latent] bf16 + config: MuseGlimmerVisionConfig | None = None, +) -> VisionEncoderInputs: + """Produce all host-precomputed inputs for the vision encoder from one image. + + ``image`` must already be resized so H and W are multiples of + ``patch_size * downsample_factor`` (28) and normalized to [-1, 1] (mean/std + 0.5). Returns a :class:`VisionEncoderInputs` bundle. + """ + if config is None: + config = MuseGlimmerVisionConfig() + + patches, grid_h, grid_w = patchify_image(image, config) + n_tokens = grid_h * grid_w + + pos_emb = interpolate_pos_emb(pos_embed_table, grid_h, grid_w, config) + cos_2d, sin_2d = make_2d_rope(grid_h, grid_w, config) + + sparse_perm, sp_slens = sparse_perm_and_slens(grid_h, grid_w, config) + inv_perm = torch.empty_like(sparse_perm) + inv_perm[sparse_perm] = torch.arange(n_tokens, dtype=torch.int64) + + # Single image: global layers attend over all tokens (all-True); sparse + # layers attend within each 32x32 tile (block-diagonal over sp_slens, in the + # PERMUTED order). + global_mask = torch.ones(1, 1, n_tokens, n_tokens, dtype=torch.bool) + sparse_mask = block_diag_mask(sp_slens).unsqueeze(0).unsqueeze(0).contiguous() + + pixel_perm = pixel_shuffle_perm(grid_h, grid_w, config) + + return VisionEncoderInputs( + patches=patches, + pos_emb=pos_emb, + cos_2d=cos_2d, + sin_2d=sin_2d, + sparse_perm=sparse_perm, + inv_perm=inv_perm, + global_mask=global_mask, + sparse_mask=sparse_mask, + pixel_perm=pixel_perm, + ) + + +def compute_grid_size( + img_w: int, + img_h: int, + config: MuseGlimmerVisionConfig | None = None, + max_tokens: int = 4096, +) -> tuple[int, int, int]: + """Choose the closest-aspect patch grid under the image-token limit.""" + if config is None: + config = MuseGlimmerVisionConfig() + ph = config.patch_size * config.downsample_factor # 28 + i_nph = img_h / ph + i_npw = img_w / ph + ratio = i_npw / i_nph if i_nph > 0 else 1.0 + if i_nph * i_npw > max_tokens: + i_nph = (max_tokens / ratio) ** 0.5 + i_npw = i_nph * ratio + candidates = list( + set( + itertools.product( + [math.floor(i_nph), math.ceil(i_nph)], + [math.floor(i_npw), math.ceil(i_npw)], + ) + ) + ) + candidates = [ + (nph, npw) + for nph, npw in candidates + if nph >= 1 and npw >= 1 and nph * npw <= max_tokens + ] + if not candidates: + candidates = [(max(1, round(i_nph)), max(1, round(i_npw)))] + nph, npw = min(candidates, key=lambda c: abs(c[0] / c[1] - img_h / img_w)) + return nph * ph, npw * ph, nph * npw diff --git a/examples/models/muse-glimmer/vision/preprocess.h b/examples/models/muse-glimmer/vision/preprocess.h new file mode 100644 index 00000000000..826310623e9 --- /dev/null +++ b/examples/models/muse-glimmer/vision/preprocess.h @@ -0,0 +1,709 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +// C++ mirror of vision/precompute.py. It converts one decoded image into the +// host-computed inputs expected by the exported vision encoder. + +#pragma once + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace executorch { +namespace examples { +namespace muse_glimmer_vision { + +using ::executorch::extension::TensorPtr; + +// Vision constants (mirror MuseGlimmerVisionConfig / mmproj clip metadata). +static constexpr int32_t kPatchSize = 14; +static constexpr int32_t kPatchTemporal = 2; +static constexpr int32_t kDownsample = 2; +static constexpr int32_t kSparseFactor = 4; +static constexpr int32_t kPosGrid = 32; // 32x32 positional table +static constexpr int32_t kLatent = 1536; +static constexpr int32_t kHeadDim = 96; // latent / n_heads(16) +static constexpr int32_t kPatchDim = + kPatchTemporal * 3 * kPatchSize * kPatchSize; // 1176 +// Cell = patch_size * downsample (image resized to a whole number of cells). +static constexpr int32_t kCell = kPatchSize * kDownsample; // 28 +static constexpr int64_t kMaxImageTokens = 4096; + +struct VisionInputs { + TensorPtr patches; // (1, P, 1176) float32 + TensorPtr pos_emb; // (1, P, 1536) bfloat16 + TensorPtr cos_2d; // (P, 48) float32 + TensorPtr sin_2d; // (P, 48) float32 + TensorPtr sparse_perm; // (P,) int64 + TensorPtr inv_perm; // (P,) int64 + TensorPtr global_mask; // (1, 1, P, P) bool + TensorPtr sparse_mask; // (1, 1, P, P) bool + TensorPtr pixel_perm; // (P,) int64 + int64_t num_patches; // P + int64_t num_soft_tokens; // P / downsample^2 +}; + +// Reproduce vision_precompute.compute_grid_size, which picks the grid with +// +// min(list(set(itertools.product([floor, ceil], [floor, ceil]))), key=cost) +// +// Equal-cost candidates are resolved by CPython set iteration order, not by +// grid size. The helpers below reproduce the deterministic small-integer tuple +// hashing and probing used by CPython 3.8 and later. +namespace detail { + +constexpr int32_t kSetTableSize = 8; // PySet_MINSIZE; <=4 entries never resize +constexpr uint64_t kSetMask = kSetTableSize - 1; +constexpr int32_t kSetPerturbShift = 5; // CPython PERTURB_SHIFT + +// hash() of a 2-tuple of small non-negative ints under CPython >= 3.8, whose +// tuple hash is xxHash-based. hash(int) is the int itself in this range. +inline uint64_t tuple2_hash(int32_t a, int32_t b) { + constexpr uint64_t kPrime1 = 11400714785074694791ULL; + constexpr uint64_t kPrime2 = 14029467366897019727ULL; + constexpr uint64_t kPrime5 = 2870177450012600261ULL; + uint64_t acc = kPrime5; + for (const int32_t lane : {a, b}) { + acc += static_cast(lane) * kPrime2; + acc = (acc << 31) | (acc >> 33); + acc *= kPrime1; + } + acc += 2ULL ^ (kPrime5 ^ 3527539ULL); + return acc == ~uint64_t{0} ? 1546275796ULL : acc; +} + +struct GridCandidate { + int32_t nph; + int32_t npw; +}; + +// itertools.product([fh, ch], [fw, cw]) deduplicated and emitted in the order +// CPython walks the resulting set's table. At most 4 entries keep that table at +// PySet_MINSIZE, where `i + LINEAR_PROBES <= mask` never holds, so insertion is +// the plain perturbed probe below with no linear scan. Returns the count. +inline int32_t grid_candidates_in_set_order( + int32_t fh, + int32_t ch, + int32_t fw, + int32_t cw, + GridCandidate* out) { + GridCandidate table[kSetTableSize]; + bool filled[kSetTableSize] = {}; + for (const int32_t nph : {fh, ch}) { + for (const int32_t npw : {fw, cw}) { + uint64_t perturb = tuple2_hash(nph, npw); + uint64_t i = perturb & kSetMask; + while (filled[i] && (table[i].nph != nph || table[i].npw != npw)) { + perturb >>= kSetPerturbShift; + i = (i * 5 + 1 + perturb) & kSetMask; + } + table[i] = GridCandidate{nph, npw}; + filled[i] = true; + } + } + int32_t n = 0; + for (int32_t i = 0; i < kSetTableSize; ++i) { + if (filled[i]) { + out[n++] = table[i]; + } + } + return n; +} + +// Python's round() for a non-negative double: halfway cases go to even. +inline int32_t round_half_even(double x) { + const double lower = std::floor(x); + int64_t n = static_cast(lower); + const double frac = x - lower; + if (frac > 0.5 || (frac == 0.5 && (n % 2) != 0)) { + ++n; + } + return static_cast(n); +} + +} // namespace detail + +// Pick the image grid under the token cap, including the tie-break above. +inline void compute_grid_size( + int32_t img_w, + int32_t img_h, + int32_t& target_h, + int32_t& target_w, + int64_t max_tokens = kMaxImageTokens) { + const double ph = static_cast(kCell); + double i_nph = img_h / ph; + double i_npw = img_w / ph; + const double ratio = (i_nph > 0) ? (i_npw / i_nph) : 1.0; + if (i_nph * i_npw > static_cast(max_tokens)) { + i_nph = std::sqrt(static_cast(max_tokens) / ratio); + i_npw = i_nph * ratio; + } + + // Candidates are built UNCLAMPED (floor may be 0) and filtered afterwards, + // as Python does. Clamping to >=1 up front would change which tuples enter + // the set, and so both the candidate list and the order it comes back in. + detail::GridCandidate candidates[detail::kSetTableSize]; + const int32_t n_candidates = detail::grid_candidates_in_set_order( + static_cast(std::floor(i_nph)), + static_cast(std::ceil(i_nph)), + static_cast(std::floor(i_npw)), + static_cast(std::ceil(i_npw)), + candidates); + + const double aspect = static_cast(img_h) / static_cast(img_w); + int32_t best_h = 0; + int32_t best_w = 0; + double best_cost = 0.0; + bool found = false; + for (int32_t i = 0; i < n_candidates; ++i) { + const int32_t nph = candidates[i].nph; + const int32_t npw = candidates[i].npw; + if (nph < 1 || npw < 1 || static_cast(nph) * npw > max_tokens) { + continue; + } + const double cost = + std::abs(static_cast(nph) / static_cast(npw) - aspect); + // Strict <, walking the set order: exactly what Python's min() does. + if (!found || cost < best_cost) { + found = true; + best_cost = cost; + best_h = nph; + best_w = npw; + } + } + if (!found) { + best_h = std::max(1, detail::round_half_even(i_nph)); + best_w = std::max(1, detail::round_half_even(i_npw)); + } + target_h = best_h * kCell; + target_w = best_w * kCell; +} + +inline std::vector resize_rgb( + const uint8_t* src, + int32_t src_w, + int32_t src_h, + int32_t dst_w, + int32_t dst_h) { + std::vector dst(static_cast(dst_w) * dst_h * 3); + stbir_resize_uint8_generic( + src, + src_w, + src_h, + 0, + dst.data(), + dst_w, + dst_h, + 0, + 3, + STBIR_ALPHA_CHANNEL_NONE, + 0, + STBIR_EDGE_CLAMP, + STBIR_FILTER_CATMULLROM, + STBIR_COLORSPACE_SRGB, + nullptr); + return dst; +} +// PIL-compatible Lanczos resize. +// +// Downscale-aware support, fixed-point coefficients and accumulation, and a +// clipped uint8 intermediate reproduce Pillow's Image.LANCZOS output. + +static constexpr int32_t kLanczosA = 3; +// Pillow's PRECISION_BITS = 32 - 8 - 2. +static constexpr int32_t kResamplePrecisionBits = 22; + +inline double lanczos_kernel(double x) { + if (x == 0.0) { + return 1.0; + } + if (x < 0.0) { + x = -x; + } + if (x >= static_cast(kLanczosA)) { + return 0.0; + } + const double px = M_PI * x; + return (std::sin(px) / px) * (std::sin(px / kLanczosA) / (px / kLanczosA)); +} + +// Per-output-pixel taps for one axis, in Pillow's fixed-point form. +struct ResampleAxis { + int32_t ksize = 0; + std::vector bounds; // 2 per output pixel: {start, count} + std::vector kk; // out_size * ksize +}; + +inline ResampleAxis precompute_resample_axis( + int32_t in_size, + int32_t out_size) { + const double scale = static_cast(in_size) / out_size; + const double filterscale = scale < 1.0 ? 1.0 : scale; + const double support = kLanczosA * filterscale; + + ResampleAxis ax; + ax.ksize = static_cast(std::ceil(support)) * 2 + 1; + ax.bounds.assign(static_cast(out_size) * 2, 0); + ax.kk.assign(static_cast(out_size) * ax.ksize, 0); + + std::vector k(static_cast(ax.ksize), 0.0); + for (int32_t xx = 0; xx < out_size; ++xx) { + const double center = (xx + 0.5) * scale; + int32_t xmin = static_cast(center - support + 0.5); + if (xmin < 0) { + xmin = 0; + } + int32_t xmax = static_cast(center + support + 0.5); + if (xmax > in_size) { + xmax = in_size; + } + xmax -= xmin; + + double ww = 0.0; + for (int32_t x = 0; x < xmax; ++x) { + const double w = lanczos_kernel((x + xmin - center + 0.5) / filterscale); + k[static_cast(x)] = w; + ww += w; + } + if (ww != 0.0) { + for (int32_t x = 0; x < xmax; ++x) { + k[static_cast(x)] /= ww; + } + } + int32_t* out_k = ax.kk.data() + static_cast(xx) * ax.ksize; + for (int32_t x = 0; x < xmax; ++x) { + const double v = + k[static_cast(x)] * (1 << kResamplePrecisionBits); + out_k[x] = static_cast(v < 0 ? v - 0.5 : v + 0.5); + } + ax.bounds[static_cast(xx) * 2 + 0] = xmin; + ax.bounds[static_cast(xx) * 2 + 1] = xmax; + } + return ax; +} + +inline uint8_t resample_clip8(int64_t acc) { + const int64_t v = acc >> kResamplePrecisionBits; + if (v <= 0) { + return 0; + } + if (v >= 255) { + return 255; + } + return static_cast(v); +} + +// One separable pass along x over interleaved RGB24. The vertical pass reuses +// this by being handed a transposed view, exactly as Pillow runs two 1-D +// passes. +inline void resample_pass_x( + const uint8_t* src, + int32_t src_w, + int32_t rows, + const ResampleAxis& ax, + int32_t out_w, + uint8_t* dst) { + constexpr int64_t kInit = int64_t{1} << (kResamplePrecisionBits - 1); + (void)src_w; + for (int32_t y = 0; y < rows; ++y) { + const uint8_t* srow = src + static_cast(y) * src_w * 3; + uint8_t* drow = dst + static_cast(y) * out_w * 3; + for (int32_t xx = 0; xx < out_w; ++xx) { + const int32_t xmin = ax.bounds[static_cast(xx) * 2 + 0]; + const int32_t xcnt = ax.bounds[static_cast(xx) * 2 + 1]; + const int32_t* k = ax.kk.data() + static_cast(xx) * ax.ksize; + int64_t s0 = kInit, s1 = kInit, s2 = kInit; + for (int32_t x = 0; x < xcnt; ++x) { + const uint8_t* p = srow + static_cast(xmin + x) * 3; + s0 += static_cast(p[0]) * k[x]; + s1 += static_cast(p[1]) * k[x]; + s2 += static_cast(p[2]) * k[x]; + } + drow[xx * 3 + 0] = resample_clip8(s0); + drow[xx * 3 + 1] = resample_clip8(s1); + drow[xx * 3 + 2] = resample_clip8(s2); + } + } +} + +inline void +transpose_rgb(const uint8_t* src, int32_t w, int32_t h, uint8_t* dst) { + for (int32_t y = 0; y < h; ++y) { + for (int32_t x = 0; x < w; ++x) { + const uint8_t* p = src + (static_cast(y) * w + x) * 3; + uint8_t* q = dst + (static_cast(x) * h + y) * 3; + q[0] = p[0]; + q[1] = p[1]; + q[2] = p[2]; + } + } +} + +// Resize interleaved RGB24 with Pillow's LANCZOS semantics. +inline std::vector resize_rgb_lanczos( + const uint8_t* src, + int32_t src_w, + int32_t src_h, + int32_t dst_w, + int32_t dst_h) { + const ResampleAxis hx = precompute_resample_axis(src_w, dst_w); + std::vector horiz(static_cast(dst_w) * src_h * 3); + resample_pass_x(src, src_w, src_h, hx, dst_w, horiz.data()); + + // Vertical pass as a horizontal pass over the transpose, then transpose back. + std::vector t(static_cast(src_h) * dst_w * 3); + transpose_rgb(horiz.data(), dst_w, src_h, t.data()); + const ResampleAxis vx = precompute_resample_axis(src_h, dst_h); + std::vector tv(static_cast(dst_h) * dst_w * 3); + resample_pass_x(t.data(), src_h, dst_w, vx, dst_h, tv.data()); + + std::vector dst(static_cast(dst_w) * dst_h * 3); + transpose_rgb(tv.data(), dst_h, dst_w, dst.data()); + return dst; +} + +namespace detail { + +// Bilinear grid_sample of the 32x32 pos table, matching the eager reference's +// meshgrid(ys, xs, indexing="xy") and align_corners=False semantics. The +// resulting tokens are flattened over [grid_w, grid_h], with grid_h fastest. +// ``table`` is [pos_tokens(=1024), latent] row-major (float). +inline void interpolate_pos_emb( + const std::vector& table, + int32_t grid_h, + int32_t grid_w, + std::vector& out /* [grid_h*grid_w, latent] */) { + const int32_t gh = kPosGrid, gw = kPosGrid; + out.assign(static_cast(grid_h) * grid_w * kLatent, 0.0f); + const double inv_h = 1.0 / grid_h; + const double inv_w = 1.0 / grid_w; + for (int32_t oy = 0; oy < grid_w; ++oy) { + // meshgrid(ys, xs, indexing="xy") puts xs in grid_sample's y slot. + const double ny = (grid_w == 1) + ? 0.0 + : (-1.0 + inv_w + oy * (2.0 - 2.0 * inv_w) / (grid_w - 1)); + const double sy = (ny + 1.0) * 0.5 * gh - 0.5; + const int32_t y0 = static_cast(std::floor(sy)); + const double wy = sy - y0; + for (int32_t ox = 0; ox < grid_h; ++ox) { + // meshgrid puts ys in grid_sample's x slot. + const double nx = (grid_h == 1) + ? 0.0 + : (-1.0 + inv_h + ox * (2.0 - 2.0 * inv_h) / (grid_h - 1)); + const double sx = (nx + 1.0) * 0.5 * gw - 0.5; + const int32_t x0 = static_cast(std::floor(sx)); + const double wx = sx - x0; + + const int32_t y1 = y0 + 1; + const int32_t x1 = x0 + 1; + const auto in_bounds = [gh, gw](int32_t y, int32_t x) { + return y >= 0 && y < gh && x >= 0 && x < gw; + }; + // F.grid_sample defaults to zero padding. This matters whenever a + // runtime grid dimension exceeds the 32x32 source table: the first and + // last sample centers then straddle the source boundary. + const float* p00 = in_bounds(y0, x0) + ? table.data() + (static_cast(y0) * gw + x0) * kLatent + : nullptr; + const float* p01 = in_bounds(y0, x1) + ? table.data() + (static_cast(y0) * gw + x1) * kLatent + : nullptr; + const float* p10 = in_bounds(y1, x0) + ? table.data() + (static_cast(y1) * gw + x0) * kLatent + : nullptr; + const float* p11 = in_bounds(y1, x1) + ? table.data() + (static_cast(y1) * gw + x1) * kLatent + : nullptr; + float* dst = + out.data() + (static_cast(oy) * grid_h + ox) * kLatent; + for (int32_t c = 0; c < kLatent; ++c) { + const double top = (p00 == nullptr ? 0.0 : p00[c]) * (1.0 - wx) + + (p01 == nullptr ? 0.0 : p01[c]) * wx; + const double bot = (p10 == nullptr ? 0.0 : p10[c]) * (1.0 - wx) + + (p11 == nullptr ? 0.0 : p11[c]) * wx; + dst[c] = static_cast(top * (1.0 - wy) + bot * wy); + } + } + } +} + +// 2D-RoPE cos/sin, mirroring vision_precompute.make_2d_rope. +inline void make_2d_rope( + int32_t grid_h, + int32_t grid_w, + std::vector& cos_out /* [P, 48] */, + std::vector& sin_out) { + const int32_t half = kHeadDim / 2; // 48 + const int32_t quarter = half / 2; // 24 + const double theta = 10000.0; + std::vector inv_freq(quarter); + for (int32_t i = 0; i < quarter; ++i) { + inv_freq[i] = 1.0 / std::pow(theta, static_cast(2 * i) / half); + } + const int64_t p = static_cast(grid_h) * grid_w; + cos_out.assign(static_cast(p) * half, 0.0f); + sin_out.assign(static_cast(p) * half, 0.0f); + for (int32_t r = 0; r < grid_h; ++r) { + for (int32_t c = 0; c < grid_w; ++c) { + const int64_t tok = static_cast(r) * grid_w + c; + float* crow = cos_out.data() + tok * half; + float* srow = sin_out.data() + tok * half; + // freq = concat(freq_w, freq_h); each is quarter-wide. + for (int32_t i = 0; i < quarter; ++i) { + const double fw = (c + 1) * inv_freq[i]; + crow[i] = static_cast(std::cos(fw)); + srow[i] = static_cast(std::sin(fw)); + } + for (int32_t i = 0; i < quarter; ++i) { + const double fh = (r + 1) * inv_freq[i]; + crow[quarter + i] = static_cast(std::cos(fh)); + srow[quarter + i] = static_cast(std::sin(fh)); + } + } + } +} + +// Sparse tiling permutation + per-group lengths, mirroring +// vision_precompute.sparse_perm_and_slens (32x32 window tiling). +inline void sparse_perm_and_slens( + int32_t grid_h, + int32_t grid_w, + std::vector& perm, + std::vector& slens) { + const int32_t gh = kPosGrid, gw = kPosGrid; + const int32_t pad_h = ((grid_h + gh - 1) / gh) * gh; + const int32_t pad_w = ((grid_w + gw - 1) / gw) * gw; + perm.clear(); + slens.clear(); + for (int32_t bh = 0; bh < pad_h / gh; ++bh) { + for (int32_t bw = 0; bw < pad_w / gw; ++bw) { + int32_t count = 0; + for (int32_t iy = 0; iy < gh; ++iy) { + for (int32_t ix = 0; ix < gw; ++ix) { + const int32_t y = bh * gh + iy; + const int32_t x = bw * gw + ix; + if (y < grid_h && x < grid_w) { + perm.push_back(static_cast(y) * grid_w + x); + ++count; + } + } + } + if (count > 0) { + slens.push_back(count); + } + } + } +} + +// Pixel-shuffle permutation, mirroring vision_precompute.pixel_shuffle_perm. +inline void +pixel_shuffle_perm(int32_t grid_h, int32_t grid_w, std::vector& perm) { + const int32_t f = kDownsample; + perm.assign(static_cast(grid_h) * grid_w, 0); + int64_t idx = 0; + for (int32_t oh = 0; oh < grid_h / f; ++oh) { + for (int32_t ow = 0; ow < grid_w / f; ++ow) { + for (int32_t iy = 0; iy < f; ++iy) { + for (int32_t ix = 0; ix < f; ++ix) { + const int32_t y = oh * f + iy; + const int32_t x = ow * f + ix; + perm[idx++] = static_cast(y) * grid_w + x; + } + } + } + } +} + +} // namespace detail + +// Preprocess a decoded RGB image (HWC uint8) into the 9 vision_encoder inputs. +// ``pos_table`` is the [pos_tokens(=1024), latent(=1536)] float positional +// table loaded from pos_embed.bin (written by export.py). +inline VisionInputs preprocess_image( + const uint8_t* rgb, + int32_t width, + int32_t height, + const std::vector& pos_table, + int64_t max_image_tokens = kMaxImageTokens) { + namespace ext = ::executorch::extension; + using SizesType = ::executorch::aten::SizesType; + + int32_t target_h = 0, target_w = 0; + compute_grid_size(width, height, target_h, target_w, max_image_tokens); + + std::vector resized; + const uint8_t* img = rgb; + if (target_h != height || target_w != width) { + resized = resize_rgb_lanczos(rgb, width, height, target_w, target_h); + img = resized.data(); + height = target_h; + width = target_w; + } + + const int32_t grid_h = height / kPatchSize; + const int32_t grid_w = width / kPatchSize; + const int64_t P = static_cast(grid_h) * grid_w; + const int64_t n_out = (grid_h / kDownsample) * (grid_w / kDownsample); + const int32_t half = kHeadDim / 2; + + // --- patches [1, P, 1176] float32 (normalize to [-1,1], replicate temporal). + auto patches = ext::zeros( + {1, static_cast(P), kPatchDim}, + executorch::aten::ScalarType::Float); + float* pv = patches->mutable_data_ptr(); + const int32_t hp = kPatchSize * kPatchSize; // 196 + for (int32_t py = 0; py < grid_h; ++py) { + for (int32_t px = 0; px < grid_w; ++px) { + const int64_t tok = static_cast(py) * grid_w + px; + float* prow = pv + tok * kPatchDim; + // Layout mirrors eager: permute to [c, ps, ps] then temporal replicate. + // eager patches reshape is [pt, 3, ps, ps] flattened -> here we fill the + // first (3*ps*ps) block and copy it to the 2nd temporal block. + for (int32_t c = 0; c < 3; ++c) { + for (int32_t dy = 0; dy < kPatchSize; ++dy) { + for (int32_t dx = 0; dx < kPatchSize; ++dx) { + const int32_t iy = py * kPatchSize + dy; + const int32_t ix = px * kPatchSize + dx; + const int32_t src = (iy * width + ix) * 3 + c; + const float val = (img[src] / 255.0f - 0.5f) / 0.5f; + prow[(c * hp) + dy * kPatchSize + dx] = val; + } + } + } + // Temporal replicate: 2nd half == 1st half (3*ps*ps floats). + const int32_t block = 3 * hp; + for (int32_t i = 0; i < block; ++i) { + prow[block + i] = prow[i]; + } + } + } + + // --- positional embedding [1, P, 1536] bf16 (host grid_sample interp). + std::vector pos_f; + detail::interpolate_pos_emb(pos_table, grid_h, grid_w, pos_f); + auto pos_emb = ext::zeros( + {1, static_cast(P), kLatent}, + executorch::aten::ScalarType::BFloat16); + auto* pe = pos_emb->mutable_data_ptr(); + for (int64_t i = 0; i < P * kLatent; ++i) { + pe[i] = static_cast(pos_f[i]); + } + + // --- 2D-RoPE cos/sin [P, 48] float32. + std::vector cos_f, sin_f; + detail::make_2d_rope(grid_h, grid_w, cos_f, sin_f); + auto cos_t = ext::zeros( + {static_cast(P), half}, executorch::aten::ScalarType::Float); + auto sin_t = ext::zeros( + {static_cast(P), half}, executorch::aten::ScalarType::Float); + std::memcpy( + cos_t->mutable_data_ptr(), + cos_f.data(), + cos_f.size() * sizeof(float)); + std::memcpy( + sin_t->mutable_data_ptr(), + sin_f.data(), + sin_f.size() * sizeof(float)); + + // --- sparse perm / inv perm [P] int64 + block-diagonal masks [1,1,P,P] bool. + std::vector perm; + std::vector slens; + detail::sparse_perm_and_slens(grid_h, grid_w, perm, slens); + std::vector inv(perm.size()); + for (size_t i = 0; i < perm.size(); ++i) { + inv[perm[i]] = static_cast(i); + } + auto perm_t = ext::zeros( + {static_cast(P)}, executorch::aten::ScalarType::Long); + auto inv_t = ext::zeros( + {static_cast(P)}, executorch::aten::ScalarType::Long); + std::memcpy( + perm_t->mutable_data_ptr(), perm.data(), P * sizeof(int64_t)); + std::memcpy( + inv_t->mutable_data_ptr(), inv.data(), P * sizeof(int64_t)); + + // global_mask: all-True (single image); sparse_mask: block-diagonal by slens + // in PERMUTED order. + auto global_mask = ext::full( + {1, 1, static_cast(P), static_cast(P)}, + true, + executorch::aten::ScalarType::Bool); + auto sparse_mask = ext::zeros( + {1, 1, static_cast(P), static_cast(P)}, + executorch::aten::ScalarType::Bool); + auto* sm = sparse_mask->mutable_data_ptr(); + int64_t offset = 0; + for (int32_t s : slens) { + for (int64_t r = 0; r < s; ++r) { + for (int64_t c = 0; c < s; ++c) { + sm[(offset + r) * P + (offset + c)] = true; + } + } + offset += s; + } + + // --- pixel-shuffle perm [P] int64. + std::vector px_perm; + detail::pixel_shuffle_perm(grid_h, grid_w, px_perm); + auto pixel_t = ext::zeros( + {static_cast(P)}, executorch::aten::ScalarType::Long); + std::memcpy( + pixel_t->mutable_data_ptr(), + px_perm.data(), + P * sizeof(int64_t)); + + return VisionInputs{ + std::move(patches), + std::move(pos_emb), + std::move(cos_t), + std::move(sin_t), + std::move(perm_t), + std::move(inv_t), + std::move(global_mask), + std::move(sparse_mask), + std::move(pixel_t), + P, + n_out, + }; +} + +// Read the pos_embed.bin table (float32 [pos_tokens, latent]) written by +// export.py. Returns the flat table; throws on size mismatch. +inline std::vector load_pos_embed_table(const std::string& path) { + std::ifstream f(path, std::ios::binary); + if (!f.is_open()) { + throw std::runtime_error("Cannot open pos_embed.bin: " + path); + } + f.seekg(0, std::ios::end); + const int64_t nbytes = f.tellg(); + f.seekg(0, std::ios::beg); + const int64_t n = nbytes / static_cast(sizeof(float)); + const int64_t expected = static_cast(kPosGrid) * kPosGrid * kLatent; + if (n != expected) { + throw std::runtime_error( + "pos_embed.bin size mismatch: got " + std::to_string(n) + + " floats, expected " + std::to_string(expected)); + } + std::vector table(static_cast(n)); + f.read(reinterpret_cast(table.data()), nbytes); + return table; +} + +} // namespace muse_glimmer_vision +} // namespace examples +} // namespace executorch diff --git a/examples/models/muse_glimmer b/examples/models/muse_glimmer new file mode 120000 index 00000000000..be003a426ed --- /dev/null +++ b/examples/models/muse_glimmer @@ -0,0 +1 @@ +muse-glimmer \ No newline at end of file