Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 113 additions & 0 deletions docs/source/python-api-reference/mooncake-store.md
Original file line number Diff line number Diff line change
Expand Up @@ -1632,6 +1632,64 @@ def batch_get_tensor_with_tp(self, base_keys: List[str], tp_rank: int = 0, tp_si

- `List[torch.Tensor]`: List of retrieved tensors (or shards). Contains `None` for missing keys.

#### put_tensor_chunk_with_tp()

Put one already-split TP shard under `key_tp_<tp_rank>` and write TP metadata alongside it.
This API is useful when the caller already owns the sharding plan and wants Mooncake to persist shard placement metadata without reconstructing or re-splitting the full tensor.

```python
def put_tensor_chunk_with_tp(self, key: str, tensor_chunk: torch.Tensor, tp_rank: int = 0, tp_size: int = 1, split_dim: int = 0, full_shape: Optional[List[int]] = None, config: ReplicateConfig = None) -> int
```

**Parameters:**

- `key` (str): Base identifier for the logical tensor.
- `tensor_chunk` (torch.Tensor): One shard for rank `tp_rank`.
- `tp_rank` (int): Writer rank for this shard.
- `tp_size` (int): Total writer shard count.
- `split_dim` (int): Tensor dimension used for sharding.
- `full_shape` (Optional[List[int]]): Full logical tensor shape. Required when the final shard sizes cannot be inferred by `chunk_shape * tp_size`, such as uneven splits.
- `config` (ReplicateConfig, optional): Replication configuration for the shard and metadata objects.

**Returns:**

- `int`: Status code (0 = success, non-zero = error code).

**Metadata written:**

- When `tp_size > 1`, the API writes:
- `key_tp_<tp_rank>`: the shard payload
- `key_tp_<tp_rank>_meta`: `ChunkMetadata(start_idx, size)` for this shard
- `key_global_meta`: `GlobalMetadata(dtype, ndim, split_dim, put_tp_size, shape)` written by rank 0
- When `tp_size == 1`, this API falls back to plain `put_tensor()` and does not write TP metadata objects.

#### batch_put_tensor_chunk_with_tp()

Batch version of `put_tensor_chunk_with_tp()`. Each input tensor is treated as one already-split shard for the same `tp_rank`.

```python
def batch_put_tensor_chunk_with_tp(self, base_keys: List[str], tensor_chunks: List[torch.Tensor], tp_rank: int = 0, tp_size: int = 1, split_dim: int = 0, full_shapes: Optional[List[List[int]]] = None, config: ReplicateConfig = None) -> List[int]
```

**Parameters:**

- `base_keys` (List[str]): Base identifiers for logical tensors.
- `tensor_chunks` (List[torch.Tensor]): One shard per logical tensor.
- `tp_rank` (int): Writer rank shared by all input shards.
- `tp_size` (int): Total writer shard count.
- `split_dim` (int): Tensor dimension used for sharding.
- `full_shapes` (Optional[List[List[int]]]): Full logical tensor shapes, one per item. Provide these for uneven splits.
- `config` (ReplicateConfig, optional): Replication configuration.

**Returns:**

- `List[int]`: Per-item status codes.

**Notes:**

- When `tp_rank != 0`, batch shard put writes `key_tp_<tp_rank>` and `key_tp_<tp_rank>_meta`, but does not write `key_global_meta`.
- When `tp_size == 1`, this API falls back to plain `batch_put_tensor()` and does not write TP metadata objects.

---
#### put_tensor()

Expand Down Expand Up @@ -2090,6 +2148,61 @@ def batch_put_tensor_with_tp_from(self, base_keys: List[str], buffer_ptrs: List[

- `List[int]`: List of status codes for each tensor operation (0 = success, non-zero = error code).

#### put_tensor_chunk_with_tp_from()

Store one serialized TP shard from a registered buffer and write the corresponding TP metadata. The buffer layout must be **\[TensorMetadata\]\[tensor data\]** for the shard itself, not the full logical tensor.

```python
def put_tensor_chunk_with_tp_from(self, key: str, buffer_ptr: int, size: int, tp_rank: int, tp_size: int = 1, split_dim: int = 0, full_shape: Optional[List[int]] = None, config: ReplicateConfig = None) -> int
```

**Parameters:**

- `key` (str): Base identifier for the logical tensor.
- `buffer_ptr` (int): Registered buffer pointer containing one serialized shard.
- `size` (int): Actual serialized byte length of the shard buffer.
- `tp_rank` (int): Writer rank for this shard.
- `tp_size` (int): Total writer shard count.
- `split_dim` (int): Tensor dimension used for sharding.
- `full_shape` (Optional[List[int]]): Full logical tensor shape. Provide this for uneven splits.
- `config` (ReplicateConfig, optional): Replication configuration.

**Returns:**

- `int`: Status code (0 = success, non-zero = error code).

**Notes:**

- When `tp_size == 1`, this API falls back to plain `put_tensor_from()` and does not write TP metadata objects.

#### batch_put_tensor_chunk_with_tp_from()

Batch version of `put_tensor_chunk_with_tp_from()`. Each buffer contains one serialized shard in **\[TensorMetadata\]\[tensor data\]** layout.

```python
def batch_put_tensor_chunk_with_tp_from(self, base_keys: List[str], buffer_ptrs: List[int], sizes: List[int], tp_rank: int, tp_size: int = 1, split_dim: int = 0, full_shapes: Optional[List[List[int]]] = None, config: ReplicateConfig = None) -> List[int]
```

**Parameters:**

- `base_keys` (List[str]): Base identifiers for logical tensors.
- `buffer_ptrs` (List[int]): Registered buffer pointers, one shard per item.
- `sizes` (List[int]): Actual serialized byte lengths for each shard buffer.
- `tp_rank` (int): Writer rank shared by all input shards.
- `tp_size` (int): Total writer shard count.
- `split_dim` (int): Tensor dimension used for sharding.
- `full_shapes` (Optional[List[List[int]]]): Full logical tensor shapes, one per item. Provide these for uneven splits.
- `config` (ReplicateConfig, optional): Replication configuration.

**Returns:**

- `List[int]`: Per-item status codes.

**Notes:**

- When `tp_rank != 0`, batch shard put writes `key_tp_<tp_rank>` and `key_tp_<tp_rank>_meta`, but does not write `key_global_meta`.
- When `tp_size == 1`, this API falls back to plain `batch_put_tensor_from()` and does not write TP metadata objects.

---

### Batch Zero-Copy Operations
Expand Down
59 changes: 59 additions & 0 deletions mooncake-integration/integration_utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

#include <array>
#include <functional>
#include <stdexcept>

namespace py = pybind11;

Expand Down Expand Up @@ -96,10 +97,68 @@ inline TensorDtype get_tensor_dtype(py::object dtype_obj) {
return TensorDtype::UNKNOWN;
}

inline size_t get_element_size(int32_t dtype) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Why not directly use sizeof?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

This follows the existing put_tensor serialization path.
In this code path we only have the runtime TensorDtype value from TensorMetadata, not a concrete compile-time C++ type, so sizeof(...) is not directly applicable here.
We therefore keep a runtime dtype-to-element-size mapping, consistent with the current put_tensor / put_tensor_from logic.

switch (static_cast<TensorDtype>(dtype)) {
case TensorDtype::FLOAT32:
return sizeof(float);
case TensorDtype::FLOAT64:
return sizeof(double);
case TensorDtype::INT8:
case TensorDtype::UINT8:
return 1;
case TensorDtype::INT16:
case TensorDtype::UINT16:
return 2;
case TensorDtype::INT32:
case TensorDtype::UINT32:
return 4;
case TensorDtype::INT64:
case TensorDtype::UINT64:
return 8;
case TensorDtype::BOOL:
return 1;
case TensorDtype::FLOAT16:
case TensorDtype::BFLOAT16:
return 2;
case TensorDtype::FLOAT8_E4M3:
case TensorDtype::FLOAT8_E5M2:
return 1;
default:
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));
}
}

struct TensorMetadata {
int32_t dtype;
int32_t ndim;
int64_t shape[4];
};

// Global metadata stored once per logical key
// Contains information about the full tensor
// Use packed struct to avoid alignment issues
#pragma pack(push, 1)
struct GlobalMetadata {
int32_t dtype;
int32_t ndim;
int32_t split_dim;
int32_t put_tp_size; // Number of writer chunks
int64_t shape[4]; // Full tensor shape
};
#pragma pack(pop)

// Chunk metadata stored per chunk
// Contains information about a single chunk's position in the split dimension
#pragma pack(push, 1)
struct ChunkMetadata {
int64_t start_idx; // Starting index in split_dim
int64_t size; // Size in split_dim
};
#pragma pack(pop)

} // namespace mooncake
Loading
Loading