Skip to content

[Store] Unified parallel tensor IO - #1389

Merged
stmatengss merged 25 commits into
kvcache-ai:mainfrom
openanolis:cruz/flex_put_get
Apr 27, 2026
Merged

stmatengss merged 25 commits into
kvcache-ai:mainfrom
openanolis:cruz/flex_put_get

Conversation

@zxpdemonio

@zxpdemonio zxpdemonio commented Jan 16, 2026 •

Copy link
Copy Markdown
Collaborator

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_partition for single-key APIs and writer_partitions for 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 _from paths 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 _into reconstruction 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, while writer_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_partitions across the unified put/upsert APIs, including _from variants. Batch equests now explicitly reject ambiguous mixed inputs such as parallelisms + 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 as PP+TP where 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 _into round trips, batch writer-partition upsert and upsert-from paths, multi-axis batch shard reads, multi-axis batch _into reads, and explicit invalid mixed-routing cases. Formatting was also rechecked and fixed with the repository formatter.

Support Matrix

Scenario Supported Read support Write optimization Notes
TP only Yes Shard read, full reconstruction, _into Raw-buffer shard write fast path Mature path
Heterogeneous TP Yes Shard read, full reconstruction, batch _into Same as TP path Supported through unified API
DP metadata layout Yes Exact-match shard identity support Metadata/layout only Does not by itself mean “write only one slice of a full tensor”
PP metadata layout Yes Exact-match shard identity support Metadata/layout only Supports stage-aware layout identity
EP metadata layout Yes Exact-match shard identity support Metadata/layout only Supports expert-aware layout identity
DP + TP Yes Exact-match shard read, batch read, _into, full reconstruction where applicable TP shard persistence + unified metadata Good fit for RL mixed layouts
PP + TP Yes Exact-match shard read, batch read, _into TP shard persistence + unified metadata Axis-order matching issue was fixed
EP + TP Yes Exact-match shard read TP shard persistence + unified metadata Supports expert-aware shard identity
Writer-side partial persistence from full tensor Yes Full reconstruction and shard access writer_partition / writer_partitions Main optimization for RL weight sync
Batch writer-side partial persistence Yes Full reconstruction and shard access Batch writer_partitions Newly added in this update
Mixed parallelisms + writer_partitions in one batch request Rejected N/A N/A Explicitly invalid to avoid ambiguous semantics

High-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 --> Output                                                                                                                                                           
Loading

Public API shape

This PR centers tensor IO around the following API families:

put_tensor_with_parallelism(...)                                                                                                                                                   
batch_put_tensor_with_parallelism(...)                                                                                                                                             
                                                                                                                                                                                   
get_tensor_with_parallelism(...)                                                                                                                                               
batch_get_tensor_with_parallelism(...)                                                                                                                                             
                                                                                                                                                                                   
get_tensor_with_parallelism_into(...)                                                                                                                                              
batch_get_tensor_with_parallelism_into(...)                                                                                                                                        
                                                                                                                                                                               
upsert_tensor_with_parallelism(...)                                                                                                                                                
batch_upsert_tensor_with_parallelism(...)                                                                                                                                          

The core public request objects are:

TensorParallelism                
ParallelAxis                     
ReadTarget                       

TensorParallelism describes where a tensor object belongs in the parallel layout.

ReadTarget describes what the caller wants to materialize on read:

  • stored object
  • target shard
  • reconstructed full tensor

Multi-axis write flow

For a request such as:

put_tensor_with_parallelism(                                                                                                                                                       
    key,                                                                                                                                                                           
    full_tensor,                                                                                                                                                                   
    TensorParallelism([                                                                                                                                                            
        ParallelAxis(kind="dp", rank=0, size=2),                                                                                                                               
        ParallelAxis(kind="tp", rank=1, size=4, split_dim=0),                                                                                                                      
    ]),                                                                                                                                                                            
)                                                                                                                                                                                  

Mooncake internally performs:

1. Parse TensorParallelism                                                                                                                                                     
2. Find the TP axis              
3. Validate uniform sharding   
4. Compute the requested TP shard range       
5. Slice the requested shard from the full tensor                                                                                                                                  
6. Store only that shard                                                                                                                                                           
7. Store metadata and manifest for later reads                                                                                                                                     

This lets callers express DP+TP, PP+TP, and EP+TP writes without pre-splitting tensors themselves.

Read-side semantics

Read behavior is explicit through ReadTarget.

ReadTarget mode Caller intent Internal behavior
as_stored Return exactly what was stored Direct object read
shard Return a target shard Direct shard read if available; otherwise reconstruct the requested shard
full Return the full tensor Reconstruct from shard metadata / manifest

This avoids guessing read behavior from parallelism alone.

For example, a TP axis can appear in multiple valid read requests:

ReadTarget(mode="as_stored")                
ReadTarget(mode="shard", parallelism=tp_parallelism)                                                                                                                               
ReadTarget(mode="full", parallelism=tp_parallelism)                                                                                                                                

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 --> Output          
Loading

Full and reconstructed-shard reads lower to internal range plans and reuse:

get_into_ranges(...)                                                                                                                                                               

The public API does not expose:

  • byte ranges
  • source offsets
  • destination offsets
  • reconstruction plans

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.

Metadata field Purpose
layout_kind Full tensor or shard tensor
global_shape Logical full tensor shape
local_shape Stored object shape
dtype Tensor dtype
layout_axes Parallel layout axes such as TP / DP / PP / EP
split_dim Dimension split by TP, when applicable
shard_rank Rank of this shard along the split axis
shard_count Number of shards along the split axis

For shard sets, Mooncake also stores a manifest containing reconstruction-level information:

Manifest field Purpose
global_shape Shape of the reconstructed tensor
dtype Tensor dtype
split_dim Split dimension
shard_count Number of uniform shards

How Different Parallelism Axes Are Handled

The unified with_parallelism API models parallelism as an explicit list of axes, but not every axis affects tensor storage in the same way.

The key distinction is:

  • layout-affecting axes: determine how tensor bytes are physically split
  • scope / ownership axes: identify which replica, stage, or expert owns the tensor object, but do not define a byte split by themselves

Axis semantics

Axis Meaning Affects tensor byte layout? Handling
TP Tensor-parallel shard Yes Defines rank, size, and split_dim; Mooncake can derive the shard range.
DP Data-parallel replica No Treated as replica scope; does not imply tensor splitting.
PP Pipeline stage No Treated as stage ownership; does not imply tensor splitting.
EP Expert identity No, by itself Treated as expert scope; does not imply TP-style tensor splitting.
DP+TP Replica-scoped tensor shard TP does DP scopes the object; TP defines the physical shard.
PP+TP Stage-scoped tensor shard TP does PP scopes the object; TP defines the physical shard.
EP+TP Expert-scoped tensor shard TP does EP scopes the object; TP defines the physical shard.

Why TP is handled differently

TP is the only axis in the current implementation that directly tells Mooncake how to split a tensor.

A TP axis carries:

rank                                                                                                                                                                               
size                                                                                                                                                                               
split_dim                                                                                                                                                                          

From those fields, Mooncake can compute:

shard_extent = global_shape[split_dim] / tp_size                                                                                                                                   
shard_start  = tp_rank * shard_extent                                                                                                                                              

So for TP-containing layouts, Mooncake can safely derive the requested shard from a full source tensor.

That is why layouts such as:

TensorParallelism([DP, TP])                                                                                                                                                        
TensorParallelism([PP, TP])                                                                                                                                                        
TensorParallelism([EP, TP])                                                                                                                                                        

can accept full-tensor input and internally store only the requested TP shard.

Why DP / PP / EP do not imply splitting

DP, PP, and EP identify ownership, not a generic tensor slicing rule.

For example:

TensorParallelism([DP(rank=0, size=2)])                                                                                                                                            

means:

this tensor belongs to data-parallel replica 0                                                                                                                                     

It does not tell Mooncake:

which dimension should be split?                                                                                                                                                   
how large is each shard?                                                                                                                                                           
which byte range belongs to this rank?                                                                                                                                             

The same applies to PP and EP:

  • PP identifies a pipeline stage.
  • EP identifies an expert or expert-local scope.
  • Neither defines a universal tensor split by itself.

Therefore pure DP, PP, or EP layouts 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:

TensorParallelism([                                                                                                                                                                
    ParallelAxis(kind="dp", rank=0, size=2),                                                                                                                                       
    ParallelAxis(kind="tp", rank=1, size=4, split_dim=0),                                                                                                                          
])                                                                                                                                                                                 

This means:

DP says: this object belongs to replica 0                                                                                                                                          
TP says: store rank 1 of a 4-way split along dimension 0                                                                                                                           

So the handling is:

full tensor input                                                                                                                                                                  
    -> DP scopes the stored object key/metadata                                                                                                                                    
    -> TP determines the shard slice                                                                                                                                               
    -> Mooncake stores only the requested TP shard                                                                                                                                 

This keeps the semantics explicit and avoids treating mixed parallelism as a vague special case.

Current write behavior by layout

Layout Caller input Stored object Reason
parallelism=None Full tensor Full tensor No parallel layout requested.
[TP] TP shard tensor TP shard Preserves existing single-axis TP compatibility behavior.
[DP] Tensor object Tensor object DP is replica scope, not a split rule.
[PP] Tensor object Tensor object PP is stage scope, not a split rule.
[EP] Tensor object Tensor object EP is expert scope, not a split rule.
[DP, TP] Full tensor Requested TP shard DP scopes the object; TP defines the shard.
[PP, TP] Full tensor Requested TP shard PP scopes the object; TP defines the shard.
[EP, TP] Full tensor Requested TP shard EP scopes the object; TP defines the shard.

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 _from fast 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

  • Types
    • Bug fix
    • New feature
      • Transfer Engine
      • Mooncake Store
      • Mooncake EP
      • Integration
      • P2P Store
      • Python Wheel
    • Breaking change
    • CI/CD
    • Documentation update
    • Other

How Has This Been Tested?

Checklist

  • I have performed a self-review of my own code.
  • I have formatted my own code using ./scripts/code_format.sh before submitting.
  • I have updated the documentation.
  • I have added tests to prove my changes are effective.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @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

  • Flexible Tensor Parallelism (TP) Sizes: The MooncakeStore now supports decoupling of Tensor Parallel (TP) sizes between put and get tensor operations, allowing for different parallelism configurations during storage and retrieval.
  • Intelligent Tensor Reconstruction: A new reconstruct_tensor_from_chunks logic has been implemented to intelligently compute overlaps and assemble requested tensor data on-the-fly, even when the read TP size differs from the write TP size.
  • Metadata Mechanism for Tensor Shards: New GlobalMetadata and ChunkMetadata structures track full tensor information and individual chunk positions, enabling readers to request shards with arbitrary TP sizes (e.g., write with TP=4, read with TP=2, or vice-versa).
  • New Tensor Chunk APIs: Introduced put_tensor_chunk_with_tp and get_tensor_with_tp (along with their batch variants) to handle dynamic tensor splitting and reconstruction, enhancing the store's tensor manipulation capabilities.
  • Comprehensive Testing: Extensive tests have been added, covering various split dimensions, uneven tensor splits, and complex cross-TP-size reconstruction scenarios to ensure robustness and correctness.

🧠 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 Assist

The 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 /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

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 .gemini/ folder in the base of the repository. Detailed instructions can be found here.

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

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread mooncake-integration/store/store_py.cpp Outdated
Comment on lines +459 to +481
// 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);
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

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.

Comment on lines +124 to +125
default:
return 4;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

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.

Suggested change
default:
return 4;
default:
throw std::runtime_error("Unsupported or unknown tensor dtype: " + std::to_string(dtype));

Comment thread mooncake-integration/store/store_py.cpp Outdated
Comment on lines +415 to +440
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;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

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.

Comment thread mooncake-integration/store/store_py.cpp Resolved
Comment thread mooncake-integration/store/store_py.cpp Resolved
Comment thread mooncake-integration/store/store_py.cpp Resolved
Comment thread mooncake-integration/store/store_py.cpp Outdated
Comment on lines +541 to +554
// 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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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-commenter

codecov-commenter commented Jan 16, 2026 •

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 0% with 2719 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...ooncake-integration/store/store_py_parallel_read.h 0.00% 861 Missing ⚠️
mooncake-integration/store/store_py_internal.h 0.00% 836 Missing ⚠️
...oncake-integration/store/store_py_parallel_write.h 0.00% 699 Missing ⚠️
mooncake-integration/store/store_py.cpp 0.00% 233 Missing ⚠️
mooncake-integration/integration_utils.h 0.00% 75 Missing ⚠️
mooncake-store/src/real_client.cpp 0.00% 15 Missing ⚠️

📢 Thoughts on this report? Let us know!

@XucSh XucSh self-assigned this Jan 22, 2026
@zxpdemonio

zxpdemonio commented Mar 13, 2026 •

Copy link
Copy Markdown
Collaborator Author

Changes

  1. CCRP optimization
    Add internal batch_get_buffer_ranges in RealClient (not exposed via PyClient/DummyClient). Optimize reconstruct_tensor_from_chunks to batch-fetch ChunkMetadata and perform a single batch_get_buffer_ranges call instead of looping over get_buffer_range.

  2. Test script
    scripts/test_tensor_tp_reconstruction.py — multi-process TP reconstruction perf test, CCRP vs All Gather.

  3. Docs
    docs/source/design/tp-tensor-storage-and-ccrp.md — interfaces, metadata, CCRP design.

  4. Format
    clang-format on modified C++ files.


Test Cases

We evaluated 6 cases covering three TP relationships and two split dimensions:

  • put_tp > get_tp: (put_tp=4, get_tp=2)
  • put_tp = get_tp: (put_tp=2, get_tp=2)
  • put_tp < get_tp: (put_tp=2, get_tp=4)

For each relationship, we tested:

  • split_dim = 0
  • split_dim = 1

Test Setup

  • Tensor size: 512 MB
  • Iterations per case: 3
  • Protocol: RDMA
  • Segment config:
    • MOONCAKE_GLOBAL_SEGMENT_SIZE=8gb
    • MOONCAKE_LOCAL_BUFFER_SIZE=1gb
  • Master config:
    • --default_kv_lease_ttl=5000000000
  • MC_STORE_MEMCPY disabled

Measurement Method

For each scheme (ccrp, all_gather, gather_tp), we split latency into three parts:

  1. Gather+Put
    - Writer-side preprocessing + data write
    - For all_gather / gather_tp, this includes the gather/prep cost
    - For ccrp, prep cost is effectively 0
  2. Get Call+Slice
    - Pure get-path execution time
    - Includes reconstruction / local slicing
    - Does not include wait time before the object becomes ready
  3. End-to-End
    - Full overlapped makespan measured by the benchmark

Results
Metrics:

  • Gather+Put = avg put_with_prep_max_ms
  • Get call+slice = avg call_max_ms
  • End-to-end = avg makespan
  • All values are averaged over 3 iterations.

split_dim = 0

put_tp=4, get_tp=2 (put_tp > get_tp)

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.

@stmatengss
stmatengss requested a review from Copilot March 18, 2026 17:46
@stmatengss

Copy link
Copy Markdown
Collaborator

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread mooncake-integration/store/store_py.cpp Outdated
Comment on lines +487 to +492
// 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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The put_tp_size variable is read from the global_meta struct, but there is no validation that this value is reasonable. Add a check to ensure that put_tp_size is within an acceptable range (e.g., greater than 0 and less than a reasonable maximum) to prevent potential issues.

Comment thread mooncake-integration/store/store_py.cpp Outdated
Comment on lines +1261 to +1264
if (size < sizeof(TensorMetadata) + info.output_size) {
LOG(ERROR) << "Buffer size is too small for reconstruction: "
<< size << " < "
<< sizeof(TensorMetadata) + info.output_size;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The buffer size check only verifies that the size is greater than the metadata size, but it doesn't account for the actual data size that will be copied into the buffer. Add a check to ensure that size is large enough to hold the tensor data, which can be determined from global_meta.

- `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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The phrase "this API assumes buffer_ptr already points to a single pre-split shard." is no longer accurate, as the API now handles splitting. Consider revising for clarity.

Comment on lines +127 to +132
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));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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.

Suggested change
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));

Comment thread mooncake-integration/store/store_py.cpp Outdated
Comment on lines 322 to 324
static std::string get_tp_key_name(const std::string &base_key, int rank) {
return base_key + "_tp_" + std::to_string(rank);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This function could be a non-member function since it does not access any member variables of the class. Making it a non-member function improves encapsulation and reduces dependencies.

    

    static std::string get_tp_key_name(const std::string &base_key, int rank) {

Comment thread mooncake-integration/store/store_py.cpp Outdated
Comment on lines +848 to +849
info.output_size = output_elements * info.element_size;
info.valid = true;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The output_size variable is calculated but not used before being passed into reconstruct_tensor_from_chunks. This suggests a potential error in the calculation or a missed opportunity for optimization.

Comment on lines +1563 to +1564
std::vector<int> final_results(base_keys.size(),
to_py_ret(ErrorCode::INVALID_PARAMS));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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

Comment thread mooncake-integration/store/store_py.cpp Outdated
Comment on lines +1583 to +1586
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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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;
                }

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 + new put_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.

Comment thread mooncake-integration/store/store_py.cpp Outdated
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
Comment thread mooncake-store/src/transfer_task.cpp Outdated
return std::nullopt;
}
} else {
// For file read, offset is handled differently
Comment thread mooncake-store/src/real_client.cpp Outdated
Comment on lines +1820 to +1845
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());
}
}
Comment on lines +102 to +110
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
Comment thread mooncake-integration/store/store_py.cpp Outdated
Comment on lines +618 to +623
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];
Comment thread mooncake-integration/store/store_py.cpp Outdated
Comment on lines +531 to +534
if (!chunk_meta_buffers[writer_rank] ||
chunk_meta_buffers[writer_rank]->size() < kChunkMetaSize) {
break; // No more chunks
}
Comment thread scripts/test_tensor_chunk_api.py Outdated

chunks = t.chunk(put_tp_size, split_dim)
for rank in range(put_tp_size):
self.store.put_tensor_chunk_with_tp(
Comment thread mooncake-integration/store/store_py.cpp Outdated
Comment on lines +671 to +674
void check_and_remove_tp_meta(const std::string &key) {
// 1. Try to remove chunk meta
store_->remove(key + "_meta");

@XucSh

XucSh commented Apr 2, 2026

Copy link
Copy Markdown
Collaborator

This pr is too huge to review, could you split it

@zxpdemonio zxpdemonio mentioned this pull request Apr 16, 2026
8 of 21 tasks
@zxpdemonio
zxpdemonio force-pushed the cruz/flex_put_get branch 2 times, most recently from 6549211 to b2a6355 Compare April 22, 2026 09:03
@zxpdemonio zxpdemonio changed the title [Store]: Support flexible TP sizes for tensor storage with automatic reconstruction [Store] Unified parallel tensor IO Apr 23, 2026
zxpdemonio and others added 6 commits April 23, 2026 19:42
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>
zxpdemonio and others added 2 commits April 23, 2026 19:42
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>
zxpdemonio and others added 3 commits April 24, 2026 11:40
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>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 _from and _into variants.
  • 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.

Comment thread mooncake-integration/store/store_py.cpp Resolved
Comment thread mooncake-integration/store/store_py.cpp Resolved
@zxpdemonio

Copy link
Copy Markdown
Collaborator Author

Benchmark Configuration

Item Value
Total data sizes 1GB, 4GB
Tensor size 256MB
TP size 4
Split dimensions 0, 1
Iterations 3
Environment Local Mooncake store over TCP
Metric Effective throughput in Gbps

1GB Results

Mode Split Dim Scenario Avg Time (s) Throughput (Gbps)
TP 0 all-gather + all-read 5.5556 6.18
TP 0 all-gather + put_tp + read_tp 1.8683 18.39
TP 0 put_parallelism + read_parallelism 1.8313 18.76
DP+TP 0 put_parallelism + read_parallelism 1.0845 31.68
PP+TP 0 put_parallelism + read_parallelism 1.0578 32.48
EP+TP 0 put_parallelism + read_parallelism 1.0590 32.45
TP 1 all-gather + all-read 4.4453 7.73
TP 1 all-gather + put_tp + read_tp 1.9149 17.94
TP 1 put_parallelism + read_parallelism 1.8298 18.78
DP+TP 1 put_parallelism + read_parallelism 1.1529 29.80
PP+TP 1 put_parallelism + read_parallelism 1.1535 29.79
EP+TP 1 put_parallelism + read_parallelism 1.1548 29.75

4GB Results

Mode Split Dim Scenario Avg Time (s) Throughput (Gbps)
TP 0 all-gather + all-read 20.9390 6.56
TP 0 all-gather + put_tp + read_tp 7.8182 17.58
TP 0 put_parallelism + read_parallelism 7.2091 19.06
DP+TP 0 put_parallelism + read_parallelism 4.2357 32.45
PP+TP 0 put_parallelism + read_parallelism 4.2261 32.52
EP+TP 0 put_parallelism + read_parallelism 4.2514 32.33
TP 1 all-gather + all-read 19.1191 7.19
TP 1 all-gather + put_tp + read_tp 8.0390 17.10
TP 1 put_parallelism + read_parallelism 7.1310 19.27
DP+TP 1 put_parallelism + read_parallelism 4.5002 30.54
PP+TP 1 put_parallelism + read_parallelism 4.5016 30.53
EP+TP 1 put_parallelism + read_parallelism 4.5217 30.40

Conclusions

  1. The unified with_parallelism shard path significantly outperforms the all-gather baseline.

    Compared with all-gather + all-read, the put_parallelism + read_parallelism path improves effective throughput by roughly:

    • 4.1x–5.3x on the 1GB benchmark
    • 4.6x–4.9x on the 4GB benchmark
  2. The multi-axis parallelism paths are the fastest tested paths.

    DP+TP, PP+TP, and EP+TP reach around:

    • 29.8–32.5 Gbps on 1GB
    • 30.4–32.5 Gbps on 4GB

    This is substantially faster than the plain TP put_parallelism + read_parallelism path, which stays around 18–19 Gbps.

  3. The new full-tensor-input semantics for TP-containing multi-axis layouts are performance-effective.

    For DP+TP, PP+TP, and EP+TP, callers pass the full tensor and Mooncake persists only the shard selected by the requested TP rank/layout. The benchmark shows this avoids
    the expensive all-gather-style write/read pattern while keeping the unified API shape.

  4. Split dimension 0 is slightly faster than split dimension 1 for multi-axis layouts.

    On 4GB:

    • split_dim 0: about 32.3–32.5 Gbps
    • split_dim 1: about 30.4–30.5 Gbps

    The difference is modest but consistent in this run.

  5. The old all-gather baseline scales poorly.

    The all-gather + all-read path stays around 6–7 Gbps, while the unified parallelism path stays near 30+ Gbps for multi-axis layouts. This confirms that avoiding full
    materialization and reading only rank-local shards is the main performance win.

zxpdemonio and others added 4 commits April 24, 2026 17:31
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>
@stmatengss

Copy link
Copy Markdown
Collaborator

All APIs are newly added and bug-free. LGTM

@stmatengss
stmatengss merged commit 02d1975 into kvcache-ai:main Apr 27, 2026
19 checks passed
A-Liuhao pushed a commit to A-Liuhao/Mooncake that referenced this pull request Jun 25, 2026
* [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>
llfl pushed a commit to openanolis/Mooncake that referenced this pull request Oct 8, 2026
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.
llfl pushed a commit to openanolis/Mooncake that referenced this pull request Oct 8, 2026
- 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.
llfl pushed a commit to openanolis/Mooncake that referenced this pull request Oct 9, 2026
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.
llfl pushed a commit to openanolis/Mooncake that referenced this pull request Oct 9, 2026
- 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.
llfl pushed a commit to openanolis/Mooncake that referenced this pull request Oct 9, 2026
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.
llfl pushed a commit to openanolis/Mooncake that referenced this pull request Oct 9, 2026
- 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.
Bo-Vincent pushed a commit that referenced this pull request Nov 19, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants