diff --git a/.ci/scripts/muse_glimmer_batching_workload.h b/.ci/scripts/muse_glimmer_batching_workload.h index 33f25418cb9..e9ce319d536 100644 --- a/.ci/scripts/muse_glimmer_batching_workload.h +++ b/.ci/scripts/muse_glimmer_batching_workload.h @@ -107,6 +107,9 @@ class EvidenceExecutor final : public batching::Executor { bool initialize() override { return inner_.initialize(); } + void on_idle() override { + inner_.on_idle(); + } std::size_t preferred_batch_tokens() const override { return inner_.preferred_batch_tokens(); } diff --git a/.ci/scripts/tests/muse_glimmer_batching_workload_test.cpp b/.ci/scripts/tests/muse_glimmer_batching_workload_test.cpp index 94ba8ed639b..2dee107cb53 100644 --- a/.ci/scripts/tests/muse_glimmer_batching_workload_test.cpp +++ b/.ci/scripts/tests/muse_glimmer_batching_workload_test.cpp @@ -35,6 +35,10 @@ void rejected(F action) { class FakeExecutor final : public batching::Executor { public: bool succeeds = true; + int idle_calls = 0; + void on_idle() override { + ++idle_calls; + } std::optional open_session() override { return 1; } @@ -95,6 +99,8 @@ void workload_limits() { void successful_batch_owners() { FakeExecutor inner; ci::EvidenceExecutor executor(inner); + executor.on_idle(); + require(inner.idle_calls == 1); batching::BatchOutput out; require(executor.execute({{input(1), input(1)}}, out)); require(executor.execute({{input(2)}}, out)); diff --git a/.ci/scripts/tests/test_muse_glimmer_batching_ci.py b/.ci/scripts/tests/test_muse_glimmer_batching_ci.py index 5c8fcead860..4a315710f8f 100644 --- a/.ci/scripts/tests/test_muse_glimmer_batching_ci.py +++ b/.ci/scripts/tests/test_muse_glimmer_batching_ci.py @@ -4,6 +4,7 @@ # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. +import ast import re import subprocess import unittest @@ -23,6 +24,148 @@ class MuseGlimmerBatchingCITest(unittest.TestCase): + def test_private_buck_targets_include_the_imported_cuda_packages(self): + cuda = ROOT / "backends/cuda" + tree = ast.parse((cuda / "tests/targets.bzl").read_text()) + targets = {} + for node in ast.walk(tree): + if isinstance(node, ast.Call): + fields = {keyword.arg: keyword.value for keyword in node.keywords} + name = fields.get("name") + if isinstance(name, ast.Constant) and name.value in ( + "test_sdpa_varlen_private", + "test_private_kv_manifest", + ): + targets[name.value] = fields + self.assertEqual(len(targets), 2) + packages = { + "executorch.backends.cuda.passes.": "//executorch/backends/cuda:cuda_passes", + "executorch.backends.cuda.triton.kernels.": "//executorch/backends/cuda:triton_kernels", + } + for name, fields in targets.items(): + dependencies = ast.literal_eval(fields["deps"]) + for source in ast.literal_eval(fields["srcs"]): + imports = ast.parse((cuda / "tests" / source).read_text()) + for node in ast.walk(imports): + if isinstance(node, ast.ImportFrom) and node.module: + for prefix, dependency in packages.items(): + if node.module.startswith(prefix): + with self.subTest(target=name, module=node.module): + self.assertIn(dependency, dependencies) + + def test_imported_kernels_are_in_buck_package(self): + cuda = ROOT / "backends/cuda" + tree = ast.parse((cuda / "BUCK").read_text()) + targets = [ + node.value + for node in tree.body + if isinstance(node, ast.Expr) + and isinstance(node.value, ast.Call) + and any( + keyword.arg == "name" + and isinstance(keyword.value, ast.Constant) + and keyword.value.value == "triton_kernels" + for keyword in node.value.keywords + ) + ] + self.assertEqual(len(targets), 1) + sources = next( + ast.literal_eval(keyword.value) + for keyword in targets[0].keywords + if keyword.arg == "srcs" + ) + imports = ast.parse((cuda / "passes/lower_offgraph_kv.py").read_text()) + prefix = "executorch.backends.cuda." + for node in imports.body: + if isinstance(node, ast.ImportFrom) and node.module.startswith( + prefix + "triton.kernels." + ): + source = node.module.removeprefix(prefix).replace(".", "/") + ".py" + with self.subTest(imported_module=node.module): + self.assertIn(source, sources) + + def test_production_ring_geometry_is_qualified_separately(self): + workflow = (ROOT / ".github/workflows/cuda.yml").read_text() + job = workflow.split(" unittest-cuda-private-kv-mg-ring:", 1)[1].split( + " unittest-cuda-runtime:", 1 + )[0] + self.assertIn("runner: mt-l-x86iavx512-11-125-a100", job) + self.assertIn("--profile mg-ring", job) + self.assertIn("'backends/aoti'", job) + self.assertIn("'extension/llm/batching'", job) + self.assertIn( + "PrivateVarlenTest::test_muse_glimmer_and_gemma_head_geometry", job + ) + self.assertIn( + "PrivateVarlenTest::test_restored_ring_does_not_read_unwritten_nan_slot", + job, + ) + self.assertIn("export PYTHONUNBUFFERED=1", job) + self.assertIn("-DEXECUTORCH_ENABLE_LOGGING=OFF", job) + self.assertIn("--target muse_glimmer_runtime_kv_probe --parallel", job) + self.assertIn('exit "${PRIVATE_KV_STATUS}"', job) + self.assertIn('"qualification.json", "probe.jsonl", "probe.stderr.log"', job) + shell = "\n".join( + line[8:] for line in job.split(" script: |\n", 1)[1].splitlines() + ) + shell = re.sub(r"\$\{\{[^}]+\}\}", "ci-value", shell) + result = subprocess.run(["bash", "-n"], input=shell, text=True) + self.assertEqual(result.returncode, 0) + + def test_runtime_owned_compile_buffer_tests_are_packaged_and_run(self): + cuda = ROOT / "backends/cuda" + targets = {} + for source in (cuda / "BUCK", cuda / "tests/targets.bzl"): + for node in ast.walk(ast.parse(source.read_text())): + if not isinstance(node, ast.Call): + continue + fields = {keyword.arg: keyword.value for keyword in node.keywords} + name = fields.get("name") + if isinstance(name, ast.Constant): + targets[name.value] = fields + self.assertIn( + "runtime_owned_kv.py", + ast.literal_eval(targets["runtime_owned_kv"]["srcs"]), + ) + self.assertIn( + ":runtime_owned_kv", + ast.literal_eval(targets["cuda_backend"]["deps"]), + ) + self.assertIn( + "//executorch/backends/cuda:runtime_owned_kv", + ast.literal_eval(targets["test_runtime_owned_kv"]["deps"]), + ) + workflow = (ROOT / ".github/workflows/cuda.yml").read_text() + job = workflow.split(" unittest-cuda-runtime:", 1)[1].split( + " unittest-cuda:", 1 + )[0] + self.assertIn("backends/cuda/tests/test_runtime_owned_kv.py", job) + + def test_noisy_timing_enforcement_requires_explicit_opt_in(self): + workflow = (ROOT / ".github/workflows/cuda.yml").read_text() + self.assertIn(" enforce_private_kv_performance:\n", workflow) + for name, end in ( + ("unittest-cuda-muse-glimmer-batching", "unittest-cuda-quantized-gemm"), + ("unittest-cuda-private-kv-mg-ring", "unittest-cuda-runtime"), + ): + job = workflow.split(f" {name}:\n", 1)[1].split(f" {end}:\n", 1)[0] + self.assertIn('PRIVATE_KV_TIMING_ARGS="--report-performance"', job) + self.assertIn('"${{ github.event_name }}" == "workflow_dispatch"', job) + self.assertIn( + '"${{ inputs.enforce_private_kv_performance }}" == "true"', job + ) + + def test_runtime_columns_probe_runs_in_cuda_ci(self): + workflow = (ROOT / ".github/workflows/cuda.yml").read_text() + job = workflow.split(" unittest-cuda-muse-glimmer-batching:", 1)[1].split( + " unittest-cuda-quantized-gemm:", 1 + )[0] + self.assertIn("-DMUSE_GLIMMER_BUILD_RUNTIME_KV_PROBE=ON", job) + self.assertIn("muse_glimmer_runtime_kv_probe --parallel", job) + self.assertIn("tests/check_runtime_kv_columns.py", job) + self.assertIn("-DEXECUTORCH_ENABLE_LOGGING=OFF", job) + self.assertIn("cmake --build --preset llm-release-cuda-install", job) + def test_e2e_builds_smoke_before_running_it(self): script = (SCRIPTS / "test_model_e2e.sh").read_text() build = script.index("bash .ci/scripts/build_muse_glimmer_batching_smoke.sh") diff --git a/.github/workflows/cuda.yml b/.github/workflows/cuda.yml index 03b39180db4..5df66b13156 100644 --- a/.github/workflows/cuda.yml +++ b/.github/workflows/cuda.yml @@ -63,6 +63,11 @@ on: required: false type: string default: "50" + enforce_private_kv_performance: + description: Fail private-KV qualification on more than 2% throughput regression + required: false + type: boolean + default: false concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref_name }}-${{ github.ref_type == 'branch' && github.sha }}-${{ github.event_name == 'workflow_dispatch' }}-${{ github.event_name == 'schedule' }} @@ -695,13 +700,19 @@ jobs: # The normal serving binaries and the opt-in correctness tool share # CudaExecutor; MG preparation tests also run on Linux. - make muse-glimmer-batching-cuda + # Capture qualification uses native counters in the release build. + cmake --preset llm-release-cuda -DEXECUTORCH_ENABLE_LOGGING=OFF + cmake --build --preset llm-release-cuda-install BATCHING_BIN_DIR="${PWD}/cmake-out/examples/models/muse-glimmer-batching" - cmake -S "${PWD}/examples/models/muse-glimmer" -B "${BATCHING_BIN_DIR}" \ - -DMUSE_GLIMMER_BUILD_BATCHING_TESTS=ON + cmake -S "${PWD}/examples/models/muse-glimmer" --preset muse-glimmer-cuda \ + -B "${BATCHING_BIN_DIR}" -DMUSE_GLIMMER_BUILD_BATCHING=ON \ + -DMUSE_GLIMMER_BUILD_BATCHING_TESTS=ON \ + -DMUSE_GLIMMER_BUILD_RUNTIME_KV_PROBE=ON bash .ci/scripts/build_muse_glimmer_batching_smoke.sh "${BATCHING_BIN_DIR}" cmake --build "${BATCHING_BIN_DIR}" \ - --target muse_glimmer_batching_test muse_glimmer_cuda_dflash_test --parallel + --target muse_glimmer_batching_runner muse_glimmer_batching_worker \ + muse_glimmer_batching_test muse_glimmer_cuda_dflash_test \ + muse_glimmer_runtime_kv_probe --parallel ctest --test-dir "${BATCHING_BIN_DIR}" \ -R '^muse_glimmer_batching$' --output-on-failure --no-tests=error test -x "${BATCHING_BIN_DIR}/muse_glimmer_batching_runner" @@ -710,8 +721,12 @@ jobs: # The batching export on a tiny model, and the CLI's backend dispatch. pip install gguf + python examples/models/muse-glimmer/tests/check_runtime_kv_columns.py \ + --probe "${BATCHING_BIN_DIR}/muse_glimmer_runtime_kv_probe" \ + --output-dir "${RUNNER_TEMP:-/tmp}/muse_glimmer_runtime_kv_columns" python -m pytest -v -o "addopts=" \ examples/models/muse-glimmer/tests/test_cuda_batching_pipeline.py \ + examples/models/muse-glimmer/tests/test_private_kv_rows_gate.py \ examples/models/muse-glimmer/tests/test_cuda_dflash_packed.py \ examples/models/muse-glimmer/tests/test_dflash_token_sampler.py \ examples/models/muse-glimmer/tests/test_checkpoint_context.py @@ -730,6 +745,18 @@ jobs: exit 1 fi + # Automatic jobs report noisy timings; an explicit dispatch can enforce + # the 2% gate. Numerical/memory/graph checks always remain blocking. + PRIVATE_KV_TIMING_ARGS="--report-performance" + if [[ "${{ github.event_name }}" == "workflow_dispatch" && \ + "${{ inputs.enforce_private_kv_performance }}" == "true" ]]; then + PRIVATE_KV_TIMING_ARGS="" + fi + python examples/models/muse-glimmer/tests/check_private_kv_rows.py \ + --probe "${BATCHING_BIN_DIR}/muse_glimmer_runtime_kv_probe" \ + --output-dir "${RUNNER_TEMP:-/tmp}/muse_glimmer_private_kv_rows" \ + ${PRIVATE_KV_TIMING_ARGS} + unittest-cuda-quantized-gemm: name: unittest-cuda-quantized-gemm (${{ matrix.shard }}) needs: [changed-files, run-decision] @@ -772,6 +799,88 @@ jobs: python -m pytest ${{ matrix.tests }} -v -o "addopts=" --durations=20 + unittest-cuda-private-kv-mg-ring: + name: unittest-cuda-private-kv-mg-ring + needs: [changed-files, run-decision] + if: | + contains(needs.changed-files.outputs.changed-files, 'backends/cuda') || + contains(needs.changed-files.outputs.changed-files, 'backends/aoti') || + contains(needs.changed-files.outputs.changed-files, 'extension/llm/batching') || + contains(needs.changed-files.outputs.changed-files, 'extension/llm/cache') || + contains(needs.changed-files.outputs.changed-files, 'examples/models/muse-glimmer') || + contains(needs.changed-files.outputs.changed-files, '.github/workflows/cuda.yml') || + needs.run-decision.outputs.is-full-run == 'true' + uses: pytorch/test-infra/.github/workflows/linux_job_v3.yml@main + permissions: + id-token: write + contents: read + with: + timeout: 180 + # Production Ring geometry needs room for ABI 2's temporary replacement + # allocations as well as ABI 3's bounded host undo history. + runner: mt-l-x86iavx512-11-125-a100 + gpu-arch-type: cuda + gpu-arch-version: "13.2" + submodules: recursive + upload-artifact: cuda-private-kv-mg-ring + ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} + script: | + set -eux + bash ./install_executorch.sh + conda install -y -c conda-forge 'libstdcxx-ng>=12' + export LD_LIBRARY_PATH=/opt/conda/lib:$LD_LIBRARY_PATH + pip install gguf + export PYTHONUNBUFFERED=1 + + python - <<'PY' + import torch + + assert torch.cuda.get_device_capability() == (8, 0) + print(torch.cuda.get_device_properties(0)) + PY + + # A100 exercises D=256's unchanged multi-stage pipeline as well. + python -m pytest backends/cuda/tests/test_sdpa_varlen_private.py::PrivateVarlenTest::test_muse_glimmer_and_gemma_head_geometry backends/cuda/tests/test_sdpa_varlen_private.py::PrivateVarlenTest::test_restored_ring_does_not_read_unwritten_nan_slot -v -o "addopts=" + + cmake --preset llm-release-cuda -DEXECUTORCH_ENABLE_LOGGING=OFF + cmake --build --preset llm-release-cuda-install + BATCHING_BIN_DIR="${PWD}/cmake-out/examples/models/muse-glimmer-batching" + cmake -S "${PWD}/examples/models/muse-glimmer" --preset muse-glimmer-cuda \ + -B "${BATCHING_BIN_DIR}" -DMUSE_GLIMMER_BUILD_BATCHING=ON \ + -DMUSE_GLIMMER_BUILD_RUNTIME_KV_PROBE=ON + cmake --build "${BATCHING_BIN_DIR}" \ + --target muse_glimmer_runtime_kv_probe --parallel + + PRIVATE_KV_TIMING_ARGS="--report-performance" + if [[ "${{ github.event_name }}" == "workflow_dispatch" && \ + "${{ inputs.enforce_private_kv_performance }}" == "true" ]]; then + PRIVATE_KV_TIMING_ARGS="" + fi + export PRIVATE_KV_PRODUCTION_DIR="${RUNNER_TEMP:-/tmp}/muse_glimmer_private_kv_mg_ring" + PRIVATE_KV_STATUS=0 + python examples/models/muse-glimmer/tests/check_private_kv_rows.py \ + --profile mg-ring \ + --probe "${BATCHING_BIN_DIR}/muse_glimmer_runtime_kv_probe" \ + --output-dir "${PRIVATE_KV_PRODUCTION_DIR}" \ + ${PRIVATE_KV_TIMING_ARGS} || PRIVATE_KV_STATUS=$? + # Keep diagnostics on failure without uploading generated model blobs. + python - <<'PY' + import os + import shutil + from pathlib import Path + + source = Path(os.environ["PRIVATE_KV_PRODUCTION_DIR"]) + destination = Path(os.environ["RUNNER_ARTIFACT_DIR"]) + for path in source.rglob("*"): + if path.is_file() and path.name in ( + "qualification.json", "probe.jsonl", "probe.stderr.log" + ): + target = destination / path.relative_to(source) + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(path, target) + PY + exit "${PRIVATE_KV_STATUS}" + unittest-cuda-runtime: name: unittest-cuda-runtime needs: [changed-files, run-decision] @@ -803,11 +912,12 @@ jobs: python -m pytest \ backends/cuda/tests/test_cuda_weight_metadata.py \ + backends/cuda/tests/test_runtime_owned_kv.py \ backends/cuda/tests/test_merge_ptes.py \ -v -o "addopts=" - cmake --preset llm-release-cuda -DEXECUTORCH_BUILD_TESTS=ON - cmake --build cmake-out --target test_cuda_allocator test_cuda_allocator_exit test_cuda_mutable_state test_cuda_weight_cache test_cuda_output_copy test_cuda_backend_execute test_cuda_sort_rand test_cuda_current_stream test_cuda_kv_cache test_cuda_guard test_cuda_stream_guard test_step_plan test_cuda_executor -j$(nproc) + cmake --preset llm-release-cuda -DEXECUTORCH_BUILD_TESTS=ON -DEXECUTORCH_ENABLE_LOGGING=OFF + cmake --build cmake-out --target test_cuda_allocator test_cuda_allocator_exit test_cuda_mutable_state test_cuda_weight_cache test_cuda_output_copy test_cuda_backend_execute test_cuda_sort_rand test_cuda_current_stream test_cuda_ring_history test_cuda_private_row_layout test_cuda_kv_cache test_cuda_guard test_cuda_stream_guard test_step_plan test_cuda_executor -j$(nproc) ctest --test-dir cmake-out -R test_cuda_allocator --output-on-failure -V ctest --test-dir cmake-out -R test_cuda_mutable_state --output-on-failure -V ctest --test-dir cmake-out -R test_cuda_weight_cache --output-on-failure -V @@ -816,6 +926,8 @@ jobs: ctest --test-dir cmake-out -R test_cuda_sort_rand --output-on-failure -V ctest --test-dir cmake-out -R test_cuda_current_stream --output-on-failure -V ctest --test-dir cmake-out -R test_cuda_kv_cache --output-on-failure -V + ctest --test-dir cmake-out -R '^test_cuda_ring_history$' --output-on-failure --no-tests=error -V + ctest --test-dir cmake-out -R '^test_cuda_private_row_layout$' --output-on-failure --no-tests=error -V ctest --test-dir cmake-out -R test_step_plan --output-on-failure -V # CudaExecutor end to end on a toy decoder, against its eager greedy # output. The test skips without the model, so fail if it skipped. diff --git a/backends/aoti/aoti_backend.py b/backends/aoti/aoti_backend.py index 785d89d9c9f..ed64301c51a 100644 --- a/backends/aoti/aoti_backend.py +++ b/backends/aoti/aoti_backend.py @@ -140,6 +140,14 @@ def get_extra_aoti_compile_context_manager( """ return contextlib.nullcontext() + @classmethod + def get_aoti_program_compile_context_manager(cls, program, compile_specs): + """Scope compilation to the final, lowered program's buffer identities. + + Preserve existing subclasses' compile-spec-only context hook. + """ + return cls.get_extra_aoti_compile_context_manager(compile_specs) + @classmethod def codesign_so(cls, so_path: str, compile_specs: List[CompileSpec]) -> None: """Sign the compiled .so before packing into .pte. @@ -356,7 +364,9 @@ def preprocess( # Compile with fallback kernel collection with cls.collect_unsupported_fallback_kernels( missing_fallback_kernels - ), torch.no_grad(), cls.get_extra_aoti_compile_context_manager(compile_specs): + ), torch.no_grad(), cls.get_aoti_program_compile_context_manager( + device_edge_program, compile_specs + ): paths = torch._inductor.aot_compile( edge_program_module, tuple(user_input_placeholders), options=options ) diff --git a/backends/cuda/BUCK b/backends/cuda/BUCK index cf7eda172e3..3a07a34fad4 100644 --- a/backends/cuda/BUCK +++ b/backends/cuda/BUCK @@ -124,6 +124,14 @@ fbcode_target( ], ) +fbcode_target( + _kind = runtime.python_library, + name = "runtime_owned_kv", + srcs = ["runtime_owned_kv.py"], + visibility = ["//executorch/backends/cuda/..."], + deps = ["//caffe2:torch"], +) + fbcode_target( _kind = runtime.python_library, name = "cuda_backend", @@ -136,6 +144,7 @@ fbcode_target( deps = [ ":autotune", ":cuda_passes", + ":runtime_owned_kv", ":triton_measured_routing", ":triton_replacement_pass", "//caffe2:torch", @@ -230,6 +239,7 @@ fbcode_target( "triton/kernels/int6_quantized_gemm.py", "triton/kernels/int8_quantized_gemm.py", "triton/kernels/int4_matmul.py", + "triton/kernels/private_kv_write.py", "triton/kernels/quantized_gemm_family.py", "triton/kernels/quantized_gemm_utils.py", "triton/kernels/sdpa.py", diff --git a/backends/cuda/CMakeLists.txt b/backends/cuda/CMakeLists.txt index 9715234c1ad..445ad25da18 100644 --- a/backends/cuda/CMakeLists.txt +++ b/backends/cuda/CMakeLists.txt @@ -506,6 +506,11 @@ if(BUILD_TESTING) runtime/test/test_cuda_backend_execute.cpp EXTRA_LIBS aoti_cuda_backend ) target_compile_definitions(test_cuda_backend_execute PRIVATE CUDA_AVAILABLE=1) + if(EXECUTORCH_BUILD_EXTENSION_LLM) + target_compile_definitions( + test_cuda_backend_execute PRIVATE EXECUTORCH_BUILD_EXTENSION_LLM + ) + endif() # sort.cu and rand.cu are compiled only under this condition (see # _aoti_cuda_shim_sources), so the test that calls them is too. if(NOT EXECUTORCH_BUILD_ROCM AND CMAKE_CUDA_COMPILER) @@ -522,6 +527,14 @@ if(BUILD_TESTING) target_compile_definitions(test_cuda_current_stream PRIVATE CUDA_AVAILABLE=1) if(EXECUTORCH_BUILD_EXTENSION_LLM) + et_cxx_test( + test_cuda_ring_history SOURCES runtime/test/test_ring_history.cpp + EXTRA_LIBS aoti_cuda_backend + ) + et_cxx_test( + test_cuda_private_row_layout SOURCES + runtime/test/test_private_row_layout.cpp EXTRA_LIBS aoti_cuda_backend + ) et_cxx_test( test_cuda_kv_cache SOURCES runtime/test/test_cuda_kv_cache.cpp EXTRA_LIBS aoti_cuda_backend diff --git a/backends/cuda/batching/cuda_executor.cpp b/backends/cuda/batching/cuda_executor.cpp index b33cb492fbf..bc992e0227e 100644 --- a/backends/cuda/batching/cuda_executor.cpp +++ b/backends/cuda/batching/cuda_executor.cpp @@ -268,7 +268,8 @@ CudaExecutor::CudaExecutor( std::vector methods, int min_selected_rows, bool has_sampler, - bool has_argmax) + bool has_argmax, + bool runtime_columns) : install_guard_(cache), module_(std::move(module)), ctl_(cache->as()), @@ -281,7 +282,8 @@ CudaExecutor::CudaExecutor( min_selected_rows_(min_selected_rows), sessions_(*ctl_, max_sessions, max_session_tokens, vocab_size), has_sampler_(has_sampler), - has_argmax_(has_argmax) {} + has_argmax_(has_argmax), + runtime_columns_(runtime_columns) {} CudaExecutor::~CudaExecutor() { if (device_params_ != nullptr) { @@ -369,6 +371,15 @@ Result> CudaExecutor::create( declared_seqs, metadata::detail::read_int_method(*module, kMaxSeqsMethod)); const bool sequence_layout = declared_seqs.has_value(); + ET_ASSIGN_OR_RETURN( + sequence_info_abi, + metadata::detail::read_int_method(*module, kSequenceInfoABIMethod)); + ET_CHECK_OR_RETURN_ERROR( + sequence_info_abi.value_or(1) == 1 || + ((sequence_info_abi == 2 || sequence_info_abi == 3) && + sequence_layout && !geometry.dflash_block_size.has_value()), + InvalidProgram, + "CudaExecutor: unsupported sequence-info ABI"); std::int64_t max_cells = 0; if (sequence_layout) { ET_CHECK_OR_RETURN_ERROR( @@ -537,14 +548,14 @@ Result> CudaExecutor::create( llm_cache::valid(geometry, cfg), InvalidProgram, "CudaExecutor: the program's layout is unusable"); - auto built = llm_cache::CacheFactory::global().build( - backend_id, - sequence_layout ? llm_cache::kind::kBatchedSequence - : llm_cache::kind::kBatchedCell, - geometry, - cfg); - ET_CHECK_OK_OR_RETURN_ERROR(built.error()); - std::shared_ptr cache = built.get(); + const char* kind = sequence_info_abi == 3 + ? llm_cache::kind::kBatchedSequencePrivate + : sequence_info_abi == 2 ? llm_cache::kind::kBatchedSequenceRuntime + : sequence_layout ? llm_cache::kind::kBatchedSequence + : llm_cache::kind::kBatchedCell; + ET_ASSIGN_OR_RETURN( + cache, + llm_cache::CacheFactory::global().build(backend_id, kind, geometry, cfg)); auto* const ctl = cache->as(); ET_CHECK_OR_RETURN_ERROR( ctl != nullptr && cache->as() != nullptr, @@ -588,7 +599,8 @@ Result> CudaExecutor::create( std::move(methods), min_selected_rows, has_sampler, - has_argmax)); + has_argmax, + sequence_info_abi == 2 || sequence_info_abi == 3)); executor->embeddings_method_ = embeddings_method; return executor; } @@ -640,14 +652,17 @@ bool CudaExecutor::initialize() { } std::optional CudaExecutor::open_session() { + last_cache_activity_ = std::chrono::steady_clock::now(); return sessions_.open(); } void CudaExecutor::close_session(SessionId session) { + last_cache_activity_ = std::chrono::steady_clock::now(); sessions_.close(session); } std::optional CudaExecutor::clone(SessionId source, Position upto) { + last_cache_activity_ = std::chrono::steady_clock::now(); return sessions_.clone(source, upto); } @@ -680,7 +695,7 @@ Error CudaExecutor::set_input_embedder(InputEmbedder embedder) { bool CudaExecutor::execute_raw( const RawTargetStep& step, const std::function& consume) { - if (!initialized_ || raw_executing_ || !consume || + if (raw_executing_ || !initialized_ || !consume || step.tokens.size() > static_cast(std::numeric_limits::max()) || step.positions.size() != step.tokens.size() || @@ -699,19 +714,16 @@ bool CudaExecutor::execute_raw( return false; } } - struct Reset { - explicit Reset(bool& target) : flag(target) { - flag = true; - } - Reset(const Reset&) = delete; - Reset& operator=(const Reset&) = delete; - Reset(Reset&&) = delete; - Reset& operator=(Reset&&) = delete; - ~Reset() { - flag = false; + last_cache_activity_ = std::chrono::steady_clock::now(); + raw_executing_ = true; + struct ExecutionScope { + bool& executing; + std::chrono::steady_clock::time_point& activity; + ~ExecutionScope() { + executing = false; + activity = std::chrono::steady_clock::now(); } - bool& flag; - } reset(raw_executing_); + } execution_scope{raw_executing_, last_cache_activity_}; if (step.embeddings) { return execute_embeddings(step, consume); } @@ -1089,6 +1101,41 @@ OffGraphKVMetrics CudaExecutor::kv_metrics() const { return kv_->metrics(); } +CudaGraphMetrics CudaExecutor::graph_metrics(std::string_view method) const { + return kv_->graph_metrics(method); +} + +Error CudaExecutor::compact_kv_columns(int spare_columns) { + ET_CHECK_OR_RETURN_ERROR( + !raw_executing_, InvalidState, "CudaExecutor: compact between executes"); + return kv_->compact_columns(spare_columns); +} + +void CudaExecutor::on_idle() { + if (!runtime_columns_) { + return; + } + if (raw_executing_ || + std::chrono::steady_clock::now() - last_cache_activity_ < + std::chrono::milliseconds(500)) { + return; + } + const auto metrics = kv_->metrics(); + if (metrics.physical_columns <= 2 || + 2 * metrics.live_sequences + 1 >= metrics.physical_columns) { + return; + } + last_cache_activity_ = std::chrono::steady_clock::now(); + const Error error = + kv_->compact_columns(static_cast(metrics.live_sequences)); + if (error != Error::Ok) { + ET_LOG( + Error, + "CudaExecutor: idle KV compaction failed (%d)", + static_cast(error)); + } +} + std::vector CudaExecutor::method_calls() const { std::vector calls; calls.reserve(methods_.size() + 1); diff --git a/backends/cuda/batching/cuda_executor.h b/backends/cuda/batching/cuda_executor.h index 4e0cf7bc7da..0ee47f917b6 100644 --- a/backends/cuda/batching/cuda_executor.h +++ b/backends/cuda/batching/cuda_executor.h @@ -17,13 +17,17 @@ // and optionally one dynamic `forward_others` for anything wider. Each forward // runs the method with the smallest width that holds it; a static method's // extra rows are padding. +// All execution, session and maintenance calls are confined to the engine +// thread, matching Executor. execute_raw rejects re-entrant execution. +#include #include #include #include #include #include #include +#include #include #include @@ -51,6 +55,10 @@ inline constexpr char kMaxCellsMethod[] = "get_offgraph_kv_max_cells"; // Published instead of the cell count by a program whose KV cache keeps a // private history per sequence. inline constexpr char kMaxSeqsMethod[] = "get_offgraph_kv_max_seqs"; +// Optional: seq_info field layout. Defaults to ABI 1 (fixed columns). +inline constexpr char kSequenceInfoABIMethod[] = + "get_offgraph_kv_sequence_info_abi"; + // Optional: the fewest selected rows forward_others was exported for. Its // selector is padded up to it. Defaults to 1. inline constexpr char kMinSelectedRowsMethod[] = "get_min_prefill_chunk"; @@ -227,6 +235,13 @@ class ET_EXPERIMENTAL CudaExecutor : public llm_batching::Executor { // The cache's pool usage, for memory reporting. OffGraphKVMetrics kv_metrics() const; + // Read between executes, on the engine thread. + CudaGraphMetrics graph_metrics(std::string_view method) const; + // Engine-thread only, between execute calls. A call from execute_raw's + // consumer is rejected. The scratch column is additional to spare_columns + // unused owner columns; compaction never increases the physical width. + ::executorch::runtime::Error compact_kv_columns(int spare_columns = 1); + void on_idle() override; // Every method, narrowest first, with how many forwards it ran. Read it // between executes, not while one runs. @@ -252,7 +267,8 @@ class ET_EXPERIMENTAL CudaExecutor : public llm_batching::Executor { std::vector methods, int min_selected_rows, bool has_sampler, - bool has_argmax); + bool has_argmax, + bool runtime_columns); // Draws one token per row of `logits`, rows [0, sessions.size()), on the // device; returns them in row order. @@ -273,7 +289,7 @@ class ET_EXPERIMENTAL CudaExecutor : public llm_batching::Executor { llm_cache::InstallGuard install_guard_; std::unique_ptr<::executorch::extension::Module> module_; llm_cache::BatchControl* const ctl_; - const CudaKVCache* const kv_; + CudaKVCache* const kv_; std::string backend_id_; std::int32_t vocab_size_; int max_session_tokens_; @@ -293,6 +309,7 @@ class ET_EXPERIMENTAL CudaExecutor : public llm_batching::Executor { llm_batching::util::SessionTable sessions_; bool has_sampler_; bool has_argmax_; + const bool runtime_columns_; // Device staging for the sampler's params, grown to the widest row count. void* device_params_ = nullptr; std::size_t device_params_rows_ = 0; @@ -301,6 +318,8 @@ class ET_EXPERIMENTAL CudaExecutor : public llm_batching::Executor { std::optional device_logits_; bool initialized_ = false; bool raw_executing_ = false; + std::chrono::steady_clock::time_point last_cache_activity_ = + std::chrono::steady_clock::now(); }; } // namespace executorch::backends::cuda::batching diff --git a/backends/cuda/cuda_backend.py b/backends/cuda/cuda_backend.py index ba8aa3cf1f9..87456126340 100644 --- a/backends/cuda/cuda_backend.py +++ b/backends/cuda/cuda_backend.py @@ -40,6 +40,7 @@ CheckOffGraphKVStepWidthPass, LowerOffGraphKVPass, OFFGRAPH_KV_COMPILE_SPEC, + OFFGRAPH_KV_FQN_PREFIX, OFFGRAPH_KV_STEP_WIDTH_COMPILE_SPEC, PACKED_LAYOUTS, parse_offgraph_kv_manifest, @@ -57,6 +58,7 @@ from executorch.backends.cuda.passes.replace_masked_copy_with_where import ( ReplaceMaskedCopyWithWherePass, ) +from executorch.backends.cuda.runtime_owned_kv import RuntimeOwnedKVCompileBuffers from executorch.backends.cuda.target_smem import target_smem_context from executorch.backends.cuda.triton.kernels import triton_mutation_cache from executorch.backends.cuda.triton.measured_routing import ( @@ -585,6 +587,7 @@ def _compile_time_cpu_clones(target_device: torch.device): # noqa: C901 orig_clone = _cfx.clone_preserve_strides orig_codegen_device = _Cpp.codegen_device + orig_codegen_model_constructor = _Cpp.codegen_model_constructor orig_get_const = _GL.get_original_value_of_constant orig_is_same = _graph.is_same_tensor orig_tensor_properties = _codecache.TensorProperties @@ -624,6 +627,9 @@ def _cpu_clone_preserve_strides(x: torch.Tensor) -> torch.Tensor: # content is all zeros, so re-synthesize zeros (on CPU, strides # preserved) instead of cloning the now-empty storage. if _is_emptied(x): + runtime_owned = getattr(_CPU_CLONE_GUARD, "runtime_owned_kv", None) + if runtime_owned is not None and runtime_owned.owns_empty(x): + return runtime_owned.cpu_placeholder(x) return _full_zeros_preserving_strides(x, "cpu") return orig_clone(x).cpu() return orig_clone(x) @@ -650,6 +656,11 @@ def _get_const_synthesize_zeros(self, name): # holds a correctly-zeroed KV cache. value = orig_get_const(self, name) if _is_emptied(value): + runtime_owned = getattr(_CPU_CLONE_GUARD, "runtime_owned_kv", None) + if runtime_owned is not None and runtime_owned.owns_empty(value): + # The structured collector retains this FQN's view metadata, + # but the runtime supplies its bytes; no zero blob is needed. + return value return _full_zeros_preserving_strides(value, "cpu") return value @@ -666,8 +677,37 @@ def _codegen_device_target_aware(self, device): device = target_device return orig_codegen_device(self, device) + def _codegen_model_constructor_with_owned_sizes(self): + runtime_owned = getattr(_CPU_CLONE_GUARD, "runtime_owned_kv", None) + if ( + runtime_owned is None + or not _is_cpu_clone_active() + or getattr(_CPU_CLONE_GUARD, "constant_info_active", False) + ): + return orig_codegen_model_constructor(self) + from torch._inductor.virtualized import V + + constants = [ + (name, V.graph.get_original_value_of_constant(name)) + for name in V.graph.constants + ] + all_cuda = all( + tensor.is_cuda + for name, tensor in constants + if name not in V.graph.folded_constants + ) + _CPU_CLONE_GUARD.constant_info_active = True + try: + with runtime_owned.constant_info_sizes( + self, [tensor for _, tensor in constants], 1 if all_cuda else 64 + ): + return orig_codegen_model_constructor(self) + finally: + _CPU_CLONE_GUARD.constant_info_active = False + _cfx.clone_preserve_strides = _cpu_clone_preserve_strides _Cpp.codegen_device = _codegen_device_target_aware + _Cpp.codegen_model_constructor = _codegen_model_constructor_with_owned_sizes _GL.get_original_value_of_constant = _get_const_synthesize_zeros _graph.is_same_tensor = _is_same_skip_emptied _codecache.TensorProperties = functools.partial( @@ -683,6 +723,7 @@ def _codegen_device_target_aware(self, device): _CPU_CLONE_GUARD.active = prev_active _cfx.clone_preserve_strides = orig_clone _Cpp.codegen_device = orig_codegen_device + _Cpp.codegen_model_constructor = orig_codegen_model_constructor _GL.get_original_value_of_constant = orig_get_const _graph.is_same_tensor = orig_is_same _codecache.TensorProperties = orig_tensor_properties @@ -1681,6 +1722,22 @@ def get_aoti_compile_options( ), "shim_library_path should not be set for Linux" return options + @classmethod + @contextlib.contextmanager + def get_aoti_program_compile_context_manager(cls, program, compile_specs): + # The lowering pass creates runtime-owned buffers after device move. + # Inspect the final program, including any decompositions, rather than + # the earlier list of moved parameters or a compile-spec-only flag. + previous = getattr(_CPU_CLONE_GUARD, "runtime_owned_kv", None) + _CPU_CLONE_GUARD.runtime_owned_kv = RuntimeOwnedKVCompileBuffers( + program, OFFGRAPH_KV_FQN_PREFIX + ) + try: + with cls.get_extra_aoti_compile_context_manager(compile_specs): + yield + finally: + _CPU_CLONE_GUARD.runtime_owned_kv = previous + @classmethod def get_extra_aoti_compile_context_manager( cls, compile_specs: Optional[List[CompileSpec]] = None diff --git a/backends/cuda/passes/lower_offgraph_kv.py b/backends/cuda/passes/lower_offgraph_kv.py index 15c994a9708..81ffa6076fd 100644 --- a/backends/cuda/passes/lower_offgraph_kv.py +++ b/backends/cuda/passes/lower_offgraph_kv.py @@ -10,12 +10,17 @@ from typing import Any import torch +from executorch.backends.cuda.triton.kernels.private_kv_write import ( # noqa: F401 + private_kv_stage, + private_kv_write, +) # Imported for its registration side effect: the decomposition calls # torch.ops.triton.sdpa, which only exists once this module has been loaded. from executorch.backends.cuda.triton.kernels.sdpa import sdpa # noqa: F401 from executorch.backends.cuda.triton.kernels.sdpa_varlen import ( # noqa: F401 sdpa_varlen, + sdpa_varlen_private, ) from executorch.backends.transforms.utils import create_constant_placeholder from executorch.exir.dialects._ops import ops as exir_ops @@ -25,6 +30,7 @@ OFFGRAPH_KV_COMPILE_SPEC = "offgraph_kv_manifest" +OFFGRAPH_KV_SEQUENCE_INFO_ABI_METHOD = "get_offgraph_kv_sequence_info_abi" # Consumed by the runtime, not by this pass: "input_index:dim" naming # the input whose extent is the number of tokens a step writes. OFFGRAPH_KV_STEP_WIDTH_COMPILE_SPEC = "offgraph_kv_step_width" @@ -45,6 +51,8 @@ # forward. Declared once per program at a fixed shape, like the cell buffers. OFFGRAPH_KV_SEQ_COLS_FQN = OFFGRAPH_KV_FQN_PREFIX + "seq_cols" OFFGRAPH_KV_SEQ_INFO_FQN = OFFGRAPH_KV_FQN_PREFIX + "seq_info" +OFFGRAPH_KV_OWNER_STEP_FQN = OFFGRAPH_KV_FQN_PREFIX + "owner_step" +OFFGRAPH_KV_STAGE_ROWS_FQN = OFFGRAPH_KV_FQN_PREFIX + "stage_rows" # Layouts whose step packs tokens of several sequences on one axis. PACKED_LAYOUTS = ("cell", "batched-sequence") @@ -95,6 +103,16 @@ def parse_offgraph_kv_manifest(value: bytes) -> dict[str, Any]: # noqa: C901 layout = manifest.setdefault("layout", "sequence") if layout not in ("sequence", *PACKED_LAYOUTS): raise ValueError(f"invalid off-graph KV layout {layout!r}") + runtime_columns = manifest.setdefault("runtime_columns", False) + if not isinstance(runtime_columns, bool): + raise ValueError("off-graph runtime_columns must be a bool") + if runtime_columns and layout != "batched-sequence": + raise ValueError("off-graph runtime columns require batched-sequence layout") + private_rows = manifest.setdefault("private_rows", False) + if not isinstance(private_rows, bool): + raise ValueError("off-graph private_rows must be a bool") + if private_rows and (layout != "batched-sequence" or runtime_columns): + raise ValueError("private rows require batched-sequence layout without ABI 2") if layout == "batched-sequence": for key in ("max_seqs", "max_segments"): if not isinstance(manifest.get(key), int) or manifest[key] <= 0: @@ -112,6 +130,12 @@ def parse_offgraph_kv_manifest(value: bytes) -> dict[str, Any]: # noqa: C901 raise ValueError("off-graph context_window must be a bool") if manifest["context_window"] and manifest["causal"]: raise ValueError("off-graph context_window requires non-causal attention") + if runtime_columns and manifest["context_window"]: + raise ValueError("off-graph runtime columns do not support context_window") + if private_rows and (manifest["context_window"] or not manifest["causal"]): + raise ValueError( + "private rows do not support draft or non-causal attention" + ) if layout == "cell": # A cell step packs tokens of several sequences into the shared pool, # so the pool bounds its width, not one sequence's capacity. @@ -139,6 +163,19 @@ def parse_offgraph_kv_manifest(value: bytes) -> dict[str, Any]: # noqa: C901 return manifest +def offgraph_kv_constant_methods(value: bytes) -> dict[str, int]: + """Runtime sequence metadata derived from the lowering manifest.""" + manifest = parse_offgraph_kv_manifest(value) + if manifest["layout"] != "batched-sequence": + return {} + return { + "get_offgraph_kv_max_seqs": manifest["max_seqs"], + OFFGRAPH_KV_SEQUENCE_INFO_ABI_METHOD: ( + 3 if manifest["private_rows"] else 2 if manifest["runtime_columns"] else 1 + ), + } + + def ring_attention_mask( position: torch.Tensor, buf_size: int, window: int ) -> torch.Tensor: @@ -297,11 +334,13 @@ def batched_sequence_step( causal: bool, out_dtype: torch.dtype | None = None, context_window: bool = False, + runtime_columns: bool = False, ) -> torch.Tensor: """Write this step's K/V into each sequence's column, then attend. The storage is declared ``[1, rows * columns, H, D]``: row ``r`` of - column ``c`` is slot ``r * columns + c``, so it is ``[rows, columns, H, D]`` + column ``c`` is slot ``r * pitch + c``, where ``pitch`` is ``columns`` + for ABI 1 and ``seq_info[0, 4]`` for ABI 2. It is ``[rows, pitch, H, D]`` and grows by whole rows, as the sequence layout's does. Token ``i`` lands in column ``seq_cols[i]`` at row ``position % rows`` (a ring layer's rows wrap; a flat layer's never do). ``seq_info`` names each segment's query @@ -311,9 +350,12 @@ def batched_sequence_step( K/V-width entries. ``k``/``v`` are BHSD; the storage is BSHD. ``context_window`` gives every draft block query the same retained context before the block; ordinary attention uses each query's own window. + With ``runtime_columns``, 5-wide ABI-2 ``seq_info[:, 4]`` supplies the physical + pitch for writes and attention; ``columns`` remains the declared maximum. """ position = position.reshape(-1) - slots = (position % rows) * columns + seq_cols[: k.shape[2]] + pitch = seq_info[0, 4].to(torch.int64) if runtime_columns else columns + slots = (position % rows) * pitch + seq_cols[: k.shape[2]] _write(k_storage, slots, k) _write(v_storage, slots, v) heads, dim = k_storage.shape[2], k_storage.shape[3] @@ -333,6 +375,67 @@ def batched_sequence_step( return out +def _private_batched_sequence_step_fn(scale, rows, columns, window, ring, out_dtype): + def fn( + q, + k, + v, + position, + k_storage, + v_storage, + seq_cols, + seq_info, + owner_layout, + owner_step, + stage_rows, + k_stage, + v_stage, + ): + position = position.reshape(-1) + if ring: + torch.ops.triton.private_kv_stage(k, v, stage_rows, k_stage, v_stage) + else: + torch.ops.triton.private_kv_write( + k, + v, + position, + seq_cols, + owner_layout, + owner_step, + k_storage, + v_storage, + ) + heads, dim = k_storage.shape[2:] + out = torch.ops.triton.sdpa_varlen_private( + q, + k_storage.view(rows, columns, heads, dim), + v_storage.view(rows, columns, heads, dim), + seq_info, + owner_layout, + owner_step, + k_stage, + v_stage, + scale, + window, + rows if ring else 0, + ) + if ring: + torch.ops.triton.private_kv_write( + k, + v, + position, + seq_cols, + owner_layout, + owner_step, + k_storage, + v_storage, + True, + ) + return out if out_dtype is None else out.to(out_dtype) + + return fn + + def _batched_sequence_step_fn( scale: float, rows: int, @@ -342,6 +445,7 @@ def _batched_sequence_step_fn( causal: bool, out_dtype, context_window: bool = False, + runtime_columns: bool = False, ): def fn(q, k, v, position, k_storage, v_storage, seq_cols, seq_info): return batched_sequence_step( @@ -361,6 +465,7 @@ def fn(q, k, v, position, k_storage, v_storage, seq_cols, seq_info): causal, out_dtype, context_window, + runtime_columns, ) return fn @@ -737,13 +842,68 @@ def _lower_batched_sequence( seq_info = self._cell_buffer( exported_program, OFFGRAPH_KV_SEQ_INFO_FQN, - (self._manifest["max_segments"], 4), + ( + self._manifest["max_segments"], + 5 if self._manifest["runtime_columns"] else 4, + ), torch.int32, device, ) call_args = (*node.args[0:4], k_storage, v_storage, seq_cols, seq_info) - example_args = tuple(n.meta["val"] for n in call_args) ring = layer["policy"] == "ring" + if self._manifest.get("private_rows", False): + prefix = f"{OFFGRAPH_KV_FQN_PREFIX}layer_{layer['layer_id']}" + layout = self._cell_buffer( + exported_program, + f"{prefix}_owner_layout", + (self._columns, 2), + torch.int32, + device, + ) + owner_step = self._cell_buffer( + exported_program, + OFFGRAPH_KV_OWNER_STEP_FQN, + (self._columns, 3), + torch.int32, + device, + ) + stage_rows = seq_cols + stages = (k_storage, v_storage) + if ring: + stage_rows = self._cell_buffer( + exported_program, + OFFGRAPH_KV_STAGE_ROWS_FQN, + (self._manifest["max_write"],), + torch.int64, + device, + ) + kv = node.args[1].meta["val"] + shape = (1, self._manifest["max_write"], kv.shape[1], kv.shape[3]) + stages = tuple( + self._cell_buffer( + exported_program, + f"{prefix}_{lane}_stage", + shape, + kv.dtype, + device, + ) + for lane in ("k", "v") + ) + call_args += (layout, owner_step, stage_rows, *stages) + example_args = tuple(n.meta["val"] for n in call_args) + return ( + _private_batched_sequence_step_fn( + node.args[5], + self._layer_capacity(layer), + self._columns, + layer["window"] if ring else 0, + ring, + out_dtype, + ), + call_args, + example_args, + ) + example_args = tuple(n.meta["val"] for n in call_args) fn = _batched_sequence_step_fn( node.args[5], self._layer_capacity(layer), @@ -753,6 +913,7 @@ def _lower_batched_sequence( self._manifest["causal"], out_dtype, self._manifest.get("context_window", False), + self._manifest["runtime_columns"], ) return fn, call_args, example_args diff --git a/backends/cuda/runtime/cuda_backend.cpp b/backends/cuda/runtime/cuda_backend.cpp index b105363f310..c551cdc0c73 100644 --- a/backends/cuda/runtime/cuda_backend.cpp +++ b/backends/cuda/runtime/cuda_backend.cpp @@ -791,6 +791,16 @@ class ET_EXPERIMENTAL CudaBackend final // the step is driven from here rather than by the runner. int64_t kv_step_width = 0; #if defined(EXECUTORCH_BUILD_EXTENSION_LLM) + bool kv_prepared = false; + executorch::backends::aoti::ScopeGuard abort_kv_step([&]() noexcept { + if (kv_prepared) { + const Error error = handle->kv_cache->abort_step(); + ET_CHECK_OR_LOG_ERROR( + error == Error::Ok, + "offgraph_kv: failed to abort prepared forward"); + (void)error; + } + }); if (handle->kv_cache != nullptr) { const auto step_width = read_offgraph_kv_step_width( handle->kv_step_width, Span(args.data(), n_inputs)); @@ -802,10 +812,20 @@ class ET_EXPERIMENTAL CudaBackend final ET_CHECK_OK_OR_RETURN_ERROR(step_stream.error()); ET_CHECK_OK_OR_RETURN_ERROR( handle->kv_cache->prepare_step(kv_step_width, step_stream.get())); + kv_prepared = true; ET_CHECK_OK_OR_RETURN_ERROR(handle->kv_cache->rebind_for_execute(handle)); } #endif ET_CHECK_OK_OR_RETURN_ERROR(mutable_state_rebind_for_execute(handle)); + const auto commit_kv_step = [&]() { + const Error error = commit_offgraph_kv_step(handle, kv_step_width); +#if defined(EXECUTORCH_BUILD_EXTENSION_LLM) + if (error == Error::Ok) { + kv_prepared = false; + } +#endif + return error; + }; // --------------------------------------------------------------- // CUDA graph REPLAY path — skip all tensor setup and just replay @@ -854,6 +874,7 @@ class ET_EXPERIMENTAL CudaBackend final Internal, "cudaGraphLaunch failed: %s", cudaGetErrorString(gerr)); + ++handle->cuda_graph_state.metrics.replays; // Copy outputs from static buffers into the planned GPU ET buffers (D2D) for (size_t i = 0; i < n_outputs; i++) { @@ -867,7 +888,7 @@ class ET_EXPERIMENTAL CudaBackend final } ET_CUDA_CHECK_OR_RETURN_ERROR(cudaStreamSynchronize(cs)); - return commit_offgraph_kv_step(handle, kv_step_width); + return commit_kv_step(); } const bool is_capture_step = @@ -877,6 +898,7 @@ class ET_EXPERIMENTAL CudaBackend final Error error = run_once( handle, args, n_inputs, n_outputs, is_capture_step, graph_launched); if (error != Error::Ok && is_capture_step && !graph_launched) { + ++handle->cuda_graph_state.metrics.capture_failures; // A capture records kernels without running them, so until the new graph // runs, the inputs and any state the program updates are untouched. A // program that keeps state in host memory, where host code does run @@ -897,7 +919,7 @@ class ET_EXPERIMENTAL CudaBackend final graph_launched); } ET_CHECK_OK_OR_RETURN_ERROR(error); - return commit_offgraph_kv_step(handle, kv_step_width); + return commit_kv_step(); } void destroy(DelegateHandle* handle_) const override { @@ -1298,6 +1320,7 @@ class ET_EXPERIMENTAL CudaBackend final } handle->cuda_graph_state.phase = CudaGraphPhase::Replay; + ++handle->cuda_graph_state.metrics.captures; ET_LOG( Info, "CUDA graph: captured and instantiated for '%s'", @@ -1310,6 +1333,7 @@ class ET_EXPERIMENTAL CudaBackend final Internal, "cudaGraphLaunch (first replay) failed: %s", cudaGetErrorString(gerr)); + ++handle->cuda_graph_state.metrics.replays; graph_launched = true; handle->cuda_graph_state.note_graph_allocations(); diff --git a/backends/cuda/runtime/cuda_delegate_handle.h b/backends/cuda/runtime/cuda_delegate_handle.h index 4c4093e9eb5..2db0f86f876 100644 --- a/backends/cuda/runtime/cuda_delegate_handle.h +++ b/backends/cuda/runtime/cuda_delegate_handle.h @@ -132,10 +132,18 @@ enum class CudaGraphPhase { Replay = 2, }; +struct CudaGraphMetrics { + uint64_t captures{0}; + uint64_t replays{0}; + uint64_t capture_failures{0}; +}; + // All CUDA graph related state grouped into a single struct. struct CudaGraphState { CudaGraphPhase phase = CudaGraphPhase::Disabled; int warmup_remaining = 0; + // Lifetime counts survive release/recapture; read between executions. + CudaGraphMetrics metrics; // Captured graph and executable instance cudaGraph_t graph = nullptr; @@ -259,6 +267,7 @@ struct CudaGraphState { CudaGraphState(CudaGraphState&& other) noexcept : phase(other.phase), warmup_remaining(other.warmup_remaining), + metrics(other.metrics), graph(other.graph), graph_exec(other.graph_exec), static_input_ptrs(std::move(other.static_input_ptrs)), @@ -269,6 +278,7 @@ struct CudaGraphState { graph_allocations(std::move(other.graph_allocations)) { other.graph = nullptr; other.graph_exec = nullptr; + other.metrics = {}; } CudaGraphState& operator=(CudaGraphState&& other) noexcept { @@ -277,6 +287,7 @@ struct CudaGraphState { phase = other.phase; warmup_remaining = other.warmup_remaining; + metrics = other.metrics; graph = other.graph; graph_exec = other.graph_exec; static_input_ptrs = std::move(other.static_input_ptrs); @@ -288,6 +299,7 @@ struct CudaGraphState { other.graph = nullptr; other.graph_exec = nullptr; + other.metrics = {}; } return *this; } diff --git a/backends/cuda/runtime/cuda_kv_cache.cpp b/backends/cuda/runtime/cuda_kv_cache.cpp index 98bc447449c..5e8ea04a114 100644 --- a/backends/cuda/runtime/cuda_kv_cache.cpp +++ b/backends/cuda/runtime/cuda_kv_cache.cpp @@ -9,11 +9,13 @@ #include #include +#include #include #include #include #include #include +#include #include #include #include @@ -23,7 +25,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -38,6 +42,23 @@ namespace slimc10 = ::executorch::backends::aoti::slim::c10; using ::executorch::extension::cuda::CUDAGuard; using ::executorch::runtime::Error; +class CachePhaseTimer final { + public: + explicit CachePhaseTimer(uint64_t& elapsed) + : elapsed_(elapsed), start_(std::chrono::steady_clock::now()) {} + ~CachePhaseTimer() { + elapsed_ += std::chrono::duration_cast( + std::chrono::steady_clock::now() - start_) + .count(); + } + CachePhaseTimer(const CachePhaseTimer&) = delete; + CachePhaseTimer& operator=(const CachePhaseTimer&) = delete; + + private: + uint64_t& elapsed_; + const std::chrono::steady_clock::time_point start_; +}; + bool is_ring(const cache::LayerGeometry& layer) { return layer.policy.kind == cache::LayerPolicy::Kind::Ring; } @@ -190,7 +211,7 @@ class CudaSequenceKVCache final : public cache::SequenceCache, ET_CHECK_OR_RETURN_ERROR( step.has_value(), InvalidArgument, "offgraph_kv: uncommittable step"); cache::SequenceCache::commit(*step); - return pool_.mark_step_done(); + return pool_.mark_step_done(pool_.stream()); } OffGraphKVMetrics metrics() const override { @@ -442,7 +463,7 @@ class CudaCellCache final : public cache::CellCache, public CudaKVCache { ET_CHECK_OR_RETURN_ERROR( !poisoned_ && (!dflash_block_size_ || pending_width_ == 0), InvalidState, - "offgraph_kv: uncommitted or failed draft co-batch; clear required"); + "offgraph_kv: uncommitted step or failed cache operation; clear required"); if (!validated_) { const Error valid = pool_.validate(); if (valid != Error::Ok) { @@ -532,13 +553,13 @@ class CudaCellCache final : public cache::CellCache, public CudaKVCache { write_length > 0, InvalidArgument, "write length must be positive"); ET_CHECK_OK_OR_RETURN_ERROR(error_); if (!dflash_block_size_) { - return pool_.mark_step_done(); + return pool_.mark_step_done(pool_.stream()); } if (poisoned_ || pending_width_ == 0 || write_length != pending_width_) { poisoned_ = true; return Error::InvalidState; } - const Error marked = pool_.mark_step_done(); + const Error marked = pool_.mark_step_done(pool_.stream()); const Error fenced = marked == Error::Ok ? pool_.synchronize() : marked; if (fenced != Error::Ok) { poisoned_ = true; @@ -802,9 +823,10 @@ class CudaCellCache final : public cache::CellCache, public CudaKVCache { // Batched-sequence layout: every sequence keeps a private history in its own // column of each layer's storage, as MLX's batched-sequence cache keeps one // buffer per sequence. A layer's storage is [rows, columns, H, D] (declared -// [1, rows * columns, H, D]): row = the position, or position % rows on a ring -// layer, so each sequence is contiguous by position and attention reads only -// its own column, bounded by its own length. The last column is scratch, +// [1, rows * declared_columns, H, D]): ABI 2 supplies the physical row pitch +// in a fifth seq_info field. Row = the position, or position % rows on a ring +// layer. Attention reads only its own column, bounded by its own length. +// The last column is scratch, // written by static-width padding and never read. // // The neutral SequenceCache plans each sequence: admission against its @@ -813,12 +835,15 @@ class CudaCellCache final : public cache::CellCache, public CudaKVCache { // token's column (seq_cols) and one (q_start, q_len, column, length) row per // run of one sequence's query rows (seq_info) into buffers the program reads // at fixed addresses, so a captured CUDA graph serves any mix of sequences. +// ABI 2 grows owner columns on admission and reserves a final scratch column. // // A DFlash draft step declares, per owner, its new context then its block; // only the block is queried, it sees all of that owner's history, and it is // dropped again after the forward, as on the cell layout. constexpr char kSeqColsFqn[] = "__et_offgraph_kv_seq_cols"; constexpr char kSeqInfoFqn[] = "__et_offgraph_kv_seq_info"; +constexpr char kOwnerStepFqn[] = "__et_offgraph_kv_owner_step"; +constexpr char kStageRowsFqn[] = "__et_offgraph_kv_stage_rows"; constexpr size_t kSeqColsBuffer = 0; constexpr size_t kSeqInfoBuffer = 1; @@ -829,31 +854,77 @@ class CudaBatchedSequenceCache final : public cache::Cache, CudaBatchedSequenceCache( const cache::CacheGeometry& geometry, const cache::CacheConfig& cfg, - slimc10::ScalarType storage_dtype) + slimc10::ScalarType storage_dtype, + bool runtime_columns, + bool private_rows) : geometry_(geometry), cfg_(cfg), max_seqs_(*cfg.max_seqs), - columns_(*cfg.max_seqs + 1), + runtime_columns_(runtime_columns || private_rows), + private_rows_(private_rows), max_write_(*cfg.max_write), max_segments_(batched_sequence_max_segments(*cfg.max_seqs)), + info_width_(runtime_columns ? 5 : 4), dflash_block_size_(geometry.dflash_block_size), + columns_( + private_rows ? 1 + : runtime_columns ? 2 + : *cfg.max_seqs + 1), pool_( - pool_layers(geometry, cfg), - {{kSeqColsFqn, slimc10::ScalarType::Long, {*cfg.max_write}}, - {kSeqInfoFqn, - slimc10::ScalarType::Int, - {batched_sequence_max_segments(*cfg.max_seqs), 4}}}, + pool_layers(geometry, cfg, private_rows), + side_buffers(geometry, cfg, runtime_columns, private_rows), storage_dtype, - static_cast(cfg.initial_capacity) * (*cfg.max_seqs + 1)) { + static_cast(cfg.initial_capacity) * (*cfg.max_seqs + 1), + *cfg.max_seqs + 1, + runtime_columns || private_rows ? 2 : *cfg.max_seqs + 1, + private_rows) { for (const cache::LayerGeometry& layer : geometry.layers) { layer_rows_.push_back(rows_of(layer, cfg)); } + if (private_rows_) { + private_required_.resize( + geometry.layers.size(), std::vector(max_seqs_, 0)); + private_live_.resize(max_seqs_, 0); + archive_staging_.resize(geometry.layers.size(), nullptr); + archive_bytes_.resize(geometry.layers.size(), 0); + const size_t copies = 4 + geometry.layers.size() * 2; + copy_destinations_.reserve(copies); + copy_sources_.reserve(copies); + copy_sizes_.reserve(copies); + int side = has_ring(geometry) ? 4 : 3; + for (const auto& layer : geometry.layers) { + private_layout_buffers_.push_back(side++); + private_stage_buffers_.push_back(is_ring(layer) ? side : -1); + std::unique_ptr history; + if (is_ring(layer)) { + side += 2; + auto result = RingHistory::create( + layer.policy.window, + max_write_, + cfg.capacity, + static_cast(layer.n_kv_heads) * layer.head_dim * + slimc10::elementSize(storage_dtype), + 2); + if (!result.ok()) { + error_ = result.error(); + return; + } + history = std::move(result.get()); + } + histories_.push_back(std::move(history)); + } + } } CudaBatchedSequenceCache(const CudaBatchedSequenceCache&) = delete; CudaBatchedSequenceCache& operator=(const CudaBatchedSequenceCache&) = delete; ~CudaBatchedSequenceCache() override { + if (private_rows_) { + // Undo pages and pinned destinations can still be referenced by a failed + // restore/archive. Drain them before member destruction releases bytes. + (void)pool_.synchronize(/*all_streams=*/true); + } if (staged_ != nullptr) { (void)cudaEventSynchronize(staged_); (void)cudaEventDestroy(staged_); @@ -861,6 +932,11 @@ class CudaBatchedSequenceCache final : public cache::Cache, if (staging_ != nullptr) { (void)cudaFreeHost(staging_); } + for (void* data : archive_staging_) { + if (data != nullptr) { + (void)cudaFreeHost(data); + } + } } // -- CacheControl / BatchControl. @@ -874,7 +950,8 @@ class CudaBatchedSequenceCache final : public cache::Cache, // nor invalidates captured graphs. void clear() override { std::lock_guard guard(mutex_); - if (dflash_block_size_ && pool_.allocated()) { + if ((dflash_block_size_ || runtime_columns_) && + (pool_.allocated() || pool_.requires_clear())) { // A failed forward can be abandoned by a different host thread. Fence // the originating stream before reusing its sequence columns. if (pool_.synchronize(/*all_streams=*/true) != Error::Ok) { @@ -887,18 +964,31 @@ class CudaBatchedSequenceCache final : public cache::Cache, seqs_.clear(); step_seq_ids_.clear(); pending_owners_.clear(); + pending_runs_.clear(); + pending_width_ = 0; + for (auto& history : histories_) { + if (history) { + history->clear(); + } + } + pool_.reset_failure_after_clear(); poisoned_ = false; + inflight_ = false; } bool declare_step(const std::vector& seq_ids) override { std::lock_guard guard(mutex_); + if (private_rows_ && (poisoned_ || inflight_)) { + return false; + } if (seq_ids.empty() || seq_ids.size() > static_cast(max_write_)) { return false; } std::map counts; int runs = 0; for (size_t i = 0; i < seq_ids.size(); ++i) { - if (seqs_.count(seq_ids[i]) == 0) { + const auto sequence = seqs_.find(seq_ids[i]); + if (sequence == seqs_.end() || sequence->second.failed) { return false; } ++counts[seq_ids[i]]; @@ -929,13 +1019,24 @@ class CudaBatchedSequenceCache final : public cache::Cache, std::optional seq_new() override { std::lock_guard guard(mutex_); - const auto column = free_column(); - if (!column) { + const auto id = free_sequence_id(); + if (!id || poisoned_ || (runtime_columns_ && inflight_)) { + return std::nullopt; + } + const int column = runtime_columns_ && !private_rows_ ? -1 : *id; + seqs_.emplace(*id, Sequence{column, cache::SequenceCache(geometry_, cfg_)}); + bool admitted = false; + aoti::ScopeGuard rollback([&]() noexcept { + if (!admitted) { + seqs_.erase(*id); + } + }); + if (runtime_columns_ && !private_rows_ && + ensure_columns(false, 0, cudaStreamPerThread) != Error::Ok) { return std::nullopt; } - seqs_.emplace( - *column, Sequence{*column, cache::SequenceCache(geometry_, cfg_)}); - return *column; + admitted = true; + return *id; } // Copies the retained prefix into a free column: a sequence's history is @@ -944,8 +1045,9 @@ class CudaBatchedSequenceCache final : public cache::Cache, override { std::lock_guard guard(mutex_); const auto source = seqs_.find(src); - const auto column = free_column(); - if (source == seqs_.end() || !column || !pool_.allocated()) { + const auto id = free_sequence_id(); + if (source == seqs_.end() || source->second.failed || !id || + !pool_.allocated() || poisoned_ || (runtime_columns_ && inflight_)) { return std::nullopt; } // The copies below run on this thread's stream, which may not be the @@ -958,23 +1060,95 @@ class CudaBatchedSequenceCache final : public cache::Cache, const int length = source->second.plan.length(); const int keep = std::min(upto.value_or(length), length); cache::SequenceCache plan(source->second.plan); - if (keep <= 0 || !plan.rewind(keep) || - copy_column(source->second.column, *column, keep) != Error::Ok || - pool_.mark_step_done() != Error::Ok) { + if (keep <= 0 || !plan.rewind(keep)) { return std::nullopt; } - seqs_.emplace(*column, Sequence{*column, std::move(plan)}); - return *column; + if (private_rows_) { + return clone_private(src, *id, keep, std::move(plan)); + } + const int column = runtime_columns_ ? -1 : *id; + seqs_.emplace(*id, Sequence{column, std::move(plan)}); + bool admitted = false; + aoti::ScopeGuard rollback([&]() noexcept { + if (!admitted) { + seqs_.erase(*id); + } + }); + if (runtime_columns_ && + ensure_columns(false, 0, cudaStreamPerThread) != Error::Ok) { + return std::nullopt; + } + const cudaStream_t stream = + runtime_columns_ ? cudaStreamPerThread : pool_.stream(); + if (copy_column( + source->second.column, seqs_.at(*id).column, keep, stream) != + Error::Ok || + pool_.mark_step_done(stream) != Error::Ok) { + // A failed ABI-2 copy must finish before its column can be reused. + if (runtime_columns_ && + pool_.synchronize(/*all_streams=*/true) != Error::Ok) { + poisoned_ = true; + } + return std::nullopt; + } + admitted = true; + return *id; } bool seq_rm(int32_t seq_id) override { std::lock_guard guard(mutex_); + if (private_rows_) { + if (inflight_ || poisoned_) { + return false; + } + if (pool_.allocated() && + pool_.synchronize(/*all_streams=*/true) != Error::Ok) { + poisoned_ = true; + return false; + } + for (auto& history : histories_) { + if (history) { + history->erase(seq_id); + } + } + } + if (std::find(step_seq_ids_.begin(), step_seq_ids_.end(), seq_id) != + step_seq_ids_.end()) { + step_seq_ids_.clear(); + } + // Logical removal does not free storage; verbs run between forwards. return seqs_.erase(seq_id) > 0; } bool rewind(int32_t seq_id, int position) override { std::lock_guard guard(mutex_); const auto it = seqs_.find(seq_id); + if (private_rows_) { + if (it == seqs_.end() || it->second.failed || inflight_ || poisoned_) { + return false; + } + cache::SequenceCache plan(it->second.plan); + if (!plan.rewind(position)) { + return false; + } + if (position == it->second.plan.length()) { + return true; + } + if (restore_private(seq_id, seq_id, position) != Error::Ok) { + it->second.failed = true; + return false; + } + for (auto& history : histories_) { + if (history && position > 0 && !history->rewind(seq_id, position)) { + poisoned_ = true; + return false; + } + if (history && position == 0) { + history->erase(seq_id); + } + } + return it->second.plan.rewind(position); + } return it != seqs_.end() && it->second.plan.rewind(position); } @@ -1015,11 +1189,14 @@ class CudaBatchedSequenceCache final : public cache::Cache, Error prepare_step(int64_t write_length, cudaStream_t stream) override { std::lock_guard guard(mutex_); + const CachePhaseTimer timer(prepare_time_ns_); ET_CHECK_OK_OR_RETURN_ERROR(error_); ET_CHECK_OR_RETURN_ERROR( !poisoned_ && (!dflash_block_size_ || pending_owners_.empty()), InvalidState, - "offgraph_kv: uncommitted or failed draft co-batch; clear required"); + "offgraph_kv: uncommitted step or failed cache operation; clear required"); + ET_CHECK_OR_RETURN_ERROR( + !inflight_, InvalidState, "offgraph_kv: a forward is still prepared"); if (!validated_) { const Error valid = pool_.validate(); if (valid != Error::Ok) { @@ -1066,24 +1243,47 @@ class CudaBatchedSequenceCache final : public cache::Cache, for (const auto& [seq_id, end] : ends) { required = std::max(required, end); } - ET_CHECK_OK_OR_RETURN_ERROR(pool_.prepare( - std::min(required, cfg_.capacity) * columns_, - live * columns_, - stream)); + if (runtime_columns_ && !private_rows_) { + ET_CHECK_OR_RETURN_ERROR( + static_cast(seqs_.size()) < columns_, + InvalidState, + "offgraph_kv: admission must provide every owner a column"); + } + if (private_rows_) { + ET_CHECK_OK_OR_RETURN_ERROR(prepare_private(ends, write_length, stream)); + ET_CHECK_OK_OR_RETURN_ERROR(reserve_archive_staging(write_length)); + } else { + ET_CHECK_OK_OR_RETURN_ERROR(pool_.prepare( + std::min(required, cfg_.capacity) * columns_, + live * columns_, + stream)); + } ET_CHECK_OK_OR_RETURN_ERROR(reserve_staging( static_cast(max_write_) * sizeof(int64_t) + - static_cast(max_segments_) * 4 * sizeof(int32_t))); + static_cast(max_segments_) * info_width_ * sizeof(int32_t) + + (private_rows_ ? private_metadata_bytes() : 0))); auto* cols = reinterpret_cast(staging_); auto* info = reinterpret_cast(cols + max_write_); - std::fill(cols, cols + write_length, static_cast(max_seqs_)); - std::fill(info, info + max_segments_ * 4, 0); + std::fill( + cols, + cols + write_length, + static_cast(private_rows_ ? max_seqs_ : columns_ - 1)); + std::fill(info, info + max_segments_ * info_width_, 0); + if (runtime_columns_ && !private_rows_) { + for (int index = 0; index < max_segments_; ++index) { + info[index * info_width_ + 4] = columns_; + } + } + if (private_rows_) { + build_private_step(ends, tokens, static_cast(write_length)); + } int q_start = 0; for (size_t index = 0; index < runs.size(); ++index) { const Run& run = runs[index]; const int column = seqs_.at(run.seq_id).column; std::fill(cols + run.start, cols + run.start + run.length, column); - int32_t* row = info + index * 4; + int32_t* row = info + index * info_width_; const int end = next[run.seq_id] + run.length; next[run.seq_id] = end; // A draft queries only each owner's block, packed owner by owner. @@ -1112,19 +1312,40 @@ class CudaBatchedSequenceCache final : public cache::Cache, } } step_seq_ids_.clear(); + pending_width_ = private_rows_ ? static_cast(write_length) : 0; + inflight_ = runtime_columns_; return Error::Ok; } Error commit_step(int64_t write_length) override { std::lock_guard guard(mutex_); + const CachePhaseTimer timer(commit_time_ns_); ET_CHECK_OR_RETURN_ERROR( write_length > 0, InvalidArgument, "write length must be positive"); + ET_CHECK_OR_RETURN_ERROR( + !runtime_columns_ || inflight_, + InvalidState, + "offgraph_kv: no prepared forward to commit"); ET_CHECK_OK_OR_RETURN_ERROR(error_); ET_CHECK_OR_RETURN_ERROR( !poisoned_, InvalidState, - "offgraph_kv: uncommitted or failed draft co-batch; clear required"); - ET_CHECK_OK_OR_RETURN_ERROR(pool_.mark_step_done()); + "offgraph_kv: uncommitted step or failed cache operation; clear required"); + if (private_rows_) { + ET_CHECK_OR_RETURN_ERROR( + write_length == pending_width_, + InvalidArgument, + "offgraph_kv: commit width differs from preparation"); + const Error archived = archive_private_step(); + if (archived != Error::Ok) { + // abort_step fences the failed forward and retires only its owners. + return archived; + } + } + ET_CHECK_OK_OR_RETURN_ERROR(pool_.mark_step_done(pool_.stream())); + inflight_ = false; + pending_runs_.clear(); + pending_width_ = 0; // A draft's block is scratch: the next draft rewrites it. for (const int32_t owner : pending_owners_) { const auto it = seqs_.find(owner); @@ -1139,21 +1360,115 @@ class CudaBatchedSequenceCache final : public cache::Cache, return Error::Ok; } - // logical_length is the longest sequence: every column holds that many rows. + Error abort_step() override { + std::lock_guard guard(mutex_); + if (!inflight_) { + return Error::Ok; + } + const Error error = pool_.synchronize(/*all_streams=*/true); + if (error != Error::Ok) { + poisoned_ = true; + return error; + } + inflight_ = false; + if (private_rows_) { + poisoned_ |= pool_.requires_clear(); + // A failed forward may already have overwritten physical Ring slots; + // only its owners have uncertain contents. The runner retires them; + // unrelated owners must remain usable without a whole-cache clear. + for (const auto& run : pending_runs_) { + seqs_.at(run.owner).failed = true; + } + pending_runs_.clear(); + pending_width_ = 0; + } + return Error::Ok; + } + + // Logical length is the longest owner; physical capacities may differ. OffGraphKVMetrics metrics() const override { std::lock_guard guard(mutex_); OffGraphKVMetrics metrics; + metrics.prepare_time_ns = prepare_time_ns_; + metrics.commit_time_ns = commit_time_ns_; + metrics.archive_transfer_time_ns = archive_transfer_time_ns_; + metrics.archive_append_time_ns = archive_append_time_ns_; for (const auto& [seq_id, sequence] : seqs_) { metrics.logical_length = std::max(metrics.logical_length, sequence.plan.length()); } - metrics.flat_capacity = - std::min(pool_.rows() / columns_, cfg_.capacity); + if (private_rows_) { + if (pool_.allocated()) { + for (size_t layer = 0; layer < geometry_.layers.size(); ++layer) { + for (const auto& span : pool_.private_layout(layer).spans) { + metrics.flat_capacity = + std::max(metrics.flat_capacity, span.capacity); + } + } + } + } else { + metrics.flat_capacity = + std::min(pool_.rows() / columns_, cfg_.capacity); + } metrics.growth_count = pool_.growth_count(); metrics.allocated_bytes = pool_.allocated_bytes(); + metrics.physical_columns = columns_; + metrics.declared_columns = max_seqs_ + 1; + metrics.live_sequences = seqs_.size(); + metrics.column_resize_count = pool_.column_resize_count(); + for (size_t layer = 0; layer < histories_.size(); ++layer) { + if (histories_[layer]) { + metrics.host_undo_bytes += + histories_[layer]->resident_bytes() + archive_bytes_[layer]; + if (pool_.allocated()) { + metrics.device_staging_bytes += + pool_.side_buffer_bytes(private_stage_buffers_[layer]) + + pool_.side_buffer_bytes(private_stage_buffers_[layer] + 1); + } + } + } return metrics; } + CudaGraphMetrics graph_metrics(std::string_view method) const override { + std::lock_guard guard(mutex_); + return pool_.graph_metrics(method); + } + + Error compact_columns(int spare_columns) override { + std::lock_guard guard(mutex_); + ET_CHECK_OR_RETURN_ERROR( + runtime_columns_, + NotSupported, + "offgraph_kv: program uses fixed physical columns"); + ET_CHECK_OR_RETURN_ERROR( + !poisoned_ && pending_owners_.empty(), + InvalidState, + "offgraph_kv: cannot compact a poisoned cache or pending draft step"); + ET_CHECK_OR_RETURN_ERROR( + spare_columns >= 0 && spare_columns <= max_seqs_, + InvalidArgument, + "offgraph_kv: invalid spare columns"); + ET_CHECK_OR_RETURN_ERROR( + !inflight_, + InvalidState, + "offgraph_kv: cannot compact during a forward"); + if (private_rows_) { + if (!pool_.allocated()) { + return Error::Ok; + } + ET_CHECK_OK_OR_RETURN_ERROR(prepare_private( + {}, 0, cudaStreamPerThread, /*compact=*/true, spare_columns)); + // Owner geometry now agrees with the committed storage. + const Error fenced = pool_.synchronize(/*all_streams=*/true); + poisoned_ |= pool_.requires_clear(); + ET_CHECK_OK_OR_RETURN_ERROR(fenced); + extension::cuda::CudaAllocator::release_cached_memory(pool_.device()); + return Error::Ok; + } + return ensure_columns(true, spare_columns, cudaStreamPerThread); + } + protected: void* face(cache::FaceId id) override { return cache::expose(this, id); @@ -1163,6 +1478,7 @@ class CudaBatchedSequenceCache final : public cache::Cache, struct Sequence { int column; cache::SequenceCache plan; + bool failed{false}; }; // A ring never needs more rows than a sequence can hold; it then never wraps. @@ -1179,7 +1495,8 @@ class CudaBatchedSequenceCache final : public cache::Cache, static std::vector pool_layers( const cache::CacheGeometry& geometry, - const cache::CacheConfig& cfg) { + const cache::CacheConfig& cfg, + bool private_rows) { std::vector layers; for (const cache::LayerGeometry& layer : geometry.layers) { layers.push_back(CudaKVPool::Layer{ @@ -1188,26 +1505,510 @@ class CudaBatchedSequenceCache final : public cache::Cache, rows_of(layer, cfg) * (*cfg.max_seqs + 1), // A ring cannot wrap before it holds all its rows, so until then it // grows with the flat layers. - /*growable=*/true}); + /*growable=*/true, + private_rows && is_ring(layer) ? layer.policy.window : 0}); } return layers; } - std::optional free_column() const { - for (int column = 0; column < max_seqs_; ++column) { - if (seqs_.count(column) == 0) { - return column; + static bool has_ring(const cache::CacheGeometry& geometry) { + return std::any_of(geometry.layers.begin(), geometry.layers.end(), is_ring); + } + + static std::vector side_buffers( + const cache::CacheGeometry& geometry, + const cache::CacheConfig& cfg, + bool runtime_columns, + bool private_rows) { + std::vector buffers{ + {kSeqColsFqn, slimc10::ScalarType::Long, {*cfg.max_write}}, + {kSeqInfoFqn, + slimc10::ScalarType::Int, + {batched_sequence_max_segments(*cfg.max_seqs), + runtime_columns ? 5 : 4}}}; + if (!private_rows) { + return buffers; + } + buffers.push_back( + {kOwnerStepFqn, slimc10::ScalarType::Int, {*cfg.max_seqs + 1, 3}}); + if (has_ring(geometry)) { + buffers.push_back( + {kStageRowsFqn, slimc10::ScalarType::Long, {*cfg.max_write}}); + } + for (size_t index = 0; index < geometry.layers.size(); ++index) { + const auto& layer = geometry.layers[index]; + buffers.push_back( + {offgraph_kv_layer_fqn(index, "owner_layout"), + slimc10::ScalarType::Int, + {*cfg.max_seqs + 1, 2}}); + if (is_ring(layer)) { + for (const char* lane : {"k_stage", "v_stage"}) { + buffers.push_back( + {offgraph_kv_layer_fqn(index, lane), + slimc10::ScalarType::BFloat16, + {1, *cfg.max_write, layer.n_kv_heads, layer.head_dim}, + true}); + } + } + } + return buffers; + } + + Error prepare_private( + const std::map& ends, + int64_t width, + cudaStream_t stream, + bool compact = false, + int spare = 0, + int new_owner = -1) { + std::fill(private_live_.begin(), private_live_.end(), 0); + for (auto& layer : private_required_) { + std::fill(layer.begin(), layer.end(), 0); + } + for (const auto& [owner, sequence] : seqs_) { + private_live_[owner] = owner == new_owner ? 0 : sequence.plan.length(); + const auto found = ends.find(owner); + const int64_t end = + found == ends.end() ? sequence.plan.length() : found->second; + for (size_t layer = 0; layer < geometry_.layers.size(); ++layer) { + private_required_[layer][owner] = is_ring(geometry_.layers[layer]) + ? std::min(end, geometry_.layers[layer].policy.window) + : end; + } + } + if (compact) { + for (int owner = 0; owner < max_seqs_ && spare > 0; ++owner) { + if (seqs_.count(owner) != 0) { + continue; + } + bool held = false; + for (size_t layer = 0; layer < geometry_.layers.size(); ++layer) { + const int capacity = + pool_.private_layout(layer).spans[owner].capacity; + private_required_[layer][owner] = capacity; + held |= capacity > 0; + } + spare -= held; + } + } + const Error prepared = pool_.prepare_private( + private_required_, private_live_, width, stream, compact); + poisoned_ |= pool_.requires_clear(); + ET_CHECK_OK_OR_RETURN_ERROR(prepared); + columns_ = 1; + for (int owner = 0; owner < max_seqs_; ++owner) { + columns_ += pool_.private_layout(0).spans[owner].capacity > 0; + } + return Error::Ok; + } + + size_t private_metadata_bytes() const { + return static_cast(max_write_) * sizeof(int64_t) + + static_cast(max_seqs_ + 1) * sizeof(int32_t) * + (3 + 2 * geometry_.layers.size()); + } + + void build_private_step( + const std::map& ends, + int tokens, + int width) { + auto* info = reinterpret_cast( + reinterpret_cast(staging_) + max_write_); + auto* rows = reinterpret_cast(info + max_segments_ * info_width_); + auto* steps = reinterpret_cast(rows + max_write_); + auto* layouts = steps + (max_seqs_ + 1) * 3; + std::fill(steps, layouts, 0); + std::iota(rows, rows + width, int64_t{0}); + std::vector next(max_seqs_, 0); + pending_runs_.clear(); + int cursor = 0; + for (const auto& [owner, end] : ends) { + const int start = seqs_.at(owner).plan.length(); + steps[owner * 3] = cursor; + steps[owner * 3 + 1] = start; + steps[owner * 3 + 2] = end - start; + pending_runs_.push_back({owner, cursor, end - start, start}); + next[owner] = cursor; + cursor += end - start; + } + for (int token = 0; token < tokens; ++token) { + rows[token] = next[step_seq_ids_[token]]++; + } + if (layout_uploaded_ == pool_.column_resize_count()) { + return; + } + for (size_t layer = 0; layer < geometry_.layers.size(); ++layer) { + const auto& layout = pool_.private_layout(layer); + for (int owner = 0; owner < max_seqs_; ++owner) { + layouts[owner * 2] = layout.spans[owner].base; + layouts[owner * 2 + 1] = layout.spans[owner].capacity; + } + layouts[max_seqs_ * 2] = layout.rows - 1; + layouts[max_seqs_ * 2 + 1] = 1; + layouts += (max_seqs_ + 1) * 2; + } + } + + Error reserve_archive_staging(int width) { + for (size_t layer = 0; layer < histories_.size(); ++layer) { + if (!histories_[layer]) { + continue; + } + const auto& geometry = geometry_.layers[layer]; + const size_t bytes = static_cast(width) * 2 * + geometry.n_kv_heads * geometry.head_dim * sizeof(uint16_t); + if (bytes <= archive_bytes_[layer]) { + continue; + } + void* replacement = nullptr; + ET_CHECK_OR_RETURN_ERROR( + cudaMallocHost(&replacement, bytes) == cudaSuccess, + MemoryAllocationFailed, + "offgraph_kv: cannot allocate Ring undo staging"); + if (archive_staging_[layer]) { + (void)cudaFreeHost(archive_staging_[layer]); + } + archive_staging_[layer] = static_cast(replacement); + archive_bytes_[layer] = bytes; + } + return Error::Ok; + } + + Error enqueue_private_copies(cudaStream_t stream, cudaMemcpyKind kind) { +#if CUDART_VERSION >= 13020 + if (stream != nullptr && stream != cudaStreamLegacy) { + cudaMemcpyAttributes attributes{}; + attributes.srcAccessOrder = cudaMemcpySrcAccessOrderStream; + size_t first = 0; + ET_CHECK_OR_RETURN_ERROR( + cudaMemcpyBatchAsync( + copy_destinations_.data(), + copy_sources_.data(), + copy_sizes_.data(), + copy_sizes_.size(), + &attributes, + &first, + 1, + stream) == cudaSuccess, + Internal, + "offgraph_kv: cannot enqueue private copy batch"); + return Error::Ok; + } +#endif + for (size_t index = 0; index < copy_sizes_.size(); ++index) { + ET_CHECK_OR_RETURN_ERROR( + cudaMemcpyAsync( + copy_destinations_[index], + copy_sources_[index], + copy_sizes_[index], + kind, + stream) == cudaSuccess, + Internal, + "offgraph_kv: cannot enqueue private copy"); + } + return Error::Ok; + } + + Error archive_private_step() { + if (!has_ring(geometry_)) { + return Error::Ok; + } + const auto device = CUDAGuard::create(pool_.device()); + ET_CHECK_OK_OR_RETURN_ERROR(device.error()); + { + const CachePhaseTimer transfer_timer(archive_transfer_time_ns_); + copy_destinations_.clear(); + copy_sources_.clear(); + copy_sizes_.clear(); + for (size_t layer = 0; layer < histories_.size(); ++layer) { + if (!histories_[layer]) { + continue; + } + const auto& geometry = geometry_.layers[layer]; + const size_t bytes = static_cast(pending_width_) * + geometry.n_kv_heads * geometry.head_dim * sizeof(uint16_t); + for (int plane = 0; plane < 2; ++plane) { + copy_destinations_.push_back(archive_staging_[layer] + plane * bytes); + copy_sources_.push_back( + pool_.side_buffer(private_stage_buffers_[layer] + plane)); + copy_sizes_.push_back(bytes); + } + } + const Error copied = + enqueue_private_copies(pool_.stream(), cudaMemcpyDeviceToHost); + if (copied != Error::Ok) { + (void)pool_.synchronize(/*all_streams=*/true); + return copied; + } + ET_CHECK_OK_OR_RETURN_ERROR(pool_.synchronize()); + } + const CachePhaseTimer append_timer(archive_append_time_ns_); + for (size_t layer = 0; layer < histories_.size(); ++layer) { + if (histories_[layer]) { + ET_CHECK_OK_OR_RETURN_ERROR(histories_[layer]->append( + {pending_runs_.data(), pending_runs_.size()}, + {archive_staging_[layer], + static_cast(pending_width_) * 2 * + geometry_.layers[layer].n_kv_heads * + geometry_.layers[layer].head_dim * sizeof(uint16_t)}, + pending_width_)); + } + } + return Error::Ok; + } + + Error restore_private(int32_t source, int32_t destination, int keep) { + if (keep == 0) { + return Error::Ok; + } + // Validate every layer before a rewind modifies any physical history. + for (size_t layer = 0; layer < histories_.size(); ++layer) { + if (histories_[layer]) { + ET_CHECK_OR_RETURN_ERROR( + histories_[layer]->has_window(source, keep) && + pool_.private_layout(layer).spans[destination].capacity >= + std::min(keep, geometry_.layers[layer].policy.window), + InvalidArgument, + "offgraph_kv: unavailable Ring restore window"); + } + } + const auto device = CUDAGuard::create(pool_.device()); + ET_CHECK_OK_OR_RETURN_ERROR(device.error()); + ET_CHECK_OK_OR_RETURN_ERROR( + pool_.follow_previous_step(cudaStreamPerThread)); + bool copied = false; + aoti::ScopeGuard fence([&]() noexcept { + if (!copied && pool_.synchronize(/*all_streams=*/true) != Error::Ok) { + poisoned_ = true; + } + }); + const int resident_end = seqs_.at(source).plan.length(); + for (size_t layer = 0; layer < histories_.size(); ++layer) { + if (!histories_[layer]) { + continue; + } + const auto& spans = pool_.private_layout(layer).spans; + const auto src = spans[source]; + const auto dst = spans[destination]; + const auto restore = RingHistory::restore_plan( + geometry_.layers[layer].policy.window, keep, resident_end); + ET_CHECK_OR_RETURN_ERROR( + restore.has_value(), InvalidArgument, "invalid Ring restore plan"); + const size_t bytes = + static_cast(geometry_.layers[layer].n_kv_heads) * + geometry_.layers[layer].head_dim * sizeof(uint16_t); + for (int plane = 0; plane < 2; ++plane) { + auto* data = static_cast(pool_.layer_data(layer, plane != 0)); + int position = restore->start; + while (position < restore->resident_start) { + const int physical = position % dst.capacity; + const auto rows = histories_[layer]->read( + source, + position, + std::min( + restore->resident_start - position, dst.capacity - physical), + plane); + ET_CHECK_OR_RETURN_ERROR( + rows.has_value(), InvalidArgument, "missing Ring undo rows"); + const auto error = cudaMemcpyAsync( + data + (static_cast(dst.base) + physical) * bytes, + rows->data, + static_cast(rows->count) * bytes, + cudaMemcpyHostToDevice, + cudaStreamPerThread); + ET_CHECK_OR_RETURN_ERROR( + error == cudaSuccess, Internal, "Ring undo copy failed"); + position += rows->count; + } + // A rewind leaves resident rows in place. A clone copies that portion + // device-to-device; only already evicted rows need pageable H2D. + if (source != destination) { + while (position < keep) { + const int from = position % src.capacity; + const int to = position % dst.capacity; + const int count = std::min( + keep - position, + std::min(src.capacity - from, dst.capacity - to)); + ET_CHECK_OR_RETURN_ERROR( + cudaMemcpyAsync( + data + (static_cast(dst.base) + to) * bytes, + data + (static_cast(src.base) + from) * bytes, + static_cast(count) * bytes, + cudaMemcpyDeviceToDevice, + cudaStreamPerThread) == cudaSuccess, + Internal, + "Ring clone copy failed"); + position += count; + } + } + } + } + // The host pages may be reused by rewind or erased by clone rollback. + if (cudaStreamSynchronize(cudaStreamPerThread) != cudaSuccess) { + poisoned_ = true; + return Error::Internal; + } + copied = true; + const Error marked = pool_.mark_step_done(cudaStreamPerThread); + poisoned_ |= marked != Error::Ok; + return marked; + } + + std::optional clone_private( + int32_t source, + int32_t destination, + int keep, + cache::SequenceCache plan) { + bool admitted = false; + aoti::ScopeGuard rollback([&]() noexcept { + if (!admitted) { + if (pool_.synchronize(/*all_streams=*/true) != Error::Ok) { + poisoned_ = true; + } + seqs_.erase(destination); + for (auto& history : histories_) { + if (history) { + history->erase(destination); + } + } + } + }); + for (auto& history : histories_) { + if (history && !history->clone(source, destination, keep)) { + return std::nullopt; + } + } + seqs_.emplace(destination, Sequence{destination, std::move(plan)}); + if (prepare_private({}, 0, cudaStreamPerThread, false, 0, destination) != + Error::Ok) { + return std::nullopt; + } + for (size_t layer = 0; layer < geometry_.layers.size(); ++layer) { + if (histories_[layer]) { + continue; + } + const auto& spans = pool_.private_layout(layer).spans; + const size_t bytes = + static_cast(geometry_.layers[layer].n_kv_heads) * + geometry_.layers[layer].head_dim * sizeof(uint16_t); + for (bool value : {false, true}) { + auto* data = static_cast(pool_.layer_data(layer, value)); + if (cudaMemcpyAsync( + data + static_cast(spans[destination].base) * bytes, + data + static_cast(spans[source].base) * bytes, + static_cast(keep) * bytes, + cudaMemcpyDeviceToDevice, + cudaStreamPerThread) != cudaSuccess) { + poisoned_ = pool_.synchronize(/*all_streams=*/true) != Error::Ok; + return std::nullopt; + } + } + } + if (restore_private(source, destination, keep) != Error::Ok) { + return std::nullopt; + } + admitted = true; + return destination; + } + + std::optional free_sequence_id() const { + for (int id = 0; id < max_seqs_; ++id) { + if (seqs_.count(id) == 0) { + return id; } } return std::nullopt; } + Error ensure_columns(bool compact, int spare_columns, cudaStream_t stream) { + const int live = static_cast(seqs_.size()); + // Grow geometrically (doubling the live columns) instead of one column + // per admission: each resize is a device-wide sync plus a full KV copy, + // so admitting N sessions one column at a time costs N full copies. + // The declared maximum still caps the width, and compact_columns() + // is the only path that shrinks back down. + const int grown = live + 1 <= columns_ + ? columns_ + : static_cast(std::min( + max_seqs_ + 1LL, + std::max(live + 1LL, 2LL * (columns_ - 1) + 1))); + const int target = compact + ? std::min( + columns_, + std::min(max_seqs_, std::max(1, live + spare_columns)) + 1) + : std::min(max_seqs_ + 1, std::max(columns_, grown)); + std::map next; + std::unordered_set used; + for (const auto& [id, sequence] : seqs_) { + if (sequence.column >= 0 && (!compact || sequence.column < target - 1)) { + ET_CHECK_OR_RETURN_ERROR( + sequence.column < target - 1 && used.insert(sequence.column).second, + InvalidState, + "offgraph_kv: invalid physical owner mapping"); + next.emplace(id, sequence.column); + } + } + for (const auto& [id, sequence] : seqs_) { + if (next.count(id) != 0) { + continue; + } + int column = 0; + while (used.count(column) != 0) { + ++column; + } + ET_CHECK_OR_RETURN_ERROR( + column < target - 1, + InvalidState, + "offgraph_kv: missing physical column"); + next.emplace(id, column); + used.insert(column); + } + if (target != columns_ || compact) { + std::vector> retained; + for (const auto& [id, sequence] : seqs_) { + if (sequence.column >= 0) { + retained.emplace_back(sequence.column, next.at(id)); + } + } + int live_rows = 0; + for (const auto& [id, sequence] : seqs_) { + live_rows = std::max(live_rows, sequence.plan.length()); + } + bool committed = false; + // Reallocation is already a synchronization boundary. Return replaced + // allocations rather than retaining every former column width. + const Error error = pool_.resize_columns( + target, + retained, + live_rows, + stream, + /*trim_unused=*/true, + &committed); + if (error != Error::Ok && !committed) { + return error; + } + columns_ = target; + for (auto& [id, sequence] : seqs_) { + sequence.column = next.at(id); + } + if (error != Error::Ok) { + poisoned_ = true; + return error; + } + } else { + for (auto& [id, sequence] : seqs_) { + sequence.column = next.at(id); + } + } + return Error::Ok; + } + // Copies rows [0, keep) of every flat layer, and a ring layer's whole ring, // from one column to another, ordered behind the previous step: the copies // run on this thread's stream, which may not be the stream that step wrote // on. - Error copy_column(int from, int to, int keep) { - ET_CHECK_OK_OR_RETURN_ERROR(pool_.follow_previous_step(pool_.stream())); + Error copy_column(int from, int to, int keep, cudaStream_t stream) { + ET_CHECK_OK_OR_RETURN_ERROR(pool_.follow_previous_step(stream)); for (size_t index = 0; index < geometry_.layers.size(); ++index) { const cache::LayerGeometry& layer = geometry_.layers[index]; const size_t slot = static_cast(layer.n_kv_heads) * @@ -1227,12 +2028,12 @@ class CudaBatchedSequenceCache final : public cache::Cache, slot, static_cast(rows), cudaMemcpyDeviceToDevice, - pool_.stream()); + stream); if (error != cudaSuccess) { // Earlier layers may already have queued copies into the free // column. Fence them before a failed clone lets that column be // reused. - (void)pool_.synchronize(); + (void)cudaStreamSynchronize(stream); ET_LOG( Error, "offgraph_kv: cannot copy a sequence's history: %s", @@ -1251,13 +2052,17 @@ class CudaBatchedSequenceCache final : public cache::Cache, } Error upload(size_t width, cudaStream_t stream) { + if (private_rows_) { + return upload_private(width, stream); + } const size_t cols_bytes = static_cast(max_write_) * sizeof(int64_t); for (const auto& [index, offset, bytes] : {std::tuple{kSeqColsBuffer, size_t{0}, width * sizeof(int64_t)}, std::tuple{ kSeqInfoBuffer, cols_bytes, - static_cast(max_segments_) * 4 * sizeof(int32_t)}}) { + static_cast(max_segments_) * info_width_ * + sizeof(int32_t)}}) { const cudaError_t error = cudaMemcpyAsync( pool_.side_buffer(index), staging_ + offset, @@ -1270,6 +2075,52 @@ class CudaBatchedSequenceCache final : public cache::Cache, "offgraph_kv: cannot write the step's sequences: %s", cudaGetErrorString(error)); } + + return Error::Ok; + } + + Error upload_private(size_t width, cudaStream_t stream) { + const size_t cols_bytes = static_cast(max_write_) * sizeof(int64_t); + const size_t info_bytes = + static_cast(max_segments_) * info_width_ * sizeof(int32_t); + copy_destinations_.clear(); + copy_sources_.clear(); + copy_sizes_.clear(); + copy_destinations_.push_back(pool_.side_buffer(kSeqColsBuffer)); + copy_sources_.push_back(staging_); + copy_sizes_.push_back(width * sizeof(int64_t)); + copy_destinations_.push_back(pool_.side_buffer(kSeqInfoBuffer)); + copy_sources_.push_back(staging_ + cols_bytes); + copy_sizes_.push_back(info_bytes); + size_t offset = cols_bytes + info_bytes; + if (has_ring(geometry_)) { + copy_destinations_.push_back(pool_.side_buffer(3)); + copy_sources_.push_back(staging_ + offset); + copy_sizes_.push_back(width * sizeof(int64_t)); + } + offset += static_cast(max_write_) * sizeof(int64_t); + const size_t step_bytes = + static_cast(max_seqs_ + 1) * 3 * sizeof(int32_t); + copy_destinations_.push_back(pool_.side_buffer(2)); + copy_sources_.push_back(staging_ + offset); + copy_sizes_.push_back(step_bytes); + offset += step_bytes; + const bool layout_changed = layout_uploaded_ != pool_.column_resize_count(); + if (layout_changed) { + const size_t bytes = + static_cast(max_seqs_ + 1) * 2 * sizeof(int32_t); + for (size_t layer = 0; layer < geometry_.layers.size(); ++layer) { + copy_destinations_.push_back( + pool_.side_buffer(private_layout_buffers_[layer])); + copy_sources_.push_back(staging_ + offset + layer * bytes); + copy_sizes_.push_back(bytes); + } + } + ET_CHECK_OK_OR_RETURN_ERROR( + enqueue_private_copies(stream, cudaMemcpyHostToDevice)); + if (layout_changed) { + layout_uploaded_ = pool_.column_resize_count(); + } return Error::Ok; } @@ -1331,21 +2182,41 @@ class CudaBatchedSequenceCache final : public cache::Cache, const cache::CacheGeometry geometry_; const cache::CacheConfig cfg_; const int max_seqs_; - const int columns_; + const bool runtime_columns_; + const bool private_rows_; const int max_write_; const int max_segments_; + const int info_width_; const std::optional dflash_block_size_; + int columns_; + bool inflight_{false}; + uint64_t prepare_time_ns_{0}; + uint64_t commit_time_ns_{0}; + uint64_t archive_transfer_time_ns_{0}; + uint64_t archive_append_time_ns_{0}; std::vector layer_rows_; CudaKVPool pool_; std::map seqs_; std::vector step_seq_ids_; std::vector pending_owners_; + std::vector> private_required_; + std::vector private_live_; + std::vector private_layout_buffers_; + std::vector private_stage_buffers_; + std::vector> histories_; + std::vector archive_staging_; + std::vector archive_bytes_; + std::vector pending_runs_; + std::vector copy_destinations_; + std::vector copy_sources_; + std::vector copy_sizes_; + int pending_width_{0}; + int64_t layout_uploaded_{-1}; uint8_t* staging_{nullptr}; size_t staging_bytes_{0}; cudaEvent_t staged_{nullptr}; bool validated_{false}; - // Set when a clear() fence fails; prepare/commit refuse until a later - // clear() fences cleanly. + // A failed device fence or post-commit resize requires a successful clear(). bool poisoned_{false}; Error error_{Error::Ok}; }; @@ -1419,16 +2290,22 @@ std::shared_ptr make_cuda_cell_kv_cache( std::shared_ptr make_cuda_batched_sequence_kv_cache( const cache::CacheGeometry& geometry, - const cache::CacheConfig& cfg) { + const cache::CacheConfig& cfg, + bool runtime_columns, + bool private_rows) { slimc10::ScalarType storage_dtype = slimc10::ScalarType::BFloat16; if (!cache::valid(geometry, cfg) || cfg.initial_capacity <= 0 || cfg.initial_capacity > cfg.capacity || - !storage_dtype_of(cfg.kv_dtype, storage_dtype)) { + ((runtime_columns || private_rows) && geometry.dflash_block_size) || + (runtime_columns && private_rows) || + !storage_dtype_of(cfg.kv_dtype, storage_dtype) || + (private_rows && storage_dtype != slimc10::ScalarType::BFloat16)) { ET_LOG(Error, "offgraph_kv: invalid cache geometry or config"); return nullptr; } // The storage is one column per sequence and the step buffers are declared - // [max_write] and [segments, 4]; all are fixed by the program. + // [max_write] and [segments, 4 (or 5 with runtime columns)]; all are fixed + // by the program. if (!cfg.max_seqs || !cfg.max_write || *cfg.max_write > cfg.capacity || (geometry.dflash_block_size && (*geometry.dflash_block_size <= 0 || @@ -1440,7 +2317,7 @@ std::shared_ptr make_cuda_batched_sequence_kv_cache( return nullptr; } return std::make_shared( - geometry, cfg, storage_dtype); + geometry, cfg, storage_dtype, runtime_columns, private_rows); } runtime::Error attach_offgraph_kv_cache( @@ -1490,7 +2367,18 @@ const bool cuda_cache_builders_registered = [] { } builders[] = { {cache::kind::kSingle, make_cuda_sequence_kv_cache}, {cache::kind::kBatchedCell, make_cuda_cell_kv_cache}, - {cache::kind::kBatchedSequence, make_cuda_batched_sequence_kv_cache}, + {cache::kind::kBatchedSequence, + [](const cache::CacheGeometry& geometry, const cache::CacheConfig& cfg) { + return make_cuda_batched_sequence_kv_cache(geometry, cfg); + }}, + {cache::kind::kBatchedSequenceRuntime, + [](const cache::CacheGeometry& geometry, const cache::CacheConfig& cfg) { + return make_cuda_batched_sequence_kv_cache(geometry, cfg, true); + }}, + {cache::kind::kBatchedSequencePrivate, + [](const cache::CacheGeometry& geometry, const cache::CacheConfig& cfg) { + return make_cuda_batched_sequence_kv_cache(geometry, cfg, false, true); + }}, // The cell layout is the batch layout this backend serves. {cache::kind::kBatched, make_cuda_cell_kv_cache}, }; diff --git a/backends/cuda/runtime/cuda_kv_cache.h b/backends/cuda/runtime/cuda_kv_cache.h index 82430e40e3e..10f5def021f 100644 --- a/backends/cuda/runtime/cuda_kv_cache.h +++ b/backends/cuda/runtime/cuda_kv_cache.h @@ -28,12 +28,28 @@ namespace cache = ::executorch::extension::llm::cache; struct OffGraphKVMetrics { int64_t logical_length{0}; - // Rows currently allocated for each flat layer. + // Maximum private owner row capacity, or the shared flat row capacity. int64_t flat_capacity{0}; - // Times flat storage has been reallocated. Every growth moves the storage, - // so this also identifies the addresses a compiled program was bound to. + // Times flat row storage has grown. Column resizes are counted separately. int64_t growth_count{0}; + // Live K/V allocations, excluding step buffers and allocator retention. int64_t allocated_bytes{0}; + // Physical/declared widths include the final scratch column. + int64_t physical_columns{0}; + int64_t declared_columns{0}; + // Logical owners, including cloned prefix owners. + int64_t live_sequences{0}; + int64_t column_resize_count{0}; + // ABI 3 per-layer shared device K/V staging, separate from live history. + int64_t device_staging_bytes{0}; + // ABI 3 host undo pages and pinned transfer buffers; excludes containers. + int64_t host_undo_bytes{0}; + // Cumulative batched-sequence cache CPU wall time, including device waits. + // These are diagnostics, not GPU-kernel durations; clear does not reset them. + uint64_t prepare_time_ns{0}; + uint64_t commit_time_ns{0}; + uint64_t archive_transfer_time_ns{0}; + uint64_t archive_append_time_ns{0}; }; // Backend face of the off-graph KV cache: what the CUDA delegate needs from @@ -82,7 +98,27 @@ class CudaKVCache { cudaStream_t stream) = 0; virtual runtime::Error commit_step(int64_t write_length) = 0; + // A prepared forward failed. Fence its queued work before permitting + // storage to move again. Claimed logical rows are not rolled back. ABI 3 + // retires only owners in that forward until seq_rm; other owners remain + // usable. A failed device fence requires a fenced clear of the whole cache. + virtual runtime::Error abort_step() { + return runtime::Error::Ok; + } + virtual OffGraphKVMetrics metrics() const = 0; + + // Successful captures/launches and failed captures for a named method. + // Read between executes under the executor's engine-thread contract. + virtual CudaGraphMetrics graph_metrics(std::string_view) const { + return {}; + } + + // An explicit idle boundary; callers must serialize this with execution. + // spare_columns counts unused owner columns, excluding the scratch column. + virtual runtime::Error compact_columns(int spare_columns) { + return runtime::Error::NotSupported; + } }; // Compile spec naming where a method's inputs carry the step width. @@ -194,7 +230,7 @@ std::shared_ptr make_cuda_cell_kv_cache( const cache::CacheConfig& cfg); // Segments of a batched-sequence step: runs of one sequence's query rows. The -// program declares its seq_info buffer [segments, 4] from the same rule. +// program declares seq_info [segments, 4], or [segments, 5] for ABI 2. inline int batched_sequence_max_segments(int max_seqs) { return 2 * max_seqs; } @@ -208,9 +244,16 @@ inline int batched_sequence_max_segments(int max_seqs) { // fix shapes the program declared, so they must match the export exactly. // Every layer starts at cfg.initial_capacity rows and grows geometrically: a // flat layer to cfg.capacity, a ring layer to min(capacity, window + -// max_write - 1). +// max_write - 1). runtime_columns selects ABI 2: physical owner columns +// start at one and grow on admission up to cfg.max_seqs; ABI 1 keeps the +// declared width. Both reserve one additional scratch column. +// private_rows selects ABI 3 instead: stable owner descriptors address +// independent row spans; Ring history caps at the window and per-layer step +// staging is shared. Host undo history preserves clone/rewind semantics. std::shared_ptr make_cuda_batched_sequence_kv_cache( const cache::CacheGeometry& geometry, - const cache::CacheConfig& cfg); + const cache::CacheConfig& cfg, + bool runtime_columns = false, + bool private_rows = false); } // namespace executorch::backends::cuda diff --git a/backends/cuda/runtime/cuda_kv_pool.cpp b/backends/cuda/runtime/cuda_kv_pool.cpp index 74fcf6a2be8..d2f758e843b 100644 --- a/backends/cuda/runtime/cuda_kv_pool.cpp +++ b/backends/cuda/runtime/cuda_kv_pool.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -31,6 +32,9 @@ using ::executorch::backends::aoti::slim::SlimTensor; using ::executorch::extension::cuda::CUDAGuard; using ::executorch::runtime::Error; +thread_local CudaKVPool::FenceFunction CudaKVPool::private_fence_for_testing_ = + nullptr; + std::string offgraph_kv_layer_fqn(int64_t layer_id, const char* suffix) { return std::string(kOffGraphKVFqnPrefix) + "layer_" + std::to_string(layer_id) + "_" + suffix; @@ -56,14 +60,22 @@ CudaKVPool::CudaKVPool( std::vector layers, std::vector side_buffers, slimc10::ScalarType storage_dtype, - int64_t initial_rows) + int64_t initial_rows, + int declared_columns, + int initial_columns, + bool private_rows) : layers_(std::move(layers)), side_specs_(std::move(side_buffers)), storage_dtype_(storage_dtype), - initial_rows_(initial_rows) { + initial_rows_( + initial_rows / declared_columns * + (private_rows ? 1 : initial_columns)), + declared_columns_(declared_columns), + columns_(initial_columns), + private_rows_(private_rows) { for (const Layer& layer : layers_) { if (layer.growable) { - max_rows_ = std::max(max_rows_, layer.declared_rows); + max_rows_ = std::max(max_rows_, physical_limit(layer)); } } } @@ -146,6 +158,8 @@ Error CudaKVPool::prepare( int64_t required_rows, int64_t live_rows, cudaStream_t stream) { + ET_CHECK_OR_RETURN_ERROR( + !private_rows_, InvalidState, "private storage requires owner row plans"); const auto device = CUDAGuard::create(device_); ET_CHECK_OK_OR_RETURN_ERROR(device.error()); ET_CHECK_OK_OR_RETURN_ERROR(follow_previous_step(stream)); @@ -161,7 +175,332 @@ Error CudaKVPool::prepare( return Error::Ok; } -Error CudaKVPool::mark_step_done() { +Error CudaKVPool::prepare_private( + const std::vector>& required_rows, + const std::vector& live_lengths, + int64_t step_rows, + cudaStream_t stream, + bool compact) { + ET_CHECK_OR_RETURN_ERROR( + !private_fence_failed_, + InvalidState, + "offgraph_kv: failed private fence requires a fenced clear"); + ET_CHECK_OR_RETURN_ERROR( + private_rows_ && device_known_ && declared_columns_ > 1 && + required_rows.size() == layers_.size() && + live_lengths.size() == static_cast(declared_columns_ - 1) && + step_rows >= 0 && (allocated_ || step_rows > 0), + InvalidArgument, + "offgraph_kv: invalid private row preparation"); + for (int64_t length : live_lengths) { + ET_CHECK_OR_RETURN_ERROR( + length >= 0 && (allocated_ || length == 0), + InvalidArgument, + "offgraph_kv: invalid retained length"); + } + // Steady decode updates metadata, not allocation geometry. Validate its + // bounds without building replacement vectors or allocating host memory. + if (allocated_) { + bool change = false; + for (size_t index = 0; index < layers_.size(); ++index) { + const Layer& layer = layers_[index]; + ET_CHECK_OR_RETURN_ERROR( + layer.growable && layer.private_window >= 0 && + layer.declared_rows > 0 && + layer.declared_rows % declared_columns_ == 0 && + required_rows[index].size() == live_lengths.size(), + InvalidArgument, + "offgraph_kv: invalid private layer %zu", + index); + const int64_t virtual_rows = layer.declared_rows / declared_columns_; + const int64_t limit = layer.private_window > 0 + ? std::min(layer.private_window, virtual_rows) + : virtual_rows; + int64_t occupied_rows = 1; + for (size_t owner = 0; owner < live_lengths.size(); ++owner) { + const int64_t required = required_rows[index][owner]; + const int64_t capacity = private_layouts_[index].spans[owner].capacity; + ET_CHECK_OR_RETURN_ERROR( + required >= 0 && required <= limit, + InvalidArgument, + "offgraph_kv: owner requirement is out of bounds"); + const int64_t retained = layer.private_window > 0 + ? std::min(live_lengths[owner], limit) + : live_lengths[owner]; + ET_CHECK_OR_RETURN_ERROR( + retained <= capacity && required >= retained, + InvalidArgument, + "offgraph_kv: retained history exceeds its private span"); + change |= required > capacity || (compact && required < capacity); + occupied_rows += capacity; + } + change |= compact && occupied_rows < private_layouts_[index].rows; + } + for (size_t index = 0; index < side_specs_.size(); ++index) { + const SideBuffer& spec = side_specs_[index]; + if (!spec.step_rows) { + continue; + } + ET_CHECK_OR_RETURN_ERROR( + step_rows <= spec.sizes[1], + InvalidArgument, + "offgraph_kv: step staging is out of bounds"); + const size_t row_bytes = + contiguous_nbytes(spec.sizes, spec.dtype) / spec.sizes[1]; + change |= step_rows > + static_cast(side_allocated_bytes_[index] / row_bytes); + } + if (!change) { + const auto device = CUDAGuard::create(device_); + ET_CHECK_OK_OR_RETURN_ERROR(device.error()); + ET_CHECK_OK_OR_RETURN_ERROR(follow_previous_step(stream)); + stream_ = stream; + return Error::Ok; + } + } + std::vector plans; + plans.reserve(layers_.size()); + bool layout_changed = !allocated_; + bool grew = false; + for (size_t index = 0; index < layers_.size(); ++index) { + const Layer& layer = layers_[index]; + ET_CHECK_OR_RETURN_ERROR( + layer.growable && layer.private_window >= 0 && + layer.declared_rows > 0 && + layer.declared_rows % declared_columns_ == 0 && + required_rows[index].size() == live_lengths.size(), + InvalidArgument, + "offgraph_kv: invalid private layer %zu", + index); + const int64_t virtual_rows = layer.declared_rows / declared_columns_; + const int64_t limit = layer.private_window > 0 + ? std::min(layer.private_window, virtual_rows) + : virtual_rows; + std::vector required = required_rows[index]; + runtime::Span previous; + if (allocated_) { + const auto& spans = private_layouts_.at(index).spans; + previous = {spans.data(), spans.size()}; + if (!compact) { + for (size_t owner = 0; owner < required.size(); ++owner) { + if (required[owner] == 0) { + required[owner] = spans[owner].capacity; + } + } + } + } + auto result = make_private_row_layout( + {required.data(), required.size()}, + previous, + initial_rows_, + limit, + compact); + ET_CHECK_OK_OR_RETURN_ERROR(result.error()); + const auto& spans = result.get().spans; + if (allocated_) { + layout_changed |= result.get().rows != private_layouts_[index].rows || + result.get().repacked; + for (size_t owner = 0; owner < spans.size(); ++owner) { + layout_changed |= spans[owner].base != previous[owner].base || + spans[owner].capacity != previous[owner].capacity; + grew |= spans[owner].capacity > previous[owner].capacity; + } + } + ET_CHECK_OR_RETURN_ERROR( + result.get().rows <= layer.declared_rows, + InvalidArgument, + "offgraph_kv: private rows exceed declared storage"); + plans.push_back(std::move(result.get())); + } + + std::vector next_side_bytes(side_specs_.size()); + bool side_changed = !allocated_; + for (size_t index = 0; index < side_specs_.size(); ++index) { + const SideBuffer& spec = side_specs_[index]; + auto sizes = spec.sizes; + if (spec.step_rows) { + ET_CHECK_OR_RETURN_ERROR( + sizes.size() == 4 && sizes[0] == 1 && sizes[1] > 0 && sizes[2] > 0 && + sizes[3] > 0 && step_rows <= sizes[1], + InvalidArgument, + "offgraph_kv: invalid step staging %s", + spec.fqn.c_str()); + const size_t row_bytes = contiguous_nbytes(sizes, spec.dtype) / sizes[1]; + ET_CHECK_OR_RETURN_ERROR( + row_bytes > 0, + InvalidArgument, + "offgraph_kv: empty step staging row"); + const int64_t old = + allocated_ ? side_allocated_bytes_[index] / row_bytes : 0; + int64_t capacity = old > 0 ? old : std::min(initial_rows_, sizes[1]); + if (step_rows > capacity) { + capacity = std::min(sizes[1], std::max(step_rows, capacity * 2)); + } + sizes[1] = capacity; + } + next_side_bytes[index] = contiguous_nbytes(sizes, spec.dtype); + side_changed |= + !allocated_ || next_side_bytes[index] != side_allocated_bytes_[index]; + } + const auto device = CUDAGuard::create(device_); + ET_CHECK_OK_OR_RETURN_ERROR(device.error()); + ET_CHECK_OK_OR_RETURN_ERROR(follow_previous_step(stream)); + stream_ = stream; + if (!layout_changed && !side_changed) { + return Error::Ok; + } + bool storage_moves = side_changed; + for (size_t index = 0; index < plans.size(); ++index) { + storage_moves |= !allocated_ || plans[index].repacked || + plans[index].rows != allocations_[index].rows; + } + if (allocated_ && storage_moves) { + ET_CHECK_OK_OR_RETURN_ERROR(synchronize(/*all_streams=*/true)); + } + + // Construct all host bookkeeping before allocating or committing device + // storage. Side staging carries no state across completed forwards. + std::vector replacements(layers_.size()); + std::vector next_allocations = allocations_; + next_allocations.resize(layers_.size()); + std::vector side_replacements(side_specs_.size(), nullptr); + std::vector next_sides = side_buffers_; + next_sides.resize(side_specs_.size(), nullptr); + bool committed = false; + bool work_queued = false; + bool payload_copied = false; + aoti::ScopeGuard rollback([&]() noexcept { + if (!committed) { + // A failed allocation can follow a copy into a free region of the live + // arena. The preceding completed-step event does not cover that copy. + if (work_queued) { + (void)synchronize(/*all_streams=*/true); + } + for (size_t index = 0; index < replacements.size(); ++index) { + if (replacements[index].k != nullptr) { + discard(layers_[index], replacements[index], stream); + } + } + for (void* replacement : side_replacements) { + release(replacement, stream); + } + } + }); + if (layout_changed) { + for (size_t index = 0; index < layers_.size(); ++index) { + const auto& next = plans[index]; + bool changed = !allocated_; + if (allocated_) { + const auto& old = private_layouts_[index]; + for (size_t owner = 0; owner < next.spans.size(); ++owner) { + changed |= old.spans[owner].base != next.spans[owner].base || + old.spans[owner].capacity != next.spans[owner].capacity; + } + } + if (!changed) { + continue; + } + const bool replace = + !allocated_ || next.repacked || next.rows != allocations_[index].rows; + if (replace) { + work_queued = true; + ET_CHECK_OK_OR_RETURN_ERROR(allocate_layer( + layers_[index], next.rows, stream, replacements[index])); + next_allocations[index] = replacements[index]; + } + if (!allocated_) { + continue; + } + const size_t bytes_per_row = row_bytes(layers_[index]); + for (size_t owner = 0; owner < live_lengths.size(); ++owner) { + const PrivateRowSpan& src = private_layouts_[index].spans[owner]; + const PrivateRowSpan& dst = next.spans[owner]; + const int64_t live = std::min( + live_lengths[owner], std::min(src.capacity, dst.capacity)); + if (live == 0) { + continue; + } + if (!replace && src.base == dst.base) { + continue; + } + ET_CHECK_OR_RETURN_ERROR( + layers_[index].private_window == 0 || + src.capacity == dst.capacity || + live_lengths[owner] <= src.capacity, + InvalidState, + "offgraph_kv: a wrapped Ring cannot change its private modulus"); + for (const auto& [from, to] : + {std::pair{allocations_[index].k, next_allocations[index].k}, + std::pair{allocations_[index].v, next_allocations[index].v}}) { + work_queued = true; + const cudaError_t error = cudaMemcpyAsync( + static_cast(to) + dst.base * bytes_per_row, + static_cast(from) + src.base * bytes_per_row, + live * bytes_per_row, + cudaMemcpyDeviceToDevice, + stream); + ET_CHECK_OR_RETURN_ERROR( + error == cudaSuccess, + Internal, + "offgraph_kv: private row copy failed: %s", + cudaGetErrorString(error)); + payload_copied = true; + } + } + } + } + for (size_t index = 0; index < side_specs_.size(); ++index) { + if (allocated_ && next_side_bytes[index] == side_allocated_bytes_[index]) { + continue; + } + work_queued = true; + auto result = + CudaAllocator::allocate_async(next_side_bytes[index], device_, stream); + ET_CHECK_OK_OR_RETURN_ERROR(result.error()); + side_replacements[index] = result.get(); + next_sides[index] = result.get(); + if (!side_specs_[index].step_rows) { + ET_CHECK_OR_RETURN_ERROR( + cudaMemsetAsync(result.get(), 0, next_side_bytes[index], stream) == + cudaSuccess, + Internal, + "offgraph_kv: cannot clear private metadata"); + } + } + if (storage_moves || payload_copied) { + ET_CHECK_OK_OR_RETURN_ERROR(synchronize()); + } + if (storage_moves) { + invalidate_bindings(); + } + for (size_t index = 0; index < replacements.size(); ++index) { + if (replacements[index].k != nullptr && allocated_) { + discard(layers_[index], allocations_[index], stream); + } + } + for (size_t index = 0; index < side_replacements.size(); ++index) { + if (side_replacements[index] != nullptr && allocated_) { + release(side_buffers_[index], stream); + } + } + if (allocated_ && layout_changed) { + ++column_resize_count_; + growth_count_ += grew; + } + allocations_.swap(next_allocations); + side_buffers_.swap(next_sides); + side_allocated_bytes_.swap(next_side_bytes); + private_layouts_.swap(plans); + rows_ = 0; + for (const auto& layout : private_layouts_) { + rows_ = std::max(rows_, layout.rows); + } + allocated_ = true; + committed = true; + return Error::Ok; +} + +Error CudaKVPool::mark_step_done(cudaStream_t stream) { const auto device = CUDAGuard::create(device_); ET_CHECK_OK_OR_RETURN_ERROR(device.error()); if (last_step_done_ == nullptr) { @@ -173,12 +512,13 @@ Error CudaKVPool::mark_step_done() { "offgraph_kv: cannot create the step event: %s", cudaGetErrorString(error)); } - const cudaError_t error = cudaEventRecord(last_step_done_, stream_); + const cudaError_t error = cudaEventRecord(last_step_done_, stream); ET_CHECK_OR_RETURN_ERROR( error == cudaSuccess, Internal, "offgraph_kv: cannot record the step event: %s", cudaGetErrorString(error)); + stream_ = stream; return Error::Ok; } @@ -187,9 +527,18 @@ Error CudaKVPool::synchronize(bool all_streams) { return Error::Ok; } const auto device = CUDAGuard::create(device_); - ET_CHECK_OK_OR_RETURN_ERROR(device.error()); + if (device.error() != Error::Ok) { + private_fence_failed_ |= private_rows_; + return device.error(); + } const cudaError_t error = - all_streams ? cudaDeviceSynchronize() : cudaStreamSynchronize(stream_); + private_rows_ && private_fence_for_testing_ != nullptr + ? private_fence_for_testing_(stream_, all_streams) + : (all_streams ? cudaDeviceSynchronize() + : cudaStreamSynchronize(stream_)); + if (private_rows_) { + private_fence_failed_ |= error != cudaSuccess; + } ET_CHECK_OR_RETURN_ERROR( error == cudaSuccess, Internal, @@ -210,6 +559,9 @@ void* CudaKVPool::side_buffer(size_t index) const { } size_t CudaKVPool::side_buffer_bytes(size_t index) const { + if (index < side_allocated_bytes_.size()) { + return side_allocated_bytes_[index]; + } const SideBuffer& spec = side_specs_.at(index); return contiguous_nbytes(spec.sizes, spec.dtype); } @@ -220,6 +572,10 @@ size_t CudaKVPool::row_bytes(const Layer& layer) const { slimc10::elementSize(storage_dtype_); } +int64_t CudaKVPool::physical_limit(const Layer& layer) const { + return layer.declared_rows / declared_columns_ * columns_; +} + // BSHD at the declared rows: no stride depends on the rows, so the storage // behind it may hold fewer. std::vector CudaKVPool::layer_sizes(const Layer& layer) { @@ -295,7 +651,7 @@ Error CudaKVPool::allocate_initial(int64_t required_rows, cudaStream_t stream) { }; for (const Layer& layer : layers_) { const int64_t rows = layer.growable - ? std::min(growable_rows, layer.declared_rows) + ? std::min(growable_rows, physical_limit(layer)) : layer.declared_rows; Allocation allocation; const Error error = allocate_layer(layer, rows, stream, allocation); @@ -325,7 +681,9 @@ Error CudaKVPool::allocate_initial(int64_t required_rows, cudaStream_t stream) { // a well-defined value rather than whatever the allocator handed back. Error CudaKVPool::allocate_side_buffers(cudaStream_t stream) { std::vector buffers; + std::vector sizes; buffers.reserve(side_specs_.size()); + sizes.reserve(side_specs_.size()); auto roll_back = [&]() { for (void* buffer : buffers) { release(buffer, stream); @@ -339,6 +697,7 @@ Error CudaKVPool::allocate_side_buffers(cudaStream_t stream) { return buffer.error(); } buffers.push_back(buffer.get()); + sizes.push_back(bytes); const cudaError_t error = cudaMemsetAsync(buffer.get(), 0, bytes, stream); if (error != cudaSuccess) { roll_back(); @@ -351,6 +710,7 @@ Error CudaKVPool::allocate_side_buffers(cudaStream_t stream) { } } side_buffers_ = std::move(buffers); + side_allocated_bytes_ = std::move(sizes); return Error::Ok; } @@ -377,7 +737,7 @@ Error CudaKVPool::grow( }; for (size_t index = 0; index < layers_.size(); ++index) { const Layer& layer = layers_[index]; - const int64_t rows = std::min(new_rows, layer.declared_rows); + const int64_t rows = std::min(new_rows, physical_limit(layer)); if (!layer.growable || rows <= allocations_.at(index).rows) { continue; } @@ -418,6 +778,32 @@ Error CudaKVPool::grow( } rows_ = new_rows; growth_count_++; + invalidate_bindings(); + ET_LOG( + Info, + "offgraph_kv: grew flat_capacity=%lld->%lld allocated_bytes=%lld " + "growth_count=%lld", + static_cast(old_rows), + static_cast(new_rows), + static_cast(allocated_bytes_), + static_cast(growth_count_)); + return Error::Ok; +} + +CudaGraphMetrics CudaKVPool::graph_metrics(std::string_view method) const { + CudaGraphMetrics result; + for (const auto& [handle, descriptors] : descriptors_) { + if (handle->method_name == method) { + const auto& metrics = handle->cuda_graph_state.metrics; + result.captures += metrics.captures; + result.replays += metrics.replays; + result.capture_failures += metrics.capture_failures; + } + } + return result; +} + +void CudaKVPool::invalidate_bindings() { // Every program sharing this pool now points at freed storage: drop the // bindings so each rebinds before its next run, and any captured CUDA graph // so it is captured again against the new storage. Prefill usually grows @@ -437,14 +823,172 @@ Error CudaKVPool::grow( graph.warmup_remaining = std::max(graph.warmup_remaining, 1); } } +} + +Error CudaKVPool::resize_columns( + int columns, + const std::vector>& retained_columns, + int64_t live_rows, + cudaStream_t stream, + bool trim_unused, + bool* committed) { + if (committed != nullptr) { + *committed = false; + } + ET_CHECK_OR_RETURN_ERROR( + !private_rows_ && declared_columns_ > 1 && columns >= 2 && + columns <= declared_columns_ && live_rows >= 0, + InvalidArgument, + "offgraph_kv: invalid physical columns %d/%d", + columns, + declared_columns_); + std::unordered_set sources; + std::unordered_set destinations; + bool relocate = false; + for (const auto& [from, to] : retained_columns) { + ET_CHECK_OR_RETURN_ERROR( + from >= 0 && from < columns_ - 1 && to >= 0 && to < columns - 1 && + sources.insert(from).second && destinations.insert(to).second, + InvalidArgument, + "offgraph_kv: invalid retained column %d->%d", + from, + to); + relocate |= from != to; + } + for (const Layer& layer : layers_) { + ET_CHECK_OR_RETURN_ERROR( + layer.growable && layer.declared_rows % declared_columns_ == 0, + InvalidArgument, + "offgraph_kv: physical-column resizing needs growable whole-row layers"); + } + if (!allocated_) { + initial_rows_ = initial_rows_ / columns_ * columns; + max_rows_ = max_rows_ / columns_ * columns; + columns_ = columns; + if (committed != nullptr) { + *committed = true; + } + return Error::Ok; + } + if (columns == columns_ && !relocate) { + return Error::Ok; + } + const auto device = CUDAGuard::create(device_); + ET_CHECK_OK_OR_RETURN_ERROR(device.error()); + // Resize is an explicit boundary, not a synchronization in every forward. + ET_CHECK_OK_OR_RETURN_ERROR(synchronize(/*all_streams=*/true)); + stream_ = stream; + if (trim_unused) { + CudaAllocator::release_cached_memory(device_); + } + const int old_columns = columns_; + int64_t next_rows = rows_ / old_columns; + if (trim_unused && columns < old_columns) { + // Drop unused height before allocating the new pitch. Retaining a former + // long owner's height in every replacement can exhaust memory while both + // layouts are live. A wrapped Ring keeps its modulus whenever live_rows + // extends beyond it; shorter histories fit below the new modulus. + const int64_t limit = next_rows; + next_rows = + std::min(limit, std::max(1, initial_rows_ / old_columns)); + const int64_t required = std::min(live_rows, limit - 1) + 1; + while (next_rows < required) { + next_rows = std::min(limit, next_rows * 2); + } + } + std::vector replacements; + replacements.reserve(layers_.size()); + auto roll_back = [&]() { + for (size_t index = 0; index < replacements.size(); ++index) { + discard(layers_[index], replacements[index], stream); + } + if (cudaStreamSynchronize(stream) == cudaSuccess && trim_unused) { + CudaAllocator::release_cached_memory(device_); + } + }; + for (size_t index = 0; index < layers_.size(); ++index) { + const int64_t logical_rows = + std::min(allocations_[index].rows / old_columns, next_rows); + Allocation replacement; + const Error error = allocate_layer( + layers_[index], logical_rows * columns, stream, replacement); + if (error != Error::Ok) { + roll_back(); + return error; + } + replacements.push_back(replacement); + } + for (size_t index = 0; index < layers_.size(); ++index) { + const Allocation& current = allocations_[index]; + const Allocation& replacement = replacements[index]; + const size_t slot = row_bytes(layers_[index]); + const size_t logical_rows = + static_cast(std::min(live_rows, current.rows / old_columns)); + if (logical_rows == 0) { + continue; + } + for (const auto& [from, to] : retained_columns) { + for (const auto& [dst, src] : + {std::pair{replacement.k, current.k}, + std::pair{replacement.v, current.v}}) { + const cudaError_t error = cudaMemcpy2DAsync( + static_cast(dst) + slot * to, + slot * columns, + static_cast(src) + slot * from, + slot * old_columns, + slot, + logical_rows, + cudaMemcpyDeviceToDevice, + stream); + if (error != cudaSuccess) { + ET_LOG( + Error, + "offgraph_kv: column copy failed: %s", + cudaGetErrorString(error)); + roll_back(); + return Error::Internal; + } + } + } + } + const cudaError_t synchronize_error = cudaStreamSynchronize(stream); + if (synchronize_error != cudaSuccess) { + ET_LOG( + Error, + "offgraph_kv: column copy fence failed: %s", + cudaGetErrorString(synchronize_error)); + roll_back(); + return Error::Internal; + } + invalidate_bindings(); + for (size_t index = 0; index < layers_.size(); ++index) { + discard(layers_[index], allocations_[index], stream); + } + allocations_ = std::move(replacements); + rows_ = next_rows * columns; + initial_rows_ = initial_rows_ / old_columns * columns; + max_rows_ = max_rows_ / old_columns * columns; + columns_ = columns; + column_resize_count_++; + if (committed != nullptr) { + *committed = true; + } + if (trim_unused) { + ET_CHECK_OR_RETURN_ERROR( + cudaStreamSynchronize(stream) == cudaSuccess, + Internal, + "offgraph_kv: cannot finish freeing obsolete column storage"); + CudaAllocator::release_cached_memory(device_); + } ET_LOG( Info, - "offgraph_kv: grew flat_capacity=%lld->%lld allocated_bytes=%lld " - "growth_count=%lld", - static_cast(old_rows), - static_cast(new_rows), + "offgraph_kv: resized columns=%d->%d live_columns=%zu " + "allocated_bytes=%lld column_resize_count=%lld", + old_columns, + columns_, + retained_columns.size(), static_cast(allocated_bytes_), - static_cast(growth_count_)); + static_cast(column_resize_count_)); return Error::Ok; } @@ -531,6 +1075,17 @@ Error CudaKVPool::build_descriptors(CudaDelegateHandle* handle) { "offgraph_kv: program carries %zu of %zu side buffers", found_side, side_specs_.size()); + for (const auto& [fqn, constant] : compiled) { + (void)constant; + ET_CHECK_OR_RETURN_ERROR( + fqn.compare(0, kOffGraphKVFqnPrefix.size(), kOffGraphKVFqnPrefix) != + 0 || + std::find(found_fqns.begin(), found_fqns.end(), fqn) != + found_fqns.end(), + InvalidProgram, + "offgraph_kv: unsupported storage metadata %s", + fqn.c_str()); + } discovered_fqns_.insert(found_fqns.begin(), found_fqns.end()); // A reload of the same handle replaces what it had rather than adding to // it, so its constants are never bound twice. diff --git a/backends/cuda/runtime/cuda_kv_pool.h b/backends/cuda/runtime/cuda_kv_pool.h index c78f85431bd..a30df2e39bc 100644 --- a/backends/cuda/runtime/cuda_kv_pool.h +++ b/backends/cuda/runtime/cuda_kv_pool.h @@ -11,13 +11,16 @@ #include #include #include +#include #include #include +#include #include #include #include #include +#include #include #include #include @@ -43,6 +46,9 @@ class CudaKVPool final { // Rows the compiled program declares for this layer's storage. int64_t declared_rows{0}; bool growable{false}; + // Private storage caps physical history at this window, while the program + // retains its legacy virtual Ring extent. Zero denotes a flat layer. + int64_t private_window{0}; }; // A constant the program declares by FQN with a fixed, contiguous shape. @@ -51,13 +57,18 @@ class CudaKVPool final { ::executorch::backends::aoti::slim::c10::ScalarType dtype{ ::executorch::backends::aoti::slim::c10::ScalarType::Byte}; std::vector sizes; + // BSHD step staging can grow along dimension 1 up to its declared shape. + bool step_rows{false}; }; CudaKVPool( std::vector layers, std::vector side_buffers, ::executorch::backends::aoti::slim::c10::ScalarType storage_dtype, - int64_t initial_rows); + int64_t initial_rows, + int declared_columns = 1, + int initial_columns = 1, + bool private_rows = false); CudaKVPool(const CudaKVPool&) = delete; CudaKVPool& operator=(const CudaKVPool&) = delete; @@ -82,9 +93,38 @@ class CudaKVPool final { runtime::Error prepare(int64_t required_rows, int64_t live_rows, cudaStream_t stream); + // Per-layer requirements and prior logical lengths, indexed by stable owner + // id. All spans and staging replacements commit together after their copies + // finish. No allocator trimming or fallible work follows the commit. + runtime::Error prepare_private( + const std::vector>& required_rows, + const std::vector& live_lengths, + int64_t step_rows, + cudaStream_t stream, + bool compact = false); + + const PrivateRowLayout& private_layout(size_t layer) const { + return private_layouts_.at(layer); + } + + // Flattened row counts remain multiples of the current physical width. + // Each pair is a retained old column and its new column. Dummy data is not + // retained. live_rows is the retained logical prefix, capped by each ring. + // Replacements commit only after all copies pass. committed may be true + // even on error if post-commit allocator trimming fails. + // A shrinking pitch with trim_unused also sheds unused row capacity before + // allocating replacements; live history and wrapped Ring moduli survive. + runtime::Error resize_columns( + int columns, + const std::vector>& retained_columns, + int64_t live_rows, + cudaStream_t stream, + bool trim_unused, + bool* committed = nullptr); + // Records where the step's work ends on its stream, for the next step to // follow if it runs on another. - runtime::Error mark_step_done(); + runtime::Error mark_step_done(cudaStream_t stream); // Orders `stream` behind the previous step's stream, so work issued on // another host thread (where cudaStreamPerThread names another stream) still @@ -94,6 +134,17 @@ class CudaKVPool final { // Host fence on the pool's device before cells can be reclaimed or reset. runtime::Error synchronize(bool all_streams = false); + bool requires_clear() const { + return private_fence_failed_; + } + + // Only the owning cache's successful device-wide clear permits reuse. + void reset_failure_after_clear() { + private_fence_failed_ = false; + } + + CudaGraphMetrics graph_metrics(std::string_view method) const; + // Points `handle`'s constants at the current storage. Cached until storage // moves. Precondition: allocated(). runtime::Error bind(CudaDelegateHandle* handle); @@ -127,8 +178,20 @@ class CudaKVPool final { int64_t growth_count() const { return growth_count_; } + int columns() const { + return columns_; + } + int64_t column_resize_count() const { + return column_resize_count_; + } private: + friend struct CudaKVPoolTestPeer; + using FenceFunction = cudaError_t (*)(cudaStream_t, bool); + // Isolated per-thread fault injection by the native CUDA unit tests. + static thread_local FenceFunction private_fence_for_testing_; + bool private_fence_failed_{false}; + struct Allocation { void* k{nullptr}; void* v{nullptr}; @@ -150,6 +213,8 @@ class CudaKVPool final { }; size_t row_bytes(const Layer& layer) const; + int64_t physical_limit(const Layer& layer) const; + void invalidate_bindings(); static std::vector layer_sizes(const Layer& layer); runtime::Error allocate_layer( const Layer& layer, @@ -174,6 +239,10 @@ class CudaKVPool final { ::executorch::backends::aoti::slim::c10::ScalarType storage_dtype_; int64_t initial_rows_; int64_t max_rows_{0}; + const int declared_columns_; + int columns_; + const bool private_rows_; + int64_t column_resize_count_{0}; int device_{0}; bool device_known_{false}; @@ -189,6 +258,8 @@ class CudaKVPool final { int64_t growth_count_{0}; std::vector allocations_; std::vector side_buffers_; + std::vector side_allocated_bytes_; + std::vector private_layouts_; std::unordered_map> descriptors_; std::unordered_map bound_; diff --git a/backends/cuda/runtime/private_kv_rows.md b/backends/cuda/runtime/private_kv_rows.md new file mode 100644 index 00000000000..7bcec1fe1d0 --- /dev/null +++ b/backends/cuda/runtime/private_kv_rows.md @@ -0,0 +1,182 @@ +# Private owner rows and shared Ring staging (ABI 3) + +CUDA solo, text-only batching exports opt into this layout with +`--private-kv-rows`. It requires the batched-sequence layout and BF16 KV storage; +it does not support DFlash, non-causal attention, or ABI 2's runtime-pitch flag. +Absent this option, existing ABI 1/2 exports and runtime paths are unchanged. +`get_offgraph_kv_sequence_info_abi = 3` selects the matching cache factory. + +The export still declares its maximum context, owner count, and step width. +These are addressing and admission ceilings, not initial allocations. Each +layer stores independently sized owner spans `(base_row, capacity)` in an arena, +plus one scratch row. An owner ID with no retained span has no rows until touched. Its +capacity then grows geometrically from `initial_capacity`, capped by the context +for a flat layer or the sliding window for a Ring layer. A long owner does not +increase other owners' row capacities. Geometric arena slack amortizes owner +admission; unrelated spans keep their positions. Growth uses free regions +disjoint from old payloads, so it can relocate one owner without changing device +addresses or recapturing graphs. Arena exhaustion or fragmentation at the +addressing ceiling creates a packed replacement. +Automatic packing preserves each owner's geometric growth capacity; it does +not shrink those capacities to the current token count. This retains growth +slack across subsequent decode steps without repacking at every token. +Removed owners' spans can be +retained for burst reuse. Reusing an ID can temporarily inherit that capacity; +explicit compaction plans live spans from their current requirements and the +initial capacity, releasing inherited excess as well as unused spans and arena +slack. It retains bounded geometric growth slack (at most the current span's +capacity), so resumed decode does not immediately regrow partially filled +spans. A wrapped Ring retains its window and modulus during compaction. + +ABI 2 width contraction with allocator trimming also sheds unused row height +before allocating the replacement pitch, keeping initial capacity and bounded +geometric slack for live prefixes. All replacements and copies still succeed +before commit; wrapped Rings keep their modulus when the live prefix exceeds it. + +The executor's automatic idle heuristic still uses owner counts. Closing a few +long owners while many short owners remain may therefore retain their spans +until explicit compaction. Byte-aware idle reclamation is a separate allocator +maintenance change; this layout does not yet provide that policy. + +## Frozen program and runtime contract + +All layer K/V constants retain the legacy BSHD virtual shape. The allocation +backing that shape can be smaller: only the private operators may access it, +using the runtime descriptors. No generic tensor copy or linear indexing over +the declared extent is valid. Constant metadata from a different cache layout +is rejected at load time. + +During low-memory AOTI compilation, explicitly runtime-owned empty KV buffers +remain storage-free CPU metadata views when Inductor clones or serializes +constants. Ownership is identified from the final lowered program's FQNs and +storage identities. Any graph-owned alias excludes its storage from this +optimization. Shape, stride, offset and nonzero metadata are preserved; +graph-owned cache clones keep their existing zero-initialization behavior. +Autotuning continues to hydrate real inputs and measure the original shapes. +The generated AOTI constant metadata still declares each runtime buffer's +logical byte extent, using Inductor's existing alignment rule. Only that size +field is corrected for identified empty storage after constructor generation; +no KV payload is initialized or serialized. An unexpected or missing size emission fails export rather than +silently producing an incompatible library. + +`seq_cols[T]` supplies stable owner IDs in the original query order and +`seq_info[2 * max_seqs, 4]` describes query runs. Each layer's +`owner_layout[max_seqs + 1, 2]` contains its private span descriptors. +`owner_step[max_seqs + 1, 3]` contains `(stage_start, absolute_start, +token_count)`. The last owner is padding and never contributes a visible +key. `stage_rows[T]` is a unique permutation that packs each owner's new K/V +rows contiguously without changing query order. + +Flat layers write their private span before attention. Ring layers first put +new K/V into shared per-layer staging, attend to frozen private history plus +that staging, and only then write the newest retained rows into the Ring. +This prevents a long chunk from overwriting history needed by its earlier +queries, without reserving `max_write - 1` extra device rows for every owner. +Stage allocations grow with the actual prepared step width, up to the export +ceiling. Attention selects a history or staging address before loading each +row, avoiding separate pipelined K/V tiles and their shared-memory overhead. +Logical visibility and reduction order follow the legacy virtual +key sweep; private placement does not reorder keys or change split-K dispatch. +For D=256, pipeline buffering is reduced on targets below 160 KiB of effective +shared memory. The original pipeline remains on large-SMEM targets; tiles are +unchanged on both. + +Private descriptor uploads and Ring undo transfers use one independent-copy +batch on CUDA 13.2+ streams using the batch API; older runtimes and the +legacy default stream retain individual copies. Both paths keep the same +stream ordering and host fences, and share reusable copy descriptors. Owner +layout contents are rebuilt only when the physical-layout generation changes. +Sorted unique archive runs validate without temporary per-owner map nodes; +interleaved or repeated-owner runs retain combined-end validation. + +Preparation uploads descriptor contents before execution. Descriptor addresses +stay fixed; stage or arena address changes fence the previous step and invalidate +bindings and CUDA graphs. Within-arena relocation copies only that owner's +retained rows, preserving every old source until commit. Failed preparation +fences queued copies before returning, including copies into unused arena rows. +Stable allocations replay graphs with new +metadata. The cache verbs and execution must remain serialized by the engine +thread. An aborted ABI 3 forward fences queued work and retires only the owners +in that step, whose Ring writes may have happened. `seq_rm` releases those +owners for reuse; unrelated owners can keep serving. A failed device fence +poisons the whole cache until a successful fenced `clear()`. + +## Clone, rewind, and memory accounting + +After a successful forward, the runtime archives the actual staged K/V rows +to pinned host transfer buffers and tagged, copy-on-write host pages. This +preserves the legacy rewind and clone window while device Ring history holds +only its window. Commit includes this transfer and synchronization; it is a +performance cost that same-work benchmarks must include. Clone does not mutate +its source. Restore validates the retained window before copying and fences +host page use before reuse or destruction. Rewind restores only the prefix +overwritten since the target position, and a no-op rewind performs no copies. +Clone copies still-resident Ring rows device-to-device and reads only evicted +rows from host history. The unused oldest Ring slot is masked out of both +key and value loads, so an unwritten slot cannot inject NaNs into attention. + +`allocated_bytes` counts device K/V history only. `device_staging_bytes` counts +shared device K/V staging separately. `host_undo_bytes` counts unique undo-page +payloads, tags, and pinned archive buffers; it excludes container overhead. +Driver/allocator peaks also include metadata, model weights, activations, +temporary replacement allocations, and retained allocator memory. + +Undo pages trade host RAM for device headroom; they are not free or hidden from +the accounting. For each Ring layer, the retained host bound is +`max_seqs * ceil(min(context, W + max_write - 1) / 64) * +(2 * 64 * row_bytes + 64 * sizeof(int32_t)) + 2 * max_write * row_bytes`, +including BF16 K/V pages, row tags, and pinned transfer staging. There is no +separate RAM-budget knob; the session and export limits bound this storage. +For 39 Ring layers with W=2048 and 2 KV heads of dimension 128, max_write=4096 +and 64 owners, this is about 14.8 GiB of retained host storage. The checker +asserts each profile's corresponding bound and reports host bytes beside the +device saving, including peak accounted undo storage across the workload. + +`check_private_kv_rows.py` compares identical mini model weights against ABI 2 +for exact logits, clone/rewind boundaries, heterogeneous owner lengths, graph +recapture/replay, driver memory contraction, and c1 through c64 same-work timing. +Four rounds balance AB/BA order. Timing covers steady decode, staggered +admission/growth, and clone/rewind cycles including GPU completion. A median +throughput regression beyond 2% fails performance qualification. Inputs vary by +owner, position and session lifetime so row-placement and stale-owner errors +change the selected logits; matching non-finite output is rejected. PR CI reports +timing independently from its blocking numerical/memory/graph checks. Automatic +CI reports timing; an explicit workflow dispatch can enforce it with +`enforce_private_kv_performance=true`. The same checker enforces timing when +invoked without `--report-performance`. A green report-only check does not qualify performance +or full-model serving. + +`--profile mg-ring` uses 52 layers, 32 query heads, two KV heads of dimension +128, the production `[2048,2048,2048,0]` attention pattern, a 4096-token write +budget, and a 128K logical context. Embedding/MLP dimensions and vocabulary +remain small: this qualifies production attention/cache geometry, not 30B +quantized GEMM or full-model serving performance. It includes 4096-token +writes and restores evicted Ring history at the legal 8192-to-4096 rollback +floor, then measures c1 through c64 with saturated Ring history. Its separate +A100 CI job preserves these limits rather than reducing them to fit the +mini test's A10G. + +The checker prints flushed CPU peak-RSS and available Linux cgroup memory +snapshots before model construction, before export and after export. These +diagnostics help distinguish export resource failures from GPU qualification; +they do not change the model dimensions or benchmark timing. Reproduce it with: + +```bash +python examples/models/muse-glimmer/tests/check_private_kv_rows.py \ + --probe /path/to/muse_glimmer_runtime_kv_probe \ + --output-dir /path/to/new-qualification-directory --profile mg-ring +``` + +Omitting `--report-performance` enforces the same 2% performance gate. + +The probe also reports cumulative CPU wall-time counters for preparation, +commit, archive transfer plus its device wait, and host-page append. The checker +differences these counters per operation and reports balanced-round medians. +Archive transfer and append are subcomponents of commit, not additional times +to sum with it. These measurements locate cache-side overhead; they are not +isolated GPU-kernel timings. Clear preserves counters for a complete run. + +A separate pressure phase keeps 48 short owners alive while closing 16 long +owners. It requires at least 16 MiB less live KV and at least 8 MiB less allocator +reservation and driver-used memory after compaction, exceeding pool page +granularity. Lower live-byte counters without actual driver release do not pass. diff --git a/backends/cuda/runtime/private_row_layout.h b/backends/cuda/runtime/private_row_layout.h new file mode 100644 index 00000000000..f4fae423deb --- /dev/null +++ b/backends/cuda/runtime/private_row_layout.h @@ -0,0 +1,184 @@ +/* + * 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 + +namespace executorch::backends::cuda { + +struct PrivateRowSpan { + int32_t base{0}; + int32_t capacity{0}; +}; + +struct PrivateRowLayout { + // Stable owner indices. The last entry is one scratch row. Unassigned arena + // space amortizes admissions; it does not change any owner's capacity. + std::vector spans; + int32_t rows{0}; + bool repacked{false}; +}; + +// Plan without touching live payloads. Normal growth keeps unrelated spans +// fixed and chooses destinations disjoint from every old source. Compaction +// and fragmentation fallback pack live spans and require a fresh allocation. +inline runtime::Result make_private_row_layout( + runtime::Span required_rows, + runtime::Span previous, + int64_t initial_rows, + int64_t limit, + bool compact = false) { + constexpr int64_t max_rows = std::numeric_limits::max(); + if (initial_rows <= 0 || limit <= 0 || limit > max_rows || + required_rows.size() >= static_cast(max_rows) || + (!previous.empty() && previous.size() != required_rows.size() + 1)) { + return runtime::Error::InvalidArgument; + } + const int64_t arena_limit = std::min( + max_rows, static_cast(required_rows.size()) * limit + 1); + const int64_t old_rows = previous.empty() + ? 0 + : static_cast(previous[required_rows.size()].base) + 1; + if (!previous.empty() && + (old_rows <= 0 || old_rows > arena_limit || + previous[required_rows.size()].capacity != 1)) { + return runtime::Error::InvalidArgument; + } + struct Occupied { + int64_t base; + int64_t end; + size_t owner; + }; + std::vector occupied; + std::vector capacities(required_rows.size()); + int64_t packed_rows = 0; + for (size_t owner = 0; owner < required_rows.size(); ++owner) { + const int64_t required = required_rows[owner]; + const int64_t old = previous.empty() ? 0 : previous[owner].capacity; + const int64_t base = previous.empty() ? 0 : previous[owner].base; + if (required < 0 || required > limit || old < 0 || old > limit || + base < 0 || (!previous.empty() && base + old >= old_rows)) { + return runtime::Error::InvalidArgument; + } + if (old > 0) { + occupied.push_back({base, base + old, owner}); + } + int64_t capacity = 0; + if (required > 0) { + capacity = old > 0 && !compact ? old : std::min(initial_rows, limit); + if (compact) { + // Preserve bounded geometric decode slack while shedding inherited + // oversized spans. Never grow a live span merely to compact it. + const int64_t target = std::min(limit, required + 1); + while (capacity < target) { + capacity = std::min(limit, capacity * 2); + } + if (old >= required) { + capacity = std::min(capacity, old); + } + } else if (required > capacity) { + capacity = std::min(limit, std::max(required, capacity * 2)); + } + } + if (capacity > arena_limit - packed_rows - 1) { + return runtime::Error::InvalidArgument; + } + capacities[owner] = capacity; + packed_rows += capacity; + } + std::sort(occupied.begin(), occupied.end(), [](const auto& a, const auto& b) { + return a.base < b.base; + }); + for (size_t i = 1; i < occupied.size(); ++i) { + if (occupied[i].base < occupied[i - 1].end) { + return runtime::Error::InvalidArgument; + } + } + PrivateRowLayout layout; + layout.spans.resize(required_rows.size() + 1); + const auto packed_layout = [&]() { + int64_t base = 0; + for (size_t owner = 0; owner < capacities.size(); ++owner) { + layout.spans[owner] = { + static_cast(base), static_cast(capacities[owner])}; + base += capacities[owner]; + } + layout.rows = static_cast(base + 1); + layout.spans.back() = {static_cast(base), 1}; + if (!previous.empty()) { + layout.repacked = layout.rows != old_rows; + for (size_t owner = 0; owner < capacities.size(); ++owner) { + layout.repacked |= layout.spans[owner].base != previous[owner].base; + } + } + return layout; + }; + if (compact || previous.empty()) { + return packed_layout(); + } + int64_t end = 0; + for (size_t owner = 0; owner < capacities.size(); ++owner) { + const int64_t capacity = capacities[owner]; + const auto old = previous[owner]; + int64_t base = old.base; + if (capacity > old.capacity) { + // Extending an unwrapped owner's span in place preserves its payload. + bool extends = old.capacity > 0 && base + capacity < arena_limit; + for (const auto& range : occupied) { + if (range.owner != owner && base < range.end && + base + capacity > range.base) { + extends = false; + } + } + if (!extends) { + // Old sources remain occupied until the entire transaction commits. + std::sort( + occupied.begin(), occupied.end(), [](const auto& a, const auto& b) { + return a.base < b.base; + }); + base = 0; + for (const auto& range : occupied) { + if (base + capacity <= range.base) { + break; + } + base = std::max(base, range.end); + } + } + if (base + capacity >= arena_limit) { + // All owners can fit by capacity; fragmentation is not admission + // failure. A packed replacement can overlap old sources safely. Keep + // the capacities already chosen for growth; only explicit compaction + // may shrink them to the current requirements. + return packed_layout(); + } + occupied.push_back({base, base + capacity, owner}); + } + layout.spans[owner] = { + static_cast(base), static_cast(capacity)}; + if (capacity > 0) { + end = std::max(end, base + capacity); + } + } + int64_t rows = std::max(old_rows, end + 1); + if (rows > old_rows) { + rows = std::min(arena_limit, std::max(rows, 2 * (old_rows - 1) + 1)); + } + layout.rows = static_cast(rows); + layout.spans.back() = {static_cast(rows - 1), 1}; + return layout; +} + +} // namespace executorch::backends::cuda diff --git a/backends/cuda/runtime/ring_history.h b/backends/cuda/runtime/ring_history.h new file mode 100644 index 00000000000..8a34fd5b69f --- /dev/null +++ b/backends/cuda/runtime/ring_history.h @@ -0,0 +1,290 @@ +/* + * 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 + +namespace executorch::backends::cuda { + +// Host undo history for a device ring with no per-owner write headroom. +// A completed step arrives as [planes, step_tokens, row_bytes]; only real +// segments enter the archive. Page tags distinguish retained logical rows +// from stale rows after wrapping. Clones share pages until a later write. +// Not thread-safe: the owning cache serializes calls and fences the incoming +// device-to-host transfer before append(). Returned rows remain valid until +// the next mutation, so a restore must finish before pages can be released. +class RingHistory final { + public: + struct Run { + int32_t owner; + int packed_start; + int length; + int absolute_start; + }; + + struct Rows { + const uint8_t* data; + int count; + }; + + struct RestorePlan { + // [start, resident_start) comes from undo history; the remaining rows + // through end are still in the source's device Ring. + int start; + int resident_start; + int end; + }; + + static std::optional + restore_plan(int window, int keep, int resident_end) { + if (window <= 0 || keep < 0 || resident_end < keep) { + return std::nullopt; + } + const int start = std::max(0, keep - window + 1); + const int resident = std::max(0, resident_end - window + 1); + return RestorePlan{start, std::min(keep, std::max(start, resident)), keep}; + } + + static runtime::Result> create( + int window, + int max_write, + int context_limit, + size_t row_bytes, + size_t planes) { + if (window <= 0 || max_write <= 0 || context_limit < max_write || + row_bytes == 0 || planes == 0 || + row_bytes > std::numeric_limits::max() / kPageRows / planes || + row_bytes > std::numeric_limits::max() / max_write / planes) { + return runtime::Error::InvalidArgument; + } + const int rows = static_cast(std::min( + context_limit, static_cast(window) + max_write - 1)); + return std::unique_ptr(new RingHistory( + std::min(window, context_limit), + max_write, + context_limit, + rows, + row_bytes, + planes)); + } + + runtime::Error append( + runtime::Span runs, + runtime::Span packed, + int step_tokens) { + if (runs.empty() || step_tokens <= 0 || step_tokens > max_write_ || + packed.size() != + planes_ * static_cast(step_tokens) * row_bytes_) { + return runtime::Error::InvalidArgument; + } + // Validate the whole step before changing any owner or shared page. + int packed_end = 0; + const bool unique_sorted = + std::adjacent_find( + runs.begin(), runs.end(), [](const Run& first, const Run& second) { + return first.owner >= second.owner; + }) == runs.end(); + std::map ends; + for (const auto& run : runs) { + if (run.owner < 0 || run.packed_start < packed_end || run.length <= 0 || + run.length > step_tokens || + run.packed_start > step_tokens - run.length || + run.absolute_start < 0 || + run.absolute_start > context_limit_ - run.length) { + return runtime::Error::InvalidArgument; + } + const auto existing = owners_.find(run.owner); + const int retained_end = + existing == owners_.end() ? 0 : existing->second.end; + if (unique_sorted) { + if (run.absolute_start != retained_end) { + return runtime::Error::InvalidState; + } + } else { + auto end = ends.emplace(run.owner, retained_end).first; + if (run.absolute_start != end->second) { + return runtime::Error::InvalidState; + } + end->second += run.length; + } + packed_end = run.packed_start + run.length; + } + for (const auto& run : runs) { + auto& owner = owners_[run.owner]; + if (owner.pages.empty()) { + owner.pages.resize((rows_ - 1) / kPageRows + 1); + } + int done = 0; + while (done < run.length) { + const int absolute = run.absolute_start + done; + const int physical = absolute % rows_; + const int page_row = physical % kPageRows; + const int count = std::min( + run.length - done, + std::min(rows_ - physical, kPageRows - page_row)); + auto& page = owner.pages[physical / kPageRows]; + if (!page) { + page = std::make_shared(planes_ * kPageRows * row_bytes_); + } else if (page.use_count() > 1) { + page = std::make_shared(*page); + } + for (size_t plane = 0; plane < planes_; ++plane) { + std::memcpy( + page->bytes.data() + (plane * kPageRows + page_row) * row_bytes_, + packed.data() + + (plane * step_tokens + run.packed_start + done) * row_bytes_, + static_cast(count) * row_bytes_); + } + for (int row = 0; row < count; ++row) { + page->positions[page_row + row] = absolute + row; + } + done += count; + } + owner.end = run.absolute_start + run.length; + owner.written = std::max(owner.written, owner.end); + } + return runtime::Error::Ok; + } + + std::optional + read(int32_t owner_id, int start, int max_rows, size_t plane) const { + const auto owner = owners_.find(owner_id); + if (owner == owners_.end() || start < 0 || start >= owner->second.end || + max_rows <= 0 || plane >= planes_) { + return std::nullopt; + } + const int physical = start % rows_; + const int page_row = physical % kPageRows; + const auto& page = owner->second.pages[physical / kPageRows]; + if (!page) { + return std::nullopt; + } + const int count = std::min( + std::min(max_rows, owner->second.end - start), + std::min(rows_ - physical, kPageRows - page_row)); + for (int row = 0; row < count; ++row) { + if (page->positions[page_row + row] != start + row) { + return std::nullopt; + } + } + return Rows{ + page->bytes.data() + (plane * kPageRows + page_row) * row_bytes_, + count}; + } + + bool clone(int32_t source, int32_t destination, int keep) { + if (destination < 0 || owners_.count(destination) != 0 || + !has_window(source, keep)) { + return false; + } + const auto& original = owners_.at(source); + owners_.emplace(destination, Owner{original.pages, keep, original.written}); + return true; + } + + bool rewind(int32_t owner, int keep) { + if (!has_window(owner, keep)) { + return false; + } + owners_.at(owner).end = keep; + return true; + } + + void erase(int32_t owner) { + owners_.erase(owner); + } + + void clear() { + owners_.clear(); + } + + bool has_window(int32_t owner, int keep) const { + const auto found = owners_.find(owner); + if (found == owners_.end() || + keep < std::max(0, found->second.written - max_write_) || + keep > found->second.end) { + return false; + } + for (int start = std::max(0, keep - window_ + 1); start < keep;) { + const auto chunk = read(owner, start, keep - start, 0); + if (!chunk) { + return false; + } + start += chunk->count; + } + return true; + } + + // Unique payload and row-tag bytes, excluding container overhead. + size_t resident_bytes() const { + std::unordered_set pages; + size_t bytes = 0; + for (const auto& [id, owner] : owners_) { + for (const auto& page : owner.pages) { + if (page && pages.insert(page.get()).second) { + bytes += page->bytes.size() + sizeof(page->positions); + } + } + } + return bytes; + } + + private: + static constexpr int kPageRows = 64; + + struct Page { + explicit Page(size_t size) : bytes(size) { + positions.fill(-1); + } + std::vector bytes; + std::array positions; + }; + + struct Owner { + std::vector> pages; + int end{0}; + int written{0}; + }; + + RingHistory( + int window, + int max_write, + int context_limit, + int rows, + size_t row_bytes, + size_t planes) + : window_(window), + max_write_(max_write), + context_limit_(context_limit), + rows_(rows), + row_bytes_(row_bytes), + planes_(planes) {} + + const int window_; + const int max_write_; + const int context_limit_; + const int rows_; + const size_t row_bytes_; + const size_t planes_; + std::map owners_; +}; + +} // namespace executorch::backends::cuda diff --git a/backends/cuda/runtime/targets.bzl b/backends/cuda/runtime/targets.bzl index 442cff2d434..e001f25c6ef 100644 --- a/backends/cuda/runtime/targets.bzl +++ b/backends/cuda/runtime/targets.bzl @@ -128,7 +128,7 @@ def define_common_targets(is_fbcode = False): "cuda_delegate_handle.h", "cuda_mutable_state.h", "cuda_weight_cache.h", - ] + (["cuda_kv_cache.h", "cuda_kv_pool.h"] if with_llm_cache else []), + ] + (["cuda_kv_cache.h", "cuda_kv_pool.h", "ring_history.h", "private_row_layout.h"] if with_llm_cache else []), # @lint-ignore BUCKLINT: Avoid `link_whole=True` (https://fburl.com/avoid-link-whole) link_whole = True, supports_python_dlopen = True, @@ -223,6 +223,24 @@ def define_common_targets(is_fbcode = False): ), ) + cpp_unittest( + name = "test_cuda_ring_history", + srcs = ["test/test_ring_history.cpp"], + deps = [ + ":cuda_backend", + "//executorch/runtime/core:core", + ], + ) + + cpp_unittest( + name = "test_cuda_private_row_layout", + srcs = ["test/test_private_row_layout.cpp"], + deps = [ + ":cuda_backend", + "//executorch/runtime/core:core", + ], + ) + cpp_unittest( name = "test_cuda_kv_cache", srcs = [ diff --git a/backends/cuda/runtime/test/test_cuda_backend_execute.cpp b/backends/cuda/runtime/test/test_cuda_backend_execute.cpp index ecdaef11f7e..0c7d99a3fed 100644 --- a/backends/cuda/runtime/test/test_cuda_backend_execute.cpp +++ b/backends/cuda/runtime/test/test_cuda_backend_execute.cpp @@ -8,6 +8,9 @@ #include #include +#if defined(EXECUTORCH_BUILD_EXTENSION_LLM) +#include +#endif #include #include @@ -20,6 +23,7 @@ using namespace ::executorch::backends::cuda; namespace { bool program_ran = false; +Error program_error = Error::Ok; Error one_tensor(aoti::AOTInductorModelContainerHandle, size_t* count) { *count = 1; @@ -40,7 +44,7 @@ Error fake_run( for (size_t i = 0; i < num_inputs; ++i) { delete reinterpret_cast(inputs[i]); } - return Error::Ok; + return program_error; } class CudaBackendExecuteTest : public ::testing::Test { @@ -59,6 +63,7 @@ class CudaBackendExecuteTest : public ::testing::Test { ASSERT_EQ(cudaMalloc(&input_, sizeof(float) * 4), cudaSuccess); ASSERT_EQ(cudaMalloc(&output_, sizeof(float) * 4), cudaSuccess); program_ran = false; + program_error = Error::Ok; } void TearDown() override { @@ -124,4 +129,180 @@ TEST_F(CudaBackendExecuteTest, OutputWithBufferRuns) { EXPECT_TRUE(program_ran); } +TEST_F( + CudaBackendExecuteTest, + GraphMetricsCountCapturesAndReplayAcrossRecapture) { + if (!handle_.cuda_graph_state.start_warmup()) { + GTEST_SKIP() << "CUDA graph allocator unavailable"; + } + for (int i = 0; i < 8; ++i) { + ASSERT_EQ(execute(input_, output_), Error::Ok); + } + const auto first = handle_.cuda_graph_state.metrics; + EXPECT_EQ(first.captures, 1); + EXPECT_GT(first.replays, first.captures); + EXPECT_EQ(first.capture_failures, 0); + handle_.cuda_graph_state.recapture(); + for (int i = 0; i < 4; ++i) { + ASSERT_EQ(execute(input_, output_), Error::Ok); + } + EXPECT_EQ(handle_.cuda_graph_state.metrics.captures, 2); + EXPECT_GT(handle_.cuda_graph_state.metrics.replays, first.replays); + EXPECT_EQ(handle_.cuda_graph_state.metrics.capture_failures, 0); +} + +TEST(CudaGraphStateTest, MetricsSurviveMoveAndResourceRelease) { + CudaGraphState source; + source.metrics = {2, 11, 1}; + CudaGraphState moved(std::move(source)); + EXPECT_EQ(source.metrics.captures, 0); + EXPECT_EQ(moved.metrics.captures, 2); + moved.release(); + EXPECT_EQ(moved.metrics.replays, 11); + CudaGraphState assigned; + assigned = std::move(moved); + EXPECT_EQ(moved.metrics.replays, 0); + EXPECT_EQ(assigned.metrics.captures, 2); + EXPECT_EQ(assigned.metrics.replays, 11); + EXPECT_EQ(assigned.metrics.capture_failures, 1); +} + +#if defined(EXECUTORCH_BUILD_EXTENSION_LLM) +class PreparedCache final : public CudaKVCache { + public: + Result note_handle(CudaDelegateHandle*) override { + return false; + } + void forget_handle(CudaDelegateHandle*) override {} + Error rebind_for_execute(CudaDelegateHandle*) override { + return rebind_error; + } + Error prepare_step(int64_t width, cudaStream_t) override { + ++prepares; + EXPECT_EQ(width, 4); + if (prepared) { + return Error::InvalidState; + } + prepared = prepare_error == Error::Ok; + return prepare_error; + } + Error commit_step(int64_t width) override { + ++commits; + EXPECT_EQ(width, 4); + if (commit_error == Error::Ok) { + prepared = false; + } + return commit_error; + } + Error abort_step() override { + ++aborts; + if (abort_error == Error::Ok) { + prepared = false; + } + return abort_error; + } + OffGraphKVMetrics metrics() const override { + return {}; + } + + bool prepared = false; + int prepares = 0; + int commits = 0; + int aborts = 0; + Error prepare_error = Error::Ok; + Error rebind_error = Error::Ok; + Error commit_error = Error::Ok; + Error abort_error = Error::Ok; +}; + +TEST_F(CudaBackendExecuteTest, FailedPreparationDoesNotAbort) { + PreparedCache cache; + handle_.kv_cache = &cache; + cache.prepare_error = Error::MemoryAllocationFailed; + EXPECT_EQ(execute(input_, output_), Error::MemoryAllocationFailed); + EXPECT_FALSE(program_ran); + EXPECT_FALSE(cache.prepared); + EXPECT_EQ(cache.prepares, 1); + EXPECT_EQ(cache.commits, 0); + EXPECT_EQ(cache.aborts, 0); +} + +TEST_F(CudaBackendExecuteTest, FailedRebindAbortsAndAllowsNextForward) { + PreparedCache cache; + handle_.kv_cache = &cache; + cache.rebind_error = Error::InvalidArgument; + EXPECT_EQ(execute(input_, output_), Error::InvalidArgument); + EXPECT_FALSE(program_ran); + EXPECT_FALSE(cache.prepared); + EXPECT_EQ(cache.aborts, 1); + EXPECT_EQ(cache.commits, 0); + + cache.rebind_error = Error::Ok; + EXPECT_EQ(execute(input_, output_), Error::Ok); + EXPECT_TRUE(program_ran); + EXPECT_FALSE(cache.prepared); + EXPECT_EQ(cache.prepares, 2); + EXPECT_EQ(cache.commits, 1); + EXPECT_EQ(cache.aborts, 1); +} + +TEST_F(CudaBackendExecuteTest, FailedProgramAbortsAndAllowsNextForward) { + PreparedCache cache; + handle_.kv_cache = &cache; + program_error = Error::Internal; + EXPECT_EQ(execute(input_, output_), Error::Internal); + EXPECT_TRUE(program_ran); + EXPECT_FALSE(cache.prepared); + EXPECT_EQ(cache.commits, 0); + EXPECT_EQ(cache.aborts, 1); + + program_error = Error::Ok; + EXPECT_EQ(execute(input_, output_), Error::Ok); + EXPECT_FALSE(cache.prepared); + EXPECT_EQ(cache.prepares, 2); + EXPECT_EQ(cache.commits, 1); + EXPECT_EQ(cache.aborts, 1); +} + +TEST_F(CudaBackendExecuteTest, FailedCommitAbortsAndAllowsNextForward) { + PreparedCache cache; + handle_.kv_cache = &cache; + cache.commit_error = Error::Internal; + EXPECT_EQ(execute(input_, output_), Error::Internal); + EXPECT_TRUE(program_ran); + EXPECT_FALSE(cache.prepared); + EXPECT_EQ(cache.commits, 1); + EXPECT_EQ(cache.aborts, 1); + + cache.commit_error = Error::Ok; + EXPECT_EQ(execute(input_, output_), Error::Ok); + EXPECT_FALSE(cache.prepared); + EXPECT_EQ(cache.prepares, 2); + EXPECT_EQ(cache.commits, 2); + EXPECT_EQ(cache.aborts, 1); +} + +TEST_F(CudaBackendExecuteTest, SuccessfulForwardCommitsWithoutAbort) { + PreparedCache cache; + handle_.kv_cache = &cache; + EXPECT_EQ(execute(input_, output_), Error::Ok); + EXPECT_TRUE(program_ran); + EXPECT_FALSE(cache.prepared); + EXPECT_EQ(cache.prepares, 1); + EXPECT_EQ(cache.commits, 1); + EXPECT_EQ(cache.aborts, 0); +} + +TEST_F(CudaBackendExecuteTest, FailedAbortPreservesOriginalError) { + PreparedCache cache; + handle_.kv_cache = &cache; + cache.rebind_error = Error::InvalidArgument; + cache.abort_error = Error::Internal; + EXPECT_EQ(execute(input_, output_), Error::InvalidArgument); + EXPECT_FALSE(program_ran); + EXPECT_TRUE(cache.prepared); + EXPECT_EQ(cache.aborts, 1); +} +#endif + } // namespace diff --git a/backends/cuda/runtime/test/test_cuda_kv_cache.cpp b/backends/cuda/runtime/test/test_cuda_kv_cache.cpp index 8d753579de0..e6b9ca98744 100644 --- a/backends/cuda/runtime/test/test_cuda_kv_cache.cpp +++ b/backends/cuda/runtime/test/test_cuda_kv_cache.cpp @@ -34,6 +34,45 @@ namespace slimc10 = ::executorch::backends::aoti::slim::c10; using ::executorch::runtime::Error; using ::executorch::runtime::EValue; +namespace executorch::backends::cuda { + +struct CudaKVPoolTestPeer { + CudaKVPoolTestPeer() + : previous_hook(CudaKVPool::private_fence_for_testing_), + previous(active) { + active = this; + CudaKVPool::private_fence_for_testing_ = fence; + } + ~CudaKVPoolTestPeer() { + CudaKVPool::private_fence_for_testing_ = previous_hook; + active = previous; + } + int device_fences{0}; + bool fail_stream_fence{false}; + bool fail_device_fence{false}; + + private: + static cudaError_t fence(cudaStream_t stream, bool all_streams) { + const auto result = + all_streams ? cudaDeviceSynchronize() : cudaStreamSynchronize(stream); + active->device_fences += all_streams; + bool& fail = + all_streams ? active->fail_device_fence : active->fail_stream_fence; + if (result == cudaSuccess && fail) { + fail = false; + return cudaErrorUnknown; + } + return result; + } + CudaKVPool::FenceFunction previous_hook; + CudaKVPoolTestPeer* previous; + static thread_local CudaKVPoolTestPeer* active; +}; + +thread_local CudaKVPoolTestPeer* CudaKVPoolTestPeer::active = nullptr; + +} // namespace executorch::backends::cuda + namespace { struct Binding { @@ -1197,6 +1236,454 @@ class CudaKVPoolTest : public CudaKVCacheTest { } // namespace +namespace { + +class CudaPrivatePoolTest : public CudaKVCacheTest { + protected: + static constexpr int kOwners = 64; + static constexpr int kColumns = kOwners + 1; + static constexpr int kFlatRows = 32; + static constexpr int kRingRows = 12; + static constexpr int kWindow = 5; + + std::unique_ptr make_private_pool(bool huge_stage = false) { + return std::make_unique( + std::vector{ + {kHeads, kDim, kFlatRows * kColumns, true, 0}, + {kHeads, kDim, kRingRows * kColumns, true, kWindow}}, + std::vector{ + {"__et_offgraph_kv_private_layout", + slimc10::ScalarType::Int, + {kColumns, 2}}, + {"__et_offgraph_kv_stage_k", + slimc10::ScalarType::BFloat16, + {1, + huge_stage ? 1 << 20 : 8, + huge_stage ? 1 : kHeads, + huge_stage ? 1 << 20 : kDim}, + true}, + {"__et_offgraph_kv_stage_v", + slimc10::ScalarType::BFloat16, + {1, huge_stage ? 1 << 20 : 8, kHeads, kDim}, + true}}, + slimc10::ScalarType::BFloat16, + 2 * kColumns, + kColumns, + kColumns, + true); + } + + static FakeContainer private_container(bool huge_stage = false) { + FakeContainer container{ + {"flat_k", + "flat_v", + "ring_k", + "ring_v", + "layout", + "stage_k", + "stage_v"}, + {"__et_offgraph_kv_layer_0_k", + "__et_offgraph_kv_layer_0_v", + "__et_offgraph_kv_layer_1_k", + "__et_offgraph_kv_layer_1_v", + "__et_offgraph_kv_private_layout", + "__et_offgraph_kv_stage_k", + "__et_offgraph_kv_stage_v"}, + {}, + 0}; + for (const char* suffix : {"k", "v"}) { + declare( + container, + cu::offgraph_kv_layer_fqn(0, suffix), + slimc10::ScalarType::BFloat16, + {1, kFlatRows * kColumns, kHeads, kDim}); + declare( + container, + cu::offgraph_kv_layer_fqn(1, suffix), + slimc10::ScalarType::BFloat16, + {1, kRingRows * kColumns, kHeads, kDim}); + } + declare( + container, + "__et_offgraph_kv_private_layout", + slimc10::ScalarType::Int, + {kColumns, 2}); + for (const char* fqn : + {"__et_offgraph_kv_stage_k", "__et_offgraph_kv_stage_v"}) { + declare( + container, + fqn, + slimc10::ScalarType::BFloat16, + huge_stage + ? (std::string(fqn) == "__et_offgraph_kv_stage_k" + ? std::initializer_list{1, 1 << 20, 1, 1 << 20} + : std::initializer_list{1, 1 << 20, kHeads, kDim}) + : std::initializer_list{1, 8, kHeads, kDim}); + } + return container; + } + + static void write_row( + cu::CudaKVPool& pool, + size_t layer, + size_t owner, + int row, + uint16_t tag) { + const auto& span = pool.private_layout(layer).spans.at(owner); + ASSERT_LT(row, span.capacity); + for (bool value : {false, true}) { + std::vector payload(kHeads * kDim); + for (size_t i = 0; i < payload.size(); ++i) { + payload[i] = tag + i + (value ? 10000 : 0); + } + auto* dst = static_cast(pool.layer_data(layer, value)) + + (span.base + row) * kHeads * kDim; + ASSERT_EQ( + cudaMemcpy( + dst, + payload.data(), + payload.size() * sizeof(uint16_t), + cudaMemcpyHostToDevice), + cudaSuccess); + } + } + + static void expect_row( + cu::CudaKVPool& pool, + size_t layer, + size_t owner, + int row, + uint16_t tag) { + const auto& span = pool.private_layout(layer).spans.at(owner); + ASSERT_LT(row, span.capacity); + for (bool value : {false, true}) { + std::vector actual(kHeads * kDim); + const auto* src = + static_cast(pool.layer_data(layer, value)) + + (span.base + row) * kHeads * kDim; + ASSERT_EQ( + cudaMemcpy( + actual.data(), + src, + actual.size() * sizeof(uint16_t), + cudaMemcpyDeviceToHost), + cudaSuccess); + for (size_t i = 0; i < actual.size(); ++i) { + EXPECT_EQ(actual[i], tag + i + (value ? 10000 : 0)); + } + } + } +}; + +} // namespace + +TEST_F( + CudaPrivatePoolTest, + Heterogeneous64OwnersKeepTheirOwnCapacityAndPayload) { + auto pool = make_private_pool(); + auto container = private_container(); + auto handle = make_handle(container); + ASSERT_TRUE(pool->note_handle(&handle).get()); + ASSERT_EQ(pool->validate(), Error::Ok); + std::vector> rows(2, std::vector(kOwners, 0)); + std::vector live(kOwners, 0); + rows[0][0] = rows[1][0] = 1; + ASSERT_EQ( + pool->prepare_private(rows, live, 1, cudaStreamPerThread), Error::Ok); + EXPECT_EQ(pool->private_layout(0).rows, 3); + EXPECT_EQ(pool->private_layout(1).rows, 3); + for (auto& layer : rows) { + std::fill(layer.begin(), layer.end(), 1); + } + live[0] = 1; + ASSERT_EQ( + pool->prepare_private(rows, live, 1, cudaStreamPerThread), Error::Ok); + EXPECT_EQ(pool->private_layout(0).rows, 2 * kOwners + 1); + for (size_t owner = 0; owner < kOwners; ++owner) { + write_row(*pool, 0, owner, 0, owner * 100); + write_row(*pool, 1, owner, 0, owner * 100 + 50); + } + ASSERT_EQ(pool->mark_step_done(cudaStreamPerThread), Error::Ok); + std::fill(live.begin(), live.end(), 1); + rows[0][17] = 17; + rows[1][17] = kWindow; + ASSERT_EQ( + pool->prepare_private(rows, live, 1, cudaStreamPerThread), Error::Ok); + EXPECT_EQ(pool->private_layout(0).spans[17].capacity, 17); + EXPECT_EQ(pool->private_layout(1).spans[17].capacity, kWindow); + for (size_t owner = 0; owner < kOwners; ++owner) { + if (owner != 17) { + EXPECT_EQ(pool->private_layout(0).spans[owner].capacity, 2); + EXPECT_EQ(pool->private_layout(1).spans[owner].capacity, 2); + } + expect_row(*pool, 0, owner, 0, owner * 100); + expect_row(*pool, 1, owner, 0, owner * 100 + 50); + } + EXPECT_EQ(pool->private_layout(0).rows, 4 * kOwners + 1); + pool->forget_handle(&handle); +} + +TEST_F( + CudaPrivatePoolTest, + CompactionRetainsWrappedRingRowsAndStableStageAddresses) { + auto pool = make_private_pool(); + auto container = private_container(); + auto handle = make_handle(container); + ASSERT_TRUE(pool->note_handle(&handle).get()); + std::vector> rows(2, std::vector(kOwners, 0)); + rows[0][0] = rows[0][1] = 11; + rows[1][0] = rows[1][1] = kWindow; + std::vector live(kOwners, 0); + ASSERT_EQ( + pool->prepare_private(rows, live, 8, cudaStreamPerThread), Error::Ok); + for (int row = 0; row < kWindow; ++row) { + write_row(*pool, 1, 1, row, 200 + row); + } + const int64_t before = pool->allocated_bytes(); + void* stage_k = pool->side_buffer(1); + void* stage_v = pool->side_buffer(2); + ASSERT_EQ(pool->mark_step_done(cudaStreamPerThread), Error::Ok); + rows[0][0] = rows[1][0] = 0; + live[1] = 11; + ASSERT_EQ( + pool->prepare_private(rows, live, 0, cudaStreamPerThread, true), + Error::Ok); + EXPECT_EQ(pool->private_layout(0).spans[0].capacity, 0); + EXPECT_EQ(pool->private_layout(1).spans[1].base, 0); + EXPECT_LT(pool->allocated_bytes(), before); + EXPECT_EQ(pool->side_buffer(1), stage_k); + EXPECT_EQ(pool->side_buffer(2), stage_v); + for (int row = 0; row < kWindow; ++row) { + expect_row(*pool, 1, 1, row, 200 + row); + } + pool->forget_handle(&handle); +} + +TEST_F( + CudaPrivatePoolTest, + StageGrowthMovesOnlyStageAndInvalidatesReplayBindings) { + auto pool = make_private_pool(); + auto container = private_container(); + auto handle = make_handle(container); + ASSERT_TRUE(pool->note_handle(&handle).get()); + std::vector> rows(2, std::vector(kOwners, 0)); + rows[0][0] = 10; + rows[1][0] = kWindow; + std::vector live(kOwners, 0); + ASSERT_EQ( + pool->prepare_private(rows, live, 1, cudaStreamPerThread), Error::Ok); + ASSERT_EQ(pool->bind(&handle), Error::Ok); + void* key = pool->layer_data(0, false); + void* layout = pool->side_buffer(0); + void* stage = pool->side_buffer(1); + EXPECT_EQ(pool->side_buffer_bytes(1), 2 * kHeads * kDim * sizeof(uint16_t)); + handle.cuda_graph_state.phase = cu::CudaGraphPhase::Replay; + handle.cuda_graph_state.warmup_remaining = 0; + ASSERT_EQ( + pool->prepare_private(rows, live, 5, cudaStreamPerThread), Error::Ok); + EXPECT_EQ(pool->layer_data(0, false), key); + EXPECT_EQ(pool->side_buffer(0), layout); + EXPECT_NE(pool->side_buffer(1), stage); + EXPECT_EQ(pool->side_buffer_bytes(1), 5 * kHeads * kDim * sizeof(uint16_t)); + EXPECT_EQ(handle.cuda_graph_state.phase, cu::CudaGraphPhase::Warmup); + ASSERT_EQ(pool->bind(&handle), Error::Ok); + EXPECT_EQ(container.bound["layout"].data, layout); + EXPECT_EQ(container.bound["stage_k"].data, pool->side_buffer(1)); + stage = pool->side_buffer(1); + handle.cuda_graph_state.warmup_remaining = 0; + ASSERT_EQ( + pool->prepare_private(rows, live, 4, cudaStreamPerThread), Error::Ok); + EXPECT_EQ(pool->side_buffer(1), stage); + EXPECT_EQ(handle.cuda_graph_state.warmup_remaining, 0); + pool->forget_handle(&handle); +} + +TEST_F(CudaPrivatePoolTest, StaggeredAdmissionsAmortizeGraphInvalidation) { + auto pool = make_private_pool(); + auto fake = private_container(); + auto handle = make_handle(fake); + ASSERT_TRUE(pool->note_handle(&handle).get()); + std::vector> rows(2, std::vector(kOwners, 0)); + std::vector live(kOwners, 0); + int moves = 0; + for (int owner = 0; owner < kOwners; ++owner) { + const bool allocated = pool->allocated(); + void* old_key = allocated ? pool->layer_data(0, false) : nullptr; + const auto previous = allocated ? pool->private_layout(0).spans + : std::vector{}; + rows[0][owner] = rows[1][owner] = 1; + handle.cuda_graph_state.phase = cu::CudaGraphPhase::Replay; + ASSERT_EQ( + pool->prepare_private(rows, live, 1, cudaStreamPerThread), Error::Ok); + ASSERT_EQ(pool->bind(&handle), Error::Ok); + const bool moved = old_key != pool->layer_data(0, false); + moves += moved; + if (allocated) { + EXPECT_EQ( + handle.cuda_graph_state.phase, + moved ? cu::CudaGraphPhase::Warmup : cu::CudaGraphPhase::Replay); + } + for (int old = 0; old < owner; ++old) { + EXPECT_EQ(pool->private_layout(0).spans[old].base, previous[old].base); + expect_row(*pool, 0, old, 0, old * 100); + expect_row(*pool, 1, old, 0, old * 100 + 50); + } + write_row(*pool, 0, owner, 0, owner * 100); + write_row(*pool, 1, owner, 0, owner * 100 + 50); + live[owner] = 1; + ASSERT_EQ(pool->mark_step_done(cudaStreamPerThread), Error::Ok); + } + EXPECT_LE(moves, 7); + pool->forget_handle(&handle); +} + +TEST_F(CudaPrivatePoolTest, PrivateRelocationWithinArenaPreservesReplay) { + auto pool = make_private_pool(); + auto fake = private_container(); + auto handle = make_handle(fake); + ASSERT_TRUE(pool->note_handle(&handle).get()); + std::vector> rows(2, std::vector(kOwners, 0)); + std::vector live(kOwners, 0); + for (int owner = 0; owner < 3; ++owner) { + rows[0][owner] = rows[1][owner] = 1; + } + ASSERT_EQ( + pool->prepare_private(rows, live, 1, cudaStreamPerThread), Error::Ok); + for (int owner = 0; owner < 3; ++owner) { + write_row(*pool, 0, owner, 0, owner * 100); + write_row(*pool, 1, owner, 0, owner * 100 + 50); + live[owner] = 1; + } + ASSERT_EQ(pool->mark_step_done(cudaStreamPerThread), Error::Ok); + rows[0][3] = rows[1][3] = 1; + ASSERT_EQ( + pool->prepare_private(rows, live, 1, cudaStreamPerThread), Error::Ok); + ASSERT_EQ(pool->bind(&handle), Error::Ok); + write_row(*pool, 0, 3, 0, 300); + write_row(*pool, 1, 3, 0, 350); + live[3] = 1; + ASSERT_EQ(pool->mark_step_done(cudaStreamPerThread), Error::Ok); + const auto previous = pool->private_layout(0).spans; + void* key = pool->layer_data(0, false); + void* ring = pool->layer_data(1, false); + const int updates = fake.updates; + handle.cuda_graph_state.phase = cu::CudaGraphPhase::Replay; + rows[0][0] = rows[1][0] = 3; + ASSERT_EQ( + pool->prepare_private(rows, live, 1, cudaStreamPerThread), Error::Ok); + EXPECT_NE(pool->private_layout(0).spans[0].base, previous[0].base); + EXPECT_EQ(pool->private_layout(0).spans[0].capacity, 4); + EXPECT_EQ(pool->layer_data(0, false), key); + EXPECT_EQ(pool->layer_data(1, false), ring); + EXPECT_EQ(handle.cuda_graph_state.phase, cu::CudaGraphPhase::Replay); + ASSERT_EQ(pool->bind(&handle), Error::Ok); + EXPECT_EQ(fake.updates, updates); + for (int owner = 0; owner < 4; ++owner) { + if (owner > 0) { + EXPECT_EQ( + pool->private_layout(0).spans[owner].base, previous[owner].base); + } + expect_row(*pool, 0, owner, 0, owner * 100); + expect_row(*pool, 1, owner, 0, owner * 100 + 50); + } + pool->forget_handle(&handle); +} + +TEST_F( + CudaPrivatePoolTest, + InvalidPreparationLeavesCommittedPointersAndLayoutsUsable) { + auto pool = make_private_pool(); + auto container = private_container(); + auto handle = make_handle(container); + ASSERT_TRUE(pool->note_handle(&handle).get()); + std::vector> rows(2, std::vector(kOwners, 0)); + rows[0][0] = rows[1][0] = 1; + std::vector live(kOwners, 0); + ASSERT_EQ( + pool->prepare_private(rows, live, 1, cudaStreamPerThread), Error::Ok); + const int64_t bytes = pool->allocated_bytes(); + void* key = pool->layer_data(0, false); + void* stage = pool->side_buffer(1); + rows[1][7] = -1; + EXPECT_EQ( + pool->prepare_private(rows, live, 1, cudaStreamPerThread), + Error::InvalidArgument); + rows[1][7] = 0; + EXPECT_EQ( + pool->prepare_private(rows, live, 9, cudaStreamPerThread), + Error::InvalidArgument); + EXPECT_EQ(pool->allocated_bytes(), bytes); + EXPECT_EQ(pool->layer_data(0, false), key); + EXPECT_EQ(pool->side_buffer(1), stage); + EXPECT_EQ(pool->private_layout(0).spans[0].capacity, 2); + ASSERT_EQ( + pool->prepare_private(rows, live, 1, cudaStreamPerThread), Error::Ok); + ASSERT_EQ(pool->bind(&handle), Error::Ok); + pool->forget_handle(&handle); +} + +TEST_F(CudaPrivatePoolTest, FailedStageGrowthFencesUncommittedArenaCopies) { + auto pool = make_private_pool(/*huge_stage=*/true); + auto fake = private_container(/*huge_stage=*/true); + auto handle = make_handle(fake); + ASSERT_TRUE(pool->note_handle(&handle).get()); + std::vector> rows(2, std::vector(kOwners, 0)); + std::vector live(kOwners, 0); + for (int owner = 0; owner < 3; ++owner) { + rows[0][owner] = rows[1][owner] = 1; + } + ASSERT_EQ( + pool->prepare_private(rows, live, 1, cudaStreamPerThread), Error::Ok); + for (int owner = 0; owner < 3; ++owner) { + write_row(*pool, 0, owner, 0, owner * 100); + write_row(*pool, 1, owner, 0, owner * 100 + 50); + live[owner] = 1; + } + ASSERT_EQ(pool->mark_step_done(cudaStreamPerThread), Error::Ok); + rows[0][3] = rows[1][3] = 1; + ASSERT_EQ( + pool->prepare_private(rows, live, 1, cudaStreamPerThread), Error::Ok); + ASSERT_EQ(pool->bind(&handle), Error::Ok); + write_row(*pool, 0, 3, 0, 300); + write_row(*pool, 1, 3, 0, 350); + live[3] = 1; + ASSERT_EQ(pool->mark_step_done(cudaStreamPerThread), Error::Ok); + const auto previous = pool->private_layout(0).spans; + const auto bytes = pool->allocated_bytes(); + void* key = pool->layer_data(0, false); + const int updates = fake.updates; + handle.cuda_graph_state.phase = cu::CudaGraphPhase::Replay; + rows[0][0] = rows[1][0] = 3; + cu::CudaKVPoolTestPeer fences; + // The owner copy uses spare rows of the existing arena. Only the later + // 2-TiB staging allocation fails, after that copy has been enqueued. + EXPECT_EQ( + pool->prepare_private(rows, live, 1 << 20, cudaStreamPerThread), + Error::MemoryAllocationFailed); + EXPECT_EQ(fences.device_fences, 2); + EXPECT_FALSE(pool->requires_clear()); + EXPECT_EQ(pool->allocated_bytes(), bytes); + EXPECT_EQ(pool->layer_data(0, false), key); + EXPECT_EQ(pool->private_layout(0).spans[0].base, previous[0].base); + EXPECT_EQ(pool->private_layout(0).spans[0].capacity, previous[0].capacity); + EXPECT_EQ(handle.cuda_graph_state.phase, cu::CudaGraphPhase::Replay); + cudaStream_t retry_stream; + ASSERT_EQ( + cudaStreamCreateWithFlags(&retry_stream, cudaStreamNonBlocking), + cudaSuccess); + EXPECT_EQ(pool->prepare_private(rows, live, 1, retry_stream), Error::Ok); + EXPECT_EQ(pool->bind(&handle), Error::Ok); + EXPECT_EQ(fake.updates, updates); + EXPECT_NE(pool->private_layout(0).spans[0].base, previous[0].base); + for (int owner = 0; owner < 4; ++owner) { + expect_row(*pool, 0, owner, 0, owner * 100); + expect_row(*pool, 1, owner, 0, owner * 100 + 50); + } + EXPECT_EQ(cudaStreamSynchronize(retry_stream), cudaSuccess); + EXPECT_EQ(cudaStreamDestroy(retry_stream), cudaSuccess); + pool->forget_handle(&handle); +} + TEST_F(CudaKVPoolTest, SideBuffersBindAtFixedAddressesAcrossGrowth) { auto pool = make_pool(4); auto container = full_container(); @@ -1230,7 +1717,7 @@ TEST_F(CudaKVPoolTest, SideBuffersBindAtFixedAddressesAcrossGrowth) { cudaMemcpyDeviceToHost), cudaSuccess); EXPECT_EQ(cells_host, std::vector(16, 0)); - ASSERT_EQ(pool->mark_step_done(), Error::Ok); + ASSERT_EQ(pool->mark_step_done(pool->stream()), Error::Ok); // Growth moves only the growable layer. ASSERT_EQ(pool->prepare(5, 3, cudaStreamPerThread), Error::Ok); @@ -1259,7 +1746,7 @@ TEST_F(CudaKVPoolTest, GrowthCarriesLiveRowsAndCapsAtDeclaredRows) { history.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), cudaSuccess); - ASSERT_EQ(pool->mark_step_done(), Error::Ok); + ASSERT_EQ(pool->mark_step_done(pool->stream()), Error::Ok); // Asking past twice the rows grows straight to what is asked; past the // declared rows it is capped there. @@ -1369,6 +1856,33 @@ TEST_F(CudaKVPoolTest, ConstantNotMatchingItsCompiledSizeIsRejected) { pool->note_handle(&wrong_dtype_handle).error(), Error::InvalidProgram); } +TEST_F(CudaKVPoolTest, PrivateMetadataCannotBeBoundToLegacyStorage) { + auto pool = make_pool(4); + auto container = full_container(); + container.internal_names.push_back("owner_step"); + container.fqns.push_back("__et_offgraph_kv_owner_step"); + declare( + container, + "__et_offgraph_kv_owner_step", + slimc10::ScalarType::Int, + {5, 3}); + auto handle = make_handle(container); + EXPECT_EQ(pool->note_handle(&handle).error(), Error::InvalidProgram); + EXPECT_FALSE(pool->serves(&handle)); +} + +TEST_F(CudaKVPoolTest, NonCacheConstantsDoNotNeedRuntimeBinding) { + auto pool = make_pool(4); + auto container = full_container(); + container.internal_names.push_back("weight"); + container.fqns.push_back("attention.weight"); + declare(container, "attention.weight", slimc10::ScalarType::BFloat16, {16}); + auto handle = make_handle(container); + ASSERT_TRUE(pool->note_handle(&handle).get()); + EXPECT_EQ(pool->validate(), Error::Ok); + pool->forget_handle(&handle); +} + TEST_F(CudaKVPoolTest, ProgramMissingSideBuffersIsRejected) { auto pool = make_pool(4); // Every layer, but only one of the two side buffers: the lowering and the @@ -2422,6 +2936,25 @@ TEST_F(CudaBatchedSequenceCacheTest, ClearRecoversAbandonedDFlashStep) { kv->forget_handle(&handle); } +TEST_F(CudaBatchedSequenceCacheTest, PendingDFlashOwnerCanClose) { + auto cache_ptr = make(kCapacity, 2); + auto* control = cache_ptr->as(); + auto* kv = cache_ptr->as(); + auto fake = container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + const auto id = control->seq_new(); + ASSERT_TRUE(id.has_value()); + ASSERT_TRUE(control->declare_step({*id, *id, *id})); + ASSERT_EQ(kv->prepare_step(3, cudaStreamPerThread), Error::Ok); + ASSERT_TRUE(control->seq_rm(*id)); + EXPECT_EQ(kv->commit_step(3), Error::Ok); + EXPECT_EQ(control->seq_new(), id); + EXPECT_EQ(control->pos(*id), 0); + ASSERT_EQ(step(*cache_ptr, handle, {*id, *id, *id}), Error::Ok); + kv->forget_handle(&handle); +} + TEST_F(CudaBatchedSequenceCacheTest, CloneOnAnotherStreamWaitsForTheCopy) { auto cache_ptr = make(kCapacity); auto* control = cache_ptr->as(); @@ -2719,23 +3252,1371 @@ TEST_F(CudaBatchedSequenceCacheTest, DFlashQueriesOnlyEachOwnersBlock) { kv->forget_handle(&handle); } -TEST_F(CudaBatchedSequenceCacheTest, BuilderValidatesAndIsRegistered) { - auto no_seqs = sequence_config(); - no_seqs.max_seqs.reset(); - EXPECT_EQ( - cu::make_cuda_batched_sequence_kv_cache(flat_and_ring(kWindow), no_seqs), - nullptr); - auto no_write = sequence_config(); - no_write.max_write.reset(); - EXPECT_EQ( - cu::make_cuda_batched_sequence_kv_cache(flat_and_ring(kWindow), no_write), - nullptr); - auto built = cache::CacheFactory::global().build( - cu::kCudaBackendId, - cache::kind::kBatchedSequence, - flat_and_ring(kWindow), - sequence_config()); - ASSERT_TRUE(built.ok()); - EXPECT_NE(built.get()->as(), nullptr); - EXPECT_NE(built.get()->as(), nullptr); +namespace { + +class CudaRuntimeColumnCacheTest : public CudaKVCacheTest { + protected: + static constexpr int kCapacity = 64; + static constexpr int kMaxWrite = 32; + static constexpr int kMaxSeqs = 21; + static constexpr int kDeclaredColumns = kMaxSeqs + 1; + static constexpr int kSegments = 2 * kMaxSeqs; + + static std::shared_ptr make() { + auto cfg = config(kCapacity, 4, kMaxWrite); + cfg.max_seqs = kMaxSeqs; + return cu::make_cuda_batched_sequence_kv_cache( + flat_and_ring(2), cfg, /*runtime_columns=*/true); + } + + static FakeContainer container(int info_width = 5) { + auto fake = flat_and_ring_container(); + fake.internal_names.insert( + fake.internal_names.end(), {"seq_cols", "seq_info"}); + fake.fqns.insert( + fake.fqns.end(), + {"__et_offgraph_kv_seq_cols", "__et_offgraph_kv_seq_info"}); + for (size_t index = 0; index < 4; ++index) { + declare( + fake, + fake.fqns[index], + slimc10::ScalarType::BFloat16, + {1, + (index < 2 ? kCapacity : kMaxWrite + 1) * kDeclaredColumns, + kHeads, + kDim}); + } + declare(fake, fake.fqns[4], slimc10::ScalarType::Long, {kMaxWrite}); + declare( + fake, fake.fqns[5], slimc10::ScalarType::Int, {kSegments, info_width}); + return fake; + } + + static Error step( + cache::Cache& cache, + cu::CudaDelegateHandle& handle, + const std::vector& ids, + int width = 0) { + auto* control = cache.as(); + auto* kv = cache.as(); + if (!control->declare_step(ids)) { + return Error::InvalidArgument; + } + width = width == 0 ? static_cast(ids.size()) : width; + ET_CHECK_OK_OR_RETURN_ERROR(kv->prepare_step(width, cudaStreamPerThread)); + ET_CHECK_OK_OR_RETURN_ERROR(kv->rebind_for_execute(&handle)); + return kv->commit_step(width); + } + + static std::vector + read_column(void* data, int rows, int columns, int column) { + std::vector out(rows * kRow); + EXPECT_EQ( + cudaMemcpy2D( + out.data(), + kRow * sizeof(uint16_t), + static_cast(data) + column * kRow, + columns * kRow * sizeof(uint16_t), + kRow * sizeof(uint16_t), + rows, + cudaMemcpyDeviceToHost), + cudaSuccess); + return out; + } + + static void seed(FakeContainer& fake, int rows, int columns) { + for (size_t layer = 0; layer < 4; ++layer) { + std::vector values(rows * columns * kRow); + for (int row = 0; row < rows; ++row) { + for (int column = 0; column < columns; ++column) { + for (int element = 0; element < kRow; ++element) { + values[(row * columns + column) * kRow + element] = + static_cast( + 1000 * layer + 100 * row + 20 * column + element); + } + } + } + EXPECT_EQ( + cudaMemcpy( + fake.bound[fake.internal_names[layer]].data, + values.data(), + values.size() * sizeof(uint16_t), + cudaMemcpyHostToDevice), + cudaSuccess); + } + } +}; + +} // namespace + +TEST_F(CudaRuntimeColumnCacheTest, GrowthAndSparseIdCompactionPreserveAllKV) { + auto cache_ptr = make(); + ASSERT_NE(cache_ptr, nullptr); + auto* control = cache_ptr->as(); + auto* kv = cache_ptr->as(); + auto fake = container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + std::vector ids; + int old_columns = 0; + for (const int sessions : {1, 2, 4, 8, 16}) { + const int live_rows = ids.empty() ? 0 : control->pos(ids.front()); + std::vector, 4>> retained(ids.size()); + if (old_columns != 0) { + seed(fake, live_rows, old_columns); + for (size_t owner = 0; owner < retained.size(); ++owner) { + for (size_t layer = 0; layer < 4; ++layer) { + retained[owner][layer] = read_column( + fake.bound[fake.internal_names[layer]].data, + live_rows, + old_columns, + owner); + } + } + } + while (ids.size() < static_cast(sessions)) { + const auto id = control->seq_new(); + ASSERT_TRUE(id.has_value()); + ids.push_back(*id); + } + ASSERT_EQ(step(*cache_ptr, handle, ids), Error::Ok); + const auto metrics = kv->metrics(); + EXPECT_EQ(metrics.physical_columns, sessions + 1); + EXPECT_EQ(metrics.declared_columns, kDeclaredColumns); + EXPECT_EQ(metrics.live_sequences, sessions); + EXPECT_EQ(control->max_seqs(), kMaxSeqs); + EXPECT_EQ( + fake.bound["flat_k"].sizes, + std::vector({1, kCapacity * kDeclaredColumns, kHeads, kDim})); + if (old_columns != 0) { + for (size_t owner = 0; owner < retained.size(); ++owner) { + for (size_t layer = 0; layer < 4; ++layer) { + EXPECT_EQ( + read_column( + fake.bound[fake.internal_names[layer]].data, + live_rows, + sessions + 1, + owner), + retained[owner][layer]); + } + } + } + old_columns = sessions + 1; + } + + // Preserve a nonzero logical ID while compacting it into physical column 0. + const int32_t survivor = ids[5]; + const int rows = control->pos(survivor); + seed(fake, rows, old_columns); + std::array, 4> retained; + for (size_t layer = 0; layer < 4; ++layer) { + retained[layer] = read_column( + fake.bound[fake.internal_names[layer]].data, rows, old_columns, 5); + } + const int position = control->pos(survivor); + const auto before = kv->metrics(); + for (const int32_t id : ids) { + if (id != survivor) { + ASSERT_TRUE(control->seq_rm(id)); + } + } + ASSERT_EQ(kv->compact_columns(0), Error::Ok); + const auto after = kv->metrics(); + EXPECT_EQ(after.physical_columns, 2); + EXPECT_EQ(after.live_sequences, 1); + EXPECT_EQ(after.flat_capacity, 4); + EXPECT_EQ(control->pos(survivor), position); + EXPECT_LT(after.allocated_bytes, before.allocated_bytes); + EXPECT_LT(after.allocated_bytes * 17, before.allocated_bytes * 2); + ASSERT_EQ(kv->rebind_for_execute(&handle), Error::Ok); + for (size_t layer = 0; layer < 4; ++layer) { + EXPECT_EQ( + read_column(fake.bound[fake.internal_names[layer]].data, rows, 2, 0), + retained[layer]); + } + ASSERT_EQ(step(*cache_ptr, handle, {survivor}, 4), Error::Ok); + std::array cols{}; + ASSERT_EQ( + cudaMemcpy( + cols.data(), + fake.bound["seq_cols"].data, + sizeof(cols), + cudaMemcpyDeviceToHost), + cudaSuccess); + EXPECT_EQ(cols, (std::array{0, 1, 1, 1})); + std::vector info(kSegments * 5); + ASSERT_EQ( + cudaMemcpy( + info.data(), + fake.bound["seq_info"].data, + info.size() * sizeof(int32_t), + cudaMemcpyDeviceToHost), + cudaSuccess); + EXPECT_EQ(info[2], 0); + EXPECT_EQ(info[3], position + 1); + for (int row = 0; row < kSegments; ++row) { + EXPECT_EQ(info[row * 5 + 4], 2); + } + kv->forget_handle(&handle); +} + +TEST_F( + CudaRuntimeColumnCacheTest, + ContractionDropsClosedOwnersUnusedRowCapacity) { + auto cache_ptr = make(); + auto* control = cache_ptr->as(); + auto* kv = cache_ptr->as(); + auto fake = container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + const auto long_owner = control->seq_new(); + const auto short_owner = control->seq_new(); + ASSERT_TRUE(long_owner.has_value()); + ASSERT_TRUE(short_owner.has_value()); + for (int chunk = 0; chunk < 2; ++chunk) { + ASSERT_EQ( + step(*cache_ptr, handle, std::vector(32, *long_owner)), + Error::Ok); + } + ASSERT_EQ( + step(*cache_ptr, handle, std::vector(3, *short_owner)), + Error::Ok); + seed(fake, 3, 3); + std::array, 4> expected; + for (size_t layer = 0; layer < expected.size(); ++layer) { + expected[layer] = + read_column(fake.bound[fake.internal_names[layer]].data, 3, 3, 1); + } + const auto before = kv->metrics(); + ASSERT_GE(before.flat_capacity, 64); + ASSERT_TRUE(control->seq_rm(*long_owner)); + ASSERT_EQ(kv->compact_columns(0), Error::Ok); + ASSERT_EQ(kv->rebind_for_execute(&handle), Error::Ok); + const auto after = kv->metrics(); + EXPECT_EQ(after.physical_columns, 2); + EXPECT_EQ(after.flat_capacity, 4); + EXPECT_EQ(control->pos(*short_owner), 3); + EXPECT_EQ(control->max_seqs(), kMaxSeqs); + EXPECT_LT(after.allocated_bytes * 8, before.allocated_bytes); + EXPECT_EQ( + fake.bound["flat_k"].sizes, + std::vector({1, kCapacity * kDeclaredColumns, kHeads, kDim})); + for (size_t layer = 0; layer < expected.size(); ++layer) { + EXPECT_EQ( + read_column(fake.bound[fake.internal_names[layer]].data, 3, 2, 0), + expected[layer]); + } + const auto growth = after.growth_count; + ASSERT_EQ(step(*cache_ptr, handle, {*short_owner}), Error::Ok); + EXPECT_EQ(kv->metrics().growth_count, growth); + ASSERT_EQ(step(*cache_ptr, handle, {*short_owner}), Error::Ok); + EXPECT_GT(kv->metrics().growth_count, growth); + for (size_t layer = 0; layer < expected.size(); ++layer) { + EXPECT_EQ( + read_column(fake.bound[fake.internal_names[layer]].data, 3, 2, 0), + expected[layer]); + } + kv->forget_handle(&handle); +} + +TEST_F(CudaRuntimeColumnCacheTest, CloneAndContractionCopyWrappedRingHistory) { + auto cache_ptr = make(); + auto* control = cache_ptr->as(); + auto* kv = cache_ptr->as(); + auto fake = container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + const auto source = control->seq_new(); + ASSERT_TRUE(source.has_value()); + ASSERT_EQ( + step(*cache_ptr, handle, std::vector(32, *source)), Error::Ok); + ASSERT_EQ( + step(*cache_ptr, handle, std::vector(8, *source)), Error::Ok); + std::array, 4> expected; + for (size_t layer = 0; layer < 4; ++layer) { + const int rows = layer < 2 ? 40 : 33; + std::vector values(rows * 2 * kRow); + for (int row = 0; row < rows; ++row) { + for (int column = 0; column < 2; ++column) { + for (int element = 0; element < kRow; ++element) { + const uint16_t value = + 1000 * layer + 100 * row + 20 * column + element; + values[(row * 2 + column) * kRow + element] = value; + if (column == 0) { + expected[layer].push_back(value); + } + } + } + } + ASSERT_EQ( + cudaMemcpy( + fake.bound[fake.internal_names[layer]].data, + values.data(), + values.size() * sizeof(uint16_t), + cudaMemcpyHostToDevice), + cudaSuccess); + } + const auto clone = control->seq_clone(*source, 40); + ASSERT_TRUE(clone.has_value()); + EXPECT_EQ(kv->metrics().physical_columns, 3); + ASSERT_EQ(kv->rebind_for_execute(&handle), Error::Ok); + for (size_t layer = 0; layer < 4; ++layer) { + const int rows = layer < 2 ? 40 : 33; + EXPECT_EQ( + read_column(fake.bound[fake.internal_names[layer]].data, rows, 3, 0), + read_column(fake.bound[fake.internal_names[layer]].data, rows, 3, 1)); + } + ASSERT_TRUE(control->seq_rm(*source)); + ASSERT_EQ(kv->compact_columns(0), Error::Ok); + ASSERT_EQ(kv->rebind_for_execute(&handle), Error::Ok); + EXPECT_EQ(control->pos(*clone), 40); + for (size_t layer = 0; layer < 4; ++layer) { + const int rows = layer < 2 ? 40 : 33; + EXPECT_EQ( + read_column(fake.bound[fake.internal_names[layer]].data, rows, 2, 0), + expected[layer]); + } + ASSERT_EQ(step(*cache_ptr, handle, {*clone}), Error::Ok); + EXPECT_EQ(control->pos(*clone), 41); + kv->forget_handle(&handle); +} + +TEST_F(CudaRuntimeColumnCacheTest, DeclaredStepCanCompactOrClose) { + auto cache_ptr = make(); + auto* control = cache_ptr->as(); + auto* kv = cache_ptr->as(); + auto fake = container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + const auto id = control->seq_new(); + ASSERT_TRUE(id.has_value()); + ASSERT_TRUE(control->declare_step({*id})); + ASSERT_EQ(kv->compact_columns(0), Error::Ok); + ASSERT_EQ(kv->prepare_step(1, cudaStreamPerThread), Error::Ok); + ASSERT_EQ(kv->commit_step(1), Error::Ok); + ASSERT_TRUE(control->declare_step({*id})); + ASSERT_TRUE(control->seq_rm(*id)); + EXPECT_EQ(kv->prepare_step(1, cudaStreamPerThread), Error::InvalidArgument); + EXPECT_EQ(kv->metrics().live_sequences, 0); + EXPECT_EQ(control->seq_new(), id); + ASSERT_EQ(step(*cache_ptr, handle, {*id}), Error::Ok); + kv->forget_handle(&handle); +} + +TEST_F(CudaRuntimeColumnCacheTest, AbortFencesBeforeCloseAndReuse) { + auto cache_ptr = make(); + auto* control = cache_ptr->as(); + auto* kv = cache_ptr->as(); + auto fake = container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + const auto id = control->seq_new(); + ASSERT_TRUE(id.has_value()); + ASSERT_TRUE(control->declare_step({*id})); + ASSERT_EQ(kv->prepare_step(1, cudaStreamPerThread), Error::Ok); + EXPECT_FALSE(control->seq_clone(*id, std::nullopt).has_value()); + EXPECT_FALSE(control->seq_new().has_value()); + EXPECT_EQ(kv->metrics().live_sequences, 1); + std::atomic finished{false}; + ASSERT_EQ( + cudaLaunchHostFunc( + cudaStreamPerThread, + [](void* state) { + std::this_thread::sleep_for(std::chrono::milliseconds(30)); + static_cast*>(state)->store(true); + }, + &finished), + cudaSuccess); + ASSERT_EQ(kv->abort_step(), Error::Ok); + EXPECT_TRUE(finished.load()); + ASSERT_TRUE(control->seq_rm(*id)); + EXPECT_EQ(control->seq_new(), id); + ASSERT_EQ(step(*cache_ptr, handle, {*id}), Error::Ok); + EXPECT_TRUE(finished.load()); + EXPECT_EQ(control->pos(*id), 1); + EXPECT_EQ(kv->metrics().live_sequences, 1); + kv->forget_handle(&handle); +} + +TEST_F(CudaBatchedSequenceCacheTest, FailedDeclaredStepCanCloseAndReuseId) { + auto cache_ptr = make(/*initial=*/4); + auto* control = cache_ptr->as(); + auto* kv = cache_ptr->as(); + auto fake = container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + const auto id = control->seq_new(); + ASSERT_TRUE(id.has_value()); + ASSERT_TRUE(control->declare_step({*id})); + EXPECT_EQ(kv->prepare_step(0, cudaStreamPerThread), Error::InvalidArgument); + ASSERT_TRUE(control->seq_rm(*id)); + EXPECT_EQ(kv->prepare_step(1, cudaStreamPerThread), Error::InvalidArgument); + EXPECT_EQ(control->seq_new(), id); + ASSERT_EQ(step(*cache_ptr, handle, {*id}), Error::Ok); + kv->forget_handle(&handle); +} + +TEST_F( + CudaRuntimeColumnCacheTest, + AdmissionsGrowGeometricallyAndStepsKeepWidth) { + auto cache_ptr = make(); + auto* control = cache_ptr->as(); + auto* kv = cache_ptr->as(); + auto fake = container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + std::vector ids; + int expected_columns = 2; + for (int count = 1; count <= kMaxSeqs; ++count) { + const auto id = control->seq_new(); + ASSERT_TRUE(id.has_value()); + ids.push_back(*id); + if (count >= expected_columns) { + expected_columns = + std::min(kDeclaredColumns, 2 * (expected_columns - 1) + 1); + } + EXPECT_EQ(kv->metrics().physical_columns, expected_columns) << count; + const int64_t resizes = kv->metrics().column_resize_count; + for (int repeat = 0; repeat < 2; ++repeat) { + ASSERT_EQ(step(*cache_ptr, handle, ids), Error::Ok); + EXPECT_EQ(kv->metrics().physical_columns, expected_columns); + EXPECT_EQ(kv->metrics().column_resize_count, resizes); + } + } + EXPECT_FALSE(control->seq_new().has_value()); + kv->forget_handle(&handle); +} + +TEST_F(CudaRuntimeColumnCacheTest, ActiveStepRejectsResizeUntilExplicitAbort) { + auto cache_ptr = make(); + auto* control = cache_ptr->as(); + auto* kv = cache_ptr->as(); + auto fake = container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + const auto id = control->seq_new(); + ASSERT_TRUE(id.has_value()); + // Simulate a failed forward: prepare runs, commit never does. + ASSERT_TRUE(control->declare_step({*id})); + ASSERT_EQ(kv->prepare_step(1, cudaStreamPerThread), Error::Ok); + const auto before = kv->metrics(); + EXPECT_EQ(kv->compact_columns(0), Error::InvalidState); + EXPECT_EQ(kv->prepare_step(1, cudaStreamPerThread), Error::InvalidState); + EXPECT_EQ(kv->metrics().column_resize_count, before.column_resize_count); + EXPECT_EQ(kv->metrics().physical_columns, before.physical_columns); + ASSERT_EQ(kv->abort_step(), Error::Ok); + EXPECT_EQ(kv->abort_step(), Error::Ok); + ASSERT_TRUE(control->declare_step({*id})); + ASSERT_EQ(kv->prepare_step(1, cudaStreamPerThread), Error::Ok); + ASSERT_EQ(kv->commit_step(1), Error::Ok); + EXPECT_EQ(control->pos(*id), 2); + ASSERT_TRUE(control->seq_rm(*id)); + kv->forget_handle(&handle); +} + +TEST_F(CudaRuntimeColumnCacheTest, FixedInfoABIIsRejected) { + auto cache_ptr = make(); + auto* kv = cache_ptr->as(); + auto fake = container(4); + auto handle = make_handle(fake); + EXPECT_EQ(kv->note_handle(&handle).error(), Error::InvalidProgram); + kv->forget_handle(&handle); +} + +TEST_F(CudaRuntimeColumnCacheTest, SameWidthCompactionKeepsMappingAndBindings) { + auto cache_ptr = make(); + auto* control = cache_ptr->as(); + auto* kv = cache_ptr->as(); + auto fake = container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + const auto first = control->seq_new(); + const auto second = control->seq_new(); + ASSERT_TRUE(first.has_value()); + ASSERT_TRUE(second.has_value()); + ASSERT_EQ(step(*cache_ptr, handle, {*first, *second}), Error::Ok); + ASSERT_TRUE(control->seq_rm(*first)); + ASSERT_EQ(kv->compact_columns(0), Error::Ok); + ASSERT_EQ(kv->metrics().physical_columns, 2); + EXPECT_EQ(control->seq_new(), first); + ASSERT_EQ(step(*cache_ptr, handle, {*first, *second}), Error::Ok); + ASSERT_EQ(kv->metrics().physical_columns, 3); + seed(fake, 2, 3); + const auto before = read_column(fake.bound["flat_k"].data, 2, 3, 0); + void* const pointer = fake.bound["flat_k"].data; + const auto count = kv->metrics().column_resize_count; + handle.cuda_graph_state.phase = cu::CudaGraphPhase::Warmup; + handle.cuda_graph_state.warmup_remaining = 0; + ASSERT_EQ(kv->compact_columns(kMaxSeqs), Error::Ok); + EXPECT_EQ(kv->metrics().physical_columns, 3); + ASSERT_EQ(kv->compact_columns(0), Error::Ok); + EXPECT_EQ(kv->metrics().column_resize_count, count); + EXPECT_EQ(fake.bound["flat_k"].data, pointer); + EXPECT_EQ(handle.cuda_graph_state.phase, cu::CudaGraphPhase::Warmup); + EXPECT_EQ(handle.cuda_graph_state.warmup_remaining, 0); + EXPECT_EQ(read_column(pointer, 2, 3, 0), before); + ASSERT_EQ(step(*cache_ptr, handle, {*first, *second}), Error::Ok); + std::vector> info(2); + ASSERT_EQ( + cudaMemcpy( + info.data(), + fake.bound["seq_info"].data, + info.size() * sizeof(info[0]), + cudaMemcpyDeviceToHost), + cudaSuccess); + EXPECT_EQ( + info, + (std::vector>{{0, 1, 1, 2, 3}, {1, 1, 0, 3, 3}})); + kv->forget_handle(&handle); +} + +TEST_F(CudaRuntimeColumnCacheTest, RegistrySelectsTheRequestedColumnABI) { + auto cfg = config(kCapacity, 4, kMaxWrite); + cfg.max_seqs = kMaxSeqs; + auto fixed = cache::CacheFactory::global().build( + cu::kCudaBackendId, cache::kind::kBatchedSequence, flat_and_ring(2), cfg); + auto runtime = cache::CacheFactory::global().build( + cu::kCudaBackendId, + cache::kind::kBatchedSequenceRuntime, + flat_and_ring(2), + cfg); + ASSERT_TRUE(fixed.ok()); + ASSERT_TRUE(runtime.ok()); + EXPECT_EQ( + fixed.get()->as()->metrics().physical_columns, + kDeclaredColumns); + EXPECT_EQ( + runtime.get()->as()->metrics().physical_columns, 2); +} + +TEST_F(CudaRuntimeColumnCacheTest, MaintenanceSurvivesDestroyedCallerStream) { + auto cache_ptr = make(); + auto* control = cache_ptr->as(); + auto* kv = cache_ptr->as(); + auto fake = container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + const auto run = [&](const std::vector& ids) { + cudaStream_t stream = nullptr; + ASSERT_EQ( + cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking), cudaSuccess); + ASSERT_TRUE(control->declare_step(ids)); + ASSERT_EQ(kv->prepare_step(ids.size(), stream), Error::Ok); + ASSERT_EQ(kv->rebind_for_execute(&handle), Error::Ok); + ASSERT_EQ(kv->commit_step(ids.size()), Error::Ok); + ASSERT_EQ(cudaStreamSynchronize(stream), cudaSuccess); + ASSERT_EQ(cudaStreamDestroy(stream), cudaSuccess); + }; + const auto first = control->seq_new(); + ASSERT_TRUE(first.has_value()); + run({*first, *first, *first, *first}); + ASSERT_FALSE(HasFatalFailure()); + seed(fake, 4, 2); + const auto before = read_column(fake.bound["flat_k"].data, 4, 2, 0); + const auto clone = control->seq_clone(*first, 4); + ASSERT_TRUE(clone.has_value()); + ASSERT_EQ(kv->rebind_for_execute(&handle), Error::Ok); + EXPECT_EQ(read_column(fake.bound["flat_k"].data, 4, 3, 1), before); + run({*clone}); + ASSERT_FALSE(HasFatalFailure()); + const auto third = control->seq_new(); + ASSERT_TRUE(third.has_value()); + EXPECT_EQ(kv->metrics().physical_columns, 5); + run({*clone}); + ASSERT_FALSE(HasFatalFailure()); + ASSERT_TRUE(control->seq_rm(*first)); + ASSERT_TRUE(control->seq_rm(*third)); + ASSERT_EQ(kv->compact_columns(0), Error::Ok); + ASSERT_EQ(kv->rebind_for_execute(&handle), Error::Ok); + EXPECT_EQ(kv->metrics().physical_columns, 2); + EXPECT_EQ(read_column(fake.bound["flat_k"].data, 4, 2, 0), before); + kv->forget_handle(&handle); +} + +TEST_F(CudaRuntimeColumnCacheTest, ContractionInvalidatesEveryGraphAndBinding) { + auto cache_ptr = make(); + auto* control = cache_ptr->as(); + auto* kv = cache_ptr->as(); + auto first = container(); + auto second = container(); + auto decode = make_handle(first); + auto prefill = make_handle(second); + ASSERT_TRUE(kv->note_handle(&decode).get()); + ASSERT_TRUE(kv->note_handle(&prefill).get()); + const auto a = control->seq_new(); + const auto b = control->seq_new(); + ASSERT_TRUE(a.has_value()); + ASSERT_TRUE(b.has_value()); + ASSERT_EQ(step(*cache_ptr, decode, {*a, *b}), Error::Ok); + ASSERT_EQ(kv->rebind_for_execute(&prefill), Error::Ok); + const int first_updates = first.updates; + const int second_updates = second.updates; + decode.cuda_graph_state.phase = cu::CudaGraphPhase::Replay; + prefill.cuda_graph_state.phase = cu::CudaGraphPhase::Warmup; + prefill.cuda_graph_state.warmup_remaining = 0; + ASSERT_TRUE(control->seq_rm(*a)); + ASSERT_EQ(kv->compact_columns(0), Error::Ok); + EXPECT_EQ(decode.cuda_graph_state.phase, cu::CudaGraphPhase::Warmup); + EXPECT_EQ(decode.cuda_graph_state.warmup_remaining, 1); + EXPECT_EQ(prefill.cuda_graph_state.warmup_remaining, 1); + ASSERT_EQ(kv->rebind_for_execute(&decode), Error::Ok); + ASSERT_EQ(kv->rebind_for_execute(&prefill), Error::Ok); + EXPECT_EQ(first.updates, first_updates + 1); + EXPECT_EQ(second.updates, second_updates + 1); + EXPECT_EQ(first.bound["flat_k"].data, second.bound["flat_k"].data); + kv->forget_handle(&decode); + kv->forget_handle(&prefill); +} + +TEST_F(CudaKVPoolTest, FailedColumnGrowthKeepsOldStorageAndBindingsUsable) { + constexpr int kDeclaredColumns = 1 << 20; + constexpr int kHugeDim = 1 << 20; + cu::CudaKVPool pool( + {{kHeads, kDim, kDeclaredColumns, true}, + {1, kHugeDim, kDeclaredColumns, true}}, + {}, + slimc10::ScalarType::BFloat16, + kDeclaredColumns, + kDeclaredColumns, + 2); + auto fake = flat_and_ring_container(); + for (size_t index = 0; index < 4; ++index) { + declare( + fake, + fake.fqns[index], + slimc10::ScalarType::BFloat16, + {1, + kDeclaredColumns, + index < 2 ? kHeads : 1, + index < 2 ? kDim : kHugeDim}); + } + auto handle = make_handle(fake); + ASSERT_TRUE(pool.note_handle(&handle).get()); + ASSERT_EQ(pool.prepare(2, 0, cudaStreamPerThread), Error::Ok); + ASSERT_EQ(pool.bind(&handle), Error::Ok); + const auto history = iota_rows(2); + ASSERT_EQ( + cudaMemcpy( + pool.layer_data(0, false), + history.data(), + history.size() * sizeof(uint16_t), + cudaMemcpyHostToDevice), + cudaSuccess); + void* old_k = pool.layer_data(0, false); + void* old_large_k = pool.layer_data(1, false); + const auto before_bytes = pool.allocated_bytes(); + const int updates = fake.updates; + handle.cuda_graph_state.phase = cu::CudaGraphPhase::Replay; + for (const bool trim_unused : {false, true}) { + bool committed = true; + EXPECT_EQ( + pool.resize_columns( + kDeclaredColumns, + {{0, 0}}, + /*live_rows=*/1, + cudaStreamPerThread, + trim_unused, + &committed), + Error::MemoryAllocationFailed); + EXPECT_FALSE(committed); + EXPECT_EQ(pool.columns(), 2); + EXPECT_EQ(pool.column_resize_count(), 0); + EXPECT_EQ(pool.allocated_bytes(), before_bytes); + EXPECT_EQ(pool.layer_data(0, false), old_k); + EXPECT_EQ(pool.layer_data(1, false), old_large_k); + EXPECT_EQ(handle.cuda_graph_state.phase, cu::CudaGraphPhase::Replay); + ASSERT_EQ(pool.bind(&handle), Error::Ok); + EXPECT_EQ(fake.updates, updates); + EXPECT_EQ(read_rows(old_k, 2), history); + } + ASSERT_EQ(pool.prepare(2, 1, cudaStreamPerThread), Error::Ok); + ASSERT_EQ(pool.mark_step_done(pool.stream()), Error::Ok); + pool.forget_handle(&handle); +} + +TEST_F(CudaBatchedSequenceCacheTest, BuilderValidatesAndIsRegistered) { + auto no_seqs = sequence_config(); + no_seqs.max_seqs.reset(); + EXPECT_EQ( + cu::make_cuda_batched_sequence_kv_cache(flat_and_ring(kWindow), no_seqs), + nullptr); + auto no_write = sequence_config(); + no_write.max_write.reset(); + EXPECT_EQ( + cu::make_cuda_batched_sequence_kv_cache(flat_and_ring(kWindow), no_write), + nullptr); + auto built = cache::CacheFactory::global().build( + cu::kCudaBackendId, + cache::kind::kBatchedSequence, + flat_and_ring(kWindow), + sequence_config()); + ASSERT_TRUE(built.ok()); + EXPECT_NE(built.get()->as(), nullptr); + EXPECT_NE(built.get()->as(), nullptr); +} + +namespace { + +class CudaPrivateCacheTest : public CudaBatchedSequenceCacheTest { + protected: + static constexpr int kOwners = 64; + static constexpr int kPrivateWindow = 5; + static constexpr int kPrivateWrite = 128; + + static cache::CacheConfig private_config(int max_write = kPrivateWrite) { + auto cfg = config(256, 2, max_write); + cfg.max_seqs = kOwners; + return cfg; + } + + static std::shared_ptr make_private( + int max_write = kPrivateWrite) { + return cu::make_cuda_batched_sequence_kv_cache( + flat_and_ring(kPrivateWindow), private_config(max_write), false, true); + } + + static FakeContainer private_container(int max_write = kPrivateWrite) { + FakeContainer out{ + {"flat_k", + "flat_v", + "ring_k", + "ring_v", + "cols", + "info", + "steps", + "stage_rows", + "flat_layout", + "ring_layout", + "k_stage", + "v_stage"}, + {"__et_offgraph_kv_layer_0_k", + "__et_offgraph_kv_layer_0_v", + "__et_offgraph_kv_layer_1_k", + "__et_offgraph_kv_layer_1_v", + "__et_offgraph_kv_seq_cols", + "__et_offgraph_kv_seq_info", + "__et_offgraph_kv_owner_step", + "__et_offgraph_kv_stage_rows", + "__et_offgraph_kv_layer_0_owner_layout", + "__et_offgraph_kv_layer_1_owner_layout", + "__et_offgraph_kv_layer_1_k_stage", + "__et_offgraph_kv_layer_1_v_stage"}, + {}, + 0}; + for (int i = 0; i < 4; ++i) { + declare( + out, + out.fqns[i], + slimc10::ScalarType::BFloat16, + {1, + (i < 2 ? 256 : kPrivateWindow + max_write - 1) * (kOwners + 1), + kHeads, + kDim}); + } + declare(out, out.fqns[4], slimc10::ScalarType::Long, {max_write}); + declare(out, out.fqns[5], slimc10::ScalarType::Int, {2 * kOwners, 4}); + declare(out, out.fqns[6], slimc10::ScalarType::Int, {kOwners + 1, 3}); + declare(out, out.fqns[7], slimc10::ScalarType::Long, {max_write}); + for (int i : {8, 9}) { + declare(out, out.fqns[i], slimc10::ScalarType::Int, {kOwners + 1, 2}); + } + for (int i : {10, 11}) { + declare( + out, + out.fqns[i], + slimc10::ScalarType::BFloat16, + {1, max_write, kHeads, kDim}); + } + return out; + } + + static std::vector read_ints(void* device, int count) { + std::vector out(count); + EXPECT_EQ( + cudaMemcpy( + out.data(), + device, + count * sizeof(int32_t), + cudaMemcpyDeviceToHost), + cudaSuccess); + return out; + } + + static std::vector payload(int owner, int position, bool value) { + std::vector row(kRow); + for (int lane = 0; lane < kRow; ++lane) { + row[lane] = static_cast( + owner * 100 + position * 7 + lane + (value ? 4000 : 1)); + } + return row; + } + + // Stand in only for the GPU kernels. The production cache allocates real + // CUDA storage, uploads metadata and archives/restores exact payload bytes. + static Error write_step( + cache::Cache& ptr, + FakeContainer& fake, + cu::CudaDelegateHandle& handle, + const std::vector& owners, + cudaStream_t stream = cudaStreamPerThread) { + auto* control = ptr.as(); + auto* kv = ptr.as(); + if (!control->declare_step(owners)) { + return Error::InvalidArgument; + } + ET_CHECK_OK_OR_RETURN_ERROR(kv->prepare_step(owners.size(), stream)); + ET_CHECK_OK_OR_RETURN_ERROR(kv->rebind_for_execute(&handle)); + ET_CHECK_OR_RETURN_ERROR( + cudaStreamSynchronize(stream) == cudaSuccess, + Internal, + "complete test metadata uploads"); + const auto flat = + read_ints(fake.bound["flat_layout"].data, (kOwners + 1) * 2); + const auto ring = + read_ints(fake.bound["ring_layout"].data, (kOwners + 1) * 2); + const auto steps = read_ints(fake.bound["steps"].data, (kOwners + 1) * 3); + const auto stage = read_cols(fake.bound["stage_rows"].data, owners.size()); + std::vector consumed(kOwners, 0); + for (size_t token = 0; token < owners.size(); ++token) { + const int owner = owners[token]; + const int position = steps[owner * 3 + 1] + consumed[owner]++; + const int end = steps[owner * 3 + 1] + steps[owner * 3 + 2]; + for (bool value : {false, true}) { + const auto row = payload(owner, position, value); + const auto copy = [&](const char* name, int64_t index) { + auto* data = static_cast(fake.bound[name].data); + return cudaMemcpy( + data + index * kRow, + row.data(), + kRow * sizeof(uint16_t), + cudaMemcpyHostToDevice) == cudaSuccess; + }; + if (!copy(value ? "flat_v" : "flat_k", flat[owner * 2] + position) || + !copy(value ? "v_stage" : "k_stage", stage[token])) { + return Error::Internal; + } + if (position >= end - ring[owner * 2 + 1] && + !copy( + value ? "ring_v" : "ring_k", + ring[owner * 2] + position % ring[owner * 2 + 1])) { + return Error::Internal; + } + } + } + return kv->commit_step(owners.size()); + } + + static void expect_history(FakeContainer& fake, int owner, int keep) { + for (bool ring : {false, true}) { + const auto layout = read_ints( + fake.bound[ring ? "ring_layout" : "flat_layout"].data, + (kOwners + 1) * 2); + for (bool value : {false, true}) { + auto* data = + static_cast(fake.bound + [ring ? (value ? "ring_v" : "ring_k") + : (value ? "flat_v" : "flat_k")] + .data); + for (int position = ring ? std::max(0, keep - kPrivateWindow) : 0; + position < keep; + ++position) { + const int physical = + ring ? position % layout[owner * 2 + 1] : position; + EXPECT_EQ( + read_rows(data + (layout[owner * 2] + physical) * kRow, 1), + payload(owner, position, value)); + } + } + } + } +}; + +} // namespace + +TEST_F(CudaPrivateCacheTest, MetricsRemainSafeAfterLaterHistoryCreationFails) { + auto geometry = flat_and_ring(kPrivateWindow); + auto invalid_ring = geometry.layers.back(); + invalid_ring.n_kv_heads = 1 << 30; + invalid_ring.head_dim = 1 << 30; + geometry.layers.push_back(invalid_ring); + auto cache_ptr = cu::make_cuda_batched_sequence_kv_cache( + geometry, private_config(), false, true); + ASSERT_NE(cache_ptr, nullptr); + auto* kv = cache_ptr->as(); + const auto metrics = kv->metrics(); + EXPECT_EQ(metrics.host_undo_bytes, 0); + EXPECT_EQ(metrics.device_staging_bytes, 0); + EXPECT_EQ(kv->prepare_step(1, cudaStreamPerThread), Error::InvalidArgument); +} + +TEST_F(CudaPrivateCacheTest, SixtyFourOwnersHaveIndependentRowsAndSharedStage) { + auto ptr = make_private(); + ASSERT_NE(ptr, nullptr); + auto* ctl = ptr->as(); + auto* kv = ptr->as(); + auto fake = private_container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + std::vector owners; + for (int i = 0; i < kOwners; ++i) { + ASSERT_EQ(ctl->seq_new(), i); + owners.push_back(i); + } + EXPECT_EQ(kv->metrics().allocated_bytes, 0); + ASSERT_EQ(write_step(*ptr, fake, handle, owners), Error::Ok); + ASSERT_EQ( + write_step(*ptr, fake, handle, std::vector(127, 0)), Error::Ok); + const auto flat = + read_ints(fake.bound["flat_layout"].data, (kOwners + 1) * 2); + const auto ring = + read_ints(fake.bound["ring_layout"].data, (kOwners + 1) * 2); + EXPECT_EQ(flat[1], 128); + EXPECT_EQ(ring[1], kPrivateWindow); + for (int owner = 1; owner < kOwners; ++owner) { + EXPECT_EQ(flat[owner * 2 + 1], 2); + EXPECT_EQ(ring[owner * 2 + 1], 2); + } + const int64_t row_bytes = kRow * sizeof(uint16_t); + EXPECT_EQ( + kv->metrics().allocated_bytes, + 2 * (flat[kOwners * 2] + ring[kOwners * 2] + 2) * row_bytes); + expect_history(fake, 0, 128); + expect_history(fake, 63, 1); + kv->forget_handle(&handle); +} + +TEST_F( + CudaPrivateCacheTest, + CopyBatchesPreserveMetadataAcrossStreamsAndGrowth) { + auto ptr = make_private(); + auto* ctl = ptr->as(); + auto* kv = ptr->as(); + auto fake = private_container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + ASSERT_EQ(ctl->seq_new(), 0); + ASSERT_EQ(ctl->seq_new(), 1); + cudaStream_t stream = nullptr; + ASSERT_EQ( + cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking), cudaSuccess); + const std::array streams{ + nullptr, cudaStreamPerThread, stream}; + for (int round = 0; round < 9; ++round) { + ASSERT_EQ( + write_step(*ptr, fake, handle, {1, 0, 1}, streams[round % 3]), + Error::Ok); + const auto steps = read_ints(fake.bound["steps"].data, (kOwners + 1) * 3); + EXPECT_EQ(steps[1], round); + EXPECT_EQ(steps[2], 1); + EXPECT_EQ(steps[4], round * 2); + EXPECT_EQ(steps[5], 2); + EXPECT_EQ( + read_cols(fake.bound["stage_rows"].data, 3), + (std::vector{1, 0, 2})); + expect_history(fake, 0, round + 1); + expect_history(fake, 1, (round + 1) * 2); + } + ASSERT_EQ(ctl->seq_clone(0, 8), 2); + ASSERT_TRUE(ctl->rewind(0, 8)); + ASSERT_EQ(write_step(*ptr, fake, handle, {0}, stream), Error::Ok); + expect_history(fake, 0, 9); + kv->forget_handle(&handle); + ptr.reset(); + EXPECT_EQ(cudaStreamDestroy(stream), cudaSuccess); +} + +TEST_F(CudaPrivateCacheTest, FragmentationRetainsSlackAcrossDecodeSteps) { + auto ptr = make_private(); + ASSERT_NE(ptr, nullptr); + auto* ctl = ptr->as(); + auto* kv = ptr->as(); + auto fake = private_container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + std::vector owners; + for (int owner = 0; owner < kOwners; ++owner) { + ASSERT_EQ(ctl->seq_new(), owner); + owners.push_back(owner); + } + for (int length = 1; length <= 3; ++length) { + ASSERT_EQ(write_step(*ptr, fake, handle, owners), Error::Ok); + } + const auto before = kv->metrics(); + const auto ring_before = + read_ints(fake.bound["ring_layout"].data, (kOwners + 1) * 2); + for (int owner = 0; owner < kOwners; ++owner) { + ASSERT_EQ(ring_before[owner * 2 + 1], 4); + } + ASSERT_EQ(write_step(*ptr, fake, handle, owners), Error::Ok); + EXPECT_EQ(kv->metrics().growth_count, before.growth_count); + EXPECT_EQ( + read_ints(fake.bound["ring_layout"].data, (kOwners + 1) * 2), + ring_before); + expect_history(fake, 0, 4); + expect_history(fake, kOwners - 1, 4); + kv->forget_handle(&handle); +} + +TEST_F(CudaPrivateCacheTest, WrappedCloneAndRewindRestoreArchivedHistory) { + auto ptr = make_private(); + auto* ctl = ptr->as(); + auto* kv = ptr->as(); + auto fake = private_container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + ASSERT_EQ(ctl->seq_new(), 0); + ASSERT_EQ( + write_step(*ptr, fake, handle, std::vector(4, 0)), Error::Ok); + ASSERT_EQ( + write_step(*ptr, fake, handle, std::vector(8, 0)), Error::Ok); + const auto source_layout = + read_ints(fake.bound["ring_layout"].data, (kOwners + 1) * 2); + ASSERT_EQ(source_layout[0], 0); + ASSERT_EQ(source_layout[1], kPrivateWindow); + ASSERT_EQ(ctl->seq_clone(0, 8), 1); + ASSERT_EQ(kv->rebind_for_execute(&handle), Error::Ok); + // Private spans are densely packed by owner; only owners 0 and 1 have rows. + // Device descriptors refresh at prepare, so inspect the committed allocation + // at the clone's expected span without appending another token. + const int clone_base = source_layout[0] + source_layout[1]; + for (bool value : {false, true}) { + auto* data = + static_cast(fake.bound[value ? "ring_v" : "ring_k"].data); + for (int position = 4; position < 8; ++position) { + EXPECT_EQ( + read_rows(data + (clone_base + position % kPrivateWindow) * kRow, 1), + payload(0, position, value)); + } + } + expect_history(fake, 0, 12); + ASSERT_TRUE(ctl->seq_rm(0)); + ASSERT_TRUE(ctl->rewind(1, 6)); + for (bool value : {false, true}) { + auto* data = + static_cast(fake.bound[value ? "ring_v" : "ring_k"].data); + for (int position = 2; position < 6; ++position) { + EXPECT_EQ( + read_rows(data + (clone_base + position % kPrivateWindow) * kRow, 1), + payload(0, position, value)); + } + } + ASSERT_EQ(write_step(*ptr, fake, handle, {1}), Error::Ok); + EXPECT_EQ(ctl->pos(1), 7); + kv->forget_handle(&handle); +} + +TEST_F(CudaPrivateCacheTest, ExactRewindFloorAndCloneMatchTheLegacyContract) { + for (int max_write : {1, kPrivateWrite}) { + auto ptr = make_private(max_write); + auto* ctl = ptr->as(); + auto* kv = ptr->as(); + auto fake = private_container(max_write); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + ASSERT_EQ(ctl->seq_new(), 0); + const int written = max_write == 1 ? 12 : 256; + for (int position = 0; position < written; position += max_write) { + ASSERT_EQ( + write_step(*ptr, fake, handle, std::vector(max_write, 0)), + Error::Ok); + } + const int floor = written - max_write; + EXPECT_FALSE(ctl->rewind(0, floor - 1)); + EXPECT_FALSE(ctl->seq_clone(0, floor - 1)); + ASSERT_EQ(ctl->seq_clone(0, floor), 1); + ASSERT_TRUE(ctl->rewind(0, floor)); + ASSERT_EQ(kv->rebind_for_execute(&handle), Error::Ok); + for (int owner : {0, 1}) { + for (bool value : {false, true}) { + auto* data = static_cast( + fake.bound[value ? "ring_v" : "ring_k"].data); + for (int position = floor - kPrivateWindow + 1; position < floor; + ++position) { + EXPECT_EQ( + read_rows( + data + + (owner * kPrivateWindow + position % kPrivateWindow) * + kRow, + 1), + payload(0, position, value)); + } + } + } + ASSERT_EQ(write_step(*ptr, fake, handle, {1}), Error::Ok); + EXPECT_EQ(ctl->pos(1), floor + 1); + EXPECT_EQ(ctl->pos(0), floor); + kv->forget_handle(&handle); + } +} + +TEST_F(CudaPrivateCacheTest, AbortedForwardRetiresOnlyItsOwners) { + auto ptr = make_private(); + auto* ctl = ptr->as(); + auto* kv = ptr->as(); + auto fake = private_container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + ASSERT_EQ(ctl->seq_new(), 0); + ASSERT_EQ(ctl->seq_new(), 1); + ASSERT_EQ(ctl->seq_new(), 2); + ASSERT_EQ(write_step(*ptr, fake, handle, {0, 1, 2}), Error::Ok); + ASSERT_TRUE(ctl->declare_step({0, 2})); + ASSERT_EQ(kv->prepare_step(2, cudaStreamPerThread), Error::Ok); + ASSERT_EQ(kv->rebind_for_execute(&handle), Error::Ok); + const auto layout = + read_ints(fake.bound["ring_layout"].data, (kOwners + 1) * 2); + for (const int owner : {0, 2}) { + // Simulate a partially executed Ring write, with both an old and the new + // row corrupted. Admission must never reuse this owner's claimed history. + ASSERT_EQ( + cudaMemset( + static_cast(fake.bound["ring_v"].data) + + layout[owner * 2] * kRow, + 0xff, + layout[owner * 2 + 1] * kRow * sizeof(uint16_t)), + cudaSuccess); + } + EXPECT_FALSE(ctl->seq_rm(0)); + EXPECT_FALSE(ctl->seq_clone(0, 1)); + ASSERT_EQ(kv->abort_step(), Error::Ok); + ASSERT_EQ(kv->abort_step(), Error::Ok); + EXPECT_FALSE(ctl->declare_step({0})); + EXPECT_FALSE(ctl->declare_step({1, 2})); + EXPECT_FALSE(ctl->seq_clone(0, 1)); + EXPECT_FALSE(ctl->rewind(2, 1)); + expect_history(fake, 1, 1); + ASSERT_EQ(write_step(*ptr, fake, handle, {1}), Error::Ok); + expect_history(fake, 1, 2); + ASSERT_EQ(ctl->seq_new(), 3); + ASSERT_TRUE(ctl->seq_rm(0)); + ASSERT_EQ(ctl->seq_new(), 0); + ASSERT_EQ(write_step(*ptr, fake, handle, {0, 3}), Error::Ok); + expect_history(fake, 0, 1); + expect_history(fake, 3, 1); + ASSERT_TRUE(ctl->seq_rm(2)); + ASSERT_EQ(kv->compact_columns(0), Error::Ok); + ASSERT_EQ(write_step(*ptr, fake, handle, {0, 1, 3}), Error::Ok); + kv->forget_handle(&handle); +} + +TEST_F(CudaPrivateCacheTest, CachePhaseTimesAreCumulativeAcrossClear) { + auto ptr = make_private(); + auto* ctl = ptr->as(); + auto* kv = ptr->as(); + auto fake = private_container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + EXPECT_EQ(kv->metrics().prepare_time_ns, 0); + EXPECT_EQ(kv->metrics().commit_time_ns, 0); + ASSERT_EQ(ctl->seq_new(), 0); + ASSERT_EQ(write_step(*ptr, fake, handle, {0}), Error::Ok); + const auto before = kv->metrics(); + EXPECT_GT(before.prepare_time_ns, 0); + EXPECT_GT(before.archive_transfer_time_ns, 0); + EXPECT_GT(before.archive_append_time_ns, 0); + EXPECT_GE( + before.commit_time_ns, + before.archive_transfer_time_ns + before.archive_append_time_ns); + ctl->clear(); + const auto cleared = kv->metrics(); + EXPECT_EQ(cleared.prepare_time_ns, before.prepare_time_ns); + EXPECT_EQ(cleared.commit_time_ns, before.commit_time_ns); + EXPECT_EQ(cleared.archive_transfer_time_ns, before.archive_transfer_time_ns); + EXPECT_EQ(cleared.archive_append_time_ns, before.archive_append_time_ns); + ASSERT_EQ(ctl->seq_new(), 0); + ASSERT_EQ(write_step(*ptr, fake, handle, {0}), Error::Ok); + const auto after = kv->metrics(); + EXPECT_GT(after.prepare_time_ns, before.prepare_time_ns); + EXPECT_GT(after.commit_time_ns, before.commit_time_ns); + kv->forget_handle(&handle); +} + +TEST_F(CudaPrivateCacheTest, CurrentCloneAndRewindPreserveResidentRows) { + auto ptr = make_private(); + auto* ctl = ptr->as(); + auto* kv = ptr->as(); + auto fake = private_container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + ASSERT_EQ(ctl->seq_new(), 0); + ASSERT_EQ( + write_step(*ptr, fake, handle, std::vector(12, 0)), Error::Ok); + auto& graph = handle.cuda_graph_state; + graph.phase = cu::CudaGraphPhase::Replay; + const void* flat_before_clone = fake.bound["flat_k"].data; + ASSERT_EQ(ctl->seq_clone(0, 12), 1); + ASSERT_EQ(kv->rebind_for_execute(&handle), Error::Ok); + if (fake.bound["flat_k"].data != flat_before_clone) { + EXPECT_EQ(graph.phase, cu::CudaGraphPhase::Warmup); + EXPECT_EQ(graph.warmup_remaining, 1); + } else { + EXPECT_EQ(graph.phase, cu::CudaGraphPhase::Replay); + } + for (bool value : {false, true}) { + auto* data = + static_cast(fake.bound[value ? "ring_v" : "ring_k"].data); + for (int position = 8; position < 12; ++position) { + EXPECT_EQ( + read_rows( + data + (kPrivateWindow + position % kPrivateWindow) * kRow, 1), + payload(0, position, value)); + } + } + graph.phase = cu::CudaGraphPhase::Replay; + const auto growth = kv->metrics().growth_count; + const auto bytes = kv->metrics().allocated_bytes; + ASSERT_TRUE(ctl->rewind(1, 12)); + EXPECT_EQ(graph.phase, cu::CudaGraphPhase::Replay); + EXPECT_EQ(kv->metrics().growth_count, growth); + EXPECT_EQ(kv->metrics().allocated_bytes, bytes); + ASSERT_TRUE(ctl->rewind(1, 11)); + EXPECT_EQ(graph.phase, cu::CudaGraphPhase::Replay); + for (bool value : {false, true}) { + auto* data = + static_cast(fake.bound[value ? "ring_v" : "ring_k"].data); + for (int position = 7; position < 11; ++position) { + EXPECT_EQ( + read_rows( + data + (kPrivateWindow + position % kPrivateWindow) * kRow, 1), + payload(0, position, value)); + } + } + ASSERT_EQ(write_step(*ptr, fake, handle, {1}), Error::Ok); + EXPECT_EQ(ctl->pos(0), 12); + EXPECT_EQ(ctl->pos(1), 12); + kv->forget_handle(&handle); +} + +TEST_F(CudaPrivateCacheTest, FailedPreparationOrCompactionFenceRequiresClear) { + for (bool compact : {false, true}) { + SCOPED_TRACE(compact); + auto ptr = make_private(); + auto* ctl = ptr->as(); + auto* kv = ptr->as(); + auto fake = private_container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + ASSERT_EQ(ctl->seq_new(), 0); + ASSERT_EQ(ctl->seq_new(), 1); + ASSERT_EQ(write_step(*ptr, fake, handle, {0, 1}), Error::Ok); + if (compact) { + ASSERT_TRUE(ctl->seq_rm(1)); + } + cu::CudaKVPoolTestPeer fences; + if (compact) { + fences.fail_device_fence = true; + EXPECT_EQ(kv->compact_columns(0), Error::Internal); + } else { + ASSERT_TRUE(ctl->declare_step({0, 0})); + fences.fail_stream_fence = true; + EXPECT_EQ(kv->prepare_step(2, cudaStreamPerThread), Error::Internal); + EXPECT_EQ(kv->abort_step(), Error::Ok); + } + EXPECT_FALSE(ctl->declare_step({0})); + EXPECT_FALSE(ctl->seq_new()); + EXPECT_FALSE(ctl->seq_clone(0, 1)); + EXPECT_EQ(kv->compact_columns(0), Error::InvalidState); + ctl->clear(); + ASSERT_EQ(ctl->seq_new(), 0); + ASSERT_EQ(write_step(*ptr, fake, handle, {0}), Error::Ok); + expect_history(fake, 0, 1); + kv->forget_handle(&handle); + } +} + +TEST_F(CudaPrivateCacheTest, CompactLiveReusedOwnerDropsLongCapacity) { + auto ptr = make_private(); + auto* ctl = ptr->as(); + auto* kv = ptr->as(); + auto fake = private_container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + ASSERT_EQ(ctl->seq_new(), 0); + ASSERT_EQ(ctl->seq_new(), 1); + ASSERT_EQ( + write_step(*ptr, fake, handle, std::vector(128, 0)), Error::Ok); + ASSERT_EQ( + write_step(*ptr, fake, handle, std::vector(12, 1)), Error::Ok); + ASSERT_TRUE(ctl->seq_rm(0)); + ASSERT_EQ(ctl->seq_new(), 0); + ASSERT_EQ(write_step(*ptr, fake, handle, {0}), Error::Ok); + const auto before = kv->metrics().allocated_bytes; + ASSERT_EQ(kv->compact_columns(0), Error::Ok); + EXPECT_LT(kv->metrics().allocated_bytes, before); + // Upload the new descriptors without moving the short owner's positions. + ASSERT_EQ(write_step(*ptr, fake, handle, {0}), Error::Ok); + const auto flat = + read_ints(fake.bound["flat_layout"].data, (kOwners + 1) * 2); + const auto ring = + read_ints(fake.bound["ring_layout"].data, (kOwners + 1) * 2); + EXPECT_EQ(flat[1], 2); + EXPECT_EQ(ring[1], 2); + EXPECT_EQ(ring[3], kPrivateWindow); + expect_history(fake, 0, 2); + expect_history(fake, 1, 12); + const auto stable = kv->metrics().allocated_bytes; + ASSERT_EQ(kv->compact_columns(0), Error::Ok); + EXPECT_EQ(kv->metrics().allocated_bytes, stable); + kv->forget_handle(&handle); +} + +TEST_F(CudaPrivateCacheTest, CompactPreservesLiveDecodeSlackAndExactHistory) { + auto ptr = make_private(); + auto* ctl = ptr->as(); + auto* kv = ptr->as(); + auto fake = private_container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + ASSERT_EQ(ctl->seq_new(), 0); + ASSERT_EQ(ctl->seq_new(), 1); + ASSERT_EQ( + write_step(*ptr, fake, handle, std::vector(128, 0)), Error::Ok); + for (int length = 1; length <= 9; ++length) { + ASSERT_EQ(write_step(*ptr, fake, handle, {1}), Error::Ok); + } + const auto before = kv->metrics().allocated_bytes; + ASSERT_TRUE(ctl->seq_rm(0)); + ASSERT_EQ(kv->compact_columns(0), Error::Ok); + EXPECT_LT(kv->metrics().allocated_bytes, before); + const auto growths = kv->metrics().growth_count; + ASSERT_EQ(write_step(*ptr, fake, handle, {1}), Error::Ok); + EXPECT_EQ(kv->metrics().growth_count, growths); + const auto flat = + read_ints(fake.bound["flat_layout"].data, (kOwners + 1) * 2); + EXPECT_EQ(flat[3], 16); + void* flat_data = fake.bound["flat_k"].data; + void* ring_data = fake.bound["ring_k"].data; + for (int length = 11; length <= 16; ++length) { + ASSERT_EQ(write_step(*ptr, fake, handle, {1}), Error::Ok); + EXPECT_EQ(kv->metrics().growth_count, growths); + EXPECT_EQ(fake.bound["flat_k"].data, flat_data); + EXPECT_EQ(fake.bound["ring_k"].data, ring_data); + expect_history(fake, 1, length); + } + kv->forget_handle(&handle); +} + +TEST_F(CudaPrivateCacheTest, IdleCompactionDropsClosedPrivateSpans) { + auto ptr = make_private(); + auto* ctl = ptr->as(); + auto* kv = ptr->as(); + auto fake = private_container(); + auto handle = make_handle(fake); + ASSERT_TRUE(kv->note_handle(&handle).get()); + std::vector owners; + for (int i = 0; i < kOwners; ++i) { + ASSERT_EQ(ctl->seq_new(), i); + owners.push_back(i); + } + ASSERT_EQ(write_step(*ptr, fake, handle, owners), Error::Ok); + const auto before = kv->metrics().allocated_bytes; + for (int i = 1; i < kOwners; ++i) { + ASSERT_TRUE(ctl->seq_rm(i)); + } + ASSERT_EQ(kv->compact_columns(0), Error::Ok); + EXPECT_EQ(kv->metrics().physical_columns, 2); + EXPECT_LT(kv->metrics().allocated_bytes, before); + ASSERT_EQ(write_step(*ptr, fake, handle, {0}), Error::Ok); + expect_history(fake, 0, 2); + kv->forget_handle(&handle); } diff --git a/backends/cuda/runtime/test/test_private_row_layout.cpp b/backends/cuda/runtime/test/test_private_row_layout.cpp new file mode 100644 index 00000000000..6422f7d25be --- /dev/null +++ b/backends/cuda/runtime/test/test_private_row_layout.cpp @@ -0,0 +1,327 @@ +/* + * 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 + +namespace { + +using executorch::backends::cuda::make_private_row_layout; +using executorch::backends::cuda::PrivateRowLayout; +using executorch::backends::cuda::PrivateRowSpan; +using executorch::runtime::Error; + +executorch::runtime::Result plan( + const std::vector& required, + const std::vector& previous, + int64_t initial, + int64_t limit, + bool compact = false) { + return make_private_row_layout( + {required.data(), required.size()}, + {previous.data(), previous.size()}, + initial, + limit, + compact); +} + +TEST(PrivateRowLayoutTest, EmptyOwnersAllocateOnlyScratch) { + const std::vector rows(64, 0); + const auto result = plan(rows, {}, 512, 131072); + ASSERT_TRUE(result.ok()); + EXPECT_EQ(result.get().rows, 1); + ASSERT_EQ(result.get().spans.size(), 65); + for (size_t i = 0; i < 64; ++i) { + EXPECT_EQ(result.get().spans[i].capacity, 0); + } + EXPECT_EQ(result.get().spans.back().capacity, 1); +} + +TEST(PrivateRowLayoutTest, LongOwnerDoesNotGrowShortOwners) { + std::vector rows(64, 1); + const auto first = plan(rows, {}, 512, 131072); + ASSERT_TRUE(first.ok()); + EXPECT_EQ(first.get().rows, 64 * 512 + 1); + rows[17] = 8193; + const auto grown = plan(rows, first.get().spans, 512, 131072); + ASSERT_TRUE(grown.ok()); + EXPECT_EQ(grown.get().spans[17].capacity, 8193); + EXPECT_EQ(grown.get().rows, 64 * 512 * 2 + 1); + for (size_t i = 0; i < 64; ++i) { + if (i != 17) { + EXPECT_EQ(grown.get().spans[i].capacity, 512); + EXPECT_EQ(grown.get().spans[i].base, first.get().spans[i].base); + } + } + EXPECT_EQ(first.get().spans[17].capacity, 512); +} + +TEST(PrivateRowLayoutTest, GrowthIsGeometricAndRetainsUntouchedSpans) { + const std::vector rows{513, 3}; + const std::vector previous{{0, 512}, {512, 512}, {1024, 1}}; + const auto result = plan(rows, previous, 512, 131072); + ASSERT_TRUE(result.ok()); + EXPECT_EQ(result.get().spans[0].capacity, 1024); + EXPECT_EQ(result.get().spans[1].capacity, 512); + EXPECT_EQ(result.get().spans[1].base, 512); + EXPECT_EQ(result.get().spans[0].base, 1024); + EXPECT_EQ(result.get().rows, 2049); + EXPECT_EQ(previous[1].base, 512); +} + +TEST(PrivateRowLayoutTest, ClosingAnOwnerReclaimsOnlyItsSpan) { + const std::vector rows{8, 0, 4}; + const std::vector previous{ + {0, 16}, {16, 8192}, {8208, 8}, {8216, 1}}; + const auto result = plan(rows, previous, 4, 131072, true); + ASSERT_TRUE(result.ok()); + EXPECT_EQ(result.get().spans[0].capacity, 16); + EXPECT_EQ(result.get().spans[1].capacity, 0); + EXPECT_EQ(result.get().spans[2].capacity, 8); + EXPECT_EQ(result.get().spans[2].base, 16); + EXPECT_EQ(result.get().rows, 25); +} + +TEST(PrivateRowLayoutTest, CompactKeepsBoundedGrowthSlackForLiveOwners) { + const std::vector rows{9, 1, 64}; + const std::vector previous{ + {0, 1024}, {1024, 1024}, {2048, 64}, {2112, 1}}; + auto compact = plan(rows, previous, 2, 131072, true); + ASSERT_TRUE(compact.ok()); + EXPECT_EQ(compact.get().spans[0].capacity, 16); + EXPECT_EQ(compact.get().spans[1].capacity, 2); + // Compaction alone never increases the last owner's filled span. + EXPECT_EQ(compact.get().spans[2].capacity, 64); + EXPECT_LT(compact.get().rows, 2113); + auto layout = std::move(compact.get()); + const auto bases = layout.spans; + for (int length = 10; length <= 16; ++length) { + const std::vector next{length, 1, 64}; + auto result = plan(next, layout.spans, 2, 131072); + ASSERT_TRUE(result.ok()); + EXPECT_FALSE(result.get().repacked); + EXPECT_EQ(result.get().rows, layout.rows); + for (size_t owner = 0; owner < 3; ++owner) { + EXPECT_EQ(result.get().spans[owner].base, bases[owner].base); + EXPECT_EQ(result.get().spans[owner].capacity, bases[owner].capacity); + } + layout = std::move(result.get()); + } +} + +TEST(PrivateRowLayoutTest, CompactLiveReusedOwnerDropsInheritedCapacity) { + const std::vector rows{1, 2048, 7}; + const std::vector previous{ + {0, 8192}, {8192, 2048}, {10240, 512}, {10752, 1}}; + const auto result = plan(rows, previous, 512, 131072, true); + ASSERT_TRUE(result.ok()); + EXPECT_EQ(result.get().spans[0].capacity, 512); + EXPECT_EQ(result.get().spans[1].capacity, 2048); + EXPECT_EQ(result.get().spans[2].capacity, 512); + EXPECT_EQ(result.get().rows, 3073); + EXPECT_TRUE(result.get().repacked); + EXPECT_EQ(previous[0].capacity, 8192); +} + +TEST(PrivateRowLayoutTest, CompactWrappedRingKeepsItsModulus) { + const std::vector rows{2048, 1}; + const std::vector previous{{0, 2048}, {2048, 32}, {2080, 1}}; + const auto result = plan(rows, previous, 2, 2048, true); + ASSERT_TRUE(result.ok()); + EXPECT_EQ(result.get().spans[0].capacity, 2048); + EXPECT_EQ(result.get().spans[1].capacity, 2); + EXPECT_EQ(result.get().rows, 2051); +} + +TEST(PrivateRowLayoutTest, ReopenedOwnerStartsAtInitialCapacity) { + const std::vector rows{1, 1}; + const std::vector previous{{0, 2048}, {2048, 0}, {2048, 1}}; + const auto result = plan(rows, previous, 512, 131072); + ASSERT_TRUE(result.ok()); + EXPECT_EQ(result.get().spans[0].capacity, 2048); + EXPECT_EQ(result.get().spans[1].capacity, 512); + EXPECT_EQ(result.get().rows, 4097); +} + +TEST(PrivateRowLayoutTest, RingRowsGrowBeforeReachingWindowLimit) { + const std::vector rows{513, 1}; + const std::vector previous{{0, 512}, {512, 512}, {1024, 1}}; + const auto result = plan(rows, previous, 512, 768); + ASSERT_TRUE(result.ok()); + EXPECT_EQ(result.get().spans[0].capacity, 768); + EXPECT_EQ(result.get().spans[1].capacity, 512); + EXPECT_EQ(result.get().rows, 1281); + const std::vector small_window{80}; + const auto small = plan(small_window, {}, 512, 80); + ASSERT_TRUE(small.ok()); + EXPECT_EQ(small.get().rows, 81); +} + +TEST(PrivateRowLayoutTest, InvalidLaterOwnerDoesNotMutateLiveLayout) { + const std::vector rows{513, 131073}; + const std::vector previous{{0, 512}, {512, 512}, {1024, 1}}; + const auto result = plan(rows, previous, 512, 131072); + ASSERT_FALSE(result.ok()); + EXPECT_EQ(result.error(), Error::InvalidArgument); + EXPECT_EQ(previous[0].capacity, 512); + EXPECT_EQ(previous[1].base, 512); +} + +TEST(PrivateRowLayoutTest, RejectsDescriptorOverflowAndInvalidGeometry) { + const int64_t max = std::numeric_limits::max(); + const std::vector rows{max}; + EXPECT_FALSE(plan(rows, {}, 512, max).ok()); + const std::vector two{max / 2 + 1, max / 2 + 1}; + EXPECT_FALSE(plan(two, {}, 512, max).ok()); + const std::vector one{1}; + EXPECT_FALSE(plan(one, {}, 0, 128).ok()); + EXPECT_FALSE(plan(one, {}, 512, 0).ok()); + const std::vector wrong{{0, 2}}; + EXPECT_FALSE(plan(one, wrong, 2, 128).ok()); + const std::vector negative{-1}; + EXPECT_FALSE(plan(negative, {}, 512, 128).ok()); +} + +TEST(PrivateRowLayoutTest, RejectsOverlappingSpansAndInvalidScratch) { + const std::vector rows{1, 1}; + const std::vector overlap{{0, 8}, {7, 8}, {15, 1}}; + EXPECT_FALSE(plan(rows, overlap, 8, 128).ok()); + const std::vector gap{{0, 8}, {9, 8}, {17, 1}}; + EXPECT_TRUE(plan(rows, gap, 8, 128).ok()); + const std::vector scratch{{0, 8}, {8, 8}, {16, 0}}; + EXPECT_FALSE(plan(rows, scratch, 8, 128).ok()); +} + +TEST(PrivateRowLayoutTest, StaggeredAdmissionUsesGeometricArenaGrowth) { + std::vector required(64, 0); + PrivateRowLayout previous; + int moves = 0; + for (size_t owner = 0; owner < required.size(); ++owner) { + required[owner] = 1; + auto result = plan(required, previous.spans, 2, 131072); + ASSERT_TRUE(result.ok()); + const auto& next = result.get(); + moves += next.rows != previous.rows; + EXPECT_FALSE(next.repacked); + for (size_t old = 0; old < owner; ++old) { + EXPECT_EQ(next.spans[old].base, previous.spans[old].base); + EXPECT_EQ(next.spans[old].capacity, previous.spans[old].capacity); + } + previous = next; + } + EXPECT_LE(moves, 7); + EXPECT_EQ(previous.rows, 129); +} + +TEST(PrivateRowLayoutTest, SlackSupportsInPlaceGrowthAndDisjointAdmission) { + const std::vector previous{{0, 4}, {12, 4}, {0, 0}, {31, 1}}; + auto result = plan({5, 1, 1}, previous, 4, 128); + ASSERT_TRUE(result.ok()); + const auto& next = result.get(); + EXPECT_EQ(next.rows, 32); + EXPECT_FALSE(next.repacked); + EXPECT_EQ(next.spans[0].base, 0); + EXPECT_EQ(next.spans[0].capacity, 8); + EXPECT_EQ(next.spans[1].base, 12); + EXPECT_EQ(next.spans[2].base, 8); +} + +TEST(PrivateRowLayoutTest, FragmentationAtTheCeilingPacksIntoFreshStorage) { + const std::vector previous{{8, 8}, {4, 4}, {16, 1}}; + const auto result = plan({8, 8}, previous, 4, 8); + ASSERT_TRUE(result.ok()); + EXPECT_TRUE(result.get().repacked); + EXPECT_EQ(result.get().rows, 17); + EXPECT_EQ(result.get().spans[0].base, 0); + EXPECT_EQ(result.get().spans[1].base, 8); +} + +TEST(PrivateRowLayoutTest, FragmentationKeepsProductionRingGrowthSlack) { + constexpr int owners = 64; + constexpr int window = 2048; + std::vector previous; + std::vector required(owners, 1); + auto first = make_private_row_layout( + {required.data(), required.size()}, {}, 512, window); + ASSERT_TRUE(first.ok()); + previous = first.get().spans; + int repacks = 0; + for (int length = 2; length <= window; ++length) { + std::fill(required.begin(), required.end(), length); + const auto result = make_private_row_layout( + {required.data(), required.size()}, + {previous.data(), previous.size()}, + 512, + window); + ASSERT_TRUE(result.ok()) << length; + if (length > 1024) { + repacks += result.get().repacked; + for (int owner = 0; owner < owners; ++owner) { + ASSERT_EQ(result.get().spans[owner].capacity, window) << length; + if (length > 1025) { + EXPECT_EQ(result.get().spans[owner].base, previous[owner].base); + } + } + } + previous = result.get().spans; + } + EXPECT_EQ(repacks, 1); +} + +TEST(PrivateRowLayoutTest, MixedGrowthAndReusePreserveDisjointPayloadRanges) { + std::mt19937 rng(917); + std::vector required(64, 0); + PrivateRowLayout previous; + for (int iteration = 0; iteration < 1500; ++iteration) { + const size_t owner = rng() % required.size(); + required[owner] = rng() % 257; + const auto result = + plan(required, previous.spans, 2, 256, iteration % 23 == 0); + ASSERT_TRUE(result.ok()) << iteration; + const auto& next = result.get(); + EXPECT_LE(next.rows, 64 * 256 + 1); + for (size_t i = 0; i < required.size(); ++i) { + const auto dst = next.spans[i]; + EXPECT_GE(dst.capacity, required[i]); + EXPECT_LE(dst.capacity, 256); + EXPECT_GE(dst.base, 0); + EXPECT_LE(static_cast(dst.base) + dst.capacity, next.rows - 1); + if (dst.capacity == 0) { + continue; + } + for (size_t j = 0; j < i; ++j) { + const auto other = next.spans[j]; + if (other.capacity > 0) { + EXPECT_TRUE( + dst.base + dst.capacity <= other.base || + other.base + other.capacity <= dst.base); + } + } + // In-place copies must never overwrite another old source, including + // an owner's source that is relocated later in the same transaction. + if (!previous.spans.empty() && !next.repacked && + next.rows == previous.rows && dst.base != previous.spans[i].base) { + for (size_t j = 0; j < required.size(); ++j) { + const auto src = previous.spans[j]; + if (src.capacity > 0) { + EXPECT_TRUE( + dst.base + dst.capacity <= src.base || + src.base + src.capacity <= dst.base); + } + } + } + } + previous = next; + } +} + +} // namespace diff --git a/backends/cuda/runtime/test/test_ring_history.cpp b/backends/cuda/runtime/test/test_ring_history.cpp new file mode 100644 index 00000000000..976d662f33c --- /dev/null +++ b/backends/cuda/runtime/test/test_ring_history.cpp @@ -0,0 +1,362 @@ +/* + * 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 { + +using executorch::backends::cuda::RingHistory; +using executorch::runtime::Error; +using executorch::runtime::Span; + +constexpr size_t kRowBytes = sizeof(uint32_t); +constexpr size_t kPlanes = 4; + +uint32_t payload(int32_t owner, int position, size_t plane) { + return static_cast(owner) * 65536 + position * 8 + plane; +} + +std::vector pack( + const std::vector& runs, + int width) { + std::vector packed(kPlanes * width * kRowBytes, 0xff); + for (const auto& run : runs) { + for (size_t plane = 0; plane < kPlanes; ++plane) { + for (int row = 0; row < run.length; ++row) { + const uint32_t value = + payload(run.owner, run.absolute_start + row, plane); + std::memcpy( + packed.data() + + (plane * width + run.packed_start + row) * kRowBytes, + &value, + kRowBytes); + } + } + } + return packed; +} + +void append( + RingHistory& history, + const std::vector& runs, + int width) { + const auto packed = pack(runs, width); + ASSERT_EQ( + history.append( + {runs.data(), runs.size()}, {packed.data(), packed.size()}, width), + Error::Ok); +} + +void expect_rows( + const RingHistory& history, + int32_t owner, + int start, + int count) { + for (size_t plane = 0; plane < kPlanes; ++plane) { + int row = start; + while (row < start + count) { + const auto chunk = history.read(owner, row, start + count - row, plane); + ASSERT_TRUE(chunk); + ASSERT_GT(chunk->count, 0); + for (int offset = 0; offset < chunk->count; ++offset) { + uint32_t actual = 0; + std::memcpy(&actual, chunk->data + offset * kRowBytes, kRowBytes); + EXPECT_EQ(actual, payload(owner, row + offset, plane)); + } + row += chunk->count; + } + } +} + +class RingHistoryTest : public ::testing::Test { + protected: + void SetUp() override { + auto result = RingHistory::create(80, 96, 512, kRowBytes, kPlanes); + ASSERT_TRUE(result.ok()); + history = std::move(result.get()); + } + std::unique_ptr history; +}; + +TEST(RingRestorePlanTest, RestoresOnlyTheOverwrittenPrefix) { + const auto plan = RingHistory::restore_plan(2048, 9999, 10000); + ASSERT_TRUE(plan); + EXPECT_EQ(plan->start, 7952); + EXPECT_EQ(plan->resident_start, 7953); + EXPECT_EQ(plan->end, 9999); + EXPECT_EQ(plan->resident_start - plan->start, 1); +} + +TEST(RingRestorePlanTest, NoopAndUnwrappedRewindsNeedNoHostCopies) { + for (const auto& [keep, end] : + {std::pair{10000, 10000}, std::pair{7, 11}, std::pair{0, 0}}) { + const auto plan = RingHistory::restore_plan(2048, keep, end); + ASSERT_TRUE(plan); + EXPECT_EQ(plan->resident_start, plan->start); + EXPECT_EQ(plan->end, keep); + } +} + +TEST(RingRestorePlanTest, OldCloneAndWindowOneBoundaries) { + const auto old = RingHistory::restore_plan(2048, 5000, 10000); + ASSERT_TRUE(old); + EXPECT_EQ(old->start, 2953); + EXPECT_EQ(old->resident_start, 5000); + EXPECT_EQ(old->end, 5000); + const auto single = RingHistory::restore_plan(1, 5000, 10000); + ASSERT_TRUE(single); + EXPECT_EQ(single->start, 5000); + EXPECT_EQ(single->resident_start, 5000); + EXPECT_EQ(single->end, 5000); + EXPECT_FALSE(RingHistory::restore_plan(0, 1, 2)); + EXPECT_FALSE(RingHistory::restore_plan(8, -1, 2)); + EXPECT_FALSE(RingHistory::restore_plan(8, 3, 2)); +} + +TEST_F(RingHistoryTest, InterleavedOwnersAndPlanesRemainIndependent) { + append(*history, {{0, 0, 3, 0}, {1, 3, 2, 0}, {0, 5, 4, 3}}, 16); + expect_rows(*history, 0, 0, 7); + expect_rows(*history, 1, 0, 2); + EXPECT_FALSE(history->read(0, 7, 1, 0)); + EXPECT_FALSE(history->read(1, 2, 1, 0)); + EXPECT_FALSE(history->read(2, 0, 1, 0)); +} + +TEST_F(RingHistoryTest, SortedSparseOwnersKeepValidationTransactional) { + const std::vector initial{ + {1, 0, 2, 0}, {7, 3, 3, 0}, {63, 6, 1, 0}}; + append(*history, initial, 8); + const auto bytes = history->resident_bytes(); + const std::vector bad{ + {1, 0, 2, 2}, {7, 2, 2, 3}, {63, 4, 2, 2}}; + const auto packed = pack(bad, 8); + EXPECT_EQ( + history->append( + {bad.data(), bad.size()}, {packed.data(), packed.size()}, 8), + Error::InvalidState); + EXPECT_EQ(history->resident_bytes(), bytes); + expect_rows(*history, 1, 0, 2); + expect_rows(*history, 7, 0, 3); + expect_rows(*history, 63, 0, 1); + EXPECT_FALSE(history->read(1, 2, 1, 0)); + append(*history, {{1, 0, 2, 2}, {7, 2, 2, 3}, {63, 4, 2, 1}}, 8); + expect_rows(*history, 1, 0, 4); + expect_rows(*history, 7, 0, 5); + expect_rows(*history, 63, 0, 3); +} + +TEST_F(RingHistoryTest, AdjacentRepeatedOwnersValidateTheirCombinedEnd) { + append(*history, {{7, 0, 2, 0}, {7, 2, 2, 2}, {9, 4, 1, 0}}, 8); + expect_rows(*history, 7, 0, 4); + expect_rows(*history, 9, 0, 1); + const std::vector bad{{7, 0, 2, 4}, {7, 2, 2, 4}}; + const auto packed = pack(bad, 8); + EXPECT_EQ( + history->append( + {bad.data(), bad.size()}, {packed.data(), packed.size()}, 8), + Error::InvalidState); + expect_rows(*history, 7, 0, 4); + EXPECT_FALSE(history->read(7, 4, 1, 0)); +} + +TEST_F(RingHistoryTest, PageAndArchiveBoundariesPreserveExactRows) { + append(*history, {{0, 0, 96, 0}}, 96); + append(*history, {{0, 0, 96, 96}}, 96); + append(*history, {{0, 0, 96, 192}}, 96); + // The 175-row archive wraps at a different boundary from its 64-row pages. + expect_rows(*history, 0, 113, 175); + EXPECT_FALSE(history->read(0, 112, 1, 0)); + const auto boundary = history->read(0, 174, 20, 0); + ASSERT_TRUE(boundary); + EXPECT_EQ(boundary->count, 1); + EXPECT_TRUE(history->rewind(0, 193)); + expect_rows(*history, 0, 113, 80); + EXPECT_TRUE(history->rewind(0, 192)); + EXPECT_FALSE(history->rewind(0, 191)); +} + +TEST_F(RingHistoryTest, LargeStepAndManyWrapsRetainTheRewindWindow) { + for (int start = 0; start < 480; start += 96) { + append(*history, {{5, 0, 96, start}}, 96); + } + expect_rows(*history, 5, 305, 175); + EXPECT_TRUE(history->rewind(5, 385)); + expect_rows(*history, 5, 305, 80); + append(*history, {{5, 0, 96, 385}}, 96); + expect_rows(*history, 5, 401, 80); + EXPECT_FALSE(history->read(5, 304, 1, 0)); +} + +TEST_F(RingHistoryTest, CloneSharesPagesAndDetachDoesNotChangeItsSource) { + append(*history, {{0, 0, 40, 0}}, 40); + const size_t source_bytes = history->resident_bytes(); + ASSERT_GT(source_bytes, 0); + ASSERT_TRUE(history->clone(0, 7, 32)); + EXPECT_EQ(history->resident_bytes(), source_bytes); + // A clone retains the source's values, not values derived from its new id. + const auto before = history->read(7, 31, 1, 2); + ASSERT_TRUE(before); + uint32_t value = 0; + std::memcpy(&value, before->data, kRowBytes); + EXPECT_EQ(value, payload(0, 31, 2)); + append(*history, {{7, 0, 8, 32}}, 8); + EXPECT_GT(history->resident_bytes(), source_bytes); + expect_rows(*history, 0, 0, 40); + expect_rows(*history, 7, 32, 8); + history->erase(7); + EXPECT_EQ(history->resident_bytes(), source_bytes); +} + +TEST_F(RingHistoryTest, RewindingOneOwnerDoesNotRewindItsClone) { + append(*history, {{3, 0, 90, 0}}, 90); + ASSERT_TRUE(history->clone(3, 9, 90)); + ASSERT_TRUE(history->rewind(3, 80)); + EXPECT_FALSE(history->read(3, 80, 1, 0)); + const auto preserved = history->read(9, 80, 10, 0); + ASSERT_TRUE(preserved); + EXPECT_EQ(preserved->count, 10); + append(*history, {{3, 0, 10, 80}}, 10); + expect_rows(*history, 3, 80, 10); + uint32_t value = 0; + const auto clone = history->read(9, 89, 1, 3); + ASSERT_TRUE(clone); + std::memcpy(&value, clone->data, kRowBytes); + EXPECT_EQ(value, payload(3, 89, 3)); +} + +TEST_F(RingHistoryTest, StaleRowsCannotBeRestoredOrCloned) { + append(*history, {{0, 0, 96, 0}}, 96); + append(*history, {{0, 0, 96, 96}}, 96); + const size_t bytes = history->resident_bytes(); + EXPECT_FALSE(history->clone(0, 1, 95)); + EXPECT_FALSE(history->rewind(0, 95)); + EXPECT_EQ(history->resident_bytes(), bytes); + expect_rows(*history, 0, 112, 80); + EXPECT_TRUE(history->clone(0, 1, 96)); + EXPECT_FALSE(history->clone(0, 1, 192)); + EXPECT_FALSE(history->clone(0, -1, 192)); + EXPECT_FALSE(history->clone(123, 2, 1)); +} + +TEST_F(RingHistoryTest, OneTokenRollbackPreservesTheOriginalWrittenFloor) { + for (int window : {1, 5}) { + auto result = RingHistory::create(window, 1, 32, kRowBytes, kPlanes); + ASSERT_TRUE(result.ok()); + auto archive = std::move(result.get()); + for (int position = 0; position < 12; ++position) { + append(*archive, {{0, 0, 1, position}}, 1); + } + ASSERT_TRUE(archive->clone(0, 1, 11)); + ASSERT_TRUE(archive->rewind(0, 11)); + EXPECT_FALSE(archive->rewind(0, 10)); + EXPECT_FALSE(archive->clone(1, 2, 10)); + if (window > 1) { + expect_rows(*archive, 0, 7, 4); + } + append(*archive, {{0, 0, 1, 11}}, 1); + EXPECT_TRUE(archive->has_window(0, 11)); + EXPECT_FALSE(archive->has_window(0, 10)); + } +} + +TEST_F(RingHistoryTest, InvalidLaterSegmentDoesNotModifyEarlierOwners) { + append(*history, {{0, 0, 4, 0}, {1, 4, 4, 0}}, 8); + const auto bytes = history->resident_bytes(); + const std::vector bad{{0, 0, 4, 4}, {1, 4, 4, 99}}; + const auto packed = pack(bad, 8); + EXPECT_EQ( + history->append( + {bad.data(), bad.size()}, {packed.data(), packed.size()}, 8), + Error::InvalidState); + EXPECT_EQ(history->resident_bytes(), bytes); + expect_rows(*history, 0, 0, 4); + expect_rows(*history, 1, 0, 4); + EXPECT_FALSE(history->read(0, 4, 1, 0)); + append(*history, {{0, 0, 4, 4}, {1, 4, 4, 4}}, 8); + expect_rows(*history, 0, 0, 8); +} + +TEST_F(RingHistoryTest, RejectsOverlappingPackedRowsWithoutMutation) { + const std::vector bad{{0, 0, 4, 0}, {1, 3, 4, 0}}; + const auto packed = pack(bad, 8); + EXPECT_EQ( + history->append( + {bad.data(), bad.size()}, {packed.data(), packed.size()}, 8), + Error::InvalidArgument); + EXPECT_EQ(history->resident_bytes(), 0); + append(*history, {{0, 2, 4, 0}, {1, 6, 2, 0}}, 12); + expect_rows(*history, 0, 0, 4); + expect_rows(*history, 1, 0, 2); +} + +TEST_F(RingHistoryTest, RejectsShortTransferAndContextOverflow) { + const std::vector runs{{0, 0, 8, 0}}; + auto packed = pack(runs, 8); + packed.pop_back(); + EXPECT_EQ( + history->append( + {runs.data(), runs.size()}, {packed.data(), packed.size()}, 8), + Error::InvalidArgument); + EXPECT_EQ(history->resident_bytes(), 0); + for (int start = 0; start < 480; start += 96) { + append(*history, {{0, 0, 96, start}}, 96); + } + const std::vector overflow{{0, 0, 33, 480}}; + const auto overpacked = pack(overflow, 33); + EXPECT_EQ( + history->append( + {overflow.data(), overflow.size()}, + {overpacked.data(), overpacked.size()}, + 33), + Error::InvalidArgument); + expect_rows(*history, 0, 400, 80); +} + +TEST_F(RingHistoryTest, ErasingAndReusingAnOwnerCannotExposeOldRows) { + append(*history, {{0, 0, 20, 0}, {1, 20, 20, 0}}, 40); + history->erase(0); + EXPECT_FALSE(history->read(0, 0, 1, 0)); + expect_rows(*history, 1, 0, 20); + append(*history, {{0, 0, 3, 0}}, 8); + expect_rows(*history, 0, 0, 3); + EXPECT_FALSE(history->read(0, 3, 1, 0)); + history->clear(); + EXPECT_EQ(history->resident_bytes(), 0); + EXPECT_FALSE(history->read(1, 0, 1, 0)); +} + +TEST(RingHistoryGeometryTest, ContextShorterThanWindowRetainsEveryRow) { + auto result = RingHistory::create(80, 8, 12, kRowBytes, kPlanes); + ASSERT_TRUE(result.ok()); + auto history = std::move(result.get()); + append(*history, {{0, 0, 8, 0}}, 8); + append(*history, {{0, 0, 4, 8}}, 8); + expect_rows(*history, 0, 0, 12); + EXPECT_TRUE(history->rewind(0, 8)); + expect_rows(*history, 0, 0, 8); +} + +TEST(RingHistoryGeometryTest, RejectsImpossibleGeometryBeforeAllocatingPages) { + EXPECT_FALSE(RingHistory::create(0, 8, 12, kRowBytes, kPlanes).ok()); + EXPECT_FALSE(RingHistory::create(80, 0, 12, kRowBytes, kPlanes).ok()); + EXPECT_FALSE(RingHistory::create(80, 16, 12, kRowBytes, kPlanes).ok()); + EXPECT_FALSE(RingHistory::create(80, 8, 12, 0, kPlanes).ok()); + EXPECT_FALSE(RingHistory::create(80, 8, 12, kRowBytes, 0).ok()); + EXPECT_FALSE( + RingHistory::create(80, 8, 12, std::numeric_limits::max(), 2) + .ok()); +} + +} // namespace diff --git a/backends/cuda/runtime_owned_kv.py b/backends/cuda/runtime_owned_kv.py new file mode 100644 index 00000000000..73c96b58f9e --- /dev/null +++ b/backends/cuda/runtime_owned_kv.py @@ -0,0 +1,109 @@ +# 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. + +"""Compile-only metadata placeholders for explicitly runtime-owned KV buffers.""" + +import contextlib +import re + +import torch +from torch.multiprocessing.reductions import StorageWeakRef + + +class RuntimeOwnedKVCompileBuffers: + """Identify buffers by the lowered program's FQNs and storage identities. + + A graph-owned alias excludes a storage from this optimization. Cloned + placeholders retain the original shape, stride and offset but have no + payload; only the runtime can supply that payload. Keep this object scoped + to one program's compilation, including structured-weight collection. + """ + + def __init__(self, program, fqn_prefix: str): + named = (*program.state_dict.items(), *program.constants.items()) + owned, other = set(), set() + for name, tensor in named: + if not isinstance(tensor, torch.Tensor): + continue + key = StorageWeakRef(tensor.untyped_storage()) + target = owned if name.startswith(fqn_prefix) else other + target.add(key) + self._storages = owned - other + self._clones = [] + + def owns_empty(self, tensor) -> bool: + return ( + isinstance(tensor, torch.Tensor) + and tensor.numel() > 0 + and tensor.untyped_storage().nbytes() == 0 + and StorageWeakRef(tensor.untyped_storage()) in self._storages + ) + + def cpu_placeholder(self, tensor: torch.Tensor) -> torch.Tensor: + if not self.owns_empty(tensor): + raise ValueError("Expected an empty runtime-owned KV buffer") + required = tensor.storage_offset() + 1 + for size, stride in zip(tensor.shape, tensor.stride()): + required += (size - 1) * stride + # Reserve an uninitialized view, then immediately release its storage. + # Unlike zeros(), this never initializes a model-sized CPU KV cache. + backing = torch.empty(int(required), dtype=tensor.dtype, device="cpu") + value = torch.as_strided( + backing, tensor.shape, tensor.stride(), tensor.storage_offset() + ) + value.untyped_storage().resize_(0) + self._storages.add(StorageWeakRef(value.untyped_storage())) + self._clones.append(value) + return value + + @contextlib.contextmanager + def constant_info_sizes(self, wrapper, tensors, alignment: int): + """Keep AOTI's declared extent independent from empty payload storage. + + Inductor emits constant data_size from storage.nbytes(), which is zero + for these views. The CUDA runtime checks the declared extent before + binding its own storage. Change only that field for identified empty + runtime buffers; leave shape, dtype, offset and blob packing untouched. + """ + if alignment not in (1, 64): + raise ValueError("Unsupported AOTI constant alignment") + sizes = {} + for index, tensor in enumerate(tensors): + if self.owns_empty(tensor): + extent = tensor.storage_offset() + 1 + for size, stride in zip(tensor.shape, tensor.stride()): + extent += (size - 1) * stride + size_bytes = extent * tensor.element_size() + sizes[index] = (size_bytes + alignment - 1) // alignment * alignment + if not sizes: + yield + return + lines = wrapper.prefix.get_lines_ref() + first = len(lines) + yield + replacements = {} + seen = set() + for line_index in range(first, len(lines)): + line = lines[line_index] + match = ( + re.fullmatch(r"(\s*)constants_info_\[(\d+)\]\.data_size = (\d+);", line) + if isinstance(line, str) + else None + ) + if match is not None and int(match[2]) in sizes: + index = int(match[2]) + if int(match[3]) != 0 or index in seen: + raise RuntimeError( + "Unexpected runtime-owned AOTI constant size emission" + ) + replacements[line_index] = ( + f"{match[1]}constants_info_[{index}].data_size = {sizes[index]};" + ) + seen.add(index) + if seen != sizes.keys(): + raise RuntimeError("Missing runtime-owned AOTI constant size emission") + for line_index, line in replacements.items(): + lines[line_index] = line diff --git a/backends/cuda/tests/targets.bzl b/backends/cuda/tests/targets.bzl index 09daa0afd10..52f930828a8 100644 --- a/backends/cuda/tests/targets.bzl +++ b/backends/cuda/tests/targets.bzl @@ -384,6 +384,47 @@ def define_common_targets(is_fbcode = False): ), ) + python_unittest_remote_gpu( + name = "test_sdpa_varlen_private", + srcs = [ + "test_sdpa_varlen_private.py", + ], + visibility = [ + "//executorch/...", + ], + deps = [ + "//caffe2:torch", + "//executorch/backends/cuda:cuda_passes", + "//executorch/backends/cuda:triton_kernels", + ], + keep_gpu_sections = True, + remote_execution = re_test_utils.remote_execution( + platform = "gpu-remote-execution", + subplatform = "A100-exclusive", + ), + ) + + python_unittest( + name = "test_private_kv_manifest", + srcs = [ + "test_private_kv_manifest.py", + ], + deps = [ + "//executorch/backends/cuda:cuda_passes", + ], + ) + + python_unittest( + name = "test_runtime_owned_kv", + srcs = ["test_runtime_owned_kv.py"], + deps = [ + "//caffe2:torch", + "//executorch/backends/cuda:cuda_backend", + "//executorch/backends/cuda:runtime_owned_kv", + "//executorch/exir/backend:compile_spec_schema", + ], + ) + python_unittest_remote_gpu( name = "test_int4_large_quantized_gemm", srcs = [ diff --git a/backends/cuda/tests/test_offgraph_kv_batched_sequence.py b/backends/cuda/tests/test_offgraph_kv_batched_sequence.py index 257e81df5e7..9f5b35229dc 100644 --- a/backends/cuda/tests/test_offgraph_kv_batched_sequence.py +++ b/backends/cuda/tests/test_offgraph_kv_batched_sequence.py @@ -23,12 +23,15 @@ batched_sequence_step, CheckOffGraphKVStepWidthPass, LowerOffGraphKVPass, + offgraph_kv_constant_methods, OFFGRAPH_KV_FQN_PREFIX, OFFGRAPH_KV_SEQ_COLS_FQN, OFFGRAPH_KV_SEQ_INFO_FQN, + OFFGRAPH_KV_SEQUENCE_INFO_ABI_METHOD, parse_offgraph_kv_manifest, ring_physical_capacity, ) +from executorch.backends.cuda.triton.kernels.sdpa_varlen import _num_splits, sdpa_varlen from executorch.exir import EdgeCompileConfig, to_edge from executorch.exir.dialects._ops import ops as exir_ops from executorch.extension.llm.cache.reference_cache import ( @@ -125,7 +128,7 @@ def close(self) -> None: def _max_abs_diff(actual, expected) -> float: - return (actual.float().cpu() - expected).abs().max().item() + return (actual.float().cpu() - expected.float().cpu()).abs().max().item() # Two sequences prefilling in one step, decoding together, then one decoding @@ -261,6 +264,157 @@ def forward(self, q, k, v, position): return flat + ring +@unittest.skipUnless(torch.cuda.is_available(), "CUDA required") +class RuntimeColumnPitchTest(unittest.TestCase): + """Check runtime write/read pitch with unchanged AOT tensor dimensions. + + This test reserves the declared maximum tensor and poisons the unused + tail. Actual smaller CUDA allocations are tested by the C++ cache and + model probe; this numerical test does not establish memory savings. + """ + + def _run(self, window): + torch.manual_seed(125) + declared_columns, max_write = 22, 32 + rows = min(64, window + max_write - 1) if window else 64 + oracle = _Oracle(128, (window,)) + self.addCleanup(oracle.close) + k_store = torch.full( + (1, rows * declared_columns, N_KV_HEADS, HEAD_DIM), + float("nan"), + dtype=torch.bfloat16, + device="cuda", + ) + v_store = torch.full_like(k_store, float("nan")) + old_mapping, old_columns = {}, 0 + positions = {} + for active in (1, 2, 4, 8, 16, 1): + owners = list(range(active)) if active != 1 or not old_mapping else [5] + mapping = {owner: column for column, owner in enumerate(owners)} + physical_columns = len(owners) + 1 + for store in (k_store, v_store): + retained = { + owner: store[0, : rows * old_columns] + .view(rows, old_columns, N_KV_HEADS, HEAD_DIM)[:, column] + .clone() + for owner, column in old_mapping.items() + if owner in mapping + } + store.fill_(float("nan")) + compact = store[0, : rows * physical_columns].view( + rows, physical_columns, N_KV_HEADS, HEAD_DIM + ) + compact.zero_() + for owner, values in retained.items(): + compact[:, mapping[owner]].copy_(values) + groups = [] + for owner in owners: + start = positions.get(owner, 0) + # Different histories exercise segment boundaries and ring wrap. + length = 1 + owner % 2 if active < 16 else 1 + if not old_mapping: + length = max_write - 1 + groups.append((owner, start, length)) + positions[owner] = start + length + seq_ids, q, k, v, position = _batch(groups) + (expected,) = oracle.step(seq_ids, q, k, v, position) + seq_cols, old_info = _plan( + seq_ids, + position, + mapping, + max_write, + 42, + physical_columns - 1, + ) + seq_info = torch.cat( + [old_info, old_info.new_full((42, 1), physical_columns)], dim=1 + ) + # Exercise an uncovered padded row in both split and generic paths. + padded_q = torch.cat([q, torch.zeros_like(q[:, :, :1])], dim=2) + padded_k = torch.cat([k, torch.zeros_like(k[:, :, :1])], dim=2) + padded_v = torch.cat([v, torch.zeros_like(v[:, :, :1])], dim=2) + out = batched_sequence_step( + padded_q, + padded_k, + padded_v, + torch.cat([position, position.new_zeros(1)]), + k_store, + v_store, + seq_cols, + seq_info, + SCALE, + rows, + declared_columns, + window, + window > 0, + True, + runtime_columns=True, + ) + self.assertLess(_max_abs_diff(out[:, :, : len(seq_ids)], expected), 2e-2) + self.assertTrue((out[:, :, len(seq_ids) :] == 0).all()) + for store in (k_store, v_store): + self.assertTrue(torch.isnan(store[0, rows * physical_columns :]).all()) + old_mapping, old_columns = mapping, physical_columns + + def test_flat_pitch_and_sparse_survivor(self): + self._run(window=0) + + def test_ring_pitch_and_sparse_survivor(self): + self._run(window=2) + + def test_runtime_pitch_with_multiple_decode_splits(self): + torch.manual_seed(126) + rows, declared_columns, physical_columns = 1024, 9, 4 + query = torch.randn( + 1, N_Q_HEADS, 3, HEAD_DIM, device="cuda", dtype=torch.bfloat16 + ) + key = torch.full( + (rows, declared_columns, N_KV_HEADS, HEAD_DIM), + float("nan"), + device="cuda", + dtype=torch.bfloat16, + ) + value = torch.full_like(key, float("nan")) + live_key = key.reshape(-1, N_KV_HEADS, HEAD_DIM)[ + : rows * physical_columns + ].view(rows, physical_columns, N_KV_HEADS, HEAD_DIM) + live_value = value.reshape(-1, N_KV_HEADS, HEAD_DIM)[ + : rows * physical_columns + ].view_as(live_key) + live_key.normal_() + live_value.normal_() + info = torch.tensor( + [ + [0, 1, 2, rows, physical_columns], + [1, 1, 0, 768, physical_columns], + [0, 0, 0, 0, physical_columns], + ], + dtype=torch.int32, + device="cuda", + ) + self.assertGreater(_num_splits(query.shape[2], rows), 1) + actual = sdpa_varlen(query, key, value, info, SCALE, rows_available=rows) + expected = torch.zeros_like(query) + for token, column, length in ((0, 2, rows), (1, 0, 768)): + k = ( + live_key[:length, column] + .transpose(0, 1) + .repeat_interleave(N_Q_HEADS // N_KV_HEADS, dim=0) + .float() + ) + v = ( + live_value[:length, column] + .transpose(0, 1) + .repeat_interleave(N_Q_HEADS // N_KV_HEADS, dim=0) + .float() + ) + scores = (query[0, :, token, None].float() * k).sum(-1) * SCALE + expected[0, :, token] = ( + (scores.softmax(-1)[..., None] * v).sum(1).to(expected.dtype) + ) + self.assertLess(_max_abs_diff(actual, expected), 2e-2) + + @unittest.skipUnless(torch.cuda.is_available(), "CUDA required") class LowerBatchedSequencePassTest(unittest.TestCase): CAPACITY = 32 @@ -322,6 +476,43 @@ def test_manifest_is_validated(self) -> None: with self.assertRaises(ValueError): parse_offgraph_kv_manifest(self.manifest(**bad)) + def test_runtime_pitch_manifest_and_side_buffer(self) -> None: + manifest = self.manifest(runtime_columns=True) + parsed = parse_offgraph_kv_manifest(manifest) + self.assertTrue(parsed["runtime_columns"]) + lowered = self._lowered(manifest) + buffers = { + n.name: tuple(n.meta["val"].shape) + for n in lowered.graph_module.graph.nodes + if n.op == "placeholder" and n.name.startswith(OFFGRAPH_KV_FQN_PREFIX) + } + self.assertEqual(buffers[OFFGRAPH_KV_SEQ_INFO_FQN], (self.MAX_SEGMENTS, 5)) + self.assertEqual( + buffers[f"{OFFGRAPH_KV_FQN_PREFIX}layer_0_k"], + (1, self.CAPACITY * (self.MAX_SEQS + 1), N_KV_HEADS, HEAD_DIM), + ) + for runtime_columns in (False, True): + with self.subTest(runtime_columns=runtime_columns): + metadata = offgraph_kv_constant_methods( + self.manifest(runtime_columns=runtime_columns) + ) + self.assertEqual( + metadata[OFFGRAPH_KV_SEQUENCE_INFO_ABI_METHOD], + 2 if runtime_columns else 1, + ) + with self.assertRaises(ValueError): + parse_offgraph_kv_manifest( + self.manifest(version=2, runtime_columns=runtime_columns) + ) + with self.assertRaisesRegex(ValueError, "do not support context_window"): + parse_offgraph_kv_manifest( + self.manifest(runtime_columns=True, causal=False, context_window=True) + ) + with self.assertRaises(ValueError): + parse_offgraph_kv_manifest( + self.manifest(layout="sequence", runtime_columns=True) + ) + def test_declares_column_storage_and_step_buffers(self) -> None: lowered = self._lowered() graph = lowered.graph_module.graph @@ -352,20 +543,39 @@ def test_declares_column_storage_and_step_buffers(self) -> None: ] self.assertEqual(len(calls), 2) - def test_lowered_program_matches_the_neutral_op(self) -> None: + def _check_lowered_program(self, runtime_columns: bool) -> None: torch.manual_seed(21) - lowered = self._lowered() + declared_seqs = self.MAX_SEQS + 2 if runtime_columns else self.MAX_SEQS + segments = 2 * declared_seqs + pitch = self.MAX_SEQS + 1 + manifest = self.manifest( + runtime_columns=runtime_columns, + max_seqs=declared_seqs, + max_segments=segments, + ) + metadata = offgraph_kv_constant_methods(manifest) + self.assertEqual( + metadata[OFFGRAPH_KV_SEQUENCE_INFO_ABI_METHOD], 2 if runtime_columns else 1 + ) + self.assertEqual(metadata["get_offgraph_kv_max_seqs"], declared_seqs) + lowered = self._lowered(manifest) runtime = {} for name, value in list(lowered.constants.items()): if name.startswith(OFFGRAPH_KV_FQN_PREFIX): runtime[name] = torch.zeros( value.shape, device="cuda", dtype=value.dtype ) + if runtime_columns and name not in ( + OFFGRAPH_KV_SEQ_COLS_FQN, + OFFGRAPH_KV_SEQ_INFO_FQN, + ): + rows = value.shape[1] // (declared_seqs + 1) + runtime[name][:, rows * pitch :].fill_(float("nan")) lowered.constants[name] = runtime[name] module = lowered.module() oracle = _Oracle(4 * self.CAPACITY, (0, self.WINDOW)) self.addCleanup(oracle.close) - columns = {seq: seq for seq in range(self.MAX_SEQS)} + columns = {seq: self.MAX_SEQS - 1 - seq for seq in range(self.MAX_SEQS)} for groups in _STEPS: seq_ids, q, k, v, position = _batch(groups) flat, ring = oracle.step(seq_ids, q, k, v, position) @@ -374,13 +584,32 @@ def test_lowered_program_matches_the_neutral_op(self) -> None: position, columns, self.MAX_WRITE, - self.MAX_SEGMENTS, - self.MAX_SEQS, + segments, + pitch - 1, ) + if runtime_columns: + seq_info = torch.cat( + [ + seq_info, + seq_info.new_full((segments, 1), pitch), + ], + dim=1, + ) runtime[OFFGRAPH_KV_SEQ_COLS_FQN].copy_(seq_cols) runtime[OFFGRAPH_KV_SEQ_INFO_FQN].copy_(seq_info) out = module(q, k, v, position.reshape(-1, 1)) self.assertLess(_max_abs_diff(out, flat + ring), 3e-2) + if runtime_columns: + for name, value in runtime.items(): + if name not in (OFFGRAPH_KV_SEQ_COLS_FQN, OFFGRAPH_KV_SEQ_INFO_FQN): + rows = value.shape[1] // (declared_seqs + 1) + self.assertTrue(torch.isnan(value[:, rows * pitch :]).all()) + + def test_lowered_program_matches_the_neutral_op(self) -> None: + self._check_lowered_program(False) + + def test_lowered_runtime_pitch_matches_the_neutral_op(self) -> None: + self._check_lowered_program(True) def test_non_causal_context_window_reaches_sdpa_varlen(self) -> None: lowered = self._lowered( diff --git a/backends/cuda/tests/test_private_kv_manifest.py b/backends/cuda/tests/test_private_kv_manifest.py new file mode 100644 index 00000000000..f0d3262b99e --- /dev/null +++ b/backends/cuda/tests/test_private_kv_manifest.py @@ -0,0 +1,93 @@ +# 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 unittest + +from executorch.backends.cuda.passes.lower_offgraph_kv import ( + offgraph_kv_constant_methods, + OFFGRAPH_KV_SEQUENCE_INFO_ABI_METHOD, + parse_offgraph_kv_manifest, +) + + +class PrivateKVManifestTest(unittest.TestCase): + @staticmethod + def manifest(**overrides): + fields = { + "version": 1, + "layout": "batched-sequence", + "maximum_capacity": 131072, + "max_write": 4096, + "max_seqs": 64, + "max_segments": 128, + "layers": [ + {"layer_id": 0, "policy": "flat"}, + {"layer_id": 1, "policy": "ring", "window": 512}, + ], + } + fields.update(overrides) + return json.dumps(fields).encode() + + def test_absent_option_preserves_abi_one(self): + parsed = parse_offgraph_kv_manifest(self.manifest()) + self.assertFalse(parsed["private_rows"]) + methods = offgraph_kv_constant_methods(self.manifest()) + self.assertEqual(methods[OFFGRAPH_KV_SEQUENCE_INFO_ABI_METHOD], 1) + + def test_existing_runtime_pitch_preserves_abi_two(self): + methods = offgraph_kv_constant_methods(self.manifest(runtime_columns=True)) + self.assertEqual(methods[OFFGRAPH_KV_SEQUENCE_INFO_ABI_METHOD], 2) + + def test_private_rows_select_abi_three_without_runtime_pitch(self): + value = self.manifest(private_rows=True) + parsed = parse_offgraph_kv_manifest(value) + self.assertTrue(parsed["private_rows"]) + self.assertFalse(parsed["runtime_columns"]) + methods = offgraph_kv_constant_methods(value) + self.assertEqual(methods[OFFGRAPH_KV_SEQUENCE_INFO_ABI_METHOD], 3) + self.assertEqual(methods["get_offgraph_kv_max_seqs"], 64) + + def test_rejects_mixed_addressing_abis(self): + with self.assertRaisesRegex(ValueError, "without ABI 2"): + parse_offgraph_kv_manifest( + self.manifest(private_rows=True, runtime_columns=True) + ) + + def test_rejects_other_layouts(self): + for layout in ("sequence", "cell"): + with self.subTest(layout=layout), self.assertRaisesRegex( + ValueError, "batched-sequence" + ): + parse_offgraph_kv_manifest( + self.manifest(private_rows=True, layout=layout) + ) + + def test_rejects_draft_attention(self): + for overrides in ({"causal": False}, {"causal": False, "context_window": True}): + with self.subTest(overrides=overrides), self.assertRaisesRegex( + ValueError, "draft or non-causal" + ): + parse_offgraph_kv_manifest( + self.manifest(private_rows=True, **overrides) + ) + + def test_rejects_non_bool_option(self): + for flag in (0, 1, "true", None): + with self.subTest(flag=flag), self.assertRaisesRegex( + ValueError, "private_rows must be a bool" + ): + parse_offgraph_kv_manifest(self.manifest(private_rows=flag)) + + def test_rejects_inconsistent_segment_capacity(self): + with self.assertRaisesRegex(ValueError, "max_segments must equal"): + parse_offgraph_kv_manifest( + self.manifest(private_rows=True, max_segments=64) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/backends/cuda/tests/test_runtime_owned_kv.py b/backends/cuda/tests/test_runtime_owned_kv.py new file mode 100644 index 00000000000..7eecedd5845 --- /dev/null +++ b/backends/cuda/tests/test_runtime_owned_kv.py @@ -0,0 +1,390 @@ +# 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 ast +import contextlib +import sys +import threading +import types +import unittest +from pathlib import Path +from unittest import mock + +import torch +from executorch.backends.cuda.runtime_owned_kv import RuntimeOwnedKVCompileBuffers + + +PREFIX = "__et_offgraph_kv_" + + +def program(**buffers): + return types.SimpleNamespace(state_dict={}, constants=buffers) + + +def empty_view(shape, stride=None, offset=0): + if stride is None: + value = torch.empty(shape, dtype=torch.bfloat16) + else: + required = offset + 1 + sum((n - 1) * s for n, s in zip(shape, stride)) + value = torch.as_strided( + torch.empty(required, dtype=torch.bfloat16), shape, stride, offset + ) + value.untyped_storage().resize_(0) + return value + + +class RuntimeOwnedKVCompileBuffersTest(unittest.TestCase): + def test_production_view_clones_without_materializing_cpu_zeros(self): + source = empty_view((1, 131072 * 65, 2, 128)) + buffers = RuntimeOwnedKVCompileBuffers( + program(**{PREFIX + "layer_0_k": source}), PREFIX + ) + with mock.patch.object(torch, "zeros", side_effect=AssertionError("zeros")): + clone = buffers.cpu_placeholder(source) + self.assertEqual(clone.shape, source.shape) + self.assertEqual(clone.stride(), source.stride()) + self.assertEqual(clone.dtype, source.dtype) + self.assertEqual(clone.device.type, "cpu") + self.assertEqual(clone.untyped_storage().nbytes(), 0) + self.assertTrue(buffers.owns_empty(clone)) + + def test_placeholder_preserves_offset_and_noncontiguous_strides(self): + source = empty_view((2, 3), (9, 2), 4) + buffers = RuntimeOwnedKVCompileBuffers( + program(**{PREFIX + "layer_0_k": source}), PREFIX + ) + clone = buffers.cpu_placeholder(source) + self.assertEqual(clone.storage_offset(), 4) + self.assertEqual(clone.stride(), (9, 2)) + self.assertEqual(clone.shape, (2, 3)) + self.assertEqual(clone.untyped_storage().nbytes(), 0) + + def test_same_shape_graph_owned_cache_is_not_runtime_owned(self): + owned, graph_owned = empty_view((2, 3)), empty_view((2, 3)) + self.assertEqual(owned.data_ptr(), graph_owned.data_ptr()) + buffers = RuntimeOwnedKVCompileBuffers( + program(**{PREFIX + "layer_0_k": owned, "kv_cache.k": graph_owned}), + PREFIX, + ) + self.assertTrue(buffers.owns_empty(owned)) + self.assertFalse(buffers.owns_empty(graph_owned)) + with self.assertRaises(ValueError): + buffers.cpu_placeholder(graph_owned) + + def test_graph_owned_alias_excludes_shared_storage(self): + owned = empty_view((2, 3)) + buffers = RuntimeOwnedKVCompileBuffers( + program(**{PREFIX + "layer_0_k": owned, "kv_cache.alias": owned}), + PREFIX, + ) + self.assertFalse(buffers.owns_empty(owned)) + + def test_real_runtime_metadata_preserves_nonzero_payload(self): + value = torch.tensor([4, 9], dtype=torch.int32) + buffers = RuntimeOwnedKVCompileBuffers( + program(**{PREFIX + "owner_step": value}), PREFIX + ) + self.assertFalse(buffers.owns_empty(value)) + torch.testing.assert_close(value, torch.tensor([4, 9], dtype=torch.int32)) + + def test_program_identity_and_placeholder_lifetime_do_not_leak(self): + value = empty_view((2, 3)) + first = RuntimeOwnedKVCompileBuffers( + program(**{PREFIX + "layer_0_k": value}), PREFIX + ) + clone = first.cpu_placeholder(value) + second = RuntimeOwnedKVCompileBuffers(program(), PREFIX) + self.assertFalse(second.owns_empty(value)) + self.assertFalse(second.owns_empty(clone)) + + +class ConstantInfoCodegenTest(unittest.TestCase): + @staticmethod + @contextlib.contextmanager + def lowered_constants(tensors): + from torch._inductor import config + from torch._inductor.graph import GraphLowering + from torch._inductor.virtualized import V + + graph = torch.fx.Graph() + graph.output(()) + module = torch.fx.GraphModule({}, graph) + with config.patch({"cpp_wrapper": True}): + lowering = GraphLowering( + module, (), cpp_wrapper=True, aot_mode=True, is_inference=True + ) + with V.set_graph_handler(lowering): + lowering.run() + lowering.constants = { + f"constant_{index}": value for index, value in enumerate(tensors) + } + lowering.allocated_constant_name = { + name: PREFIX + name for name in lowering.constants + } + yield lowering + + def test_real_inductor_constructor_preserves_extent_without_payload(self): + from torch._inductor.codegen.cpp_wrapper_cpu import CppWrapperCpu + + owned = empty_view((1, 131072 * 65, 2, 128)) + graph_owned = empty_view((2, 3)) + payload = torch.tensor([4, 9], dtype=torch.int32) + buffers = RuntimeOwnedKVCompileBuffers( + program(**{PREFIX + "layer_0_k": owned, "graph": graph_owned}), PREFIX + ) + for alignment in (1, 64): + with self.subTest(alignment=alignment), self.lowered_constants( + [owned, graph_owned, payload] + ): + original = CppWrapperCpu() + original.codegen_model_constructor() + self.assertIn( + "constants_info_[0].data_size = 0;", original.prefix.getvalue() + ) + wrapper = CppWrapperCpu() + prefix = wrapper.prefix + with mock.patch.object( + torch, "zeros", side_effect=AssertionError("zeros") + ): + with buffers.constant_info_sizes( + wrapper, [owned, graph_owned, payload], alignment + ): + wrapper.codegen_model_constructor() + self.assertIs(wrapper.prefix, prefix) + expected = owned.numel() * owned.element_size() + generated = wrapper.prefix.getvalue() + self.assertIn(f"constants_info_[0].data_size = {expected};", generated) + self.assertIn("constants_info_[1].data_size = 0;", generated) + self.assertIn("constants_info_[2].data_size = 64;", generated) + self.assertIn( + "constants_info_[0].shape = {1, 8519680, 2, 128};", generated + ) + self.assertEqual(owned.untyped_storage().nbytes(), 0) + torch.testing.assert_close( + payload, torch.tensor([4, 9], dtype=torch.int32) + ) + + def test_real_constructor_preserves_noncontiguous_extent_and_offset(self): + from torch._inductor.codegen.cpp_wrapper_cpu import CppWrapperCpu + + value = empty_view((2, 3), (9, 2), 4) + buffers = RuntimeOwnedKVCompileBuffers( + program(**{PREFIX + "layer_0_k": value}), PREFIX + ) + for alignment, expected in ((1, 36), (64, 64)): + with self.subTest(alignment=alignment), self.lowered_constants([value]): + wrapper = CppWrapperCpu() + with buffers.constant_info_sizes(wrapper, [value], alignment): + wrapper.codegen_model_constructor() + generated = wrapper.prefix.getvalue() + self.assertIn(f"constants_info_[0].data_size = {expected};", generated) + self.assertIn("constants_info_[0].offset = 4;", generated) + self.assertIn("constants_info_[0].stride = {9, 2};", generated) + self.assertEqual(value.untyped_storage().nbytes(), 0) + + def test_constant_sizes_preserve_prefix_and_reject_changed_emission(self): + from torch._inductor.utils import IndentedBuffer + + value = empty_view((2, 3)) + buffers = RuntimeOwnedKVCompileBuffers( + program(**{PREFIX + "layer_0_k": value}), PREFIX + ) + for emitted in (None, "constants_info_[0].data_size = 17;"): + wrapper = types.SimpleNamespace(prefix=IndentedBuffer()) + original = wrapper.prefix + with self.subTest(emitted=emitted), self.assertRaises(RuntimeError): + with buffers.constant_info_sizes(wrapper, [value], 64): + if emitted is not None: + wrapper.prefix.writeline(emitted) + self.assertIs(wrapper.prefix, original) + wrapper = types.SimpleNamespace(prefix=IndentedBuffer()) + original = wrapper.prefix + with self.assertRaisesRegex(RuntimeError, "original failure"): + with buffers.constant_info_sizes(wrapper, [value], 64): + raise RuntimeError("original failure") + self.assertIs(wrapper.prefix, original) + + @unittest.skipUnless(torch.cuda.is_available(), "Actual CUDA compile context") + def test_actual_backend_context_installs_codegen_hook_and_restores_nested(self): + from executorch.backends.cuda.cuda_backend import _CPU_CLONE_GUARD, CudaBackend + from executorch.exir.backend.compile_spec_schema import CompileSpec + from torch._inductor.codegen.cpp_wrapper_cpu import CppWrapperCpu + + value = empty_view((2, 3)) + lowered = program(**{PREFIX + "layer_0_k": value}) + original = CppWrapperCpu.codegen_model_constructor + previous = getattr(_CPU_CLONE_GUARD, "runtime_owned_kv", None) + specs = [CompileSpec("low_memory_mode", b"ON")] + with self.lowered_constants([value]): + with CudaBackend.get_aoti_program_compile_context_manager(lowered, specs): + with CudaBackend.get_aoti_program_compile_context_manager( + lowered, specs + ): + wrapper = CppWrapperCpu() + wrapper.codegen_model_constructor() + self.assertIn( + "constants_info_[0].data_size = 64;", wrapper.prefix.getvalue() + ) + self.assertTrue(_CPU_CLONE_GUARD.runtime_owned_kv.owns_empty(value)) + self.assertIs(CppWrapperCpu.codegen_model_constructor, original) + self.assertIs(_CPU_CLONE_GUARD.runtime_owned_kv, previous) + wrapper = CppWrapperCpu() + wrapper.codegen_model_constructor() + self.assertIn( + "constants_info_[0].data_size = 0;", wrapper.prefix.getvalue() + ) + + +class ProgramCompileContextTest(unittest.TestCase): + @staticmethod + def method(path, class_name, name, namespace): + tree = ast.parse(path.read_text()) + cls = next( + n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == class_name + ) + method = next( + n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == name + ) + method.decorator_list = [] + exec( + compile(ast.Module(body=[method], type_ignores=[]), str(path), "exec"), + namespace, + ) + return namespace[name] + + def test_existing_compile_spec_hook_is_still_called(self): + root = Path(__file__).parents[2] + method = self.method( + root / "aoti/aoti_backend.py", + "AotiBackend", + "get_aoti_program_compile_context_manager", + {}, + ) + seen = [] + + class ExistingSubclass: + @classmethod + def get_extra_aoti_compile_context_manager(cls, specs): + seen.append(specs) + return contextlib.nullcontext("existing") + + specs = object() + with method(ExistingSubclass, object(), specs) as result: + self.assertEqual(result, "existing") + self.assertEqual(seen, [specs]) + + def test_cuda_scope_uses_final_program_and_restores_after_exception(self): + root = Path(__file__).parents[2] + guard = threading.local() + namespace = { + "_CPU_CLONE_GUARD": guard, + "RuntimeOwnedKVCompileBuffers": RuntimeOwnedKVCompileBuffers, + "OFFGRAPH_KV_FQN_PREFIX": PREFIX, + } + method = contextlib.contextmanager( + self.method( + root / "cuda/cuda_backend.py", + "CudaBackend", + "get_aoti_program_compile_context_manager", + namespace, + ) + ) + value = empty_view((2, 3)) + lowered = program(**{PREFIX + "layer_0_k": value}) + sentinel = object() + guard.runtime_owned_kv = sentinel + + class ExistingContext: + @classmethod + def get_extra_aoti_compile_context_manager(cls, specs): + return contextlib.nullcontext() + + with self.assertRaisesRegex(RuntimeError, "abort"): + with method(ExistingContext, lowered, []): + self.assertTrue(guard.runtime_owned_kv.owns_empty(value)) + with method(ExistingContext, program(), []): + self.assertFalse(guard.runtime_owned_kv.owns_empty(value)) + self.assertTrue(guard.runtime_owned_kv.owns_empty(value)) + raise RuntimeError("abort") + self.assertIs(guard.runtime_owned_kv, sentinel) + + def test_actual_cpu_clone_and_serialization_hooks_keep_owned_views_empty(self): + source = Path(__file__).parents[1] / "cuda_backend.py" + tree = ast.parse(source.read_text()) + context = next( + node + for node in tree.body + if isinstance(node, ast.FunctionDef) + and node.name == "_compile_time_cpu_clones" + ) + names = { + "_full_zeros_preserving_strides", + "_is_emptied", + "_cpu_clone_preserve_strides", + "_get_const_synthesize_zeros", + } + functions = [ + node + for node in (*tree.body, *context.body) + if isinstance(node, ast.FunctionDef) and node.name in names + ] + self.assertEqual(len(functions), len(names)) + guard = threading.local() + namespace = { + "torch": torch, + "sys": sys, + "_CPU_CLONE_GUARD": guard, + "orig_clone": lambda tensor: tensor.clone(), + "orig_get_const": lambda module, name: module[name], + } + exec( + compile(ast.Module(body=functions, type_ignores=[]), str(source), "exec"), + namespace, + ) + owned, graph_owned = empty_view((2, 3)), empty_view((2, 3)) + guard.runtime_owned_kv = RuntimeOwnedKVCompileBuffers( + program(**{PREFIX + "layer_0_k": owned, "kv_cache.k": graph_owned}), + PREFIX, + ) + + def _unlift_graph(tensor): + return namespace["_cpu_clone_preserve_strides"](tensor) + + clone = _unlift_graph(owned) + self.assertEqual(clone.untyped_storage().nbytes(), 0) + self.assertIs( + namespace["_get_const_synthesize_zeros"]({"k": clone}, "k"), clone + ) + graph_clone = _unlift_graph(graph_owned) + torch.testing.assert_close( + graph_clone, torch.zeros((2, 3), dtype=torch.bfloat16) + ) + graph_constant = namespace["_get_const_synthesize_zeros"]( + {"k": graph_owned}, "k" + ) + torch.testing.assert_close(graph_constant, graph_clone) + payload = torch.tensor([4, 9], dtype=torch.int32) + torch.testing.assert_close(_unlift_graph(payload), payload) + + def test_preprocess_passes_final_program_to_context_hook(self): + source = Path(__file__).parents[2] / "aoti/aoti_backend.py" + tree = ast.parse(source.read_text()) + calls = [ + node + for node in ast.walk(tree) + if isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr == "get_aoti_program_compile_context_manager" + ] + self.assertEqual(len(calls), 1) + self.assertEqual( + [ast.unparse(arg) for arg in calls[0].args], + ["device_edge_program", "compile_specs"], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/backends/cuda/tests/test_sdpa_varlen_private.py b/backends/cuda/tests/test_sdpa_varlen_private.py new file mode 100644 index 00000000000..46ebfe7cfc5 --- /dev/null +++ b/backends/cuda/tests/test_sdpa_varlen_private.py @@ -0,0 +1,258 @@ +# 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 collections +import unittest +from unittest import mock + +import torch + +from executorch.backends.cuda.passes.lower_offgraph_kv import ( + _private_batched_sequence_step_fn, +) +from executorch.backends.cuda.triton.kernels.sdpa_varlen import _num_stages, sdpa_varlen +from triton.compiler import compiler as triton_compiler + + +class VarlenLaunchPolicyTest(unittest.TestCase): + def test_device_optin_limit_selects_pipeline(self): + # All are BF16 launches. A100 keeps the prior pipeline; A10G/5090 + # fit D=256 without shrinking attention tiles or changing split-K. + for limit in (101376, 166912, 232448): + with self.subTest(shared_memory_limit=limit), mock.patch.object( + triton_compiler, + "max_shared_mem", + return_value=limit, + ) as properties: + for dim in (16, 32, 64, 128, 256): + for requested in (2, 3): + selected = _num_stages(dim, requested, 0) + expected = 1 if dim == 256 and limit < 160 * 1024 else requested + self.assertEqual(selected, expected) + self.assertEqual(properties.call_count, 2) + + def test_device_limits_are_selected_separately(self): + with mock.patch.object( + triton_compiler, + "max_shared_mem", + side_effect=lambda device_index: (101376, 166912)[device_index], + ) as query: + self.assertEqual(_num_stages(256, 2, 0), 1) + self.assertEqual(_num_stages(256, 2, 1), 2) + self.assertEqual(_num_stages(256, 2, 0), 1) + self.assertEqual(_num_stages(256, 2, 1), 2) + self.assertEqual(query.call_count, 4) + + def test_export_target_budget_is_not_stale_on_same_device(self): + # target_smem_context changes Triton's effective limit when an export + # targets a GPU with less shared memory than its host. + with mock.patch.object( + triton_compiler, + "max_shared_mem", + side_effect=(166912, 101376, 166912), + ): + self.assertEqual(_num_stages(256, 2, 0), 2) + self.assertEqual(_num_stages(256, 2, 0), 1) + self.assertEqual(_num_stages(256, 2, 0), 2) + + +def _case( + owners, previous, window, heads=2, dim=128, groups=4, padding=0, restored=False +): + """Same logical K/V in legacy columns and packed private spans. + + Torch owns full declared storage here; NaNs mark every byte outside the + runtime's private spans. Native pool tests verify the actual smaller CUDA + allocations, which cannot be expressed by a bounds-checked Torch view. + """ + torch.manual_seed(917) + columns, max_write, context = 65, 1024, 2048 + width = len(owners) + padding + counts = collections.Counter(owners) + ends = {owner: previous.get(owner, 0) + count for owner, count in counts.items()} + rows = min(context, window + max_write - 1) if window else context + shape = (rows, columns, heads, dim) + legacy_k = torch.zeros(shape, dtype=torch.bfloat16, device="cuda") + legacy_v = torch.zeros_like(legacy_k) + private_k = torch.full_like(legacy_k, float("nan")) + private_v = torch.full_like(legacy_v, float("nan")) + layouts = torch.zeros((columns, 2), dtype=torch.int32, device="cuda") + steps = torch.zeros((columns, 3), dtype=torch.int32, device="cuda") + seq_cols = torch.full((max_write,), columns - 1, dtype=torch.int64, device="cuda") + permutation = torch.arange(max_write, dtype=torch.int64, device="cuda") + seq_info = torch.zeros((2 * (columns - 1), 4), dtype=torch.int32, device="cuda") + k_step = torch.zeros((1, heads, width, dim), dtype=torch.bfloat16, device="cuda") + v_step = torch.zeros_like(k_step) + k_stage = torch.empty( + (1, max_write, heads, dim), dtype=torch.bfloat16, device="cuda" + ) + v_stage = torch.empty_like(k_stage) + q = torch.randn( + (1, heads * groups, width, dim), dtype=torch.bfloat16, device="cuda" + ) + position = torch.zeros(width, dtype=torch.int64, device="cuda") + payload, spans = {}, {} + base = stage_start = 0 + for owner, end in sorted(ends.items()): + capacity = min(window, end) if window else end + spans[owner] = (base, capacity) + layouts[owner] = torch.tensor( + [base, capacity], dtype=torch.int32, device="cuda" + ) + start = previous.get(owner, 0) + steps[owner] = torch.tensor( + [stage_start, start, counts[owner]], dtype=torch.int32, device="cuda" + ) + payload[owner] = [ + torch.randn((end, heads, dim), dtype=torch.bfloat16, device="cuda") + for _ in range(2) + ] + for values, legacy, private in zip( + payload[owner], (legacy_k, legacy_v), (private_k, private_v) + ): + positions = torch.arange(max(0, end - rows), end, device="cuda") + legacy[positions % rows, owner] = values[positions] + retained = min(capacity, window - 1) if restored and window else capacity + old = torch.arange(max(0, start - retained), start, device="cuda") + physical = old % capacity if window else old + private.reshape(-1, heads, dim)[base + physical] = values[old] + base += capacity + stage_start += counts[owner] + layouts[-1] = torch.tensor([base, 1], dtype=torch.int32, device="cuda") + cursor = dict(previous) + stage_cursor = {owner: int(steps[owner, 0]) for owner in ends} + segments = [] + for token, owner in enumerate(owners): + absolute = cursor.get(owner, 0) + seq_cols[token], position[token] = owner, absolute + permutation[token] = stage_cursor[owner] + k_step[0, :, token] = payload[owner][0][absolute] + v_step[0, :, token] = payload[owner][1][absolute] + if not segments or segments[-1][2] != owner: + segments.append([token, 0, owner, absolute]) + segments[-1][1] += 1 + segments[-1][3] += 1 + cursor[owner] = absolute + 1 + stage_cursor[owner] += 1 + assert len(segments) <= seq_info.shape[0] + seq_info[: len(segments)] = torch.tensor(segments, dtype=torch.int32, device="cuda") + scale = dim**-0.5 + expected = sdpa_varlen( + q, + legacy_k, + legacy_v, + seq_info, + scale, + window=window, + ring=rows if window else 0, + ) + fn = _private_batched_sequence_step_fn( + scale, rows, columns, window, bool(window), None + ) + args = ( + q, + k_step, + v_step, + position, + private_k.reshape(1, -1, heads, dim), + private_v.reshape(1, -1, heads, dim), + seq_cols, + seq_info, + layouts, + steps, + permutation, + k_stage, + v_stage, + ) + return fn, args, expected, payload, spans, ends, base + 1 + + +@unittest.skipUnless(torch.cuda.is_available(), "CUDA required") +class PrivateVarlenTest(unittest.TestCase): + def check_case(self, owners, previous, window, **kwargs): + fn, args, expected, payload, spans, ends, allocated = _case( + owners, previous, window, **kwargs + ) + actual = fn(*args) + # Preserve the old key sweep and reduction configuration exactly. + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + for owner, end in ends.items(): + base, capacity = spans[owner] + positions = torch.arange(max(0, end - capacity), end, device="cuda") + physical = positions % capacity if window else positions + for values, storage in zip(payload[owner], args[4:6]): + rows = storage.reshape(-1, storage.shape[-2], storage.shape[-1]) + torch.testing.assert_close( + rows[base + physical], values[positions], rtol=0, atol=0 + ) + self.assertTrue(torch.isnan(rows[allocated:]).all()) + + def test_static_decode_and_prefill(self): + for window in (0, 31, 257): + for width in (1, 2, 4, 8, 16, 32, 64, 128, 512): + with self.subTest(window=window, width=width): + self.check_case([0] * width, {0: 1024}, window) + + def test_restored_ring_does_not_read_unwritten_nan_slot(self): + # All slots except the restored W-1 rows remain NaN. Exercise both + # decode split-K and regular prefill, including the W=1 boundary. + for window in (1, 31, 257): + for dim in (128, 256): + for width in (1, 4, 8, 64): + with self.subTest(window=window, dim=dim, width=width): + self.check_case( + [0] * width, + {0: 1024}, + window, + dim=dim, + restored=True, + ) + + def test_heterogeneous_interleaved_owners_and_padding(self): + owners = [0, 1, 0, 2, 1, 2] * 12 + for window in (0, 31): + with self.subTest(window=window): + self.check_case(owners, {0: 109, 1: 7, 2: 41}, window, padding=8) + + def test_sixty_four_decode_owners(self): + for window in (0, 31): + self.check_case( + list(range(64)), {owner: owner * 3 + 1 for owner in range(64)}, window + ) + + def test_muse_glimmer_and_gemma_head_geometry(self): + for dim, heads, groups in ((128, 2, 4), (256, 1, 2)): + for prefill in (64, 512): + owners = list(range(8)) + [8] * prefill + previous = {owner: 1024 for owner in range(9)} + with self.subTest(dim=dim, prefill=prefill): + self.check_case( + owners, previous, 127, heads=heads, dim=dim, groups=groups + ) + + def test_compiled_ring_mutation_order(self): + fn, args, expected, payload, spans, ends, _ = _case( + list(range(8)) + [8] * 64, {owner: 1024 for owner in range(9)}, 31 + ) + compiled = torch.compile(fn, fullgraph=True) + actual = compiled(*args) + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + for owner, end in ends.items(): + base, capacity = spans[owner] + positions = torch.arange(end - capacity, end, device="cuda") + for values, storage in zip(payload[owner], args[4:6]): + torch.testing.assert_close( + storage.reshape(-1, storage.shape[-2], storage.shape[-1])[ + base + positions % capacity + ], + values[positions], + rtol=0, + atol=0, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/backends/cuda/triton/kernels/private_kv_write.py b/backends/cuda/triton/kernels/private_kv_write.py new file mode 100644 index 00000000000..e8eddcef420 --- /dev/null +++ b/backends/cuda/triton/kernels/private_kv_write.py @@ -0,0 +1,257 @@ +# 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. + +"""Scatter packed step K/V to independent owner spans without ring races.""" + +import torch +import triton +import triton.language as tl +from torch.library import triton_op, wrap_triton + + +@triton.jit +def _private_kv_stage_kernel( + K_ptr, + V_ptr, + Rows_ptr, + K_stage_ptr, + V_stage_ptr, + T, + H, + D, + stride_kh, + stride_kt, + stride_vh, + stride_vt, + BLOCK: tl.constexpr, +): + lanes = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK) + token = lanes // (H * D) + head = (lanes // D) % H + dim = lanes % D + valid = token < T + row = tl.load(Rows_ptr + token, mask=valid, other=0) + k = tl.load( + K_ptr + head * stride_kh + token * stride_kt + dim, mask=valid, other=0.0 + ) + v = tl.load( + V_ptr + head * stride_vh + token * stride_vt + dim, mask=valid, other=0.0 + ) + dst = row * H * D + head * D + dim + tl.store(K_stage_ptr + dst, k, mask=valid) + tl.store(V_stage_ptr + dst, v, mask=valid) + + +@triton_op("triton::private_kv_stage", mutates_args={"key_stage", "value_stage"}) +def private_kv_stage( + key: torch.Tensor, + value: torch.Tensor, + stage_rows: torch.Tensor, + key_stage: torch.Tensor, + value_stage: torch.Tensor, +) -> None: + """One launch copies both K/V planes into the runtime's unique step slots.""" + if key.dim() != 4 or key.shape[0] != 1 or value.shape != key.shape: + raise ValueError("private staging requires matching BHSD K/V") + _, heads, tokens, dim = key.shape + if ( + key.dtype != torch.bfloat16 + or value.dtype != key.dtype + or key.stride(-1) != 1 + or value.stride(-1) != 1 + or key_stage.dim() != 4 + or key_stage.shape[0] != 1 + or key_stage.shape[1] < tokens + or key_stage.shape[2:] != (heads, dim) + or value_stage.shape != key_stage.shape + or key_stage.dtype != key.dtype + or value_stage.dtype != key.dtype + or not key_stage.is_contiguous() + or not value_stage.is_contiguous() + or stage_rows.dim() != 1 + or stage_rows.shape[0] < tokens + or stage_rows.dtype != torch.int64 + or not stage_rows.is_contiguous() + ): + raise ValueError("invalid private staging tensors") + if key.device.type != "cuda" or any( + t.device != key.device for t in (value, stage_rows, key_stage, value_stage) + ): + raise ValueError("private staging tensors must share a CUDA device") + wrap_triton(_private_kv_stage_kernel)[(triton.cdiv(tokens * heads * dim, 256),)]( + key, + value, + stage_rows, + key_stage, + value_stage, + tokens, + heads, + dim, + key.stride(1), + key.stride(2), + value.stride(1), + value.stride(2), + BLOCK=256, + ) + + +@private_kv_stage.register_fake +def _private_kv_stage_fake(key, value, stage_rows, key_stage, value_stage): + return None + + +@triton.jit +def _private_kv_write_kernel( + K_ptr, + V_ptr, + Position_ptr, + Cols_ptr, + Layout_ptr, + Step_ptr, + K_cache_ptr, + V_cache_ptr, + T, + H, + D, + stride_kh, + stride_kt, + stride_vh, + stride_vt, + OWNERS: tl.constexpr, + RING: tl.constexpr, + BLOCK: tl.constexpr, +): + lanes = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK) + token = lanes // (H * D) + head = (lanes // D) % H + dim = lanes % D + in_step = token < T + col = tl.load(Cols_ptr + token, mask=in_step, other=OWNERS) + pos = tl.load(Position_ptr + token, mask=in_step, other=0) + base = tl.load(Layout_ptr + col * 2).to(tl.int64) + capacity = tl.load(Layout_ptr + col * 2 + 1) + valid = in_step & (col < OWNERS) & (capacity > 0) & (pos >= 0) + start = tl.load(Step_ptr + col * 3 + 1) + end = start + tl.load(Step_ptr + col * 3 + 2) + valid &= (pos >= start) & (pos < end) + if RING: + # A chunk can wrap repeatedly. Only its newest write to each slot + # survives, so no two programs race for the same K/V element. + valid &= pos >= end - capacity + row = pos % tl.maximum(capacity, 1) + else: + valid &= pos < capacity + row = pos + k = tl.load( + K_ptr + head * stride_kh + token * stride_kt + dim, mask=valid, other=0.0 + ) + v = tl.load( + V_ptr + head * stride_vh + token * stride_vt + dim, mask=valid, other=0.0 + ) + dst = (base + row) * H * D + head * D + dim + tl.store(K_cache_ptr + dst, k, mask=valid) + tl.store(V_cache_ptr + dst, v, mask=valid) + + +@triton_op("triton::private_kv_write", mutates_args={"key_cache", "value_cache"}) +def private_kv_write( + key: torch.Tensor, + value: torch.Tensor, + position: torch.Tensor, + seq_cols: torch.Tensor, + owner_layout: torch.Tensor, + owner_step: torch.Tensor, + key_cache: torch.Tensor, + value_cache: torch.Tensor, + ring: bool = False, +) -> None: + """BHSD step to packed BSHD storage; padding has the final scratch owner.""" + if key.dim() != 4 or key.shape[0] != 1 or value.shape != key.shape: + raise ValueError("private writes require matching BHSD K/V with batch one") + _, heads, tokens, dim = key.shape + if ( + key.dtype != torch.bfloat16 + or value.dtype != key.dtype + or key.stride(-1) != 1 + or value.stride(-1) != 1 + or key.device.type != "cuda" + ): + raise ValueError("private writes require CUDA BF16 K/V with dense head dim") + if ( + key_cache.dim() != 4 + or key_cache.shape[0] != 1 + or key_cache.shape[2:] != (heads, dim) + or value_cache.shape != key_cache.shape + or key_cache.dtype != key.dtype + or value_cache.dtype != key.dtype + or not key_cache.is_contiguous() + or not value_cache.is_contiguous() + ): + raise ValueError("private cache must be dense BSHD K/V") + if ( + position.dim() != 1 + or position.shape[0] != tokens + or position.dtype != torch.int64 + or not position.is_contiguous() + or seq_cols.dim() != 1 + or seq_cols.shape[0] < tokens + or seq_cols.dtype != torch.int64 + or not seq_cols.is_contiguous() + or owner_layout.dim() != 2 + or owner_layout.shape[1] != 2 + or owner_layout.dtype != torch.int32 + or not owner_layout.is_contiguous() + or owner_step.shape != (owner_layout.shape[0], 3) + or owner_step.dtype != torch.int32 + or not owner_step.is_contiguous() + ): + raise ValueError("private write metadata has invalid shape or storage") + for tensor in ( + value, + position, + seq_cols, + owner_layout, + owner_step, + key_cache, + value_cache, + ): + if tensor.device != key.device: + raise ValueError("private write tensors must share a CUDA device") + wrap_triton(_private_kv_write_kernel)[(triton.cdiv(tokens * heads * dim, 256),)]( + key, + value, + position, + seq_cols, + owner_layout, + owner_step, + key_cache, + value_cache, + tokens, + heads, + dim, + key.stride(1), + key.stride(2), + value.stride(1), + value.stride(2), + OWNERS=owner_layout.shape[0] - 1, + RING=ring, + BLOCK=256, + ) + + +@private_kv_write.register_fake +def _private_kv_write_fake( + key, + value, + position, + seq_cols, + owner_layout, + owner_step, + key_cache, + value_cache, + ring=False, +): + return None diff --git a/backends/cuda/triton/kernels/sdpa_varlen.py b/backends/cuda/triton/kernels/sdpa_varlen.py index bc3ecea5698..8519a591371 100644 --- a/backends/cuda/triton/kernels/sdpa_varlen.py +++ b/backends/cuda/triton/kernels/sdpa_varlen.py @@ -24,6 +24,10 @@ * ``kv_end``: one past the logical position of the segment's last row, i.e. the sequence's length once this step's writes land. +The runtime-column ABI uses ``Int32[S, 5]``. Its last field is the physical +column count, shared by every segment, which sets the K/V row pitch even when +the compiled tensor declares a larger maximum number of columns. + Rows are the segment's newest positions: row ``r`` sits at ``kv_end - q_len + r``. Active segments must be disjoint and in bounds; ``seq_info`` is read on the device, so a captured CUDA graph replays it with new @@ -34,12 +38,83 @@ import triton import triton.language as tl from torch.library import triton_op, wrap_triton +from triton.compiler import compiler as triton_compiler _SPLITK_MAX_QUERY = 4 _SPLITK_ROWS_PER_SPLIT = 256 _SPLITK_MAX_SPLITS = 16 +def _num_stages(head_dim: int, requested: int, device_index: int) -> int: + # D=256 pipelined tiles exceed the 99-KiB opt-in limit on smaller-SMEM + # GPUs. Keep the existing pipeline on devices with at least 160 KiB; + # changing only buffering preserves the key sweep and split-K reduction. + if head_dim == 256 and triton_compiler.max_shared_mem(device_index) < 160 * 1024: + return 1 + return requested + + +@triton.jit +def _private_rows( + Storage_ptr, + Stage_ptr, + Layout_ptr, + Step_ptr, + col, + h_kv, + positions, + valid, + offs_d, + stride_row, + stride_head, + RING: tl.constexpr, + WINDOW: tl.constexpr, +): + base = tl.load(Layout_ptr + col * 2).to(tl.int64) + capacity = tl.load(Layout_ptr + col * 2 + 1) + if RING > 0: + stage_start = tl.load(Step_ptr + col * 3) + absolute_start = tl.load(Step_ptr + col * 3 + 1) + count = tl.load(Step_ptr + col * 3 + 2) + staged = (positions >= absolute_start) & (positions < absolute_start + count) + # Clone/rewind need only W-1 old rows. The remaining slot can contain + # arbitrary allocator bytes; even a zero attention weight times NaN + # would corrupt the value reduction if we loaded it. + history_rows = tl.minimum(capacity, WINDOW - 1) + retained = (positions >= tl.maximum(0, absolute_start - history_rows)) & ( + positions < absolute_start + ) + physical = positions % tl.maximum(capacity, 1) + old_ptr = ( + Storage_ptr + + (base + physical[:, None]) * stride_row + + h_kv * stride_head + + offs_d[None, :] + ) + new_ptr = ( + Stage_ptr + + (stage_start + positions[:, None] - absolute_start) * stride_row + + h_kv * stride_head + + offs_d[None, :] + ) + # Select addresses before loading, so pipelining holds one K/V tile + # rather than separate history and staging tiles in shared memory. + return tl.load( + tl.where(staged[:, None], new_ptr, old_ptr), + mask=(valid & (staged | (retained & (capacity > 0))))[:, None], + other=0.0, + ) + else: + return tl.load( + Storage_ptr + + (base + positions[:, None]) * stride_row + + h_kv * stride_head + + offs_d[None, :], + mask=(valid & (positions >= 0) & (positions < capacity))[:, None], + other=0.0, + ) + + @triton.jit def _sdpa_varlen_kernel( # noqa: C901 Q_ptr, @@ -50,6 +125,10 @@ def _sdpa_varlen_kernel( # noqa: C901 M_part_ptr, L_part_ptr, Info_ptr, + Layout_ptr, + Step_ptr, + K_stage_ptr, + V_stage_ptr, Hq, T, stride_qh, @@ -65,6 +144,8 @@ def _sdpa_varlen_kernel( # noqa: C901 sm_scale, rows_available, num_qb, + INFO_WIDTH: tl.constexpr, + PRIVATE: tl.constexpr, NUM_SPLITS: tl.constexpr, IS_CAUSAL: tl.constexpr, CONTEXT_WINDOW: tl.constexpr, @@ -82,10 +163,14 @@ def _sdpa_varlen_kernel( # noqa: C901 seg = pid0 // num_qb qb = pid0 % num_qb - q_start = tl.load(Info_ptr + seg * 4 + 0) - q_len = tl.load(Info_ptr + seg * 4 + 1) - col = tl.load(Info_ptr + seg * 4 + 2) - kv_end = tl.load(Info_ptr + seg * 4 + 3) + q_start = tl.load(Info_ptr + seg * INFO_WIDTH + 0) + q_len = tl.load(Info_ptr + seg * INFO_WIDTH + 1) + col = tl.load(Info_ptr + seg * INFO_WIDTH + 2) + kv_end = tl.load(Info_ptr + seg * INFO_WIDTH + 3) + if INFO_WIDTH == 5: + columns = tl.load(Info_ptr + seg * INFO_WIDTH + 4).to(tl.int64) + stride_kr = columns * stride_kc + stride_vr = columns * stride_vc if qb * BLOCK_M >= q_len * NUM_GROUPS: return @@ -134,17 +219,34 @@ def _sdpa_varlen_kernel( # noqa: C901 for n0 in tl.range(start, stop, BLOCK_N): offs_n = n0 + tl.arange(0, BLOCK_N) n_valid = offs_n < stop - k = tl.load( - k_base + offs_n[:, None] * stride_kr + offs_d[None, :], - mask=n_valid[:, None], - other=0.0, - ) - qk = tl.dot(q, tl.trans(k)).to(tl.float32) * sm_scale if RING > 0: # The newest logical position that landed in each ring row. kv_pos = offs_n + RING * ((kv_end - 1 - offs_n) // RING) else: kv_pos = offs_n + if PRIVATE: + k = _private_rows( + K_ptr, + K_stage_ptr, + Layout_ptr, + Step_ptr, + col, + h_kv, + kv_pos, + n_valid, + offs_d, + stride_kc, + stride_kh, + RING, + WINDOW, + ) + else: + k = tl.load( + k_base + offs_n[:, None] * stride_kr + offs_d[None, :], + mask=n_valid[:, None], + other=0.0, + ) + qk = tl.dot(q, tl.trans(k)).to(tl.float32) * sm_scale visible = n_valid[None, :] & row_valid[:, None] & (kv_pos[None, :] >= 0) if IS_CAUSAL: visible = visible & (kv_pos[None, :] <= pos[:, None]) @@ -160,11 +262,28 @@ def _sdpa_varlen_kernel( # noqa: C901 m_ij = tl.maximum(m_i, tl.max(qk, axis=1)) p = tl.where(m_ij[:, None] > -float("inf"), tl.exp(qk - m_ij[:, None]), 0.0) alpha = tl.where(m_ij > -float("inf"), tl.exp(m_i - m_ij), 0.0) - v = tl.load( - v_base + offs_n[:, None] * stride_vr + offs_d[None, :], - mask=n_valid[:, None], - other=0.0, - ) + if PRIVATE: + v = _private_rows( + V_ptr, + V_stage_ptr, + Layout_ptr, + Step_ptr, + col, + h_kv, + kv_pos, + n_valid, + offs_d, + stride_vc, + stride_vh, + RING, + WINDOW, + ) + else: + v = tl.load( + v_base + offs_n[:, None] * stride_vr + offs_d[None, :], + mask=n_valid[:, None], + other=0.0, + ) acc = acc * alpha[:, None] + tl.dot(p.to(v.dtype), v) l_i = l_i * alpha + tl.sum(p, axis=1) m_i = m_ij @@ -188,7 +307,7 @@ def _sdpa_varlen_kernel( # noqa: C901 @triton.jit -def _sdpa_varlen_decode_kernel( +def _sdpa_varlen_decode_kernel( # noqa: C901 Q_ptr, K_ptr, V_ptr, @@ -197,6 +316,10 @@ def _sdpa_varlen_decode_kernel( M_part_ptr, L_part_ptr, Info_ptr, + Layout_ptr, + Step_ptr, + K_stage_ptr, + V_stage_ptr, Hq, T, stride_qh, @@ -212,6 +335,8 @@ def _sdpa_varlen_decode_kernel( sm_scale, rows_available, NUM_SEGMENTS: tl.constexpr, + INFO_WIDTH: tl.constexpr, + PRIVATE: tl.constexpr, NUM_SPLITS: tl.constexpr, IS_CAUSAL: tl.constexpr, CONTEXT_WINDOW: tl.constexpr, @@ -233,14 +358,18 @@ def _sdpa_varlen_decode_kernel( col = 0 kv_end = 0 for seg in range(NUM_SEGMENTS): - seg_q_start = tl.load(Info_ptr + seg * 4) - seg_q_len = tl.load(Info_ptr + seg * 4 + 1) + seg_q_start = tl.load(Info_ptr + seg * INFO_WIDTH) + seg_q_len = tl.load(Info_ptr + seg * INFO_WIDTH + 1) take = (t >= seg_q_start) & (t < seg_q_start + seg_q_len) owned |= take q_start = tl.where(take, seg_q_start, q_start) q_len = tl.where(take, seg_q_len, q_len) - col = tl.where(take, tl.load(Info_ptr + seg * 4 + 2), col) - kv_end = tl.where(take, tl.load(Info_ptr + seg * 4 + 3), kv_end) + col = tl.where(take, tl.load(Info_ptr + seg * INFO_WIDTH + 2), col) + kv_end = tl.where(take, tl.load(Info_ptr + seg * INFO_WIDTH + 3), kv_end) + if INFO_WIDTH == 5: + columns = tl.load(Info_ptr + 4).to(tl.int64) + stride_kr = columns * stride_kc + stride_vr = columns * stride_vc offs_g = tl.arange(0, BLOCK_G) offs_d = tl.arange(0, HEAD_DIM) @@ -279,16 +408,33 @@ def _sdpa_varlen_decode_kernel( for n0 in tl.range(start, stop, BLOCK_N): offs_n = n0 + tl.arange(0, BLOCK_N) n_valid = offs_n < stop - k = tl.load( - k_base + offs_n[:, None] * stride_kr + offs_d[None, :], - mask=n_valid[:, None] & owned, - other=0.0, - ) - qk = tl.dot(q, tl.trans(k)).to(tl.float32) * sm_scale if RING > 0: kv_pos = offs_n + RING * ((kv_end - 1 - offs_n) // RING) else: kv_pos = offs_n + if PRIVATE: + k = _private_rows( + K_ptr, + K_stage_ptr, + Layout_ptr, + Step_ptr, + col, + h_kv, + kv_pos, + n_valid & owned, + offs_d, + stride_kc, + stride_kh, + RING, + WINDOW, + ) + else: + k = tl.load( + k_base + offs_n[:, None] * stride_kr + offs_d[None, :], + mask=n_valid[:, None] & owned, + other=0.0, + ) + qk = tl.dot(q, tl.trans(k)).to(tl.float32) * sm_scale visible = n_valid[None, :] & row_valid[:, None] & (kv_pos[None, :] >= 0) if IS_CAUSAL: visible &= kv_pos[None, :] <= pos @@ -304,11 +450,28 @@ def _sdpa_varlen_decode_kernel( m_ij = tl.maximum(m_i, tl.max(qk, axis=1)) p = tl.where(m_ij[:, None] > -float("inf"), tl.exp(qk - m_ij[:, None]), 0.0) alpha = tl.where(m_ij > -float("inf"), tl.exp(m_i - m_ij), 0.0) - v = tl.load( - v_base + offs_n[:, None] * stride_vr + offs_d[None, :], - mask=n_valid[:, None] & owned, - other=0.0, - ) + if PRIVATE: + v = _private_rows( + V_ptr, + V_stage_ptr, + Layout_ptr, + Step_ptr, + col, + h_kv, + kv_pos, + n_valid & owned, + offs_d, + stride_vc, + stride_vh, + RING, + WINDOW, + ) + else: + v = tl.load( + v_base + offs_n[:, None] * stride_vr + offs_d[None, :], + mask=n_valid[:, None] & owned, + other=0.0, + ) acc = acc * alpha[:, None] + tl.dot(p.to(v.dtype), v) l_i = l_i * alpha + tl.sum(p, axis=1) m_i = m_ij @@ -374,8 +537,7 @@ def _num_splits(T: int, rows: int) -> int: return max(1, min(_SPLITK_MAX_SPLITS, triton.cdiv(rows, _SPLITK_ROWS_PER_SPLIT))) -@triton_op("triton::sdpa_varlen", mutates_args={}) -def sdpa_varlen( # noqa: C901 +def _sdpa_varlen_impl( # noqa: C901 query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, @@ -386,14 +548,21 @@ def sdpa_varlen( # noqa: C901 ring: int = 0, rows_available: int = -1, context_window: bool = False, + owner_layout: torch.Tensor | None = None, + owner_step: torch.Tensor | None = None, + k_stage: torch.Tensor | None = None, + v_stage: torch.Tensor | None = None, ) -> torch.Tensor: """Attend each segment of ``query`` to its own sequence's K/V. Args: query: ``[1, H_q, T, D]`` bfloat16, the step's queries in packed order. key, value: ``[rows, columns, H_kv, D]`` bfloat16 storage; one column per - sequence. Only the head dimension must be contiguous. - seq_info: ``Int32[S, 4]`` on the query's device, ``(q_start, q_len, + sequence. The head dimension must be contiguous. For 5-wide + seq_info, column/head lanes must also be contiguous and the row + pitch is field 4 times the column stride, not key.stride(0). + seq_info: ``Int32[S, 4]`` (or ``Int32[S, 5]`` with the runtime + pitch in field 4) on the query's device, ``(q_start, q_len, col, kv_end)`` per segment; see the module docstring. scale: softmax scale. is_causal: row ``r`` sees positions up to its own; otherwise every @@ -438,12 +607,47 @@ def sdpa_varlen( # noqa: C901 raise ValueError("head dimension must be a power of two in [16, 256]") if query.stride(-1) != 1 or key.stride(-1) != 1 or value.stride(-1) != 1: raise ValueError("sdpa_varlen needs a contiguous head dimension") - if seq_info.dtype != torch.int32 or seq_info.dim() != 2 or seq_info.shape[1] != 4: - raise ValueError("seq_info must be Int32[S, 4]") + if ( + seq_info.dtype != torch.int32 + or seq_info.dim() != 2 + or seq_info.shape[1] not in (4, 5) + ): + raise ValueError("seq_info must be Int32[S, 4] or runtime-pitch Int32[S, 5]") if seq_info.device != query.device or not seq_info.is_contiguous(): raise ValueError("seq_info must be contiguous on the query device") if context_window and is_causal: raise ValueError("context_window requires non-causal attention") + private = owner_layout is not None + if private: + if context_window or not is_causal or seq_info.shape[1] != 4: + raise ValueError("private rows require causal, four-wide sequence info") + for metadata, width in ((owner_layout, 2), (owner_step, 3)): + if ( + metadata is None + or metadata.dtype != torch.int32 + or metadata.shape != (key.shape[1], width) + or metadata.device != query.device + or not metadata.is_contiguous() + ): + raise ValueError("private owner metadata has invalid shape or storage") + if ( + key.stride(1) != Hkv * D + or key.stride(2) != D + or (value.stride(1) != Hkv * D or value.stride(2) != D) + ): + raise ValueError("private K/V rows require dense head lanes") + if ring > 0: + for stage in (k_stage, v_stage): + if ( + stage is None + or stage.dim() != 4 + or stage.shape[0] != 1 + or stage.shape[2:] != (Hkv, D) + or stage.dtype != key.dtype + or stage.device != query.device + or not stage.is_contiguous() + ): + raise ValueError("private Ring staging must be dense BSHD K/V") groups = Hq // Hkv available = rows if rows_available < 0 else min(rows_available, rows) # Branching on a symbolic T would guard (and AOTI then pin) the exported @@ -452,7 +656,13 @@ def sdpa_varlen( # noqa: C901 use_decode = static and T <= _SPLITK_MAX_QUERY block_m = 16 if static and T * groups <= 16 else 64 num_qb = (T * groups + block_m - 1) // block_m - generic_num_stages = 3 if static and T <= 64 else 2 + requested_stages = 2 if use_decode else (3 if static and T <= 64 else 2) + device_index = ( + query.device.index + if query.device.index is not None + else torch.cuda.current_device() + ) + num_stages = _num_stages(D, requested_stages, device_index) splits = _num_splits(T, rows) if static else 1 # The row-complete decode path writes uncovered rows and empty split slots. out = torch.empty_like(query) if use_decode else torch.zeros_like(query) @@ -475,6 +685,10 @@ def sdpa_varlen( # noqa: C901 m_part, l_part, seq_info, + owner_layout if private else query, + owner_step if private else query, + k_stage if private and ring > 0 else query, + v_stage if private and ring > 0 else query, Hq, T, query.stride(1), @@ -490,6 +704,8 @@ def sdpa_varlen( # noqa: C901 scale, available, NUM_SEGMENTS=seq_info.shape[0], + INFO_WIDTH=seq_info.shape[1], + PRIVATE=private, NUM_SPLITS=splits, IS_CAUSAL=is_causal, CONTEXT_WINDOW=context_window, @@ -500,7 +716,7 @@ def sdpa_varlen( # noqa: C901 NUM_GROUPS=groups, BLOCK_G=triton.next_power_of_2(groups), num_warps=4, - num_stages=2, + num_stages=num_stages, ) else: grid = (seq_info.shape[0] * num_qb, Hkv, splits) @@ -513,6 +729,10 @@ def sdpa_varlen( # noqa: C901 m_part, l_part, seq_info, + owner_layout if private else query, + owner_step if private else query, + k_stage if private and ring > 0 else query, + v_stage if private and ring > 0 else query, Hq, T, query.stride(1), @@ -528,6 +748,8 @@ def sdpa_varlen( # noqa: C901 scale, available, num_qb, + INFO_WIDTH=seq_info.shape[1], + PRIVATE=private, NUM_SPLITS=splits, IS_CAUSAL=is_causal, CONTEXT_WINDOW=context_window, @@ -538,7 +760,7 @@ def sdpa_varlen( # noqa: C901 HEAD_DIM=D, NUM_GROUPS=groups, num_warps=4, - num_stages=generic_num_stages, + num_stages=num_stages, ) if splits > 1: wrap_triton(_sdpa_varlen_reduce_kernel)[(Hq * T,)]( @@ -557,6 +779,88 @@ def sdpa_varlen( # noqa: C901 return out +@triton_op("triton::sdpa_varlen", mutates_args={}) +def sdpa_varlen( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + seq_info: torch.Tensor, + scale: float, + is_causal: bool = True, + window: int = 0, + ring: int = 0, + rows_available: int = -1, + context_window: bool = False, +) -> torch.Tensor: + return _sdpa_varlen_impl( + query, + key, + value, + seq_info, + scale, + is_causal, + window, + ring, + rows_available, + context_window, + ) + + +@triton_op("triton::sdpa_varlen_private", mutates_args={}) +def sdpa_varlen_private( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + seq_info: torch.Tensor, + owner_layout: torch.Tensor, + owner_step: torch.Tensor, + k_stage: torch.Tensor, + v_stage: torch.Tensor, + scale: float, + window: int = 0, + ring: int = 0, +) -> torch.Tensor: + """ABI 3: legacy key sweep over packed private history and shared step K/V. + + ``owner_layout`` is Int32[columns, 2] (base row, capacity), and + ``owner_step`` is Int32[columns, 3] (stage start, absolute start, count). + The declared key/value shape retains the legacy virtual Ring extent; + device storage needs only the sum of private capacities plus scratch. + Metadata values are checked by the runtime before graph replay. + """ + return _sdpa_varlen_impl( + query, + key, + value, + seq_info, + scale, + True, + window, + ring, + owner_layout=owner_layout, + owner_step=owner_step, + k_stage=k_stage, + v_stage=v_stage, + ) + + +@sdpa_varlen_private.register_fake +def _sdpa_varlen_private_fake( + query, + key, + value, + seq_info, + owner_layout, + owner_step, + k_stage, + v_stage, + scale, + window=0, + ring=0, +): + return torch.empty_like(query) + + @sdpa_varlen.register_fake def _sdpa_varlen_fake( query, diff --git a/examples/models/muse-glimmer/CMakeLists.txt b/examples/models/muse-glimmer/CMakeLists.txt index 619d835e418..9a7245a6f57 100644 --- a/examples/models/muse-glimmer/CMakeLists.txt +++ b/examples/models/muse-glimmer/CMakeLists.txt @@ -144,6 +144,34 @@ target_include_directories( dflash_timing_test PUBLIC ${_common_include_directories} ) +option(MUSE_GLIMMER_BUILD_RUNTIME_KV_PROBE "Build isolated CUDA KV diagnostic" + OFF +) +if(MUSE_GLIMMER_BUILD_RUNTIME_KV_PROBE) + if(WIN32) + message(FATAL_ERROR "Runtime KV probe requires POSIX file descriptors") + endif() + if(NOT EXECUTORCH_BUILD_CUDA) + message(FATAL_ERROR "Runtime KV probe requires the CUDA batching executor") + endif() + add_executable( + muse_glimmer_runtime_kv_probe tests/runtime_kv_columns_probe.cpp + ) + target_include_directories( + muse_glimmer_runtime_kv_probe PRIVATE ${_common_include_directories} + ${_json_include} + ) + target_link_libraries( + muse_glimmer_runtime_kv_probe PRIVATE cuda_batching CUDA::cudart + ${link_libraries} + ) + if(NOT APPLE AND NOT MSVC) + target_link_options( + muse_glimmer_runtime_kv_probe PRIVATE "LINKER:--export-dynamic" + ) + endif() +endif() + # Worker used by the OpenAI-compatible serving harness. add_executable( muse_glimmer_worker diff --git a/examples/models/muse-glimmer/export/export_solo.py b/examples/models/muse-glimmer/export/export_solo.py index 064292d8ea1..02a13b1ba7b 100644 --- a/examples/models/muse-glimmer/export/export_solo.py +++ b/examples/models/muse-glimmer/export/export_solo.py @@ -126,7 +126,22 @@ def export_and_lower( max_cells: int = 65536, kv_layout: str = "cell", max_kv_seqs: int = 4, + runtime_kv_columns: bool = False, + private_kv_rows: bool = False, ) -> None: + if runtime_kv_columns and not ( + backend == "cuda" and use_offgraph_kv_cache and kv_layout == "sequence" + ): + raise ValueError("runtime KV columns require CUDA off-graph sequence layout") + if private_kv_rows and ( + runtime_kv_columns + or backend != "cuda" + or not use_offgraph_kv_cache + or kv_layout != "sequence" + ): + raise ValueError( + "private KV rows require CUDA off-graph sequence layout without ABI 2" + ) if use_offgraph_kv_cache and use_turboquant: raise ValueError("off-graph KV cache and TurboQuant are mutually exclusive") if backend == "mlx" and use_offgraph_kv_cache: @@ -149,6 +164,8 @@ def export_and_lower( device_sampling=sample, kv_layout=kv_layout, max_kv_seqs=max_kv_seqs, + runtime_kv_columns=runtime_kv_columns, + private_kv_rows=private_kv_rows, vision_model=vision_model, pos_embed_table=pos_embed_table, max_vision_patches=max_vision_patches, @@ -249,7 +266,6 @@ def _solo_constant_methods( MAX_CELLS_METHOD = "get_offgraph_kv_max_cells" # Read by CudaExecutor in place of the cell count when each sequence keeps a # private history: the sequence columns of every layer's storage. -MAX_KV_SEQS_METHOD = "get_offgraph_kv_max_seqs" # Read by MuseGlimmerCudaDFlashExecutor for the draft's own sequence columns, # mirroring kMaxSeqs in runtime/cuda_dflash_executor.h. DRAFT_MAX_KV_SEQS_METHOD = "get_draft_offgraph_kv_max_seqs" @@ -338,6 +354,8 @@ def batched_sequence_manifest( max_seqs: int, causal: bool = True, context_window: bool = False, + runtime_columns: bool = False, + private_rows: bool = False, ) -> str: """The batched-sequence lowering manifest: one column per sequence.""" from executorch.backends.cuda.passes.lower_offgraph_kv import ( @@ -349,6 +367,10 @@ def batched_sequence_manifest( manifest["max_seqs"] = max_seqs manifest["max_segments"] = batched_sequence_max_segments(max_seqs) manifest["causal"] = causal + if runtime_columns: + manifest["runtime_columns"] = True + if private_rows: + manifest["private_rows"] = True if context_window: manifest["context_window"] = True return json.dumps(manifest, sort_keys=True, separators=(",", ":")) @@ -423,6 +445,8 @@ def export_cuda_batching( # noqa: C901 max_vision_patches: int = 16384, kv_layout: str = "cell", max_kv_seqs: int = 4, + runtime_kv_columns: bool = False, + private_kv_rows: bool = False, ): """Exports the forward methods and writes the artifact. @@ -442,6 +466,7 @@ def export_cuda_batching( # noqa: C901 from executorch.backends.cuda.cuda_partitioner import CudaPartitioner from executorch.backends.cuda.passes.lower_offgraph_kv import ( OFFGRAPH_KV_COMPILE_SPEC, + offgraph_kv_constant_methods, OFFGRAPH_KV_STEP_WIDTH_COMPILE_SPEC, ) from executorch.examples.models.muse_glimmer.source_transformations.cuda import ( @@ -464,6 +489,14 @@ def export_cuda_batching( # noqa: C901 if kv_layout not in KV_LAYOUTS: raise ValueError(f"kv_layout must be one of {KV_LAYOUTS}, got {kv_layout!r}") sequence_layout = kv_layout == "sequence" + if runtime_kv_columns and (not sequence_layout or dflash_draft is not None): + raise ValueError("runtime KV columns require solo sequence-layout export") + if private_kv_rows and ( + runtime_kv_columns or not sequence_layout or dflash_draft is not None + ): + raise ValueError( + "private KV rows require solo sequence-layout export without ABI 2" + ) if sequence_layout and max_kv_seqs <= 0: raise ValueError("the sequence layout needs max_kv_seqs > 0") has_vision = vision_model is not None and pos_embed_table is not None @@ -518,7 +551,12 @@ def export_cuda_batching( # noqa: C901 single_manifest = enable_offgraph_kv_cache(model, max_step_tokens) manifest = ( - batched_sequence_manifest(single_manifest, max_kv_seqs) + batched_sequence_manifest( + single_manifest, + max_kv_seqs, + runtime_columns=runtime_kv_columns, + private_rows=private_kv_rows, + ) if sequence_layout else cell_manifest(single_manifest, max_cells) ) @@ -676,7 +714,7 @@ def partitioner(name: str) -> CudaPartitioner: constant_methods["get_min_prefill_chunk"] = _CUDA_MIN_PREFILL_CHUNK constant_methods["use_sampling"] = False if sequence_layout: - constant_methods[MAX_KV_SEQS_METHOD] = max_kv_seqs + constant_methods.update(offgraph_kv_constant_methods(manifest.encode())) else: constant_methods[MAX_CELLS_METHOD] = max_cells if "draft_forward" in programs: @@ -1218,6 +1256,18 @@ def main() -> None: "use, up to this.", ) add_kv_layout_arguments(parser) + parser.add_argument( + "--runtime-kv-columns", + action="store_true", + help="Export the experimental runtime-pitch ABI for CUDA sequence KV storage: " + "owner columns grow on admission and compact after sustained serving idleness.", + ) + parser.add_argument( + "--private-kv-rows", + action="store_true", + help="Export experimental ABI 3: independent session row capacities and " + "per-layer Ring staging shared by the packed step (CUDA solo sequence layout).", + ) parser.add_argument( "--activation-dtype", default=None, @@ -1358,6 +1408,8 @@ def main() -> None: max_cells=args.max_cells, kv_layout=args.kv_layout, max_kv_seqs=args.max_kv_seqs, + runtime_kv_columns=args.runtime_kv_columns, + private_kv_rows=args.private_kv_rows, ) diff --git a/examples/models/muse-glimmer/tests/check_private_kv_rows.py b/examples/models/muse-glimmer/tests/check_private_kv_rows.py new file mode 100644 index 00000000000..91b1f01b609 --- /dev/null +++ b/examples/models/muse-glimmer/tests/check_private_kv_rows.py @@ -0,0 +1,710 @@ +# 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. + +"""Native ABI-2/ABI-3 equality, allocation and same-work timing qualification. + +Tests MG- and Gemma-style head dimensions on the same tiny model weights. +The mg-ring profile retains production MG attention/cache geometry, not its +30B parameter count or quantized GEMM performance. +Timing covers undo transfers, staggered growth and clone/rewind cycles; +it excludes logits file writes. +""" + +import argparse +import json +import statistics +import subprocess +import sys +from dataclasses import replace +from pathlib import Path + + +def report_export_resources(tag): + snapshot = {"tag": tag} + try: + import resource + + peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + snapshot["cpu_peak_rss_bytes"] = int(peak) * ( + 1 if sys.platform == "darwin" else 1024 + ) + except ImportError: + pass + if sys.platform.startswith("linux"): + for name in ("memory.current", "memory.max", "memory.events"): + try: + snapshot["cgroup_" + name] = ( + (Path("/sys/fs/cgroup") / name).read_text().strip() + ) + except OSError: + pass + print("PRIVATE_KV_EXPORT_RESOURCE " + json.dumps(snapshot), flush=True) + return snapshot + + +def step(owners, tag, *, save=True): + return { + "op": "step", + "seq_ids": owners, + "tokens": [13] * len(owners), + "select": list(range(len(owners))), + "tag": tag, + "save_logits": save, + "argmax": save, + } + + +def qualification_config(profile, head_dim): + if profile == "mini": + return { + "max_step_tokens": 128, + "max_context": 4096, + "seed_length": 64, + "window": 16, + "ring_layers": 1, + "model": { + "dim": 2 * head_dim, + "head_dim": head_dim, + "n_layers": 2, + "n_heads": 2, + "n_kv_heads": 1, + "max_seq_len": 4096, + "global_attn_cfg": "[16,0]", + }, + } + if profile != "mg-ring" or head_dim != 128: + raise ValueError("mg-ring requires head dimension 128") + # Production attention/cache geometry, with reduced embedding and MLP + # weights. This stresses the cache lifecycle without claiming 30B perf. + return { + "max_step_tokens": 4096, + "max_context": 131072, + "seed_length": 2048, + "window": 2048, + "ring_layers": 39, + "model": { + "dim": 256, + "head_dim": 128, + "n_layers": 52, + "n_heads": 32, + "n_kv_heads": 2, + "max_seq_len": 131072, + "global_attn_cfg": "[2048,2048,2048,0]", + }, + } + + +def seed_commands(concurrency, geometry, profile): + seed_length = geometry["seed_length"] + chunk_size = min(seed_length, 512) + owners_per_chunk = geometry["max_step_tokens"] // chunk_size + requests = [] + for first in range(0, concurrency, owners_per_chunk): + for start in range(0, seed_length, chunk_size): + owners = [ + owner + for owner in range(first, min(first + owners_per_chunk, concurrency)) + for _ in range(chunk_size) + ] + tag = f"seed-c{concurrency}-{first}" + if profile != "mini": + tag += f"-{start}" + prefill = step(owners, tag, save=False) + prefill["select"] = list(range(chunk_size - 1, len(owners), chunk_size)) + requests.append(prefill) + return requests + + +def diversify_tokens(requests): + lengths, seeds = {}, {} + generation = 0 + for request in requests: + op = request["op"] + if op == "clear": + lengths.clear() + seeds.clear() + elif op in ("new", "clone"): + owner = next(i for i in range(64) if i not in lengths) + generation += 1 + seeds[owner] = generation + lengths[owner] = 0 if op == "new" else request["upto"] + elif op == "remove": + del lengths[request["seq_id"]] + del seeds[request["seq_id"]] + elif op == "rewind": + lengths[request["seq_id"]] = request["position"] + elif op == "step": + tokens = [] + for owner in request["seq_ids"]: + position = lengths[owner] + tokens.append( + 1 + + ( + seeds[owner] * 67 + + owner * 29 + + position * 17 + + (position // 251) * 13 + ) + % 251 + ) + lengths[owner] += 1 + request["tokens"] = tokens + return requests + + +def graph_commands(): + # Exercise every exported captured stage across the same contraction. + requests = [{"op": "clear"}, {"op": "compact", "spare_columns": 0}] + requests += [{"op": "new"} for _ in range(64)] + for first in range(0, 64, 2): + seed = step( + [owner for owner in (first, first + 1) for _ in range(64)], + f"graph-seed-{first}", + save=False, + ) + seed["select"] = [63, 127] + requests.append(seed) + for phase, owners in (("before", 64), ("after", 48)): + if phase == "after": + requests += [{"op": "remove", "seq_id": owner} for owner in range(48, 64)] + requests.append({"op": "compact", "spare_columns": 0}) + for repeat in range(2): + for width in (1, 2, 4, 8, 16, 32, 64): + batch = sorted(row % owners for row in range(width)) + requests.append(step(batch, f"graph-{phase}-{repeat}-{width}")) + return requests + + +def commands(profile="mini"): + geometry = qualification_config(profile, 128) + seed_length = geometry["seed_length"] + requests = [{"op": "new"} for _ in range(64)] + requests += [step(list(range(64)), "decode64-first")] + long = step([0] * 96, "long") + long["select"] = [95] + requests += [long, step(list(range(64)), "decode64-mixed")] + requests += [ + {"op": "remove", "seq_id": 63}, + {"op": "clone", "seq_id": 0, "upto": 95}, + {"op": "rewind", "seq_id": 63, "position": 94}, + ] + requests += [step(list(range(64)), f"before-{i}") for i in range(7)] + requests += [ + {"op": "remove", "seq_id": 0}, + {"op": "remove", "seq_id": 63}, + {"op": "compact", "spare_columns": 0}, + ] + requests += [step(list(range(1, 63)), f"after-{i}") for i in range(5)] + requests += graph_commands() + requests += [ + {"op": "clear"}, + {"op": "compact", "spare_columns": 0}, + {"op": "new"}, + ] + for i in range(2): + request = step([0] * 128, f"floor-seed-{i}") + request["select"] = [127] + requests.append(request) + requests += [ + {"op": "clone", "seq_id": 0, "upto": 128}, + {"op": "rewind", "seq_id": 0, "position": 128}, + step([0, 1], "floor-replay"), + ] + if profile == "mg-ring": + requests += [ + {"op": "clear"}, + {"op": "compact", "spare_columns": 0}, + {"op": "new"}, + ] + width = geometry["max_step_tokens"] + for chunk in range(2): + seed = step([0] * width, f"production-ring-seed-{chunk}", save=False) + seed["select"] = [width - 1] + seed["tokens"] = [13 + (chunk * width + i) % 23 for i in range(width)] + requests.append(seed) + requests += [ + {"op": "clone", "seq_id": 0, "upto": width}, + {"op": "rewind", "seq_id": 0, "position": width}, + step([0, 1], "production-ring-floor-replay"), + ] + for concurrency in (1, 2, 4, 8, 16, 32, 64): + requests += [{"op": "clear"}, {"op": "compact", "spare_columns": 0}] + requests += [{"op": "new"} for _ in range(concurrency)] + requests += seed_commands(concurrency, geometry, profile) + requests += [ + step(list(range(concurrency)), f"warm-c{concurrency}-{i}", save=False) + for i in range(4) + ] + requests += [ + step(list(range(concurrency)), f"bench-c{concurrency}-{i}", save=False) + for i in range(20) + ] + # Leave one free slot at c64 for a fork. + destination = max(1, concurrency - 1) + if concurrency > 1: + requests.append({"op": "remove", "seq_id": destination}) + for i in range(8): + tag = f"restore-c{concurrency}-{i}" + requests += [ + { + "op": "clone", + "seq_id": 0, + "upto": seed_length + 23, + "tag": tag + "-clone", + }, + { + "op": "rewind", + "seq_id": destination, + "position": seed_length + 22, + "tag": tag + "-rewind", + }, + step([destination], tag + "-step", save=False), + {"op": "remove", "seq_id": destination, "tag": tag + "-remove"}, + ] + requests += [{"op": "clear"}, {"op": "compact", "spare_columns": 0}] + for owner in range(concurrency): + tag = f"growth-c{concurrency}-{owner}" + seed = step([owner] * 8, tag + "-seed", save=False) + seed["select"] = [7] + requests += [ + {"op": "new", "tag": tag + "-new"}, + seed, + step(list(range(owner + 1)), tag + "-decode", save=False), + ] + requests.append(step(list(range(concurrency)), f"growth-verify-c{concurrency}")) + # Free enough private history to exceed CUDA pool page granularity. This + # phase is separate from timing and keeps 48 short owners alive throughout. + requests += [{"op": "clear"}, {"op": "compact", "spare_columns": 0}] + requests += [{"op": "new"} for _ in range(64)] + requests.append(step(list(range(64)), "driver-seed", save=False)) + for owner in range(16): + for chunk in range(16): + prefill = step([owner] * 128, f"driver-prefill-{owner}-{chunk}", save=False) + prefill["select"] = [127] + requests.append(prefill) + requests.append(step(list(range(64)), "driver-before", save=False)) + requests += [{"op": "remove", "seq_id": owner} for owner in range(16)] + requests.append({"op": "compact", "spare_columns": 0, "tag": "driver-compact"}) + requests.append(step(list(range(16, 64)), "driver-after")) + # Reuse a long owner's ID while a short owner stays live, then compact. + requests += [ + {"op": "clear"}, + {"op": "compact", "spare_columns": 0}, + {"op": "new"}, + {"op": "new"}, + ] + long = step([0] * 128, "reuse-long", save=False) + long["select"] = [127] + requests += [ + long, + step([1], "reuse-short", save=False), + {"op": "remove", "seq_id": 0}, + {"op": "new"}, + step([0, 1], "reuse-before"), + {"op": "compact", "spare_columns": 0, "tag": "reuse-compact"}, + step([0, 1], "reuse-after"), + ] + return diversify_tokens(requests) + + +def run(probe, root, head_dim, abi, repeat=0, profile="mini"): + import numpy as np + + geometry = qualification_config(profile, head_dim) + prefix = "" if profile == "mini" else profile + "-" + artifact = root / f"{prefix}d{head_dim}-abi{abi}" + if repeat == 0: + import torch + from executorch.examples.models.muse_glimmer.export.export_solo import ( + export_cuda_batching, + ) + from executorch.examples.models.muse_glimmer.model.model import MuseGlimmerModel + from executorch.examples.models.muse_glimmer.tests.test_pipeline import ( + TINY_CONFIG, + ) + + artifact.mkdir() + torch.manual_seed(123) + config = replace(TINY_CONFIG, **geometry["model"]) + report_export_resources(f"{profile}/d{head_dim}/abi{abi}/before-model") + model = MuseGlimmerModel(config).to(torch.bfloat16).eval() + model.activation_dtype = torch.bfloat16 + report_export_resources(f"{profile}/d{head_dim}/abi{abi}/before-export") + export_cuda_batching( + model, + config, + str(artifact), + max_step_tokens=geometry["max_step_tokens"], + max_cells=64 * geometry["max_context"], + forward_sizes=(1, 2, 4, 8, 16, 32, 64), + kv_layout="sequence", + max_kv_seqs=64, + runtime_kv_columns=abi == 2, + private_kv_rows=abi == 3, + ) + report_export_resources(f"{profile}/d{head_dim}/abi{abi}/after-export") + run_dir = artifact / f"run-{repeat}" + run_dir.mkdir() + logits_dir = run_dir / "logits" + logits_dir.mkdir() + requests = commands(profile) + completed = subprocess.run( + [ + str(probe), + f"--pte={artifact / 'model.pte'}", + f"--data_path={artifact / 'aoti_cuda_blob.ptd'}", + f"--output_dir={logits_dir}", + "--max_sessions=64", + f"--max_context={geometry['max_context']}", + "--initial_kv_capacity=2", + ], + input="".join(json.dumps(r) + "\n" for r in requests), + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + timeout=900, + ) + (run_dir / "probe.stderr.log").write_text(completed.stderr) + (run_dir / "probe.jsonl").write_text(completed.stdout) + if completed.returncode != 0: + replies = completed.stdout.splitlines() + print( + f"PRIVATE_KV_PROBE_FAILURE {profile}/d{head_dim}/abi{abi}: " + f"{replies[-1] if replies else 'no protocol response'}", + flush=True, + ) + print(completed.stderr[-2000:], file=sys.stderr, flush=True) + completed.check_returncode() + replies = [json.loads(line) for line in completed.stdout.splitlines()] + assert replies[0]["ready"] and len(replies) == len(requests) + 1 + pairs = list(zip(requests, replies[1:], strict=True)) + logits, steps = {}, {} + previous_snapshot = replies[0]["snapshot"] + for request, response in pairs: + assert not response.get("failed") and request["op"] == response["op"] + response["cache_phase_seconds"] = { + name.removesuffix("_ns") + + "_s": (response["snapshot"][name] - previous_snapshot[name]) * 1e-9 + for name in ( + "cache_prepare_time_ns", + "cache_commit_time_ns", + "archive_transfer_time_ns", + "archive_append_time_ns", + ) + } + assert all(t >= 0 for t in response["cache_phase_seconds"].values()) + previous_snapshot = response["snapshot"] + if request["op"] == "step": + steps[request["tag"]] = response + if request["save_logits"]: + arrays = [ + np.fromfile(x["file"], dtype=np.float32).reshape(x["shape"]) + for x in response["logits"] + ] + logits[request["tag"]] = np.concatenate(arrays) + return logits, steps, pairs + + +def graph(snapshot, name): + return next(x for x in snapshot["method_calls"] if x["method"] == name) + + +def require_graph_contraction(before, after): + for width in (1, 2, 4, 8, 16, 32, 64): + name = f"forward_{width}" + old_graph, new_graph = graph(before, name), graph(after, name) + assert old_graph["captures"] > 0, name + assert new_graph["captures"] - old_graph["captures"] == 1, name + assert new_graph["replays"] - old_graph["replays"] > 0, name + assert new_graph["capture_failures"] == 0, name + + +def host_undo_budget(geometry): + # BF16 K/V, 64 tagged rows per page, including pinned archive staging. + undo_rows = min( + geometry["max_context"], + geometry["window"] + geometry["max_step_tokens"] - 1, + ) + undo_pages = (undo_rows + 63) // 64 + row_bytes = geometry["model"]["n_kv_heads"] * geometry["model"]["head_dim"] * 2 + return geometry["ring_layers"] * ( + 64 * undo_pages * (2 * 64 * row_bytes + 64 * 4) + + 2 * geometry["max_step_tokens"] * row_bytes + ) + + +def require_exact_logits(candidate, baseline, tag): + import numpy as np + + for name, logits in (("ABI 2", baseline), ("ABI 3", candidate)): + if not np.isfinite(logits).all(): + raise RuntimeError(f"{tag}: {name} returned non-finite logits") + np.testing.assert_array_equal(candidate, baseline, err_msg=tag) + + +def require_performance(evidence): + """Block qualification on decode or lifecycle median regressions.""" + regressions = [ + f"d{dim}/{'c' if str(c).isdigit() else ''}{c}" + for dim, result in evidence.items() + for c, timing in { + **result["same_work_timings"], + **result.get("lifecycle_timings", {}), + }.items() + if timing["throughput_ratio"] < 0.98 + ] + if regressions: + raise RuntimeError("Over 2% throughput regression: " + ", ".join(regressions)) + + +def require_driver_contraction(before, compact): + released = before["live_KV_bytes"] - compact["live_KV_bytes"] + reserved_drop = ( + before["allocator_reserved_bytes"] - compact["allocator_reserved_bytes"] + ) + driver_drop = before["device_used_bytes"] - compact["device_used_bytes"] + # Require a material fixture and actual release, with room for CUDA pool + # page granularity and graph bookkeeping; lower live bytes alone do not pass. + if released < 16 * 1024**2: + raise RuntimeError("Driver contraction fixture released less than 16 MiB") + if reserved_drop < 8 * 1024**2 or driver_drop < 8 * 1024**2: + raise RuntimeError("Compaction did not return at least 8 MiB to the driver") + return { + "live_KV_drop_bytes": released, + "allocator_reserved_drop_bytes": reserved_drop, + "driver_used_drop_bytes": driver_drop, + } + + +def paired_timings(repeats): + timings = {} + for c in (1, 2, 4, 8, 16, 32, 64): + rounds = [] + for old_steps, new_steps, _, _ in repeats: + old = [old_steps[f"bench-c{c}-{i}"]["elapsed_seconds"] for i in range(20)] + new = [new_steps[f"bench-c{c}-{i}"]["elapsed_seconds"] for i in range(20)] + old_median, new_median = statistics.median(old), statistics.median(new) + rounds.append( + { + "abi2_median_s": old_median, + "abi3_median_s": new_median, + "throughput_ratio": old_median / new_median, + "cache_cpu_wall_s": { + f"abi{abi}": { + phase: statistics.median( + steps[f"bench-c{c}-{i}"]["cache_phase_seconds"][phase] + for i in range(20) + ) + for phase in steps[f"bench-c{c}-0"].get( + "cache_phase_seconds", {} + ) + } + for abi, steps in ((2, old_steps), (3, new_steps)) + }, + } + ) + ratio = statistics.median(r["throughput_ratio"] for r in rounds) + timings[c] = { + "rounds": rounds, + "throughput_ratio": ratio, + "investigate_over_2_percent_regression": ratio < 0.98, + } + lifecycle = {} + for phase in ("growth", "restore"): + for c in (1, 2, 4, 8, 16, 32, 64): + prefix = f"{phase}-c{c}-" + rounds = [] + for _, _, old_pairs, new_pairs in repeats: + totals = [ + sum( + response["elapsed_seconds"] + for request, response in pairs + if request.get("tag", "").startswith(prefix) + ) + for pairs in (old_pairs, new_pairs) + ] + assert all(t > 0 for t in totals) + rounds.append( + { + "abi2_total_s": totals[0], + "abi3_total_s": totals[1], + "throughput_ratio": totals[0] / totals[1], + } + ) + ratio = statistics.median(r["throughput_ratio"] for r in rounds) + lifecycle[f"{phase}-c{c}"] = { + "rounds": rounds, + "throughput_ratio": ratio, + "investigate_over_2_percent_regression": ratio < 0.98, + } + return timings, lifecycle + + +def write_qualification(output_dir, evidence, report_performance): + failure = None + try: + require_performance(evidence) + except RuntimeError as error: + failure = error + result = { + "timing_mode": "report-only" if report_performance else "enforced", + "performance_qualified": not report_performance and failure is None, + "timing_threshold_met": failure is None, + "performance_error": None if failure is None else str(failure), + "results": evidence, + } + (output_dir / "qualification.json").write_text(json.dumps(result, indent=2) + "\n") + print(json.dumps(result, indent=2)) + if report_performance: + print( + "PERFORMANCE_REPORT_ONLY: " + + (str(failure) if failure is not None else "all median ratios >= 0.98") + + "; performance not qualified" + ) + elif failure is not None: + raise failure + else: + print("PERFORMANCE_QUALIFIED: all median ratios >= 0.98") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--probe", required=True, type=Path) + parser.add_argument("--output-dir", required=True, type=Path) + parser.add_argument( + "--profile", + choices=("mini", "mg-ring"), + default="mini", + help="mg-ring uses production MG attention/cache geometry with small weights", + ) + parser.add_argument( + "--report-performance", + action="store_true", + help="Report timing regressions without failing PR CI; does not qualify perf", + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + evidence = {} + for dim in (128, 256) if args.profile == "mini" else (128,): + geometry = qualification_config(args.profile, dim) + baseline, old_steps, old_pairs = run( + args.probe.resolve(), args.output_dir, dim, 2, profile=args.profile + ) + candidate, new_steps, pairs = run( + args.probe.resolve(), args.output_dir, dim, 3, profile=args.profile + ) + assert baseline.keys() == candidate.keys() + for tag in baseline: + require_exact_logits(candidate[tag], baseline[tag], f"d{dim}/{tag}") + memory = {} + undo_budget = host_undo_budget(geometry) + memory_tags = ("decode64-first", "decode64-mixed", "before-6", "after-4") + savings_tags = set(memory_tags[1:]) + if args.profile == "mg-ring": + # The first heterogeneous phase is shorter than the 2K window. + # Also measure saturated Ring history, where headroom is removed. + memory_tags += ("bench-c64-19", "driver-before") + savings_tags = {"bench-c64-19", "driver-before"} + for tag in memory_tags: + old = old_steps[tag]["snapshot"] + new = new_steps[tag]["snapshot"] + combined = new["live_KV_bytes"] + new["device_staging_bytes"] + memory[tag] = { + "abi2_live_KV_bytes": old["live_KV_bytes"], + "abi3_live_KV_bytes": new["live_KV_bytes"], + "abi3_device_staging_bytes": new["device_staging_bytes"], + "abi3_host_undo_bytes": new["host_undo_bytes"], + "abi3_host_undo_budget_bytes": undo_budget, + "abi2_allocator_used_bytes": old["allocator_used_bytes"], + "abi3_allocator_used_bytes": new["allocator_used_bytes"], + } + # Before either ring reaches its window there is little duplicated + # headroom to remove; shared staging can cost more at this point. + if tag in savings_tags: + assert combined < old["live_KV_bytes"], (tag, old, new) + assert new["allocator_used_bytes"] < old["allocator_used_bytes"], ( + tag, + old, + new, + ) + assert new["host_undo_bytes"] > 0 + assert new["host_undo_bytes"] <= undo_budget, (tag, new, undo_budget) + peak_host_undo = max(reply["snapshot"]["host_undo_bytes"] for _, reply in pairs) + assert peak_host_undo <= undo_budget, (peak_host_undo, undo_budget) + compact = next( + reply["snapshot"] for request, reply in pairs if request["op"] == "compact" + ) + before = new_steps["before-6"]["snapshot"] + assert compact["live_KV_bytes"] < before["live_KV_bytes"] + assert compact["allocator_used_bytes"] < before["allocator_used_bytes"] + assert compact["allocator_reserved_bytes"] <= before["allocator_reserved_bytes"] + require_graph_contraction( + new_steps["graph-before-1-64"]["snapshot"], + new_steps["graph-after-1-64"]["snapshot"], + ) + driver_before = new_steps["driver-before"]["snapshot"] + driver_compact = next( + reply["snapshot"] + for request, reply in pairs + if request.get("tag") == "driver-compact" + ) + driver = require_driver_contraction(driver_before, driver_compact) + driver["before"] = driver_before + driver["compact"] = driver_compact + driver["after"] = new_steps["driver-after"]["snapshot"] + reuse_before = new_steps["reuse-before"]["snapshot"] + reuse_compact = next( + reply["snapshot"] + for request, reply in pairs + if request.get("tag") == "reuse-compact" + ) + assert reuse_compact["flat_capacity"] <= 4, reuse_compact + assert reuse_compact["live_KV_bytes"] < reuse_before["live_KV_bytes"] + repeats = [(old_steps, new_steps, old_pairs, pairs)] + for repeat in (1, 2, 3): + # Four rounds balance AB/BA order without re-exporting. + order = (3, 2) if repeat % 2 else (2, 3) + results = { + abi: run( + args.probe.resolve(), + args.output_dir, + dim, + abi, + repeat, + profile=args.profile, + ) + for abi in order + } + for tag in results[2][0]: + require_exact_logits( + results[3][0][tag], results[2][0][tag], f"d{dim}/{tag}" + ) + repeats.append((results[2][1], results[3][1], results[2][2], results[3][2])) + timings, lifecycle = paired_timings(repeats) + evidence[dim] = { + "profile": args.profile, + "geometry": geometry, + "exact_logits": True, + "memory": memory, + "peak_host_undo_bytes": peak_host_undo, + "host_undo_budget_bytes": undo_budget, + "driver_contraction": driver, + "reused_owner_compaction": { + "before": reuse_before, + "compact": reuse_compact, + "after": new_steps["reuse-after"]["snapshot"], + }, + "same_work_timings": timings, + "lifecycle_timings": lifecycle, + } + write_qualification(args.output_dir, evidence, args.report_performance) + print( + "ABI-3 native logits, private memory, shared staging and per-stage replay passed" + ) + + +if __name__ == "__main__": + main() diff --git a/examples/models/muse-glimmer/tests/check_runtime_kv_columns.py b/examples/models/muse-glimmer/tests/check_runtime_kv_columns.py new file mode 100644 index 00000000000..d3f554ef5e1 --- /dev/null +++ b/examples/models/muse-glimmer/tests/check_runtime_kv_columns.py @@ -0,0 +1,248 @@ +# 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. + +"""Compare actual ABI-2 CUDA allocations and logits with the fixed-column ABI. + +Exports the same tiny flat/ring model twice and drives the native probe through +row growth, wrapped-history cloning, sparse-owner compaction and graph replay. +""" + +import argparse +import json +import subprocess +import sys +from dataclasses import replace +from pathlib import Path + +import numpy as np +import torch +from executorch.examples.models.muse_glimmer.export.export_solo import ( + export_cuda_batching, +) +from executorch.examples.models.muse_glimmer.model.model import MuseGlimmerModel +from executorch.examples.models.muse_glimmer.tests.test_pipeline import TINY_CONFIG + + +def commands(runtime_columns: bool) -> list[dict]: + """Cross row/column resize boundaries with deterministic inputs.""" + requests = [ + {"op": "new"}, + { + "op": "step", + "tokens": list(range(32)), + "seq_ids": [0] * 32, + "select": [31], + "tag": "prefill", + "check_reentrancy": True, + }, + { + "op": "step", + "tokens": list(range(32, 48)), + "seq_ids": [0] * 16, + "select": [15], + "tag": "wrap", + }, + {"op": "clone", "seq_id": 0, "upto": 48}, + {"op": "new"}, + { + "op": "step", + "tokens": [13, 13, 19], + "seq_ids": [0, 1, 2], + "select": [0, 1, 2], + "tag": "grow", + }, + {"op": "remove", "seq_id": 0}, + ] + for stage in range(2): + if stage == 1 and runtime_columns: + requests.append({"op": "compact", "spare_columns": 0}) + for repeat in range(5): + requests.append( + { + "op": "step", + "tokens": [20 + repeat, 30 + repeat], + "seq_ids": [1, 2], + "select": [0, 1], + "tag": f"decode-{stage}-{repeat}", + } + ) + requests.extend([{"op": "remove", "seq_id": 1}, {"op": "remove", "seq_id": 2}]) + if runtime_columns: + requests.append({"op": "idle"}) + requests.extend( + [ + {"op": "new"}, + { + "op": "step", + "tokens": [5, 6, 7, 8], + "seq_ids": [0] * 4, + "select": [3], + "tag": "reuse", + }, + ] + ) + requests.extend({"op": "new"} for _ in range(4)) + requests.append( + { + "op": "step", + "tokens": [9, 10, 11, 12, 13], + "seq_ids": list(range(5)), + "select": list(range(5)), + "tag": "burst", + } + ) + requests.extend([{"op": "remove", "seq_id": 3}, {"op": "remove", "seq_id": 4}]) + if runtime_columns: + requests.extend([{"op": "idle"}, {"op": "idle"}]) + requests.extend([{"op": "new"}, {"op": "new"}]) + requests.append( + { + "op": "step", + "tokens": [14, 15, 16, 17, 18], + "seq_ids": list(range(5)), + "select": list(range(5)), + "tag": "burst-reused", + } + ) + for request in requests: + if request["op"] == "step": + request["save_logits"] = True + return requests + + +def run(probe: Path, root: Path, runtime_columns: bool) -> tuple[dict, list[dict]]: + """Export and drive one ABI using the same model weights and queries.""" + artifact = root / ("abi2" if runtime_columns else "abi1") + artifact.mkdir() + torch.manual_seed(123) + config = replace( + TINY_CONFIG, + dim=128, + n_layers=2, + n_heads=2, + n_kv_heads=1, + global_attn_cfg="[16,0]", + ) + model = MuseGlimmerModel(config).to(torch.bfloat16).eval() + model.activation_dtype = torch.bfloat16 + export_cuda_batching( + model, + config, + str(artifact), + max_step_tokens=32, + max_cells=512, + forward_sizes=(1, 2, 4, 8, 16), + kv_layout="sequence", + max_kv_seqs=8, + runtime_kv_columns=runtime_columns, + ) + output = artifact / "logits" + output.mkdir() + requests = commands(runtime_columns) + completed = subprocess.run( + [ + str(probe), + f"--pte={artifact / 'model.pte'}", + f"--data_path={artifact / 'aoti_cuda_blob.ptd'}", + f"--output_dir={output}", + "--max_sessions=8", + "--max_context=64", + "--initial_kv_capacity=4", + ], + input="".join(json.dumps(r) + "\n" for r in requests), + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + timeout=300, + ) + (artifact / "probe.stderr.log").write_text(completed.stderr) + (artifact / "probe.jsonl").write_text(completed.stdout) + if completed.returncode: + print(completed.stderr, file=sys.stderr) + print(completed.stdout, file=sys.stderr) + completed.check_returncode() + responses = [json.loads(line) for line in completed.stdout.splitlines()] + assert responses[0]["ready"] and len(responses) == len(requests) + 1 + graph = next( + method + for method in responses[-1]["snapshot"]["method_calls"] + if method["method"] == "forward_2" + ) + assert graph["captures"] == (2 if runtime_columns else 1), graph + assert graph["replays"] > graph["captures"], graph + assert graph["capture_failures"] == 0, graph + logits = {} + for request, response in zip(requests, responses[1:], strict=True): + assert response["op"] == request["op"] and not response.get("failed") + if request["op"] == "step": + arrays = [ + np.fromfile(item["file"], dtype=np.float32).reshape(item["shape"]) + for item in response["logits"] + ] + logits[request["tag"]] = np.concatenate(arrays) + return logits, responses + + +def main() -> None: + """Require native ABI-2 numerical agreement and memory contraction.""" + parser = argparse.ArgumentParser() + parser.add_argument("--probe", required=True, type=Path) + parser.add_argument("--output-dir", required=True, type=Path) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + fixed, fixed_responses = run(args.probe.resolve(), args.output_dir, False) + dynamic, responses = run(args.probe.resolve(), args.output_dir, True) + assert fixed.keys() == dynamic.keys() + for tag in fixed: + np.testing.assert_allclose(dynamic[tag], fixed[tag], atol=5e-2, rtol=0) + np.testing.assert_array_equal(dynamic[tag].argmax(-1), fixed[tag].argmax(-1)) + np.testing.assert_allclose( + dynamic["grow"][0], dynamic["grow"][1], atol=5e-2, rtol=0 + ) + steps = [r for r in responses if r.get("op") == "step"] + fixed_steps = [r for r in fixed_responses if r.get("op") == "step"] + assert len(fixed_steps) == len(steps) + for reference, candidate in zip(fixed_steps[:-2], steps[:-2], strict=True): + assert ( + candidate["snapshot"]["live_KV_bytes"] + < reference["snapshot"]["live_KV_bytes"] + ) + for reference, candidate in zip(fixed_steps[-2:], steps[-2:], strict=True): + assert ( + candidate["snapshot"]["live_KV_bytes"] + <= reference["snapshot"]["live_KV_bytes"] + ) + assert steps[0]["snapshot"]["physical_columns"] == 2 + assert steps[2]["snapshot"]["physical_columns"] == 5 + assert steps[2]["snapshot"]["declared_columns"] == 9 + compactions = [ + r["snapshot"] for r in responses if r.get("op") in ("compact", "idle") + ] + assert [m["physical_columns"] for m in compactions] == [3, 2, 7, 7] + assert compactions[0]["live_KV_bytes"] < steps[2]["snapshot"]["live_KV_bytes"] + before_compaction = steps[7]["snapshot"] + assert ( + compactions[0]["allocator_used_bytes"] + < before_compaction["allocator_used_bytes"] + ) + assert ( + compactions[0]["allocator_reserved_bytes"] + <= before_compaction["allocator_reserved_bytes"] + ) + assert ( + compactions[-1]["column_resize_count"] == compactions[-2]["column_resize_count"] + ) + assert steps[-2]["snapshot"]["physical_columns"] == 9 + assert steps[-1]["snapshot"]["physical_columns"] == 7 + assert ( + steps[-1]["snapshot"]["column_resize_count"] + == compactions[-1]["column_resize_count"] + ) + print("ABI-2 native logits, ring cloning, compaction and graph replay passed") + + +if __name__ == "__main__": + main() diff --git a/examples/models/muse-glimmer/tests/runtime_kv_columns_probe.cpp b/examples/models/muse-glimmer/tests/runtime_kv_columns_probe.cpp new file mode 100644 index 00000000000..c21cad69c02 --- /dev/null +++ b/examples/models/muse-glimmer/tests/runtime_kv_columns_probe.cpp @@ -0,0 +1,333 @@ +/* + * 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. + */ + +// A serialized diagnostic transport over the actual CUDA batching executor. +// Raw cache IDs are never mixed with ServingRuntime or SessionTable IDs. +#include +#include +#include +#include +#if __has_include() +#include +#define ET_RUNTIME_KV_PROBE_HAS_NVTX 1 +#else +#define ET_RUNTIME_KV_PROBE_HAS_NVTX 0 +#endif +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +DEFINE_string(pte, "", "Solo text-only CUDA model"); +DEFINE_string(data_path, "", "External weight blob"); +DEFINE_string( + output_dir, + "", + "Existing unique directory for numerical outputs"); +DEFINE_int32( + max_sessions, + 21, + "Logical cache admission including snapshot owners"); +DEFINE_int32(max_context, 131072, "Logical model context"); +DEFINE_int32(initial_kv_capacity, 512, "Initial logical rows per column"); + +namespace cb = executorch::backends::cuda::batching; +using executorch::runtime::Error; +using Json = nlohmann::json; + +namespace { + +class DiagnosticRange final { + public: + explicit DiagnosticRange(const std::string& label) { +#if ET_RUNTIME_KV_PROBE_HAS_NVTX + nvtxRangePushA(label.c_str()); +#else + (void)label; +#endif + } + ~DiagnosticRange() { +#if ET_RUNTIME_KV_PROBE_HAS_NVTX + nvtxRangePop(); +#endif + } + DiagnosticRange(const DiagnosticRange&) = delete; + DiagnosticRange& operator=(const DiagnosticRange&) = delete; +}; + +void require(bool condition, const char* message) { + if (!condition) { + throw std::runtime_error(message); + } +} + +Json snapshot(cb::CudaExecutor& executor) { + require(cudaDeviceSynchronize() == cudaSuccess, "snapshot synchronization"); + size_t free_bytes = 0, total_bytes = 0; + require( + cudaMemGetInfo(&free_bytes, &total_bytes) == cudaSuccess, + "device memory"); + int device = 0; + require(cudaGetDevice(&device) == cudaSuccess, "device ordinal"); + const auto kv = executor.kv_metrics(); + Json result = { + {"pid", getpid()}, + {"physical_columns", kv.physical_columns}, + {"declared_columns", kv.declared_columns}, + {"live_sequences", kv.live_sequences}, + {"logical_length", kv.logical_length}, + {"flat_capacity", kv.flat_capacity}, + {"live_KV_bytes", kv.allocated_bytes}, + {"device_staging_bytes", kv.device_staging_bytes}, + {"host_undo_bytes", kv.host_undo_bytes}, + {"cache_prepare_time_ns", kv.prepare_time_ns}, + {"cache_commit_time_ns", kv.commit_time_ns}, + {"archive_transfer_time_ns", kv.archive_transfer_time_ns}, + {"archive_append_time_ns", kv.archive_append_time_ns}, + {"row_growth_count", kv.growth_count}, + {"column_resize_count", kv.column_resize_count}, + {"device_used_bytes", total_bytes - free_bytes}, + }; + const auto pool = + executorch::extension::cuda::CudaAllocator::pool_for_device(device); + if (pool != nullptr) { + uint64_t used = 0, reserved = 0, used_high = 0, reserved_high = 0; + require( + cudaMemPoolGetAttribute(pool, cudaMemPoolAttrUsedMemCurrent, &used) == + cudaSuccess && + cudaMemPoolGetAttribute( + pool, cudaMemPoolAttrReservedMemCurrent, &reserved) == + cudaSuccess, + "allocator memory attributes"); + require( + cudaMemPoolGetAttribute(pool, cudaMemPoolAttrUsedMemHigh, &used_high) == + cudaSuccess && + cudaMemPoolGetAttribute( + pool, cudaMemPoolAttrReservedMemHigh, &reserved_high) == + cudaSuccess, + "allocator high water attributes"); + result["allocator_used_bytes"] = used; + result["allocator_reserved_bytes"] = reserved; + result["allocator_used_high_bytes"] = used_high; + result["allocator_reserved_high_bytes"] = reserved_high; + } + result["method_calls"] = Json::array(); + for (const auto& method : executor.method_calls()) { + const auto graph = executor.graph_metrics(method.name); + result["method_calls"].push_back( + {{"method", method.name}, + {"calls", method.calls}, + {"captures", graph.captures}, + {"replays", graph.replays}, + {"capture_failures", graph.capture_failures}}); + } + return result; +} + +Json run_step(cb::CudaExecutor& executor, const Json& request) { + cb::RawTargetStep step; + step.tokens = request.at("tokens").get>(); + step.seq_ids = request.at("seq_ids").get>(); + require( + !step.tokens.empty() && step.tokens.size() == step.seq_ids.size(), + "token and sequence widths"); + auto& control = executor.cache_control(); + std::map next; + for (const auto id : step.seq_ids) { + const auto inserted = next.emplace(id, control.pos(id)); + step.positions.push_back(inserted.first->second++); + } + step.logit_indices = request.at("select").get>(); + std::vector argmax; + Json outputs = Json::array(); + const bool save_logits = request.value("save_logits", false); + const std::string tag = request.value("tag", std::string("step")); + require( + !tag.empty() && tag.find("..") == std::string::npos && + tag.find_first_not_of( + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.") == + std::string::npos, + "diagnostic tag"); + size_t part = 0; + const bool ok = + executor.execute_raw(step, [&](const cb::RawTargetOutput& out) { + if (request.value("check_reentrancy", false)) { + require( + !executor.execute_raw( + step, [](const cb::RawTargetOutput&) { return true; }), + "nested execute must be rejected"); + require( + executor.compact_kv_columns(0) == Error::InvalidState, + "nested compaction must be rejected"); + } + const size_t rows = out.selected_indices.size(); + if (rows == 0) { + return true; + } + if (save_logits) { + const auto& logits = out.logits; + require( + logits.dim() == 2 && + logits.scalar_type() == executorch::aten::ScalarType::Float && + logits.strides()[1] == 1, + "expected dense-row FP32 selected logits"); + const size_t vocab = executor.vocab_size(); + std::vector host(rows * vocab); + if (logits.device_type() == executorch::aten::DeviceType::CUDA) { + require( + cudaDeviceSynchronize() == cudaSuccess, + "logits synchronization"); + require( + cudaMemcpy2D( + host.data(), + vocab * sizeof(float), + logits.const_data_ptr(), + logits.strides()[0] * sizeof(float), + vocab * sizeof(float), + rows, + cudaMemcpyDeviceToHost) == cudaSuccess, + "logits device copy"); + } else { + for (size_t row = 0; row < rows; ++row) { + std::copy_n( + logits.const_data_ptr() + row * logits.strides()[0], + vocab, + host.data() + row * vocab); + } + } + const auto path = std::filesystem::path(FLAGS_output_dir) / + (tag + "-" + std::to_string(part++) + ".f32"); + require(!std::filesystem::exists(path), "preserve prior logits"); + std::ofstream file(path, std::ios::binary); + file.write( + reinterpret_cast(host.data()), + static_cast(host.size() * sizeof(float))); + require(file.good(), "write logits"); + outputs.push_back( + {{"file", path.string()}, + {"shape", {rows, vocab}}, + {"selected_indices", out.selected_indices}}); + } + if (request.value("argmax", true)) { + const auto sampled = executor.argmax_rows(out.logits, rows); + require(sampled.has_value(), "device argmax"); + argmax.insert(argmax.end(), sampled->begin(), sampled->end()); + } + return true; + }); + require(ok, "actual executor step failed; do not continue owners"); + return {{"argmax", argmax}, {"logits", outputs}}; +} + +} // namespace + +int main(int argc, char** argv) { + gflags::ParseCommandLineFlags(&argc, &argv, true); + require( + !FLAGS_pte.empty() && std::filesystem::is_directory(FLAGS_output_dir), + "model and unique output directory required"); + const int protocol_fd = dup(STDOUT_FILENO); + require(protocol_fd >= 0, "duplicate stdout"); + require(dup2(STDERR_FILENO, STDOUT_FILENO) >= 0, "route model diagnostics"); + std::FILE* protocol = fdopen(protocol_fd, "w"); + require(protocol != nullptr, "protocol output"); + try { + cb::CudaExecutorConfig config; + config.model_path = FLAGS_pte; + if (!FLAGS_data_path.empty()) { + config.data_files.push_back(FLAGS_data_path); + } + config.max_sessions = FLAGS_max_sessions; + config.max_session_tokens = FLAGS_max_context; + config.initial_capacity = FLAGS_initial_kv_capacity; + config.options.cuda_graph_for_static_methods = true; + auto created = cb::CudaExecutor::create(config); + require(created.ok(), "create actual CUDA executor"); + auto executor = std::move(*created); + require(executor->initialize(), "initialize actual CUDA executor"); + std::fprintf( + protocol, + "%s\n", + Json({{"ready", true}, {"snapshot", snapshot(*executor)}}) + .dump() + .c_str()); + std::fflush(protocol); + std::string line; + while (std::getline(std::cin, line)) { + const auto request = Json::parse(line); + const std::string op = request.at("op"); + const DiagnosticRange range(request.value("tag", op)); + Json result; + const auto start = std::chrono::steady_clock::now(); + auto& control = executor->cache_control(); + if (op == "new") { + const auto id = control.seq_new(); + require(id.has_value(), "new owner"); + result["seq_id"] = *id; + } else if (op == "remove") { + require( + control.seq_rm(request.at("seq_id").get()), + "remove owner"); + } else if (op == "clone") { + const auto id = control.seq_clone( + request.at("seq_id").get(), request.at("upto").get()); + require(id.has_value(), "clone owner"); + result["seq_id"] = *id; + } else if (op == "rewind") { + require( + control.rewind( + request.at("seq_id").get(), + request.at("position").get()), + "rewind owner"); + } else if (op == "clear") { + control.clear(); + } else if (op == "compact") { + const Error compact_error = + executor->compact_kv_columns(request.value("spare_columns", 0)); + const std::string detail = "compact physical KV: error=" + + std::to_string(static_cast(compact_error)); + require(compact_error == Error::Ok, detail.c_str()); + } else if (op == "idle") { + std::this_thread::sleep_for(std::chrono::milliseconds(550)); + executor->on_idle(); + } else if (op == "step") { + result = run_step(*executor, request); + } else if (op != "metrics") { + throw std::runtime_error("unknown diagnostic operation"); + } + require(cudaDeviceSynchronize() == cudaSuccess, "operation completion"); + result["elapsed_seconds"] = std::chrono::duration( + std::chrono::steady_clock::now() - start) + .count(); + result["snapshot"] = snapshot(*executor); + result["op"] = op; + std::fprintf(protocol, "%s\n", result.dump().c_str()); + std::fflush(protocol); + } + } catch (const std::exception& error) { + std::fprintf( + protocol, + "%s\n", + Json({{"failed", true}, {"detail", error.what()}}).dump().c_str()); + std::fflush(protocol); + std::fclose(protocol); + return 1; + } + std::fclose(protocol); + return 0; +} diff --git a/examples/models/muse-glimmer/tests/test_private_kv_rows_gate.py b/examples/models/muse-glimmer/tests/test_private_kv_rows_gate.py new file mode 100644 index 00000000000..bf596d066ef --- /dev/null +++ b/examples/models/muse-glimmer/tests/test_private_kv_rows_gate.py @@ -0,0 +1,407 @@ +# 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 ast +import importlib.util +import io +import json +import tempfile +import types +import unittest +from contextlib import redirect_stdout +from pathlib import Path +from unittest import mock + +spec = importlib.util.spec_from_file_location( + "private_kv_rows_checker", Path(__file__).with_name("check_private_kv_rows.py") +) +checker = importlib.util.module_from_spec(spec) +spec.loader.exec_module(checker) + + +class PrivateKVRowsPerformanceGateTest(unittest.TestCase): + def test_export_resource_report_converts_platform_rss_units(self): + resource = types.SimpleNamespace( + RUSAGE_SELF=0, + getrusage=lambda _: types.SimpleNamespace(ru_maxrss=17), + ) + for platform, expected in (("darwin", 17), ("linux", 17 * 1024)): + with ( + self.subTest(platform=platform), + mock.patch.dict("sys.modules", {"resource": resource}), + mock.patch.object(checker.sys, "platform", platform), + mock.patch.object(Path, "read_text", return_value="max\n"), + redirect_stdout(io.StringIO()) as output, + ): + result = checker.report_export_resources("before-export") + self.assertEqual(result["cpu_peak_rss_bytes"], expected) + self.assertEqual(result["tag"], "before-export") + if platform == "linux": + self.assertEqual(result["cgroup_memory.max"], "max") + self.assertEqual(json.loads(output.getvalue().split(" ", 1)[1]), result) + + def test_export_resource_report_tolerates_unavailable_cgroup_files(self): + with ( + mock.patch.object(checker.sys, "platform", "linux"), + mock.patch.object(Path, "read_text", side_effect=FileNotFoundError), + redirect_stdout(io.StringIO()), + ): + result = checker.report_export_resources("after-export") + self.assertEqual(result["tag"], "after-export") + self.assertFalse(any(key.startswith("cgroup_") for key in result)) + + def test_native_tokens_distinguish_owners_positions_and_reuse(self): + for profile in ("mini", "mg-ring"): + requests = checker.commands(profile) + steps = { + request["tag"]: request + for request in requests + if request["op"] == "step" + } + with self.subTest(profile=profile): + self.assertEqual(len(set(steps["decode64-first"]["tokens"])), 64) + self.assertGreater(len(set(steps["long"]["tokens"])), 80) + self.assertNotEqual( + steps["bench-c1-0"]["tokens"], steps["bench-c1-1"]["tokens"] + ) + self.assertNotEqual( + steps["reuse-long"]["tokens"][0], + steps["reuse-before"]["tokens"][0], + ) + self.assertTrue(steps["reuse-after"]["save_logits"]) + for request in steps.values(): + self.assertEqual(len(request["tokens"]), len(request["seq_ids"])) + self.assertTrue(all(0 < token < 256 for token in request["tokens"])) + self.assertEqual(requests, checker.commands(profile)) + + def test_numerical_gate_rejects_matching_nonfinite_logits(self): + for value in (float("nan"), float("inf"), -float("inf")): + with self.subTest(value=value): + with self.assertRaisesRegex(RuntimeError, "ABI 2.*non-finite"): + checker.require_exact_logits([value], [value], "matching") + with self.assertRaisesRegex(RuntimeError, "ABI 3.*non-finite"): + checker.require_exact_logits([value], [1.0], "candidate") + checker.require_exact_logits([1.0, -2.0], [1.0, -2.0], "finite") + with self.assertRaises(AssertionError): + checker.require_exact_logits([1.0], [2.0], "mismatch") + + def test_cpu_phase_report_keeps_total_throughput_gate(self): + steps, pairs = {}, [] + for c in (1, 2, 4, 8, 16, 32, 64): + for i in range(20): + steps[f"bench-c{c}-{i}"] = { + "elapsed_seconds": 0.002, + "cache_phase_seconds": { + "cache_prepare_time_s": 0.0001, + "cache_commit_time_s": 0.0003, + "archive_transfer_time_s": 0.0002, + "archive_append_time_s": 0.00001, + }, + } + for phase in ("growth", "restore"): + pairs.append(({"tag": f"{phase}-c{c}-0"}, {"elapsed_seconds": 0.001})) + old_steps = { + tag: {**response, "elapsed_seconds": 0.001} + for tag, response in steps.items() + } + timings, lifecycle = checker.paired_timings([(old_steps, steps, pairs, pairs)]) + self.assertEqual(timings[1]["throughput_ratio"], 0.5) + self.assertEqual( + timings[1]["rounds"][0]["cache_cpu_wall_s"]["abi3"]["cache_commit_time_s"], + 0.0003, + ) + with self.assertRaisesRegex(RuntimeError, "d128/c1"): + checker.require_performance( + {128: {"same_work_timings": timings, "lifecycle_timings": lifecycle}} + ) + + def test_artifact_and_output_distinguish_report_only_from_qualification(self): + for report_only in (True, False): + for ratio in (0.98, 0.97): + with ( + self.subTest(report_only=report_only, ratio=ratio), + tempfile.TemporaryDirectory() as directory, + redirect_stdout(io.StringIO()) as output, + ): + evidence = { + 128: {"same_work_timings": {1: {"throughput_ratio": ratio}}} + } + if not report_only and ratio < 0.98: + with self.assertRaisesRegex(RuntimeError, "d128/c1"): + checker.write_qualification( + Path(directory), evidence, False + ) + else: + checker.write_qualification( + Path(directory), evidence, report_only + ) + artifact = json.loads( + (Path(directory) / "qualification.json").read_text() + ) + self.assertEqual( + artifact["timing_mode"], + "report-only" if report_only else "enforced", + ) + self.assertEqual(artifact["timing_threshold_met"], ratio >= 0.98) + self.assertEqual( + artifact["performance_qualified"], + not report_only and ratio >= 0.98, + ) + self.assertEqual( + artifact["results"]["128"]["same_work_timings"]["1"][ + "throughput_ratio" + ], + ratio, + ) + if report_only: + self.assertIn("PERFORMANCE_REPORT_ONLY", output.getvalue()) + self.assertNotIn("PERFORMANCE_QUALIFIED:", output.getvalue()) + + def test_compaction_graph_gate_checks_each_exported_stage(self): + before = { + "method_calls": [ + { + "method": f"forward_{width}", + "captures": 1, + "replays": 2, + "capture_failures": 0, + } + for width in (1, 2, 4, 8, 16, 32, 64) + ] + } + after = { + "method_calls": [ + {**method, "captures": 2, "replays": 3} + for method in before["method_calls"] + ] + } + checker.require_graph_contraction(before, after) + for width in (1, 2, 4, 8, 16, 32, 64): + method = checker.graph(after, f"forward_{width}") + for field, invalid in ( + ("captures", 3), + ("replays", 2), + ("capture_failures", 1), + ): + with self.subTest(width=width, field=field): + original = method[field] + method[field] = invalid + with self.assertRaisesRegex(AssertionError, f"forward_{width}"): + checker.require_graph_contraction(before, after) + method[field] = original + + def test_boundary_and_improvements_qualify(self): + checker.require_performance( + { + 128: { + "same_work_timings": { + 1: {"throughput_ratio": 0.98}, + 64: {"throughput_ratio": 1.2}, + } + } + } + ) + + def test_measured_regression_blocks_even_without_flag(self): + with self.assertRaisesRegex(RuntimeError, "d256/c4"): + checker.require_performance( + {256: {"same_work_timings": {4: {"throughput_ratio": 0.979}}}} + ) + + def test_one_bad_concurrency_blocks_the_complete_gate(self): + with self.assertRaisesRegex(RuntimeError, "d128/c64"): + checker.require_performance( + { + 128: { + "same_work_timings": { + 1: {"throughput_ratio": 1.01}, + 64: {"throughput_ratio": 0.7}, + } + }, + 256: {"same_work_timings": {64: {"throughput_ratio": 1.1}}}, + } + ) + + def test_lifecycle_regression_is_not_hidden_by_fast_decode(self): + with self.assertRaisesRegex(RuntimeError, "d128/growth-c64"): + checker.require_performance( + { + 128: { + "same_work_timings": {64: {"throughput_ratio": 1.3}}, + "lifecycle_timings": {"growth-c64": {"throughput_ratio": 0.5}}, + } + } + ) + + def test_native_workload_keeps_lifecycle_operations_in_bounds(self): + for profile in ("mini", "mg-ring"): + with self.subTest(profile=profile): + self.check_workload(profile) + + def check_workload(self, profile): + geometry = checker.qualification_config(profile, 128) + lengths = {} + written = {} + counts = {"clone": 0, "rewind": 0, "growth": 0} + for request in checker.commands(profile): + op = request["op"] + if op == "clear": + lengths.clear() + written.clear() + elif op == "new": + owner = next(i for i in range(64) if i not in lengths) + lengths[owner] = 0 + written[owner] = 0 + elif op == "remove": + del lengths[request["seq_id"]] + del written[request["seq_id"]] + elif op == "clone": + owner = next(i for i in range(64) if i not in lengths) + source = request["seq_id"] + self.assertLessEqual(request["upto"], lengths[source]) + self.assertGreaterEqual( + request["upto"], + max(0, written[source] - geometry["max_step_tokens"]), + ) + lengths[owner] = request["upto"] + written[owner] = written[source] + counts["clone"] += request.get("tag", "").startswith("restore-") + elif op == "rewind": + owner = request["seq_id"] + old = lengths[owner] + self.assertLessEqual(request["position"], old) + self.assertGreaterEqual( + request["position"], + max(0, written[owner] - geometry["max_step_tokens"]), + ) + lengths[owner] = request["position"] + counts["rewind"] += request.get("tag", "").startswith("restore-") + elif op == "step": + self.assertLessEqual( + len(request["seq_ids"]), geometry["max_step_tokens"] + ) + for owner in request["seq_ids"]: + lengths[owner] += 1 + written[owner] = max(written[owner], lengths[owner]) + self.assertLessEqual(lengths[owner], geometry["max_context"]) + counts["growth"] += request.get("tag", "").startswith("growth-c") + self.assertLessEqual(len(lengths), 64) + self.assertEqual(counts["clone"], 7 * 8) + self.assertEqual(counts["rewind"], 7 * 8) + self.assertEqual(counts["growth"], 2 * (1 + 2 + 4 + 8 + 16 + 32 + 64)) + + def test_production_profile_matches_mg_attention_geometry(self): + source = Path(__file__).parents[1] / "model/model.py" + tree = ast.parse(source.read_text()) + config = next( + node + for node in tree.body + if isinstance(node, ast.ClassDef) and node.name == "MuseGlimmerConfig" + ) + defaults = { + node.target.id: ast.literal_eval(node.value) + for node in config.body + if isinstance(node, ast.AnnAssign) and node.value is not None + } + geometry = checker.qualification_config("mg-ring", 128) + for field in ( + "n_layers", + "n_heads", + "n_kv_heads", + "head_dim", + "global_attn_cfg", + ): + self.assertEqual(geometry["model"][field], defaults[field]) + pattern = ast.literal_eval(defaults["global_attn_cfg"]) + self.assertEqual( + geometry["ring_layers"], + sum(pattern[i % len(pattern)] > 0 for i in range(defaults["n_layers"])), + ) + self.assertEqual(geometry["window"], 2048) + self.assertEqual(geometry["max_step_tokens"], 4096) + self.assertEqual(geometry["max_context"], 131072) + self.assertLess(geometry["model"]["dim"], defaults["dim"]) + with self.assertRaises(ValueError): + checker.qualification_config("mg-ring", 256) + + def test_production_ring_replays_evicted_history_at_rollback_floor(self): + requests = checker.commands("mg-ring") + seeds = [ + request + for request in requests + if request.get("tag", "").startswith("production-ring-seed-") + ] + self.assertEqual([len(r["tokens"]) for r in seeds], [4096, 4096]) + self.assertNotEqual(seeds[0]["tokens"], seeds[1]["tokens"]) + last_seed = requests.index(seeds[-1]) + self.assertEqual( + requests[last_seed + 1 : last_seed + 3], + [ + {"op": "clone", "seq_id": 0, "upto": 4096}, + {"op": "rewind", "seq_id": 0, "position": 4096}, + ], + ) + replay = requests[last_seed + 3] + self.assertEqual(replay["tag"], "production-ring-floor-replay") + self.assertTrue(replay["save_logits"]) + self.assertEqual(replay["seq_ids"], [0, 1]) + + def test_production_host_budget_counts_all_39_ring_layers(self): + geometry = checker.qualification_config("mg-ring", 128) + expected = 39 * (64 * 96 * (2 * 64 * 512 + 64 * 4) + 2 * 4096 * 512) + self.assertEqual(checker.host_undo_budget(geometry), expected) + self.assertGreater(expected, 14 * 1024**3) + self.assertLess(expected, 15 * 1024**3) + + def test_driver_contraction_cannot_pass_on_live_bytes_alone(self): + before = { + "live_KV_bytes": 32 * 1024**2, + "allocator_reserved_bytes": 64 * 1024**2, + "device_used_bytes": 128 * 1024**2, + } + after = { + "live_KV_bytes": 1024**2, + "allocator_reserved_bytes": before["allocator_reserved_bytes"], + "device_used_bytes": before["device_used_bytes"], + } + with self.assertRaisesRegex(RuntimeError, "return at least 8 MiB"): + checker.require_driver_contraction(before, after) + after["allocator_reserved_bytes"] -= 16 * 1024**2 + with self.assertRaisesRegex(RuntimeError, "return at least 8 MiB"): + checker.require_driver_contraction(before, after) + after["device_used_bytes"] -= 16 * 1024**2 + self.assertEqual( + checker.require_driver_contraction(before, after)["driver_used_drop_bytes"], + 16 * 1024**2, + ) + after["live_KV_bytes"] = 31 * 1024**2 + with self.assertRaisesRegex(RuntimeError, "less than 16 MiB"): + checker.require_driver_contraction(before, after) + + def test_timings_count_lifecycle_work_and_exclude_verification(self): + old_steps, new_steps, old_pairs, new_pairs = {}, {}, [], [] + for c in (1, 2, 4, 8, 16, 32, 64): + for i in range(20): + old_steps[f"bench-c{c}-{i}"] = {"elapsed_seconds": 10} + new_steps[f"bench-c{c}-{i}"] = {"elapsed_seconds": 5} + for phase, old, new in (("growth", 3, 2), ("restore", 7, 4)): + for op in ("clone", "step"): + request = {"tag": f"{phase}-c{c}-0-{op}"} + old_pairs.append((request, {"elapsed_seconds": old})) + new_pairs.append((request, {"elapsed_seconds": new})) + request = {"tag": f"growth-verify-c{c}"} + old_pairs.append((request, {"elapsed_seconds": 1000})) + new_pairs.append((request, {"elapsed_seconds": 1})) + repeats = [(old_steps, new_steps, old_pairs, new_pairs)] * 4 + decode, lifecycle = checker.paired_timings(repeats) + for c in decode: + self.assertEqual(decode[c]["throughput_ratio"], 2) + self.assertEqual(lifecycle[f"growth-c{c}"]["throughput_ratio"], 1.5) + self.assertEqual(lifecycle[f"restore-c{c}"]["throughput_ratio"], 1.75) + + +if __name__ == "__main__": + unittest.main() diff --git a/extension/cuda/cuda_allocator.cpp b/extension/cuda/cuda_allocator.cpp index c3837a703ae..6aa0f702fb6 100644 --- a/extension/cuda/cuda_allocator.cpp +++ b/extension/cuda/cuda_allocator.cpp @@ -785,6 +785,7 @@ void CudaAllocator::release_cached_memory(DeviceIndex index) { #if defined(EXECUTORCH_USE_HIP) (void)index; #else + std::pair selected; std::vector> targets; { auto& state = mem_pool_state(); @@ -794,7 +795,7 @@ void CudaAllocator::release_cached_memory(DeviceIndex index) { if (it == state.pools.end()) { return; } - targets.emplace_back(it->first, it->second); + selected = {it->first, it->second}; } else { // A caller asking for everything gets every pool this allocator created, // not whichever device the calling thread happens to be current on, since @@ -805,7 +806,7 @@ void CudaAllocator::release_cached_memory(DeviceIndex index) { // The pools stay in the map. Trimming empties one without invalidating it, so // a later load reuses it rather than paying to create it again. - for (const auto& [device, pool] : targets) { + const auto trim = [](int device, cudaMemPool_t pool) { if (pool != nullptr) { // Only frees the driver has already observed can be released, and a free // still pending gives back nothing rather than less. The backend waits on @@ -842,6 +843,15 @@ void CudaAllocator::release_cached_memory(DeviceIndex index) { cudaGetErrorString(graph_err)); (void)cudaGetLastError(); } + }; + if (index >= 0) { + // A column resize trims after committing its new storage. This path must + // not allocate a host snapshot that can throw before pitch reconciliation. + trim(selected.first, selected.second); + } else { + for (const auto& [device, pool] : targets) { + trim(device, pool); + } } #endif } diff --git a/extension/cuda/test/cuda_allocator_exit.cpp b/extension/cuda/test/cuda_allocator_exit.cpp index 6370f3ca445..6a2fa9100b2 100644 --- a/extension/cuda/test/cuda_allocator_exit.cpp +++ b/extension/cuda/test/cuda_allocator_exit.cpp @@ -10,6 +10,7 @@ #include #include +#include using namespace executorch::extension::cuda; @@ -19,9 +20,10 @@ void* rounded = nullptr; executorch::runtime::DeviceAllocator* allocator = nullptr; int frees = 0; int trims = 0; +bool forbid_host_allocation = false; const auto fake_pool = reinterpret_cast(storage + 256); -void fail(const char* message) { +[[noreturn]] void fail(const char* message) { std::fprintf(stderr, "%s\n", message); std::_Exit(1); } @@ -42,6 +44,26 @@ void free_at_exit() { } } // namespace +// A per-device trim is called after the KV pool commits its replacement. It +// must not allocate a snapshot that could throw before pitch reconciliation. +void* operator new(std::size_t size) { + if (forbid_host_allocation) { + fail("per-device trim allocated host memory after storage commit"); + } + if (void* memory = std::malloc(size == 0 ? 1 : size)) { + return memory; + } + fail("host allocation failed"); +} + +void operator delete(void* memory) noexcept { + std::free(memory); +} + +void operator delete(void* memory, std::size_t) noexcept { + std::free(memory); +} + // Stand-ins keep the test independent of GPU packing and driver teardown order. extern "C" { cudaError_t cudaGetDevice(int* device) { @@ -118,5 +140,13 @@ int main() { fail("allocate_async did not create the pool"); } CudaAllocator::deallocate_async(pooled.get(), -1, nullptr); + forbid_host_allocation = true; + CudaAllocator::release_cached_memory(0); + CudaAllocator::release_cached_memory(1); + forbid_host_allocation = false; + if (trims != 1) { + fail("per-device trim did not reach exactly one existing pool"); + } + trims = 0; return 0; } diff --git a/extension/llm/batching/executor.h b/extension/llm/batching/executor.h index 5a8641f4dbf..3ec16ca1890 100644 --- a/extension/llm/batching/executor.h +++ b/extension/llm/batching/executor.h @@ -94,6 +94,11 @@ class ET_EXPERIMENTAL Executor { // double close is not an error, though Runner closes each owned id once. virtual void close_session(SessionId session) = 0; + // Engine-thread maintenance when no batch is ready, before waiting for work. + // Implementations may reclaim idle storage; live session contents must + // survive. + virtual void on_idle() {} + // Independently writable state for source's committed [0, upto) prefix, // with a lifetime-unique id and no sampling policy. Called between forwards; // source may have an active generation or hold speculative state past upto. diff --git a/extension/llm/batching/runner.cpp b/extension/llm/batching/runner.cpp index bb504fec540..5d0078906af 100644 --- a/extension/llm/batching/runner.cpp +++ b/extension/llm/batching/runner.cpp @@ -24,6 +24,8 @@ #include #include +#include + namespace executorch { namespace extension { namespace llm { @@ -796,6 +798,15 @@ void RunnerImpl::run_() { if (execute_one_batch_()) { continue; // more work may be ready } +#if ET_HAS_EXCEPTIONS + try { +#endif + executor_.on_idle(); +#if ET_HAS_EXCEPTIONS + } catch (...) { + ET_LOG(Error, "Executor idle maintenance failed"); + } +#endif std::unique_lock lock(control_mutex_); engine_cv_.wait_for(lock, std::chrono::milliseconds(20), [this] { return lifecycle_.load(std::memory_order_relaxed) != Lifecycle::Running || diff --git a/extension/llm/batching/test/runner_test.cpp b/extension/llm/batching/test/runner_test.cpp index d85118ba689..42f00f7688a 100644 --- a/extension/llm/batching/test/runner_test.cpp +++ b/extension/llm/batching/test/runner_test.cpp @@ -379,6 +379,41 @@ TEST(GenerationHandleTest, DefaultHandleIsInvalid) { handle.wait(); } +TEST(RunnerMaintenanceTest, IdleHookRunsBetweenBatchesOnTheEngineThread) { + class IdleExecutor : public FakeExecutor { + public: + void on_idle() override { + EXPECT_FALSE(in_execute()); + EXPECT_NE(std::this_thread::get_id(), caller); + ++idle_calls; + } + const std::thread::id caller = std::this_thread::get_id(); + std::atomic idle_calls{0}; + } executor; + Fixture fixture(executor); + Session session = open(fixture.runner); + executor.hold(); + auto updates = std::make_shared(); + auto handle = generate(session, tokens(1), config(1), updates); + const auto deadline = std::chrono::steady_clock::now() + kTimeout; + while (!executor.in_execute() && + std::chrono::steady_clock::now() < deadline) { + std::this_thread::yield(); + } + EXPECT_TRUE(executor.in_execute()); + const int idle_calls = executor.idle_calls.load(); + std::this_thread::sleep_for(std::chrono::milliseconds(40)); + EXPECT_EQ(executor.idle_calls.load(), idle_calls); + executor.release(); + ASSERT_TRUE(updates->wait()); + handle.wait(); + while (executor.idle_calls.load() == idle_calls && + std::chrono::steady_clock::now() < deadline) { + std::this_thread::yield(); + } + EXPECT_GT(executor.idle_calls.load(), idle_calls); +} + TEST(GenerationHandleTest, MoveTransfersValidity) { FakeExecutor executor; Fixture fixture(executor); diff --git a/extension/llm/cache/cache.h b/extension/llm/cache/cache.h index 89c7f5d9530..5f2fe1cb1a8 100644 --- a/extension/llm/cache/cache.h +++ b/extension/llm/cache/cache.h @@ -112,7 +112,8 @@ class ET_EXPERIMENTAL BatchControl : public CacheControl { // cache asks this before it hands out work seq_new would refuse. virtual std::optional max_seqs() const = 0; // An id no live sequence is using, held until that sequence's last slot is - // freed. nullopt = every id is in use. Ids may also be chosen by the caller; + // freed. nullopt = no free id or insufficient resources to admit it. + // Ids may also be chosen by the caller; // this only guarantees the one it returns is not already taken. virtual std::optional seq_new() = 0; // An independently writable snapshot of src below `upto`, all of it when diff --git a/extension/llm/cache/cache_registry.h b/extension/llm/cache/cache_registry.h index 433c4918fcb..05ee09b53c7 100644 --- a/extension/llm/cache/cache_registry.h +++ b/extension/llm/cache/cache_registry.h @@ -76,6 +76,11 @@ inline constexpr const char* kBatched = "batched"; inline constexpr const char* kBatchedCell = "batched-cell"; // Many sequences, each over its own private history. inline constexpr const char* kBatchedSequence = "batched-sequence"; +// Batched-sequence ABI 2: physical width can change between forwards. +inline constexpr const char* kBatchedSequenceRuntime = + "batched-sequence-runtime"; +inline constexpr const char* kBatchedSequencePrivate = + "batched-sequence-private"; } // namespace kind // Cache kind is expressed by which factory you call: backends register a