-
Notifications
You must be signed in to change notification settings - Fork 76
Refactor KV Cache Manager with a new torch exportable KVCache backend #400
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
geoffreyQiu
wants to merge
28
commits into
NVIDIA:main
Choose a base branch
from
geoffreyQiu:aoti_kvcache
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
28 commits
Select commit
Hold shift + click to select a range
865b86a
Refactor KV cache backend split
geoffreyQiu 189dd7b
Add export kvcache design outlines (temp)
geoffreyQiu aa81ea0
Support AOTI-compatible recsys kvcache ops
geoffreyQiu 04e32b9
Add end-to-end AOTI support for HSTU+KV-Cache inference
geoffreyQiu c4db670
Refactor KV-cache export/runtime cleanup and document AOTI flows
geoffreyQiu e2dd1eb
Updated the documents for KVcache with aoti support
geoffreyQiu 797d9b5
Update Dockerfile with full aoti build
geoffreyQiu 8ecae37
Fix pytorch Dockerfile
geoffreyQiu 5752885
Fix Docker
geoffreyQiu 0dab5d6
Support SM120 for hstu inference
geoffreyQiu 8f2b083
Setup folder for aoti related impl, and fix rebase conflicts
geoffreyQiu 7ea8412
Fix hstu kernel build for aarch64.
geoffreyQiu 0ecab41
Add code cleanup
geoffreyQiu 016f91a
Rename `offload_flush` api
geoffreyQiu d2df298
Code cleanup
geoffreyQiu 489e7b3
Fix CI tests
geoffreyQiu a35885f
Fix review errors
geoffreyQiu a765d26
Fix CI error
geoffreyQiu 6e1ffb1
Update to formal fbgemm_hstu branch
geoffreyQiu 192828e
Cleanup kvcache server env var
geoffreyQiu ebeea6d
Fix CI error
geoffreyQiu ad4a5b6
Fix CI error
geoffreyQiu 203c357
Fix CI error
geoffreyQiu c656a19
Update readme for inference_aoti
geoffreyQiu 9d6a00d
Fix review error
geoffreyQiu 675ad5f
Fix review error
geoffreyQiu cea53e0
Update documents with benchmark results
geoffreyQiu 3e3afe3
Update the readme and doc
geoffreyQiu File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| cmake_minimum_required(VERSION 3.18) | ||
| project(KVCacheManagerOps LANGUAGES CXX CUDA) | ||
|
|
||
| include(GNUInstallDirs) | ||
|
|
||
| set(CMAKE_CXX_STANDARD 17) | ||
| set(CMAKE_CXX_STANDARD_REQUIRED ON) | ||
| set(CMAKE_CXX_EXTENSIONS OFF) | ||
| set(CMAKE_CUDA_STANDARD 17) | ||
| set(CMAKE_CUDA_STANDARD_REQUIRED ON) | ||
| set(CMAKE_CUDA_EXTENSIONS OFF) | ||
| set(CMAKE_POSITION_INDEPENDENT_CODE ON) | ||
|
|
||
| find_package(Python3 COMPONENTS Interpreter REQUIRED) | ||
|
|
||
| find_package(PkgConfig REQUIRED) | ||
| pkg_check_modules(ZMQ REQUIRED libzmq) | ||
|
|
||
| if(NOT DEFINED CMAKE_PREFIX_PATH) | ||
| execute_process( | ||
| COMMAND "${Python3_EXECUTABLE}" -c "import torch; print(torch.utils.cmake_prefix_path)" | ||
| OUTPUT_VARIABLE TORCH_CMAKE_PREFIX_PATH | ||
| OUTPUT_STRIP_TRAILING_WHITESPACE | ||
| ERROR_QUIET | ||
| RESULT_VARIABLE TORCH_PREFIX_STATUS | ||
| ) | ||
| if(TORCH_PREFIX_STATUS EQUAL 0 AND TORCH_CMAKE_PREFIX_PATH) | ||
| list(APPEND CMAKE_PREFIX_PATH "${TORCH_CMAKE_PREFIX_PATH}") | ||
| endif() | ||
| endif() | ||
|
|
||
| find_package(Torch REQUIRED) | ||
| find_package(CUDAToolkit REQUIRED) | ||
|
|
||
|
|
||
| if(NOT DEFINED CMAKE_CUDA_ARCHITECTURES) | ||
| if(DEFINED SM) | ||
| set(CMAKE_CUDA_ARCHITECTURES ${SM}) | ||
| else() | ||
| set(CMAKE_CUDA_ARCHITECTURES 70 75 80 86 89 90 100 120) | ||
| endif() | ||
| endif() | ||
|
|
||
| message(STATUS "Found Torch ${TORCH_VERSION}") | ||
| message(STATUS "CUDA architectures: ${CMAKE_CUDA_ARCHITECTURES}") | ||
|
|
||
| set(KVCACHE_MANAGER_OPS_SOURCES | ||
| src/torch_binding/kvcache_manager_ops.cpp | ||
| src/torch_binding/kvcache_manager_context.cpp | ||
| src/runtime/kvcache_runtime_config.cpp | ||
| src/runtime/export_kvcache_runtime.cpp | ||
| src/gpu_kvcache_manager_impl.cpp | ||
| src/torch_binding/flexkv_cpp_client.cpp | ||
| src/torch_binding/flexkv_aoti_protocol.cpp | ||
| src/gather_scatter.cpp | ||
| src/gather_scatter_kernels.cu | ||
| ) | ||
|
|
||
| add_library(kvcache_manager_ops SHARED ${KVCACHE_MANAGER_OPS_SOURCES}) | ||
|
|
||
| separate_arguments(TORCH_CXX_FLAGS_LIST NATIVE_COMMAND "${TORCH_CXX_FLAGS}") | ||
| if(TORCH_CXX_FLAGS_LIST) | ||
| target_compile_options(kvcache_manager_ops PRIVATE ${TORCH_CXX_FLAGS_LIST}) | ||
| endif() | ||
|
|
||
| target_include_directories(kvcache_manager_ops PRIVATE | ||
| ${CMAKE_CURRENT_SOURCE_DIR}/src | ||
| ${CMAKE_CURRENT_SOURCE_DIR}/src/runtime | ||
| ${CMAKE_CURRENT_SOURCE_DIR}/src/torch_binding | ||
| ${TORCH_INCLUDE_DIRS} | ||
| ${CUDAToolkit_INCLUDE_DIRS} | ||
| ) | ||
|
|
||
| target_compile_options(kvcache_manager_ops PRIVATE | ||
| $<$<COMPILE_LANGUAGE:CXX>: | ||
| -O3 | ||
| -fdiagnostics-color=always | ||
| -fvisibility=hidden | ||
| -w | ||
| > | ||
| $<$<COMPILE_LANGUAGE:CUDA>: | ||
| -O3 | ||
| --expt-relaxed-constexpr | ||
| --expt-extended-lambda | ||
| --use_fast_math | ||
| -Xcompiler=-fvisibility=hidden | ||
| -w | ||
| -U__CUDA_NO_HALF_OPERATORS__ | ||
| -U__CUDA_NO_HALF_CONVERSIONS__ | ||
| -U__CUDA_NO_HALF2_OPERATORS__ | ||
| -U__CUDA_NO_BFLOAT16_CONVERSIONS__ | ||
| > | ||
| ) | ||
|
|
||
| target_compile_definitions(kvcache_manager_ops PRIVATE | ||
| TORCH_EXTENSION_NAME=kvcache_manager_ops | ||
| ) | ||
|
|
||
| target_link_libraries(kvcache_manager_ops PRIVATE | ||
| ${TORCH_LIBRARIES} | ||
| CUDA::cudart | ||
| zmq | ||
| ) | ||
|
|
||
| set_target_properties(kvcache_manager_ops PROPERTIES | ||
| PREFIX "" | ||
| OUTPUT_NAME "kvcache_manager_ops" | ||
| CUDA_SEPARABLE_COMPILATION OFF | ||
| ) | ||
|
|
||
| install(TARGETS kvcache_manager_ops | ||
| LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} | ||
| RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
138 changes: 138 additions & 0 deletions
138
corelib/recsys_kvcache_manager/doc/EXPORT_KVCACHE_DESIGN.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,138 @@ | ||
| # Export KVCache Design | ||
|
|
||
| ## 1. Scope and Goals | ||
| This document captures the finalized class naming and architecture for an export-friendly KV cache stack. | ||
|
|
||
| Goals: | ||
| 1. Keep one stable Python user interface. | ||
| 2. Support both default and export paths with shared workflow. | ||
| 3. Keep stateful runtime logic in C++ for export and AOTI compatibility. | ||
| 4. Keep torch custom ops thin and tensor-only. | ||
| 5. Use thread-local runtime context instead of explicit context_id in this phase. | ||
|
|
||
| ## 2. Final Naming | ||
|
|
||
| ### 2.1 Python layer | ||
| 1. `KVCacheManager`: user-facing API (kept for compatibility). | ||
| 2. `KVCacheBackend`: abstract backend interface. | ||
| 3. `DefaultKVCacheBackend`: default implementation using current Python manager stack. | ||
| 4. `DeviceKVCache`: device-side KV cache component. | ||
| 5. `NativeHostKVStorage`: native host storage component. | ||
| 6. `FlexKVStorage`: FlexKV-backed host storage component. | ||
|
|
||
| ### 2.2 C++ layer | ||
| 1. `KVCacheRuntimeContext`: thread-local context holder for current runtime instance. | ||
| 2. `IKVCacheRuntime`: abstract C++ runtime interface. | ||
| 3. `ExportKVCacheRuntime`: concrete C++ runtime implementation. | ||
|
|
||
| ## 3. High-Level Architecture and Ownership | ||
|
|
||
| ## 3.1 Layer responsibilities | ||
| 1. `KVCacheManager` | ||
| - Owns orchestration workflow used by model/inference code. | ||
| - Delegates backend-specific operations to `KVCacheBackend`. | ||
|
|
||
| 2. `KVCacheBackend` | ||
| - Defines backend contract for operations such as lookup and allocate. | ||
| - Keeps `KVCacheManager` independent of implementation details. | ||
|
|
||
| 3. `DefaultKVCacheBackend` | ||
| - Uses current Python components (`DeviceKVCache`, `NativeHostKVStorage` or `FlexKVStorage`). | ||
| - Preserves current behavior as the default path. | ||
|
|
||
| 4. `ExportKVCacheRuntime` | ||
| - Owns runtime state and policy in C++. | ||
| - Owns references to device and host storage runtime components. | ||
|
|
||
| 5. `KVCacheRuntimeContext` | ||
| - Holds the current `IKVCacheRuntime` pointer in `thread_local` storage. | ||
| - Serves runtime resolution for all kvcache torch ops on the active thread. | ||
|
|
||
| ## 3.2 Ownership model | ||
| 1. One inference instance owns one `ExportKVCacheRuntime`. | ||
| 2. The runtime is set into `KVCacheRuntimeContext` on inference entry. | ||
| 3. Torch ops read runtime from context and invoke methods. | ||
| 4. Runtime owns mutable state and backend handles. | ||
| 5. Context is cleared at inference exit. | ||
|
|
||
| ## 4. Key Relations (Composition + Shared Workflow) | ||
| 1. `KVCacheManager` has-a `KVCacheBackend`. | ||
| 2. `DefaultKVCacheBackend` has-a `DeviceKVCache` and host storage component. | ||
| 3. Export path calls ops from `torch.ops.kvcache_manager_ops` | ||
| 4. `ExportKVCacheRuntime` implements `IKVCacheRuntime`. | ||
| 5. `KVCacheRuntimeContext` stores `std::shared_ptr<IKVCacheRuntime>` per thread. | ||
|
|
||
| ## 5. lookup_kvcache: Implementation Outline | ||
|
|
||
| ## 5.1 Public API contract | ||
| `KVCacheManager.lookup_kvcache(user_ids, sequence_lengths)` returns lookup metadata/results with the same logical schema regardless of backend. | ||
|
|
||
| ## 5.2 Default path (non-export) | ||
| 1. `KVCacheManager.lookup_kvcache` delegates to `DefaultKVCacheBackend.lookup_kvcache`. | ||
| 2. Backend calls `DeviceKVCache.lookup(user_ids)`. | ||
| 3. Backend builds index metadata and calls host storage lookup. | ||
| 4. Backend merges host and device lookup results. | ||
| 5. Backend returns merged result to `KVCacheManager`. | ||
|
|
||
| ## 5.3 Export path (AOTI and torch.export focus) | ||
| 1. Inference initialization sets `ExportKVCacheRuntime` into `KVCacheRuntimeContext`. | ||
| 2. Lookup in model forward calls `torch.ops.kvcache_manager_ops.lookup_kvcache(...)`. | ||
| 3. C++ op shim resolves runtime from `KVCacheRuntimeContext`. | ||
| 4. C++ op shim calls `ExportKVCacheRuntime::lookup_kvcache(...)`. | ||
| 5. Runtime performs device lookup and host lookup, merges outputs. | ||
| 6. Runtime returns tensor-only outputs to op shim. | ||
| 7. Op shim returns outputs to Python backend. | ||
|
|
||
| ## 5.4 Export path pseudocode | ||
| ```python | ||
| # Python | ||
| class ExportableModel: | ||
| def forward(self, user_ids, sequence_lengths, ...): | ||
| lookup_results = torch.ops.kvcache_manager_ops.lookup_kvcache(user_ids, sequence_lengths, ordering_tensor) | ||
| ``` | ||
|
|
||
| ```cpp | ||
| // C++ op shim | ||
| std::vector<at::Tensor> lookup_kvcache_op(const at::Tensor& user_ids, | ||
| const at::Tensor& sequence_lengths) { | ||
| auto runtime = KVCacheRuntimeContext::instance().runtime(); | ||
| return runtime->lookup_kvcache(user_ids, sequence_lengths); | ||
| } | ||
| ``` | ||
|
|
||
| ```cpp | ||
| // C++ runtime | ||
| std::vector<at::Tensor> ExportKVCacheRuntime::lookup_kvcache( | ||
| const at::Tensor& user_ids, | ||
| const at::Tensor& sequence_lengths) { | ||
| auto gpu = device_kvcache_->lookup(user_ids); | ||
| auto idx = host_kvstorage_->build_index_meta(user_ids, sequence_lengths); | ||
| auto host = host_kvstorage_->lookup_kvcache(idx); | ||
| return merge_lookup_outputs(gpu, host); | ||
| } | ||
| ``` | ||
|
|
||
| ## 6. Thread-Local Context Decision | ||
| 1. Current phase uses thread-local context and does not use explicit `context_id` op arguments. | ||
| 2. This is valid under these assumptions: | ||
| - Each inference instance has its own device KV cache table. | ||
| - Host backend handles concurrency outside this layer. | ||
| 3. If future execution interleaves multiple inference instances on the same thread, add explicit `context_id` to op schemas. | ||
|
|
||
| ## 7. Torch Op Design Constraints | ||
| 1. Torch ops remain thin adapters only. | ||
| 2. Torch op inputs and outputs are tensor-first and export-friendly. | ||
| 3. Runtime policy and mutable state live in C++ runtime, not in op wrappers. | ||
| 4. Every exported op should provide shape-compatible Meta behavior. | ||
|
|
||
| ## 8. Migration Notes | ||
| 1. Keep existing public API name `KVCacheManager` for compatibility. | ||
| 2. Introduce backend interface and two implementations first. | ||
| 3. Route `lookup_kvcache` through backend as the first migrated API. | ||
| 4. Migrate `allocate` and onboard/offload APIs incrementally. | ||
| 5. Keep fallback to `DefaultKVCacheBackend` while validating export path. | ||
|
|
||
| ## 9. Optional Additions | ||
| 1. Add an RAII helper around thread-local context set and restore in C++ implementation. | ||
| 2. Add a backend selection config flag to switch default and export implementations. | ||
| 3. Add parity tests that compare default and export lookup outputs for identical inputs. | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.