Repository navigation
[Store] Unified parallel tensor IO - #1389
Conversation
Summary of ChangesHello @zxpdemonio, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request significantly enhances the MooncakeStore by introducing flexible Tensor Parallelism (TP) support. It allows users to store and retrieve tensors using different TP configurations, which is crucial for elastic distributed inference systems. The core changes involve new metadata structures to track tensor shards and an intelligent reconstruction engine that can reassemble tensors from chunks, even when the read and write TP sizes do not match. This provides greater adaptability and efficiency in managing distributed tensor data. Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Code Review
This pull request introduces a significant and valuable feature: supporting flexible Tensor Parallelism (TP) sizes by decoupling the put and get operations for tensors. The implementation, which involves adding global and chunk-level metadata for on-the-fly tensor reconstruction, is comprehensive. The addition of extensive tests is commendable. My review focuses on performance, correctness, and maintainability. I have identified several opportunities for significant performance improvements, especially within the tensor reconstruction logic and the implementation of new batch functions, which currently iterate over single operations instead of performing true batch requests. I've also included some suggestions for improving code safety and style.
| // Use get_into instead of get_buffer_range | ||
| int64_t chunk_total_size = store_->getSize(chunk_key); | ||
| if (chunk_total_size <= 0) { | ||
| continue; | ||
| } | ||
|
|
||
| std::vector<char> temp_buffer(chunk_total_size); | ||
| int64_t bytes_read; | ||
| { | ||
| // GIL held | ||
| bytes_read = store_->get_into( | ||
| chunk_key, temp_buffer.data(), chunk_total_size); | ||
| } | ||
|
|
||
| if (bytes_read >= chunk_total_size) { | ||
| // Verify range | ||
| if (src_slice_offset_bytes + copy_size <= | ||
| chunk_total_size) { | ||
| memcpy(output_data + dst_slice_offset_bytes, | ||
| temp_buffer.data() + src_slice_offset_bytes, | ||
| copy_size); | ||
| } | ||
| } |
There was a problem hiding this comment.
The implementation for actual_split_dim > 0 is highly inefficient. The call to store_->get_into to read the entire chunk is placed inside the for loop that iterates over slice_idx. This means the same chunk data is read from storage repeatedly for every slice, causing significant performance degradation, especially when elements_before is large.
To fix this, you should either move the get_into call outside the loop to read the chunk only once, or, for an even better solution, use the new get_buffer_range function inside the loop to read only the specific slice needed for each iteration. The latter would be the most memory and I/O efficient approach.
| default: | ||
| return 4; |
There was a problem hiding this comment.
The default case in get_element_size returns a hardcoded size of 4. This can lead to silent errors and memory corruption if an unknown or new TensorDtype is encountered that does not have a size of 4 bytes. It would be safer to handle this case explicitly by throwing an exception or logging a fatal error to prevent unexpected behavior.
| default: | |
| return 4; | |
| default: | |
| throw std::runtime_error("Unsupported or unknown tensor dtype: " + std::to_string(dtype)); |
| int64_t chunk_total_size = store_->getSize(chunk_key); | ||
| if (chunk_total_size <= 0) { | ||
| writer_rank++; | ||
| continue; | ||
| } | ||
|
|
||
| std::vector<char> temp_buffer(chunk_total_size); | ||
| int64_t bytes_read; | ||
| { | ||
| // GIL held | ||
| bytes_read = store_->get_into(chunk_key, temp_buffer.data(), | ||
| chunk_total_size); | ||
| } | ||
|
|
||
| if (bytes_read >= chunk_total_size) { | ||
| // Verify range | ||
| if (src_offset_bytes + total_copy_size <= | ||
| chunk_total_size) { | ||
| memcpy(output_data + dst_offset_bytes, | ||
| temp_buffer.data() + src_offset_bytes, | ||
| total_copy_size); | ||
| } | ||
| } else { | ||
| writer_rank++; | ||
| continue; | ||
| } |
There was a problem hiding this comment.
In reconstruct_tensor_from_chunks for the actual_split_dim == 0 case, the entire tensor chunk is read into a temporary buffer (temp_buffer) using store_->get_into, only to then copy a portion of it using memcpy. This is inefficient in terms of both memory usage and I/O, especially for large chunks.
The newly introduced get_buffer_range function is designed for this exact scenario. Using it would allow you to read only the required data slice directly into the output buffer, avoiding the intermediate allocation and copy. While the code comment mentions avoiding get_buffer_range, the new implementation of this function seems robust and should be leveraged for better performance.
| // Allocate buffer and copy global_meta to it | ||
| size_t buffer_size = sizeof(GlobalMetadata); | ||
| char *buffer = new char[buffer_size]; | ||
| memcpy(buffer, &global_meta, buffer_size); | ||
|
|
||
| { | ||
| py::gil_scoped_release release_gil; | ||
| ret = store_->put(global_meta_key, | ||
| std::span<const char>(buffer, buffer_size), | ||
| config); | ||
| } | ||
|
|
||
| // Clean up the buffer | ||
| delete[] buffer; |
There was a problem hiding this comment.
There is an unnecessary heap allocation when storing the GlobalMetadata. A new buffer is allocated with new, data is copied with memcpy, and then it's passed to store_->put. This can be simplified and made more efficient by passing a std::span of the global_meta object directly, similar to how chunk_meta is handled. This avoids the overhead of heap allocation and deallocation.
{
py::gil_scoped_release release_gil;
ret = store_->put(global_meta_key,
std::span<const char>(
reinterpret_cast<const char *>(&global_meta),
sizeof(GlobalMetadata)),
config);
}|
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
84dc0fa to
b4846f5
Compare
b4846f5 to
ff1e8bb
Compare
Changes
Test Cases We evaluated 6 cases covering three TP relationships and two split dimensions:
For each relationship, we tested:
Test Setup
Measurement Method For each scheme (ccrp, all_gather, gather_tp), we split latency into three parts:
Results
split_dim = 0put_tp=4, get_tp=2 (
|
| Scheme | Gather+Put (ms) | Get call+slice (ms) | End-to-end (ms) |
|---|---|---|---|
| CCRP | 207.65 | 428.17 | 686.22 |
| All Gather | 678.72 | 588.90 | 1350.99 |
| Gather+TP | 714.69 | 421.12 | 1214.91 |
put_tp=2, get_tp=2 (put_tp = get_tp)
| Scheme | Gather+Put (ms) | Get call+slice (ms) | End-to-end (ms) |
|---|---|---|---|
| CCRP | 359.10 | 425.32 | 818.44 |
| All Gather | 702.56 | 591.08 | 1366.97 |
| Gather+TP | 734.89 | 415.39 | 1228.85 |
put_tp=2, get_tp=4 (put_tp < get_tp)
| Scheme | Gather+Put (ms) | Get call+slice (ms) | End-to-end (ms) |
|---|---|---|---|
| CCRP | 353.40 | 360.97 | 752.61 |
| All Gather | 683.83 | 711.34 | 1480.56 |
| Gather+TP | 727.93 | 378.75 | 1187.68 |
split_dim = 1
put_tp=4, get_tp=2 (put_tp > get_tp)
| Scheme | Gather+Put (ms) | Get call+slice (ms) | End-to-end (ms) |
|---|---|---|---|
| CCRP | 222.38 | 423.10 | 680.82 |
| All Gather | 668.78 | 588.03 | 1332.88 |
| Gather+TP | 780.13 | 439.94 | 1298.44 |
put_tp=2, get_tp=2 (put_tp = get_tp)
| Scheme | Gather+Put (ms) | Get call+slice (ms) | End-to-end (ms) |
|---|---|---|---|
| CCRP | 376.05 | 424.30 | 813.03 |
| All Gather | 662.68 | 603.16 | 1347.73 |
| Gather+TP | 780.99 | 438.02 | 1294.66 |
put_tp=2, get_tp=4 (put_tp < get_tp)
| Scheme | Gather+Put (ms) | Get call+slice (ms) | End-to-end (ms) |
|---|---|---|---|
| CCRP | 371.94 | 393.22 | 776.46 |
| All Gather | 681.90 | 683.87 | 1433.22 |
| Gather+TP | 796.57 | 382.01 | 1233.40 |
Takeaway
- CCRP is the fastest in end-to-end makespan in all 6 cases.
- CCRP also has the lowest Gather+Put cost in all 6 cases.
- Reader-side Get call+slice is usually close to Gather+TP, and clearly lower than All Gather.
- The main win comes from avoiding full-tensor gather on the writer side and full-tensor fetch on the reader side.
|
/gemini review |
There was a problem hiding this comment.
Code Review
The pull request introduces tensor parallelism support to Mooncake store, enabling heterogeneous TP put/get via metadata and chunk separation. It includes new interfaces put_tensor_chunk_with_tp and get_tensor_with_tp_into, along with metadata structures and a CCRP implementation. The code review identified several areas for improvement, including validating the put_tp_size variable, ensuring sufficient buffer size for tensor data, clarifying the buffer_ptr assumption in put_tensor_with_tp_from, including the enum name in the TensorDtype error message, making get_tp_key_name a non-member function, and validating tensor_infos[i].metadata before proceeding. Also, the output_size variable is calculated but not used before being passed into reconstruct_tensor_from_chunks.
| // Use put_tp_size from metadata instead of hardcoded max | ||
| const int put_tp_size = global_meta.put_tp_size; | ||
| if (put_tp_size <= 0 || put_tp_size > 256) { | ||
| LOG(ERROR) << "Invalid put_tp_size in global metadata: " | ||
| << put_tp_size; | ||
| return; |
There was a problem hiding this comment.
| if (size < sizeof(TensorMetadata) + info.output_size) { | ||
| LOG(ERROR) << "Buffer size is too small for reconstruction: " | ||
| << size << " < " | ||
| << sizeof(TensorMetadata) + info.output_size; |
There was a problem hiding this comment.
| - `tp_rank` (int): Kept for signature compatibility with `put_tensor_with_tp()` (default: 0). It does **not** mean “only write one shard”. | ||
| - `tp_size` (int): Total tensor parallel size (default: 1). If 1, equivalent to `put_tensor_from(key, buffer_ptr, size)`. | ||
| - `split_dim` (int): Present for API consistency with other tensor-parallel methods but currently ignored; this API assumes `buffer_ptr` already points to a single pre-split shard. | ||
| - `split_dim` (int): Dimension along which the full tensor is split before storing shards. |
| LOG(ERROR) | ||
| << "Unknown or unsupported TensorDtype: " << dtype | ||
| << ". This can lead to memory corruption. " | ||
| << "Please add support for this dtype or fix the dtype value."; | ||
| throw std::runtime_error("Unknown or unsupported TensorDtype: " + | ||
| std::to_string(dtype)); |
There was a problem hiding this comment.
This logging statement and exception throw could be improved by including the enum name instead of just the integer value of the dtype. This would make debugging easier.
| LOG(ERROR) | |
| << "Unknown or unsupported TensorDtype: " << dtype | |
| << ". This can lead to memory corruption. " | |
| << "Please add support for this dtype or fix the dtype value."; | |
| throw std::runtime_error("Unknown or unsupported TensorDtype: " + | |
| std::to_string(dtype)); | |
| LOG(ERROR) | |
| << "Unknown or unsupported TensorDtype: " << dtype | |
| << ". This can lead to memory corruption. " | |
| << "Please add support for this dtype or fix the dtype value."; | |
| throw std::runtime_error("Unknown or unsupported TensorDtype: " + // Add enum name to the error message | |
| std::to_string(dtype)); |
| static std::string get_tp_key_name(const std::string &base_key, int rank) { | ||
| return base_key + "_tp_" + std::to_string(rank); | ||
| } |
There was a problem hiding this comment.
| info.output_size = output_elements * info.element_size; | ||
| info.valid = true; |
| std::vector<int> final_results(base_keys.size(), | ||
| to_py_ret(ErrorCode::INVALID_PARAMS)); |
There was a problem hiding this comment.
The default value for final_results is set to to_py_ret(ErrorCode::INVALID_PARAMS). However, if the code encounters an exception during the chunking phase, the final_results vector might not be properly updated, leading to incorrect results. Consider initializing final_results with a default success value (e.g., 0) and then setting specific elements to an error value if an issue occurs.
std::vector<int> final_results(base_keys.size(),
0); // Initialize with success code| tensor_infos[i] = extract_tensor_info(tensor, base_keys[i]); | ||
| if (!tensor_infos[i].valid()) { | ||
| final_results[i] = to_py_ret(ErrorCode::INVALID_PARAMS); | ||
| continue; |
There was a problem hiding this comment.
Consider adding a check to ensure that tensor_infos[i].metadata is valid before proceeding. This can prevent potential issues if the metadata extraction fails.
tensor_infos[i] = extract_tensor_info(tensor, base_keys[i]);
if (!tensor_infos[i].valid()) {
final_results[i] = to_py_ret(ErrorCode::INVALID_PARAMS);
continue;
}There was a problem hiding this comment.
Pull request overview
This PR adds flexible Tensor Parallel (TP) tensor storage/retrieval to Mooncake Store, allowing writers and readers to use different TP sizes by storing per-shard metadata and reconstructing requested shards on demand (including a new internal “range get” path used by CCRP-style reconstruction).
Changes:
- Add TP shard metadata (
GlobalMetadata,ChunkMetadata) and reconstruction logic in the Python binding layer (get_tensor_with_tp*slow path + newput_tensor_chunk_with_tp*APIs). - Introduce internal range-read plumbing (offset-aware transfer submit +
batch_get_buffer_ranges) to support assembling requested shards from multiple stored chunks. - Add/extend test & perf scripts and documentation for the new TP reconstruction behavior and APIs.
Reviewed changes
Copilot reviewed 15 out of 15 changed files in this pull request and generated 8 comments.
Show a summary per file
| File | Description |
|---|---|
| scripts/test_tensor_tp_reconstruction.py | Single-node perf harness for overlapped put/get TP reconstruction schemes. |
| scripts/test_tensor_chunk_api.py | New unittest suite covering chunk put/get, uneven splits, and TP-size mismatch reconstruction. |
| scripts/test_tensor_api.py | Updates existing tensor API tests to use registered buffer slots + updated TP batch get signatures. |
| scripts/test_distributed_tp_reconstruction.py | Multi-node perf harness using torch.distributed coordination. |
| mooncake-store/src/transfer_task.cpp | Add offset-aware validation and memcpy/transfer-engine submission paths (plus minor loop change). |
| mooncake-store/src/real_client.cpp | Add query retry helper + range-get helpers + batch_get_buffer_ranges internal API. |
| mooncake-store/src/client_service.cpp | Extend Client::Get / TransferRead to accept source_offset for range reads. |
| mooncake-store/include/transfer_task.h | Update TransferSubmitter APIs for offsets and new validation signature. |
| mooncake-store/include/real_client.h | Declare new internal range/batch-range APIs. |
| mooncake-store/include/client_service.h | Update Client::Get / TransferRead / TransferData signatures for offsets. |
| mooncake-integration/store/store_py.cpp | Main TP metadata + reconstruction implementation + new TP chunk put/get APIs exposed to Python. |
| mooncake-integration/integration_utils.h | Add get_element_size() and define packed GlobalMetadata/ChunkMetadata. |
| docs/source/python-api-reference/mooncake-store.md | Update docs to reflect put_tensor_with_tp_from now consumes a full-tensor buffer and splits internally. |
| docs/source/index.md | Add new TP tensor storage/CCRP design doc to the docs index. |
| docs/source/design/tp-tensor-storage-and-ccrp.md | New design doc describing the TP metadata model and reconstruction flow. |
Comments suppressed due to low confidence (1)
mooncake-store/src/transfer_task.cpp:571
- submitMemcpyOperation()/submitTransferEngineOperation() skip slices with slice.ptr == nullptr. This can hide upstream bugs and (since slice_offset isn’t advanced for skipped slices) can make computed remote offsets diverge from the intended layout. Prefer rejecting slices with size>0 but nullptr ptr, and keep slice_offset accounting consistent with the slice list.
for (size_t i = 0; i < slices.size(); ++i) {
const auto& slice = slices[i];
if (slice.ptr == nullptr) continue;
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
You can also share your feedback on Copilot code review. Take the survey.
| keys, output_data, dest_offsets, src_offsets, sizes); | ||
| } | ||
| auto transfer_end = std::chrono::steady_clock::now(); | ||
| (void)batch_res; // Results checked per-range; partial success allowed |
| return std::nullopt; | ||
| } | ||
| } else { | ||
| // For file read, offset is handled differently |
| for (size_t i = 0; i < n; ++i) { | ||
| if (sizes[i] == 0) { | ||
| results[i] = 0; | ||
| continue; | ||
| } | ||
|
|
||
| // Check query cache | ||
| auto it = query_cache.find(keys[i]); | ||
| if (it == query_cache.end()) { | ||
| it = query_cache.emplace(keys[i], query_with_retry(keys[i])).first; | ||
| } | ||
|
|
||
| if (!it->second) { | ||
| results[i] = -static_cast<int64_t>(it->second.error()); | ||
| continue; | ||
| } | ||
|
|
||
| auto ret = get_range_with_query_result( | ||
| it->second.value(), keys[i], dest_buffer, dest_offsets[i], | ||
| src_offsets[i], sizes[i]); | ||
| if (ret) { | ||
| results[i] = static_cast<int64_t>(sizes[i]); | ||
| } else { | ||
| results[i] = -static_cast<int64_t>(ret.error()); | ||
| } | ||
| } |
| One per logical key, written by put rank 0; describes the full tensor. | ||
|
|
||
| ```cpp | ||
| #pragma pack(push, 1) | ||
| struct GlobalMetadata { | ||
| int32_t dtype; | ||
| int32_t ndim; | ||
| int32_t split_dim; // Split dimension | ||
| int64_t shape[4]; // Full tensor shape |
| const ReplicateConfig &config = ReplicateConfig{}) { | ||
| // Calculate start_idx and size in split_dim for this chunk | ||
| int64_t dim_size = full_shape[split_dim]; | ||
| auto [start_idx, calculated_size] = | ||
| calculate_chunk_range(dim_size, put_tp_rank, put_tp_size); | ||
| int64_t chunk_size = tensor_meta.shape[split_dim]; |
| if (!chunk_meta_buffers[writer_rank] || | ||
| chunk_meta_buffers[writer_rank]->size() < kChunkMetaSize) { | ||
| break; // No more chunks | ||
| } |
|
|
||
| chunks = t.chunk(put_tp_size, split_dim) | ||
| for rank in range(put_tp_size): | ||
| self.store.put_tensor_chunk_with_tp( |
| void check_and_remove_tp_meta(const std::string &key) { | ||
| // 1. Try to remove chunk meta | ||
| store_->remove(key + "_meta"); | ||
|
|
|
This pr is too huge to review, could you split it |
6549211 to
b2a6355
Compare
Introduce explicit tensor object metadata for tensor read/write paths, add TP-aware tensor upsert wrappers, and update tests/docs for the new serialized layout. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Align the Python tensor IO bindings with the unified parallelism model and lock in regression coverage for the TP-compatible phase semantics. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Use registered base buffers plus computed destination offsets for TP and unified tensor _into reads, and batch ranged reads instead of issuing per-key loops. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Handle empty TP shards and align full reconstruction planning with shard-local layouts so unified full/full-into reads work for ragged, over-sharded, and higher-rank tensors. Expand the tensor API regression matrix to cover 1D/3D, batch full-into, dtype smoke, and broader stress cases. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Enable exact-match multi-axis shard metadata, keying, read/write, into, and upsert flows while keeping TP full reconstruction limited to the existing single-axis path. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Route TP and writer-partition tensor-object writes through raw-buffer shard planning and avoid the extra reconstruction tensor conversion pass on full reads. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Keep store_py.cpp focused on legacy/public wrappers by moving the remaining unified read/write helper logic into the parallel helper headers, while preserving the legacy TP read surface. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Reject non-uniform shard layouts across unified read/write paths, preserve legacy TP read compatibility, and add correctness checks for accepted uniform cases. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
5b8faca to
3740383
Compare
Preserve plain TP shard-input behavior while making multi-axis TP-containing writes and reads keep correct shard metadata and safer _into materialization semantics. Align the tensor API docs and tests with the scoped with_parallelism contract. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Apply clang-format-compatible wrapping to the store header changes so CI formatting checks can pass. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Run the repository clang-format script with clang-format-20 so the PR formatting check passes exactly. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
There was a problem hiding this comment.
Pull request overview
This PR extends Mooncake Store’s Python tensor IO to a unified “parallelism-aware” API that can persist and resolve multi-axis layout identities (TP/DP/EP/PP and combinations), and adds writer-side shard-only persistence via writer_partition(s) to reduce RL weight sync write amplification.
Changes:
- Add unified parallel tensor read/write/upsert APIs (
*_with_parallelism,ReadTarget,TensorParallelism,ParallelAxis) including_fromand_intovariants. - Implement writer-partition shard persistence and manifest handling, plus multi-axis shard keying and canonicalization.
- Add/expand Python tests and documentation for the unified API family and new tensor metadata header/layout.
Reviewed changes
Copilot reviewed 11 out of 11 changed files in this pull request and generated 5 comments.
Show a summary per file
| File | Description |
|---|---|
| scripts/test_upsert_api.py | Adds extensive Python coverage for unified parallel upsert/put/read scenarios and writer partitions. |
| mooncake-store/src/real_client.cpp | Adds registered-buffer region resolution to support sub-pointer _into planning. |
| mooncake-store/include/real_client.h | Declares RegisteredBufferRegion + resolve_registered_buffer() API. |
| mooncake-integration/store/store_py_parallel_write.h | New unified parallel write routing + batch routing + raw-buffer shard write planning. |
| mooncake-integration/store/store_py_parallel_read.h | New unified parallel read + _into planning, reconstruction, and get_into_ranges(...) lowering. |
| mooncake-integration/store/store_py_internal.h | New internal model/types/helpers for parallelism specs, keying, metadata, manifests, and validation. |
| mooncake-integration/store/store_py.cpp | Exposes new Python bindings/types and integrates unified read/write implementations. |
| mooncake-integration/integration_utils.h | Updates/defines the new tensor object header + layout metadata format and parsing/validation. |
| docs/source/python-api-reference/mooncake-store.md | Documents the unified parallel tensor IO API family and updates some tensor-buffer layout references. |
| docs/source/design/unified-parallel-tensor-io.md | Adds the design doc describing the unified API model and intended semantics. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Benchmark Configuration
1GB Results
4GB Results
Conclusions
|
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Reduce unified parallelism tensor test payloads to keep TCP gate coverage focused on correctness without excessive transfer volume. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Reduce unified parallelism stress tensor sizes and TP fanout so TCP gate coverage remains correctness-focused without triggering lease expiry. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Keep unified full reconstruction coverage in CI while reducing fragment-heavy payloads that can exceed the lease budget on TCP. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
|
All APIs are newly added and bug-free. LGTM |
* [Store] add tensor object metadata and TP upsert APIs Introduce explicit tensor object metadata for tensor read/write paths, add TP-aware tensor upsert wrappers, and update tests/docs for the new serialized layout. --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Change key format from `__writer_{rank}` to `__writer_{rank}of{size}_sd{split_dim}`
to align with PR kvcache-ai#1389. This makes writer keys self-describing,
encoding the total partition count and split dimension.
- Parallelism manifest: TP/multi-axis writes now create a
`__parallelism_manifest` key, enabling 3-tier shard discovery
(writer_manifest → parallelism_manifest → legacy _tp_N).
- Batch API: batch_{put,upsert,get}_tensor_with_parallelism and
batch_get_tensor_with_parallelism_into for bulk operations.
- _from API: put/upsert_tensor_with_parallelism_from for raw buffer
`[TensorMetadata | data]` writes, plus batch variants.
- Python wrappers in store.py for all 10 new methods.
Aligns Rust implementation with kvcache-ai#1389 feature set.
Change key format from `__writer_{rank}` to `__writer_{rank}of{size}_sd{split_dim}`
to align with PR kvcache-ai#1389. This makes writer keys self-describing,
encoding the total partition count and split dimension.
- Parallelism manifest: TP/multi-axis writes now create a
`__parallelism_manifest` key, enabling 3-tier shard discovery
(writer_manifest → parallelism_manifest → legacy _tp_N).
- Batch API: batch_{put,upsert,get}_tensor_with_parallelism and
batch_get_tensor_with_parallelism_into for bulk operations.
- _from API: put/upsert_tensor_with_parallelism_from for raw buffer
`[TensorMetadata | data]` writes, plus batch variants.
- Python wrappers in store.py for all 10 new methods.
Aligns Rust implementation with kvcache-ai#1389 feature set.
Change key format from `__writer_{rank}` to `__writer_{rank}of{size}_sd{split_dim}`
to align with PR kvcache-ai#1389. This makes writer keys self-describing,
encoding the total partition count and split dimension.
- Parallelism manifest: TP/multi-axis writes now create a
`__parallelism_manifest` key, enabling 3-tier shard discovery
(writer_manifest → parallelism_manifest → legacy _tp_N).
- Batch API: batch_{put,upsert,get}_tensor_with_parallelism and
batch_get_tensor_with_parallelism_into for bulk operations.
- _from API: put/upsert_tensor_with_parallelism_from for raw buffer
`[TensorMetadata | data]` writes, plus batch variants.
- Python wrappers in store.py for all 10 new methods.
Aligns Rust implementation with kvcache-ai#1389 feature set.
…m store_py (#5632) Remove ~2,500 net lines of unreachable C++ parallel tensor IO, writer-shard, and manifest helpers left behind in mooncake-integration/store/ after PR #3772 removed the experimental unified-parallel-tensor-io bindings introduced in PR #1389. - Delete store_py_parallel_read.h and store_py_parallel_write.h, eliminating mid-class textual #include directives inside MooncakeStorePyWrapper. - Reduce store_py_internal.h to a standard #pragma once header containing only live tensor metadata and TP shard helpers. - Remove unreachable manifest/TP helper methods from store_py.cpp while keeping all exported pybind11 APIs and the 304-byte TensorMetadata wire format unchanged. Signed-off-by: Aoi <aione.moe.dev@gmail.com>
Motivation
This work is primarily driven by weight synchronization optimization for RL workloads. In RL systems, different components often consume the same model weights under different parallel layouts: some hold the full tensor, some only need a TP shard, and some run with mixed layouts such as DP+TP, EP+TP, or PP+TP. A storage path that only supports full tensors or plain TP shards causes unnecessary write amplification, unnecessary read amplification, and limited layout expressiveness. The goal of this update is to make the unified tensor IO layer suitable for RL-style weight sync by supporting richer layout identities while also optimizing both shard-oriented writes and shard/full reads.
What is supported now
The unified tensor IO path now supports not only heterogeneous TP, but also DP, EP, PP, and their combinations, including exact-match multi-axis shard identities such as DP+TP, PP+TP, and EP+TP. In other words, the system is no longer limited to “TP-only sharded tensors”; it can now persist and resolve multi-axis layout metadata through a single unified API surface.
Write-path optimization
On the write side, the key optimization for RL weight sync is to avoid having every writer store the full tensor when only a local shard needs to be persisted. This is implemented through
writer_partitionfor single-key APIs andwriter_partitionsfor batch APIs. In practice, this allows each writer to hold a full tensor locally but write only the shard it owns, directly reducing write amplification and network/storage overhead during synchronization. The_frompaths were also optimized to use raw-buffer shard planning instead of decoding tensor-object buffers into Python tensors and then reshaping or re-sharding them, which removes unnecessary decode, tensor materialization, and extra memcpy/clone work from the hot path.Read-path optimization
On the read side, the system now supports exact-match shard reads for multi-axis layouts, so consumers can fetch only the shard they need instead of reading a full tensor and slicing locally. This improves efficiency for TP-only consumers as well as mixed DP/TP, PP/TP, and EP/TP layouts. For cases that need the full tensor view, reconstruction is optimized by reusing the existing
get_into_ranges(...)ranged-read substrate and avoiding an extra intermediate tensor conversion. As a result, both full reconstruction and_intoreconstruction remain efficient while still working on top of the unified metadata model.RL semantics
For RL workloads, an important distinction is that DP metadata and writer-side partial persistence are not the same thing. If the requirement is “each DP rank has the full tensor, but only writes its owned slice for synchronization efficiency,” that is supported through
writer_partition/writer_partitions. If the requirement is “a DP parallelism spec alone should imply automatic partial persistence of a full tensor,” that is not the semantics of the DP metadata path. In the unified API, DP/EP/PP/TP describe layout identity, whilewriter_partition(s)provides the writer-side shard-only persistence optimization needed for RL weight sync.Additional improvements
This update also closes an important API symmetry gap by adding batch support for
writer_partitionsacross the unified put/upsert APIs, including_fromvariants. Batch equests now explicitly reject ambiguous mixed inputs such asparallelisms + writer_partitions. In addition, multi-axis shard metadata matching was fixed by canonicalizing the requested parallelism before comparison, which resolved incorrect mismatch behavior in cases such asPP+TPwhere axis order differed syntactically but not semantically.Validation
The changes were validated with focused local tests covering batch writer-partition full reconstruction, batch writer-partition
_intoround trips, batch writer-partition upsert and upsert-from paths, multi-axis batch shard reads, multi-axis batch_intoreads, and explicit invalid mixed-routing cases. Formatting was also rechecked and fixed with the repository formatter.Support Matrix
_into_into_into, full reconstruction where applicable_intowriter_partition/writer_partitionswriter_partitionsparallelisms+writer_partitionsin one batch requestHigh-level architecture
flowchart TB Caller["Python caller"] API["Unified with_parallelism API<br/>put / get / upsert"] Request["Request objects<br/>TensorParallelism / ReadTarget / writer_partition"] Router["Internal route resolver"] Full["Full tensor path"] TPCompat["TP compatibility path"] MultiAxis["Multi-axis parallelism path"] WriterPartition["writer_partition path"] Metadata["Tensor metadata<br/>global/local shape, dtype, layout axes"] Manifest["Shard manifest<br/>global shape, dtype, split_dim, shard_count"] Store["Mooncake object store"] ReadPlanner["Read planner"] RangeRead["Range-based reconstruction<br/>get_into_ranges(...)"] Output["torch.Tensor / user buffer"] Caller --> API API --> Request Request --> Router Router --> Full Router --> TPCompat Router --> MultiAxis Router --> WriterPartition Full --> Metadata TPCompat --> Metadata MultiAxis --> Metadata WriterPartition --> Metadata Metadata --> Store MultiAxis --> Manifest WriterPartition --> Manifest Manifest --> Store Store --> ReadPlanner Manifest --> ReadPlanner ReadPlanner --> Output ReadPlanner --> RangeRead RangeRead --> OutputPublic API shape
This PR centers tensor IO around the following API families:
The core public request objects are:
TensorParallelismdescribes where a tensor object belongs in the parallel layout.ReadTargetdescribes what the caller wants to materialize on read:Multi-axis write flow
For a request such as:
Mooncake internally performs:
This lets callers express
DP+TP,PP+TP, andEP+TPwrites without pre-splitting tensors themselves.Read-side semantics
Read behavior is explicit through
ReadTarget.as_storedshardfullThis avoids guessing read behavior from
parallelismalone.For example, a TP axis can appear in multiple valid read requests:
These requests mean different things, so the mode is explicit.
Reconstruction path
flowchart TB Read["ReadTarget: shard or full"] Resolve["Resolve exact stored object"] Exact["Exact shard/full object found"] Reconstruct["Reconstruction needed"] Manifest["Load manifest / metadata"] Sources["Discover source shards"] Validate["Validate dtype, shape, split_dim, shard_count"] Plan["Build TensorIntoPlan"] Ranges["get_into_ranges(...)"] Header["Write tensor metadata header after successful transfer"] Output["Return tensor / user buffer"] Read --> Resolve Resolve --> Exact Resolve --> Reconstruct Exact --> Output Reconstruct --> Manifest Manifest --> Sources Sources --> Validate Validate --> Plan Plan --> Ranges Ranges --> Header Header --> OutputFull and reconstructed-shard reads lower to internal range plans and reuse:
get_into_ranges(...)The public API does not expose:
Those remain internal planner/runtime details.
Metadata model
Each stored tensor object carries enough metadata to describe both the logical tensor and the stored object.
layout_kindglobal_shapelocal_shapedtypelayout_axessplit_dimshard_rankshard_countFor shard sets, Mooncake also stores a manifest containing reconstruction-level information:
global_shapedtypesplit_dimshard_countHow Different Parallelism Axes Are Handled
The unified
with_parallelismAPI models parallelism as an explicit list of axes, but not every axis affects tensor storage in the same way.The key distinction is:
Axis semantics
TPrank,size, andsplit_dim; Mooncake can derive the shard range.DPPPEPDP+TPPP+TPEP+TPWhy TP is handled differently
TPis the only axis in the current implementation that directly tells Mooncake how to split a tensor.A TP axis carries:
From those fields, Mooncake can compute:
So for TP-containing layouts, Mooncake can safely derive the requested shard from a full source tensor.
That is why layouts such as:
can accept full-tensor input and internally store only the requested TP shard.
Why DP / PP / EP do not imply splitting
DP,PP, andEPidentify ownership, not a generic tensor slicing rule.For example:
means:
It does not tell Mooncake:
The same applies to PP and EP:
PPidentifies a pipeline stage.EPidentifies an expert or expert-local scope.Therefore pure
DP,PP, orEPlayouts store the passed tensor object directly. Mooncake does not invent an implicit split axis.Why multi-axis layouts are split only through TP
For multi-axis layouts, Mooncake separates scope from layout.
Example:
This means:
So the handling is:
This keeps the semantics explicit and avoids treating
mixedparallelism as a vague special case.Current write behavior by layout
parallelism=None[TP][DP][PP][EP][DP, TP][PP, TP][EP, TP]Summary
In short, this work extends unified tensor IO from a TP-centric design into a layout-aware IO layer that supports TP, DP, EP, PP, and their combinations, while also introducing the writer-side optimization that RL workloads actually need: each writer can persist only its owned shard instead of redundantly writing the full tensor. Combined with shard-direct reads, optimized full reconstruction, raw-buffer
_fromfast paths, and batch API symmetry, this makes the storage layer substantially better suited for RL weight synchronization and mixed-parallel deployment scenarios.Type of Change
How Has This Been Tested?
Checklist
./scripts/code_format.shbefore submitting.